LogosLinuxInstaller icon indicating copy to clipboard operation
LogosLinuxInstaller copied to clipboard

TUI crashes with RecursionError: SIGWINCH handler redraws inline and re-enters itself

Open jbellars opened this issue 3 months ago • 1 comments

Repo: https://github.com/FaithLife-Community/OuDedetai Version: 4.0.0-beta.14 (also reproduced on main @ 43fa3e5) Mode: TUI (curses), control panel

Summary

TUI.signal_resize performs the entire curses redraw inside the SIGWINCH handler. Python runs signal handlers on the main thread between bytecodes and does not mask the signal while its own handler is running, so a burst of SIGWINCH — a window drag, or a tiling WM moving things around — re-enters signal_resize on top of the in-progress call, over and over, until the interpreter hits its recursion limit and the app dies.

The nested handler also re-enters curses and choice_q mid-operation; the reported stack shows a signal landing inside queue.qsize() (main loop) and the nested handler then blocking in queue.put()'s Lock.__enter__, where the next signal nests again.

Reported traceback (abridged)

Traceback (most recent call last):
  File "ou_dedetai/main.py", line 458, in main
  File "ou_dedetai/main.py", line 397, in run
  File "ou_dedetai/main.py", line 333, in run_control_panel
  File "curses/__init__.py", line 94, in wrapper
  File "ou_dedetai/tui_app.py", line 1358, in control_panel_app
  File "ou_dedetai/tui_app.py", line 544, in run
  File "ou_dedetai/tui_app.py", line 493, in display
  File "queue.py", line 95, in qsize
  File "queue.py", line 209, in _qsize
  File "ou_dedetai/tui_app.py", line 431, in signal_resize      <-- signal lands inside qsize()
  File "ou_dedetai/tui_app.py", line 423, in resize_curses
  File "ou_dedetai/tui_app.py", line 297, in create_windows
  File "ou_dedetai/tui_app.py", line 265, in set_window_dimensions
  File "ou_dedetai/tui_app.py", line 238, in set_console_window_dimensions
  File "ou_dedetai/tui_curses.py", line 23, in wrap_text
  File "textwrap.py", line 396, in fill
  ...
  File "ou_dedetai/tui_app.py", line 432, in signal_resize      <-- re-entered
  File "queue.py", line 133, in put
  File "threading.py", line 300, in __enter__
  File "ou_dedetai/tui_app.py", line 432, in signal_resize      <-- and again, ~1000 deep
  ...
RecursionError: maximum recursion depth exceeded
[PYI-13034:ERROR] Failed to execute script 'run_app' due to unhandled exception!

The --- Logging error --- blocks and interleaved output that follow are fallout: logging catches the RecursionError, and handleError needs stack it no longer has to print the traceback.

Root cause

ou_dedetai/tui_app.py:

420  def resize_curses(self):
421      self.resizing = True
422      curses.endwin()
423      self.create_windows()      # → set_window_dimensions → wrap_text → textwrap
424      self.clear()
425      self.init_curses()         # → set_tui_menu_options → version check → logging
426      self.refresh()
427      logging.debug("Window resized.")
428      self.resizing = False

430  def signal_resize(self, signum, frame):
431      self.resize_curses()
432      self.choice_q.put("resize")

resize_curses() is slow (window creation, textwrap.fill, curses re-init, a version check that does I/O and logging), so there is a wide window for the next SIGWINCH to arrive and nest. self.resizing exists but is only consulted by the main loop (line 484), never by signal_resize, so it does not prevent re-entry.

Reproducer

Drive the TUI from a pty and change the window size in a tight loop, the way a window drag does. Against main, the app dies every time; the crash surface varies between a printed RecursionError and a hard interpreter failure (lost sys.stderr) depending on how deep it gets before something else throws.

# winch_storm.py — usage: winch_storm.py <config_file>
import fcntl, os, pty, struct, sys, termios, threading, time

pid, fd = pty.fork()
if pid == 0:
    os.environ["TERM"] = "xterm-256color"
    os.environ["DIALOG"] = "curses"
    os.execv(sys.executable,
             [sys.executable, "-m", "ou_dedetai.main", "-c", sys.argv[1], "-V"])

out = bytearray()
def reader():
    while True:
        try:
            chunk = os.read(fd, 65536)
        except OSError:
            return
        if not chunk:
            return
        out.extend(chunk)
threading.Thread(target=reader, daemon=True).start()

def set_size(rows, cols):
    fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))

set_size(40, 120)
time.sleep(8)                       # settle into the control panel
for i in range(20000):              # ~0.03s of continuous resizing
    set_size(20 + i % 25, 60 + i % 60)
time.sleep(4)

alive = os.waitpid(pid, os.WNOHANG) == (0, 0)
print("app:", "ALIVE" if alive else "DIED")
print("RecursionError:", b"RecursionError" in bytes(out))

Results:

