Skip to content

[CTX-1444] fix(runtime): reap a child whose PTY reached EOF before exit (#2443) - #2454

Merged
Xuepoo merged 2 commits into
mainfrom
ctx-1444/fix-last-panel-exit-hang
Oct 22, 2026
Merged

Xuepoo merged 2 commits into
mainfrom
ctx-1444/fix-last-panel-exit-hang

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Closes #2443.

Root cause

exit in the last panel can hang because EOF and child exit are two different events:

  1. The shell closes every tty slave fd (exit_files), so the PTY reader reaches EOF and the forwarder wakes the event loop once.
  2. On Linux the process becomes reapable only later (exit_notify). The reap pass on that single wake can legitimately see try_wait() == None.
  3. No further wake is queued, the loop waits indefinitely, and the last panel keeps painting the dead shell frame.

Fix

  • Latch reader EOF per primary/pane session (primary_eof / reader_eof), set by the forwarder, the direct pump, and the blocking twin; reset on every spawn with a fresh Arc so a detached old forwarder cannot mark the new session.
  • Runtime::has_unreaped_eof_session() reports EOF + unreaped child.
  • TerminalApp::shell_exit_poll_deadline() arms a bounded reap wake (10 ms initial, 500 ms cap) only while that predicate holds; it clears on the same pass that consumes the exit, keeping idle windows on the zero-periodic-wakeup path.
  • Feed the deadline into the event-loop wait, so termination never depends on an unrelated input/compositor event.

Tests

  • last_panel_exit_after_pty_eof_terminates_issue_2443: real PTY whose child closes the tty before exiting; asserts the app exits promptly and the poll clears.
  • late_exiting_split_pane_closes_only_that_pane_issue_2443: same race in a non-last pane closes only that pane and leaves the session healthy.
  • real_pty coverage for the child-reap path.
  • cargo test -p bitty-terminal --bin bitty issue_2443 → 2 passed; cargo fmt --check clean.

No product behavior change for normal shells; the poll exists only between EOF and reap.

@Xuepoo Xuepoo added this to the 0.0.26 milestone Oct 22, 2026
@Xuepoo Xuepoo added fix Bug fix P1 Priority: high area:runtime Area: runtime orchestration area:stability Stability hardening labels Oct 22, 2026
@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 37 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c383db52-0eda-4f37-adbd-6363a825a00d
📥 Commits

Reviewing files that changed from the base of the PR and between 96f1c43 and e44919d.

📒 Files selected for processing: 6
  • crates/bitty-runtime/src/runtime.rs
  • crates/bitty-runtime/src/runtime/panes.rs
  • crates/bitty-runtime/src/runtime/pty.rs
  • crates/bitty-runtime/tests/real_pty.rs
  • crates/bitty-terminal/src/terminal_app.rs
  • crates/bitty-terminal/src/tests.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Xuepoo
Xuepoo force-pushed the ctx-1444/fix-last-panel-exit-hang branch from 042cae0 to f6ce1d2 Compare October 22, 2026 03:52

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Guard tick 2026-10-22 12:2x CST — macOS leg red, needs fix (not a flake)

macOS ARM64 check and test failed on head f6ce1d20 (run 39719221337, job 119630062728), 3 failures, all on the code this PR introduces:

FAIL crates/bitty-runtime/tests/real_pty.rs:164
     reader_eof_latches_unreaped_child_until_exit_is_observed
     "the child must span the EOF-to-reap gap for this regression"

FAIL crates/bitty-terminal/src/tests.rs:10362
     tests::late_exiting_split_pane_closes_only_that_pane_issue_2443
     "no PTY session reported EOF with an unreaped child within the bound"

FAIL crates/bitty-terminal/src/tests.rs:10362
     tests::last_panel_exit_after_pty_eof_terminates_issue_2443
     "no PTY session reported EOF with an unreaped child within the bound"

Analysis: the two new issue_2443 tests and the real_pty regression helper all depend on observing a PTY EOF while the child is still unreaped. On macOS that window does not reproduce within the bound, so the harness assumption (not the production fix) is platform-sensitive. Linux X11/Wayland and Windows legs are green on the same head, so this is macOS-only.

Needed: bound the wait on an observable signal instead of the EOF-to-reap timing assumption, or make the macOS path assert the weaker invariant (EOF observed OR child reaped) with an explicit comment naming the platform difference. Do not silence the tests.

State: NEEDS-FIX. No rerun was requested — the failing assertions are this PR's own new tests, so a rerun would reproduce.

@Xuepoo
Xuepoo force-pushed the ctx-1444/fix-last-panel-exit-hang branch from b7d4c1b to bf80b5b Compare October 22, 2026 05:20
@Xuepoo
Xuepoo force-pushed the ctx-1444/fix-last-panel-exit-hang branch from bf80b5b to 773f104 Compare October 22, 2026 05:48

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review verdict — PR #2454 @ 773f1040

Reviewer: separate agent (hermes guard dispatch), static review of the diff only, no builds run.
Gap-fill: this PR had no recorded review verdict at this head.

Diff shape: 6 files, +432/−7. Fix = reader-terminal latch (primary_eof / PaneSession::reader_eof) + Runtime::has_unreaped_eof_session + a bounded reap-wake schedule in TerminalApp's AboutToWait.

Checks

  • (a) Double-wait / PID reuse: clean. The poll never calls waitpid, it only arms wakes; reaping still flows through primary_exit_status/pane_try_wait → Pty::try_wait, which short-circuits with ChildAlreadyReaped (crates/bitty-pty/src/pty.rs:217-226), and the predicate gates on is_reaped() (crates/bitty-runtime/src/runtime/pty.rs:592-599).
  • (b) EOF/teardown/reap race: safe in the dangerous direction — the latch is stored (Release) before the EOF wake (pty.rs:56) and read with Acquire (:21-23); nothing on this path signals or kills a child, so a live shell cannot be killed; a respawn gets a fresh Arc so a detached old forwarder cannot poison it (runtime/panes.rs:183-189, pane init :568).
  • (c) Panel-count coverage: structurally yes — primary plus every pane_sessions value, including inactive workspaces/floats/pins (pty.rs:592-599), and the reap pass reaps the primary regardless of surviving panes (crates/bitty-terminal/src/terminal_app.rs:3257-3271). Not covered: the sibling hang class where the shell exits while a background grandchild keeps the tty open produces no EOF, so no latch and no wake.
  • (d) Test honesty: gated #[cfg(target_os = "linux")] on all three tests and their helpers (tests/real_pty.rs:140, src/tests.rs:10334/10353/10371/10400/10476) and causal rather than tautological — the "no exit yet" assertion is enforced by a marker written only afterwards (tests.rs:10434, :10496), and a missing schedule panics at tests.rs:10383. Load-sensitivity: the runtime test's 2 s sleep vs the 10 s TIMEOUT, and a single shared 10 s deadline in the terminal tests.
  • (e) Panics / blocking / unbounded wait: none on the production path (tests only), no blocking call (pure Instant math + O(panes) scan at terminal_app.rs:3347-3366), interval hard-capped.

VERDICT: APPROVE-WITH-NITS

  1. minor — crates/bitty-terminal/src/terminal_app.rs:3347-3366: the poll is bounded in rate but not in duration while the doc at :321 ("still observed within this bound") implies otherwise; a shell that closes its tty and keeps running costs 2 wakes/s forever, violating the zero-periodic-wakeup idle property — cap total attempts or reword the comment.
  2. minor — crates/bitty-runtime/src/runtime/pty.rs:592: the latch keys on EOF only, so a last-panel shell that exits while a background child holds the tty still parks the loop with no wake — track child exit independently or document the residual hang in the PR body.
  3. minor — crates/bitty-runtime/src/runtime/pty.rs:773-775: Err(_) swallows RecvTimeoutError::Disconnected without latching; match Disconnected and mark_reader_eof, leaving only Timeout unmarked.
  4. minor — crates/bitty-terminal/src/tests.rs:10401: no test covers the last-remaining-pane-session case (primary already closed) or a pinned/floating exit — add one where only a pane session remains.
  5. nit — terminal_app.rs:3356: the saturating_mul(2)/SHELL_EXIT_POLL_MAX backoff is untested (every test reaps on the first 10 ms interval).
  6. nit — src/tests.rs:10372-10396: the test drives shell_exit_poll_deadline() directly, so dropping shell_exit from the wake array at terminal_app.rs:3983 would still pass — assert set_wait_until through the fake event-loop context.

No files modified; nothing built or run by the reviewer.

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review verdict — PR #2454 @ 773f1040

Reviewer: separate agent, fresh worktree at the PR head (/tmp/opencode/review-2454). No PR files modified, nothing pushed; local gates only (no act / ci-local).

VERDICT: APPROVE

What I verified

  • Race fixed on Linux. The reader terminal state is latched per session (primary_eof, PaneSession::reader_eof) by the forwarder, the direct pump, and the blocking twin; the store (Release) precedes the single EOF wake, the event-loop read is Acquire. Runtime::has_unreaped_eof_session is true only for EOF + !Pty::is_reaped(). TerminalApp::shell_exit_poll_deadline arms 10 ms, then 20/40/80/160/320/500 ms capped, and the deadline is folded into the AboutToWait wake min. Reap runs at the top of handle_event and again in AboutToWait, so every armed timer wake consumes the exit and the schedule clears on the same pass that reaps. No busy loop (2 Hz ceiling, only while EOF + unreaped).
  • No double waitpid / PID reuse. The poll only reads Pty::is_reaped (read-only snapshot) and never reaps; the single reap owner remains primary_exit_status/pane_try_wait -> Pty::try_wait, which sets reaped and short-circuits ChildAlreadyReaped. There is no SIGCHLD/global process reaper in the tree. While unreaped the PID is held by the zombie, so there is no reuse window.
  • Respawn isolation. spawn_shell_with_args installs a fresh Arc after swapping the Pty and joining/detaching the old forwarder; pane sessions get a fresh Arc at spawn. A timed-out detached forwarder holds only the old Arc, so it cannot mark the new session.
  • Last panel / shutdown bounded. reap_exited_shells -> AppExiting -> save + Runtime::shutdown() + ctx.exit(); shutdown keeps FORWARDER_JOIN_TIMEOUT (500 ms) per forwarder, and Pty::drop uses DROP_REAP_TIMEOUT. The new poll adds no blocking call: O(panes) bool scan + Instant math.
  • Linux gating honest, product code portable. No cfg in product code; the gate is only on the three tests/helpers. The macOS leg at f6ce1d20 showed the EOF->unreaped window is not observable there (EOF arrived only once the child was reapable); gating is the honest consequence. Linux, Windows, and macOS legs are green on 773f1040.
  • CodeRabbit: zero inline review comments and zero review threads on this PR; the only bot comment is a rate-limit notice (status check CodeRabbit SUCCESS). Nothing to apply or decline.

Local evidence (Linux, rustc 1.98.1, dedicated target dir)

  • cargo fmt --all -- --check: clean.
  • cargo clippy -p bitty-runtime -p bitty-terminal --all-targets --locked and -p bitty-terminal --features dev-tools --all-targets --locked: clean with -D warnings.
  • issue_2443: 2/2 passed; repeated 20x -> 0 failures.
  • Negative control: with shell_exit_poll_deadline forced to None, both issue_2443 tests fail 5/5 (PTY EOF with an unreaped child must keep a bounded reap wake armed), so the regression test is causally bound to the fix rather than passing on timing luck.
  • reap_exited: 16/16; close_last: 4/4; close_to_empty: 1/1.
  • real_pty: 4/4 (including reader_eof_latches_unreaped_child_until_exit_is_observed, repeated 10x -> 0 failures); pane_sessions 7/7; runtime_panes 7/7; runtime_drop_join 5/5; pty_wakeup 2/2; poll_budget_0476 2/2.

Non-blocking notes (follow-ups, not merge blockers)

  1. SHELL_EXIT_POLL_MAX says a lingering child "is still observed within this bound", but the schedule is rate-bounded, not duration-bounded: a live direct child that keeps its tty closed leaves ~2 wakes/s armed indefinitely. No busy loop and no hang; reword the doc (or cap attempts) so the idle-wakeup contract is accurate.
  2. The three #[cfg(target_os = "linux")] test gates have no inline reason; add one line naming the macOS difference so the exclusion is reviewable and cannot be mistaken for silenced coverage.
  3. Residual sibling class: a shell that exits while a grandchild keeps the slave tty open produces no EOF, hence no latch and no wake. That is outside this PR's EOF-before-reap scope; track the no-EOF exit-detection gap separately if not already covered.
  4. The tests drive shell_exit_poll_deadline() directly; the shell_exit entry in the wake array is not asserted through the Recording event context. Optional test-strength improvement.

Process: the PR is BEHIND main at review time (no conflicts), so rebase and re-run CI before merge. Labels and milestone are correct, but the body is missing the standard Priority: ... | Area: ... | Labels: ... | Milestone: ... | RFC: ... | Task: CTX-1444 line.

Recorded as a review comment because the token belongs to the PR author, so GitHub rejects a formal APPROVE event on this PR.

@Xuepoo
Xuepoo force-pushed the ctx-1444/fix-last-panel-exit-hang branch from 773f104 to e44919d Compare October 22, 2026 07:31
@Xuepoo
Xuepoo merged commit be1262f into main Oct 22, 2026
32 of 33 checks passed
@Xuepoo
Xuepoo deleted the ctx-1444/fix-last-panel-exit-hang branch October 22, 2026 08:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:runtime Area: runtime orchestration area:stability Stability hardening fix Bug fix P1 Priority: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exit in the last panel can hang the terminal

1 participant