Skip to content

[CTX-1866] fix(runtime): deliver the hang-recovery line without waiting on evidence sampling (bitty#3211) - #3213

Merged
Xuepoo merged 1 commit into
mainfrom
ctx-1866/stall-recovery-witness
Nov 17, 2026
Merged

Xuepoo merged 1 commit into
mainfrom
ctx-1866/stall-recovery-witness

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

[CTX-1866] fix(runtime): deliver the hang-recovery line without waiting on evidence sampling (bitty#3211)

main run 44023276410 reded on the macOS ARM64 leg only: in
stall_watchdog::tests::blocked_stage_writes_one_complete_dump the one-shot
stall dump arrived and every bitty#2830 field assertion passed, then the
recovery line never did inside the test's 5 s budget
(panicked at ...:6346:14: recovery line: Timeout). Linux and Windows passed
the identical test in the same run.

Root cause is in the state machine, not in the test's budget and not in the
evidence path:

  • Shared::mark publishes active and only then bumps progress, so a poll
    can sample the park edge together with the previous progress count.
  • That sample took MonitorState::evaluate's !active branch, which cleared
    stall_started and reported and returned MonitorAction::None without
    writing anything.
  • The advance that followed then found no episode left, so no later poll could
    ever deliver the line: a reported stall ended silently. The window between
    the two relaxed stores is nanoseconds per poll in production, which is why
    a loaded macOS runner reached it and a Linux leg did not.

Candidates from the issue, checked against the tree:

  • "the recovery is gated behind the poll that samples process evidence" -
    refuted: no build_report call sits in the recovery path, and on non-Linux
    targets sample_process_totals returns an empty snapshot, so macOS samples
    less evidence than Linux, not more.
  • "clear_wake_notifications drops a notification and the next wait_poll
    sleeps a full interval" - real but bounded: the pipe keeps the 0 Hz park
    correct and a missed wake costs one poll interval of latency, never the
    line. Left as is (making notify() drive the poll would spend monitor CPU
    per app mark and changes the parked-mode sampling contract).

Fix the mechanism:

  • MonitorState::close_episode is now the single way out of a reported
    episode. Both the advance edge and the park edge close it, so whichever one
    a poll observes first emits the one line the report owes.
  • MonitorState::take_advance consumes the advance from one snapshot at the
    top of the poll, on the wake and before any sampling or rendering.
  • MonitorState::stalled_phase makes the recovery line name the phase that
    stalled instead of whatever the closing poll sampled (idle at the park
    edge).
  • Test seam: Shared::set_publish_gap widens the mark publish gap so the
    interleaving is deterministic on every platform. Production is untouched
    (#[cfg(test)] only).

A/B evidence (same tree, only the production hunk reverted in a separate copy
with its own CARGO_TARGET_DIR):

  • old behaviour: stall_watchdog::tests -> 75 passed, 2 failed
    • park_edge_delivers_the_recovery_the_report_owes:
      left: None, right: Recovered { stalled_for: 20ms, phase: RuntimeTick }
    • recovery_line_survives_a_preempted_phase_publish:
      recovery line: Timeout (the CI panic, reproduced on Linux)
  • fixed behaviour: stall_watchdog::tests -> 77 passed, 0 failed

Tests keep the 5 s budget, the one-shot contract is intact (no second dump
while continuously stalled), and the recovery is still one line per episode.
The watchdog stays observability-only: it changes when the line is written,
not routing, timing, or app state.

Gates (host, CARGO_TARGET_DIR=.../.targets/ctx-1866):

  • rustfmt --edition 2024 --check crates/bitty-terminal/src/stall_watchdog.rs - clean
  • cargo clippy -p bitty-terminal --all-targets --offline -- -D warnings - clean
  • cargo test -p bitty-terminal --bin bitty --offline stall_watchdog - ok, 77 passed
  • RUSTFLAGS=-D warnings cargo check -p bitty-terminal --tests --target x86_64-pc-windows-gnu --offline - ok
  • cargo +1.85 check -p bitty-terminal --tests --offline - ok (MSRV 1.85)
  • cargo test -p bitty-terminal --bin bitty --offline hang - ok, 34 passed

macOS reasoning: the failing leg is macOS-only because the lost-line window is
a scheduler window, not a platform gate. Shared::mark is host-independent
common code, ARM64 (macOS) has a longer Instant::elapsed between the two
stores than an x86_64 vDSO read, and the runner hosts 1600+ tests over three
cores, which widens the preemption chance between the active store and the
progress bump. Windows and Linux reach the same code and can lose the same
line; the fix removes the loss for every platform, and the seam test proves it
on Linux without touching the budget.

Closes #3211

…ng on evidence sampling (bitty#3211)

`main` run 44023276410 reded on the macOS ARM64 leg only: in
`stall_watchdog::tests::blocked_stage_writes_one_complete_dump` the one-shot
stall dump arrived and every bitty#2830 field assertion passed, then the
recovery line never did inside the test's 5 s budget
(`panicked at ...:6346:14: recovery line: Timeout`). Linux and Windows passed
the identical test in the same run.

Root cause is in the state machine, not in the test's budget and not in the
evidence path:

* `Shared::mark` publishes `active` and only then bumps `progress`, so a poll
  can sample the park edge together with the previous progress count.
* That sample took `MonitorState::evaluate`'s `!active` branch, which cleared
  `stall_started` and `reported` and returned `MonitorAction::None` without
  writing anything.
* The advance that followed then found no episode left, so no later poll could
  ever deliver the line: a reported stall ended silently. The window between
  the two relaxed stores is nanoseconds per poll in production, which is why
  a loaded macOS runner reached it and a Linux leg did not.

Candidates from the issue, checked against the tree:
* "the recovery is gated behind the poll that samples process evidence" -
  refuted: no `build_report` call sits in the recovery path, and on non-Linux
  targets `sample_process_totals` returns an empty snapshot, so macOS samples
  less evidence than Linux, not more.
* "`clear_wake_notifications` drops a notification and the next `wait_poll`
  sleeps a full interval" - real but bounded: the pipe keeps the 0 Hz park
  correct and a missed wake costs one poll interval of latency, never the
  line. Left as is (making `notify()` drive the poll would spend monitor CPU
  per app mark and changes the parked-mode sampling contract).

Fix the mechanism:

* `MonitorState::close_episode` is now the single way out of a reported
  episode. Both the advance edge and the park edge close it, so whichever one
  a poll observes first emits the one line the report owes.
* `MonitorState::take_advance` consumes the advance from one snapshot at the
  top of the poll, on the wake and before any sampling or rendering.
* `MonitorState::stalled_phase` makes the recovery line name the phase that
  stalled instead of whatever the closing poll sampled (`idle` at the park
  edge).
* Test seam: `Shared::set_publish_gap` widens the `mark` publish gap so the
  interleaving is deterministic on every platform. Production is untouched
  (`#[cfg(test)]` only).

A/B evidence (same tree, only the production hunk reverted in a separate copy
with its own `CARGO_TARGET_DIR`):

* old behaviour: `stall_watchdog::tests` -> 75 passed, 2 failed
  - `park_edge_delivers_the_recovery_the_report_owes`:
    `left: None, right: Recovered { stalled_for: 20ms, phase: RuntimeTick }`
  - `recovery_line_survives_a_preempted_phase_publish`:
    `recovery line: Timeout` (the CI panic, reproduced on Linux)
* fixed behaviour: `stall_watchdog::tests` -> 77 passed, 0 failed

Tests keep the 5 s budget, the one-shot contract is intact (no second dump
while continuously stalled), and the recovery is still one line per episode.
The watchdog stays observability-only: it changes when the line is written,
not routing, timing, or app state.

Gates (host, `CARGO_TARGET_DIR=.../.targets/ctx-1866`):
* `rustfmt --edition 2024 --check crates/bitty-terminal/src/stall_watchdog.rs` - clean
* `cargo clippy -p bitty-terminal --all-targets --offline -- -D warnings` - clean
* `cargo test -p bitty-terminal --bin bitty --offline stall_watchdog` - ok, 77 passed
* `RUSTFLAGS=-D warnings cargo check -p bitty-terminal --tests --target x86_64-pc-windows-gnu --offline` - ok
* `cargo +1.85 check -p bitty-terminal --tests --offline` - ok (MSRV 1.85)
* `cargo test -p bitty-terminal --bin bitty --offline hang` - ok, 34 passed

macOS reasoning: the failing leg is macOS-only because the lost-line window is
a scheduler window, not a platform gate. `Shared::mark` is host-independent
common code, ARM64 (macOS) has a longer `Instant::elapsed` between the two
stores than an x86_64 vDSO read, and the runner hosts 1600+ tests over three
cores, which widens the preemption chance between the `active` store and the
`progress` bump. Windows and Linux reach the same code and can lose the same
line; the fix removes the loss for every platform, and the seam test proves it
on Linux without touching the budget.

Closes #3211
@Xuepoo Xuepoo added fix Bug fix P1 Priority: high area:stability Stability hardening area:ci CI area:testing labels Nov 17, 2026
@coderabbitai

coderabbitai Bot commented Nov 17, 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 45 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: 4a494ba2-a18d-454a-b4e8-a247791479bc
Commits

Reviewing files that changed from the base of the PR and between 4bc0fce and 8909681.

Files selected for processing: 1

  • crates/bitty-terminal/src/stall_watchdog.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

@Xuepoo Xuepoo added this to the v0.1.0 milestone Nov 17, 2026

@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 by guard reviewer subagent (read-only; discrimination proven on scratch copies with separate target dirs).

Independent review — PR #3213 (CTX-1866 stall-recovery witness)

  • Repo: bitty-terminal/bitty
  • PR: #3213 [CTX-1866] fix(runtime): deliver the hang-recovery line without waiting on evidence sampling (bitty#3211)
  • Branch: ctx-1866/stall-recovery-witness
  • Head reviewed: 890968184134d6cd4da6f83504bb26c0c8a9b5fd (matches gh pr view 3213 --json headRefOid; not moved)
  • Reviewer: independent (not the lane). All commands run on scratch clones under
    $HOME/.hermes/cache/scratch/prrev/trees/, each with its own CARGO_TARGET_DIR.
    The lane worktree .worktrees/ctx-1866-stall-recovery-witness was never opened for write.

1. Diff read end to end; head SHA matches — PASS

  • gh pr diff 3213 read in full (414 lines, 1 file).
  • git diff --stat origin/main...89096818 → crates/bitty-terminal/src/stall_watchdog.rs | 275 +++++--- (253+, 22-). One file, entirely in scope. No unrelated file, no lockfile, no workflow change.
  • Single commit 89096818 — subject carries [CTX-1866].

2. Cited root cause is in the code; fix is mechanism, not budget/test — PASS

Ordering, on the pre-fix tree (origin/main:.../stall_watchdog.rs):

  • Shared::mark publishes active before bumping progress:
    :1108 fn mark, :1110 self.active.store(active, ...), :1113 self.progress.fetch_add(1, ...).
    Same ordering on the head: :1173 fn mark, :1175 active.store, :1190 progress.fetch_add.
  • The !active branch that cleared the episode without emitting: pre-fix :1016 if !active {, :1019 self.stall_started = None;, returns MonitorAction::None. Comment there said so explicitly: "a threshold crossing that ended without a report leaves no recovery line".
  • The only recovery emission pre-fix was inside the progress-change branch (:1012 Some(stalled_for) if had_report => MonitorAction::Recovered { stalled_for }), rendered at :1832. A poll that consumed the park edge first took stall_started, so the later advance found nothing: the line was lost permanently. The cited root cause is confirmed in code, not merely asserted.

Fix shape (head):

  • :1024-1042 — the !active (park) edge now closes the episode through close_episode and returns Recovered; the advance edge does the same at :1016.
  • :1077 fn close_episode — single exit from a reported episode; take()s stall_started, takes stalled_phase, std::mem::replace(&mut self.reported, false), and returns Some only when the episode actually wrote a report (Some(stalled_for) if had_report). A silent threshold crossing still emits nothing.
  • :1096 fn take_advance — consumes the advance from one snapshot at the top of the poll (:1831-1836).
  • :2297 fn render_recovery — the line is still one bounded line.

Mechanism, not a widened sleep / ignored test — PASS:

  • No #[ignore] added anywhere in the diff.
  • Budgets unchanged: both the pre-existing test and the new one use recv_timeout(Duration::from_secs(5)) (:6407 original, :6551 new); no sleep was lengthened, no assertion relaxed. The seam test's own comment states the budget is deliberately not widened, which matches the code.

One-shot contract intact — PASS:

  • if self.reported { return MonitorAction::None } is unchanged (one-shot per episode, :1044-1047).
  • stall_watchdog::tests::blocked_stage_writes_one_complete_dump still asserts "a continuous stall must not write a second dump" (recv_timeout(400ms).is_err()) and passes on the fixed tree. monitor_is_one_shot_per_stall (:4623) also passes.
  • close_episode makes each episode emit at most one line (stall_started is taken once; reported is cleared).

Observability-only — PASS:

  • The diff touches no routing, no app state, no phase transition, no threshold. wait_poll gained only doc lines (@@ -1220,6 +1310,12), no behaviour change.
  • Hot path: Shared::mark gains only a #[cfg(test)] block (:1183-1189); the production three stores plus fetch_add are byte-identical to main (:1173-1191). The monitor's own poll loop gains exactly one atomic load (moved earlier from :1869, so the load count per poll is unchanged).

3. The new tests fail on pre-fix code — PASS (proven on a scratch copy)

Method: git clone of the repo into scratch, checkout 89096818, then revert only the behavioural hunks (the park-edge close; and, separately, the wake take_advance) while keeping the #[cfg(test)] seam, the Recovered { phase } shape and the tests, so both tests compile and fail at runtime rather than failing to build.

Variant A — park-edge close reverted to pre-fix (my h3213-parkedge, own CARGO_TARGET_DIR):

cargo test -p bitty-terminal --bin bitty --offline stall_watchdog
test result: FAILED. 75 passed; 2 failed

---- stall_watchdog::tests::park_edge_delivers_the_recovery_the_report_owes ----
panicked at crates/bitty-terminal/src/stall_watchdog.rs:6499:9:
assertion `left == right` failed
  left: None
 right: Recovered { stalled_for: 20ms, phase: RuntimeTick }

---- stall_watchdog::tests::recovery_line_survives_a_preempted_phase_publish ----
panicked at crates/bitty-terminal/src/stall_watchdog.rs:6564:14:
recovery line: Timeout

The second failure is the CI symptom reproduced verbatim (recovery line: Timeout) on Linux.

Fixed tree (h3213 at the PR head, own target dir):

test result: ok. 77 passed; 0 failed; 0 ignored; 0 measured; finished in 1.36s

macOS original test on the fixed tree: stall_watchdog::tests::blocked_stage_writes_one_complete_dump →
test result: ok. 1 passed ... finished in 0.52s (wall 0.73 s), well inside its 5 s budget.
New seam test: finished in 0.40s (includes its own 300 ms publish gap, i.e. at least one poll landed inside the widened window).

4. Dead code / cfg hazards — PASS

  • set_publish_gap (:1206), the publish_gap_ms field (:1139), its initializer (:1159) and the use inside mark (:1183-1189) are all #[cfg(test)]; nothing new is reachable in production.
  • RUSTFLAGS=-D warnings cargo check -p bitty-terminal --tests --offline → Finished, no warnings.
  • RUSTFLAGS=-D warnings cargo check -p bitty-terminal --bin bitty --offline (non-test build, i.e. the seam must vanish) → Finished, no warnings.
  • cargo +1.85 check -p bitty-terminal --tests --offline → Finished (MSRV OK, no let-chains / if let guards introduced).
  • Windows leg equivalent: RUSTFLAGS=-D warnings cargo check -p bitty-terminal --tests --target x86_64-pc-windows-gnu --offline → Finished; re-ran after touch to force Checking bitty-terminal and it is clean (the only output is the pre-existing build-script note about the icon resource on a non-Windows host).
  • cargo clippy -p bitty-terminal --all-targets --offline -- -D warnings → Finished.
  • rustfmt --edition 2024 --check crates/bitty-terminal/src/stall_watchdog.rs → clean.
  • New items are all used on every target: RecoverySpan (fields read by render_recovery, :2297), stalled_phase (set at :1056,:1060; read at :1082), Phase::Unknown fallback is a plain enum variant, no platform gate.

5./6. (3212-specific checks — n/a for this PR)

7. Correctness risks the lane understates

(a) take_advance is not discriminated by any test — and it makes evaluate's progress branch unreachable from monitor_loop.
Variant B (revert only the wake take_advance block at :1831-1836, keep the park-edge fix) was run on a scratch copy:

test result: ok. 77 passed; 0 failed
warning: method `take_advance` is never used

So no test fails without it: the park-edge close is the load-bearing fix and take_advance is an unverified latency optimisation. Worse for maintenance: take_advance sets self.last_progress = progress from the same snapshot that evaluate is then called with, so the if progress != self.last_progress branch inside evaluate (:1014-1022) can never fire from monitor_loop — there are now two closure paths for one edge, and one of them is production-dead while still being exercised only by unit tests. Not a correctness bug (both paths go through close_episode, which is idempotent per episode), but the PR body presents both mechanisms as the fix when only one is proven necessary. Non-blocking: either test the wake path (e.g. a poll that spends its delivery budget before evaluate) or drop it and let evaluate stay the single edge.

(b) Rapid stall→idle→stall cycles: exactly one line each, no loss and no duplicate — probed, PASS.
I added my own test to the scratch clone (zz_review_rapid_stall_idle_cycles_emit_one_line_each, head tree): three enter → report → idle → recovery cycles with a 100 ms threshold. Result: ok, finished in 0.98s; exactly 3 reports + 3 recoveries, every recovery names phase=runtime-tick (not idle), and recv_timeout(600ms) sees no extra line. Note honestly that this probe also passes on the pre-fix variant — without the publish gap the advance edge wins the race on an idle host, which is exactly why #3211 was a loaded-runner-only failure. The interleaving itself is covered by the unit test park_edge_delivers_the_recovery_the_report_owes (third evaluate → None, i.e. no duplicate).

(c) Pre-existing, unchanged: the parked-repeat suppression branch (:1050-1057) sets self.reported = true without writing a report; a later close_episode can therefore emit a recovery line whose report was suppressed as a duplicate of the previous one. main had the same shape (self.reported = true; return None), so this PR neither introduces nor worsens it.

8. Style / contract — PASS

  • Commit subject [CTX-1866] fix(runtime): ... ✔ ([CTX-1866] present, conventional type).
  • PR body states the failing run, the refuted and the accepted candidates, the A/B evidence with both failure texts, and the gate list; A/B numbers match mine.
  • Close directive Closes #3211 ✔ (single issue, fix PR).
  • Labels fix,P1,area:stability,area:ci,area:testing present. Milestone is unset (none) on this PR; AGENTS.md issue hygiene asks for a milestone where applicable — noted, not a code blocker.

Residual risks (summary)

  1. take_advance (:1096, :1831) has no discriminating test; reverting it leaves 77/77 green, and it renders evaluate's advance branch unreachable from the monitor loop. Follow-up: test or remove.
  2. The PR body slightly overstates the fix as two mechanisms; only close_episode is proven necessary.
  3. macOS remains unverified locally by construction (the seam makes the scheduler window deterministic instead); the original 5 s-budget test is green here in 0.52 s and the mechanism is platform-independent, so the remote macOS leg is the only remaining witness.
  4. Milestone unset (process nit).

No blocking defect found: the cited root cause is real in the code, the fix is at the mechanism, the new tests fail on the pre-fix state with the exact CI text and pass on the head, the one-shot contract and the observability-only boundary are intact, and the cfg/test seam compiles out cleanly on Linux, on the Windows target, and under the 1.85 MSRV.

VERDICT: APPROVE

@Xuepoo
Xuepoo merged commit b614fea into main Nov 17, 2026
21 checks passed
@Xuepoo
Xuepoo deleted the ctx-1866/stall-recovery-witness branch November 17, 2026 07:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI area:stability Stability hardening area:testing fix Bug fix P1 Priority: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(runtime): macOS-only stall_watchdog recovery-line race reds the M1 matrix on main

1 participant