build outcome
main @ 43fa3e5, from source DIED — interpreter failure, lost sys.stderr
main @ 43fa3e5 + a probe in signal_resize DIED — RecursionError, 1356 signal_resize frames in the traceback
released oudedetai 4.0.0-beta.14 binary DIED — RecursionError (matches the report above)
with the patch below ALIVE, still redrawing after the storm

Instrumenting the handler to record len(stack) at entry confirms the depth climbs with each nested delivery rather than staying flat.

Proposed fix

Make the handler record the request and nothing else; let display() service it on the main loop. The loop already spins at ~10 Hz (stdscr.timeout(100)), so the redraw is not noticeably delayed, and it is where the existing curses.is_term_resized fallback already calls resize_curses().

--- a/ou_dedetai/tui_app.py
+++ b/ou_dedetai/tui_app.py
@@ -66,6 +66,8 @@ class TUI(App):
 
         self.terminal_margin = 2
         self.resizing = False
+        # Set by the SIGWINCH handler, serviced by display() on the main loop
+        self.resize_requested = False
         # These two are updated in set_window_dimensions
         self.console_log_lines = 0
         self.options_per_page = 0
@@ -428,6 +430,16 @@ class TUI(App):
         self.resizing = False
 
     def signal_resize(self, signum, frame):
+        # Only record the request. Python runs signal handlers on the main
+        # thread between bytecodes and does not mask the signal while its
+        # handler runs, so redrawing here lets a burst of SIGWINCH (dragging a
+        # window edge, a tiling WM) re-enter this handler on top of itself
+        # until the interpreter hits its recursion limit. It also re-enters
+        # curses and choice_q mid-operation. display() services the request.
+        self.resize_requested = True
+
+    def handle_resize(self):
+        self.resize_requested = False
         self.resize_curses()
         self.choice_q.put("resize")
 
@@ -479,6 +491,9 @@ class TUI(App):
             # process exit happen on the correct thread.
             if self._pending_exit is not None:
                 self.exit(*self._pending_exit)
+            # Serviced here rather than in signal_resize itself; see that method
+            if self.resize_requested:
+                self.handle_resize()
             if self.window_height >= self.window_height_min and self.window_width >= 35:
                 self.terminal_margin = 2
                 if not self.resizing:

Clearing the flag before redrawing is deliberate: a SIGWINCH that arrives during resize_curses() sets it again and is serviced on the next iteration, rather than being swallowed.

Verified after the patch:

  • The storm above leaves the app alive and still drawing.
  • Normal resizing is unaffected — resizing to 24x80, 50x160 and 33x100 in turn, the app redraws its footer at rows 23, 49 and 32 respectively, identical to the behaviour on main.
  • ruff check clean; mypy ou_dedetai shows no new errors; unit tests show no new failures (the 3 failures + 1 error on main are pre-existing and unrelated).

I added tests/test_tui_app.py covering it — that signal_resize only sets the flag and calls nothing else, that 1000 back-to-back deliveries still do no work, that handle_resize does the redraw, and that a signal arriving mid-redraw survives as a fresh request. Happy to open a PR with the patch and the tests.

Possibly related

#247 (menu stops updating after a resize, terminal left needing reset) and #248 look like they could share this root cause — a handler that re-enters curses and the choice queue mid-operation can leave both in an inconsistent state without going all the way to a crash.

Environment

  • Arch Linux, kernel 7.1.9-arch1-2
  • Hyprland (tiling WM — window management sends SIGWINCH in bursts), foot terminal
  • OuDedetai 4.0.0-beta.14, released binary
  • Logos 52.2.0.19

jbellars avatar Aug 29 '26 22:08 jbellars

Some field data to add: this isn't a rare corner — it has been hitting me repeatedly during ordinary use, not just under the synthetic SIGWINCH storm in the report.

From ~/.local/state/FaithLife-Community/oudedetai.log, which covers 2026-08-25 20:16 to 2026-08-29 22:07 — 8 separate incidents in 4 days:

2026-08-27 14:38:18 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-27 14:38:18 ERROR: An error occurred in run_control_panel(): maximum recursion depth exceeded
2026-08-27 16:05:28 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-27 16:14:31 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-27 22:21:31 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-27 22:21:31 ERROR: An error occurred in run_control_panel(): maximum recursion depth exceeded
2026-08-29 09:16:46 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-29 09:24:29 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-29 09:24:29 ERROR: An error occurred in run_control_panel(): maximum recursion depth exceeded
2026-08-29 10:13:16 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded
2026-08-29 10:17:50 ERROR: An error occurred in init_curses(): maximum recursion depth exceeded

Three of the eight reached run_control_panel() and took the app down. The other five logged only the init_curses() error, and in those cases the TUI kept running but was left visibly corrupted — needing a reset after exiting. That milder mode looks a lot like what #247 describes.

No deliberate resize was involved in any of these. This is a Hyprland session, where ordinary window management (opening or closing a tiled window, switching workspaces) sends SIGWINCH in bursts to everything on screen — so the burst condition the handler needs arises just from using the desktop, without touching the terminal.

jbellars avatar Aug 30 '26 05:08 jbellars