Skip to content

[CTX-1669] fix(runtime): arm a bounded wake when damage is retained and no deadline exists - #2853

Merged
Xuepoo merged 1 commit into
mainfrom
ctx-1669/fix-bounded-wake
Nov 2, 2026
Merged

Xuepoo merged 1 commit into
mainfrom
ctx-1669/fix-bounded-wake

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Symptom

After long uptime Bitty can go unresponsive with no CPU use and come back the moment the user clicks. The same shape is deterministic in CI: winit_window on Linux X11 (xvfb), run 41280906272, sat for 18 minutes in App::run and was cancelled by the job timeout.

Mechanism

TerminalApp::handle_event (PlatformEvent::AboutToWait) joins every deadline the app can arm into one array — hover, animation, bell/notification, overlay capture, kitty-local worker, coalesced present, plugin timers, parked command, shell-exit reap, selection autoscroll, surface retry, hidden-surface repair — and then:

match wake {
    Some(deadline) => ctx.set_wait_until(deadline),
    None => ctx.set_wait(),          // <-- parks until external input
}

A frame can still be owed when that array is empty. Two reachable examples:

  • reject_stale_atlas_frame drops the assembled frame, sets pending_full_redraw = true and arms no timer (the intended rebuild happens on the "next tick" — which, under plain Wait, never comes).
  • A plugin scene revision can advance after the tick already presented (deliver_runtime_events / pump_cold_commands run after drive_tick), leaving the attached scene newer than the frame on screen with nothing armed.

The embedder then hands itself ControlFlow::Wait with retained damage: CPU-idle and frozen until unrelated input arrives — exactly the field report, and exactly the lost-redraw CI shape where the redraw request never comes back.

Fix

Runtime (crates/bitty-runtime/src/runtime/present.rs)

  • retained_present_work() is now the single definition of "damage is retained" (pending_paint_redraw / coalesced_pending / pending_full_redraw / per-origin generation mismatch). hidden_retained_work() is !surface_visible && retained_present_work(), so the occlusion gate and the new nudge cannot drift apart.
  • New pub fn present_owed(&self) -> bool = retained_present_work() || plugin_scene_owed(), with a deliberate false while hidden (the hidden_repair_deadline wake from [0.0.32] fix(runtime): built-in hang watchdog and long-run accumulation fixes (part of #2830) #2834 owns that case) and false immediately after a committed present (so an idle surface arms nothing and PB-7's zero-periodic-wakeup idle budget is preserved).

App (crates/bitty-terminal/src/terminal_app.rs)

  • PresentNudge — a bounded, self-clearing nudge. arm(now, owed, wake):
    • returns the existing wake untouched whenever any other deadline is armed (never suppressed, shortened, or moved into the past);
    • returns None when nothing is owed, so the arm still falls back to set_wait();
    • otherwise arms now + 50 ms, doubling to a 500 ms ceiling while the same frame stays owed;
    • never returns now — a past-due deadline would re-enter AboutToWait immediately and spin a loop with nothing new to present; an unrepresentable deadline fails closed to Wait.
  • Wired into the AboutToWait arm after the tick and the cold pump, so it observes post-present state (self.present_owed()).

No timeout was widened and no counter was repurposed: the nudge only guarantees another loop turn, so presented_frames / present_stale_ms / trigger=no-present still name a genuinely stuck present instead of being masked. First attempt lands in 50 ms (≈3 frames at 60 Hz) and the worst case is 2 Hz, not the 0 ms spin the previous parked-command fix had to remove.

Tests

New regression coverage:

  • bitty-runtime atlas_epoch_guard_tests::a_rejected_frame_owes_a_present_and_arms_no_deadline — builds the real "damage retained, deadline array empty" state through reject_stale_atlas_frame and asserts present_owed() plus present_coalescing_deadline() == None, hidden_repair_deadline() == None, surface_retry_deadline() == None. This is the state that used to park the loop.
  • bitty-runtime present_owed_tests — idle surface owes nothing after its present (PB-7 guard), new output owes before it is consumed and clears with the present, hidden work belongs to the repair wake not the nudge.
  • bitty-terminal about_to_wait_arms_a_bounded_present_nudge_when_a_frame_is_owed — drives the real AppHandler::handle_event(AboutToWait) against the recording EventContext with a frame owed and asserts the loop-control operation is a bounded WaitUntil, never Wait.
  • bitty-terminal about_to_wait_returns_to_wait_once_the_present_drains and present_nudge_is_bounded_and_resets — self-clearing half, non-zero first attempt, monotone backoff to the cap, reset after draining, existing deadline wins.

Red proof (wiring removed on purpose, everything else kept, same test binary):

running 2 tests
test tests::input_vm_boundary::present_nudge_is_bounded_and_resets ... ok
test tests::input_vm_boundary::about_to_wait_arms_a_bounded_present_nudge_when_a_frame_is_owed ... FAILED
thread '...about_to_wait_arms_a_bounded_present_nudge_when_a_frame_is_owed' panicked at crates/bitty-terminal/src/tests.rs:1172:9:
an owed frame must never be handed plain Wait: [Wait]
test result: FAILED. 1 passed; 1 failed

With the wiring restored:

$ cargo test -p bitty-terminal --bin bitty --features input-vm-test-support --offline -- present_nudge
running 2 tests
test tests::input_vm_boundary::present_nudge_is_bounded_and_resets ... ok
test tests::input_vm_boundary::about_to_wait_arms_a_bounded_present_nudge_when_a_frame_is_owed ... ok
test result: ok. 2 passed; 0 failed

Full runs on this branch:

$ cargo test -p bitty-runtime --lib --offline
test result: ok. 1415 passed; 0 failed; 0 ignored

$ cargo test -p bitty-terminal --bin bitty --offline
test result: ok. 1360 passed; 0 failed; 0 ignored

$ cargo test -p bitty-terminal --bin bitty --features input-vm-test-support --offline -- input_vm_boundary
test result: ok. 24 passed; 0 failed; 0 ignored

$ cargo test -p bitty-platform --test headless_run --test winit_window --offline
ok: headless environment reported owned error: ... neither WAYLAND_DISPLAY nor WAYLAND_SOCKET nor DISPLAY is set.
ok: headless owned checks passed (dpi, extent, config)
ok: winit_window integration done

(That last one took the DisplayUnavailable branch — this host has no display server, so the live-window path is not exercised here; the bounded harness itself landed in #2843.)

Gates:

$ cargo fmt --all -- --check                     # clean
$ cargo clippy --workspace --all-targets --locked --offline -- -D warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s)
    exit=0
$ cargo +1.85 check -p bitty-runtime  --offline
    Finished `dev` profile [unoptimized + debuginfo] target(s)
$ cargo +1.85 check -p bitty-terminal --offline
    Finished `dev` profile [unoptimized + debuginfo] target(s)

No Cargo.toml/Cargo.lock edge changed (no new dependency).

What stays open on #2830

This closes the lost-wakeup mechanism for the product path, not the whole issue:

  • The original long-uptime freeze was never reproduced (55-minute campaign in the owner comment, opencode-shaped stream plus a real opencode pane). This is a coverage fix that makes the class unrecoverable-by-parking, not a proven root cause for every field report.
  • Soak: [0.0.32] fix(runtime): built-in hang watchdog and long-run accumulation fixes (part of #2830) #2834 already added the bounded CI soak (opencode_soak, ~2 min on unoptimized runners, 240 s guard) and the daemon longrun_hang event-ring assertions. A genuine long-duration campaign (hours) is still not automated — this PR does not add one, so that acceptance bullet remains open.
  • The winit_window test-side bound (retry the redraw, re-arm a 50 ms wake, fail in 20 s) is fix(test): bound the winit window lifecycle test instead of hanging CI #2843, already merged; this PR is the product-side safety net that comment asked for.

Per the above, this uses Refs #2830.

Refs #2830

Summary by CodeRabbit

  • Bug Fixes
    • Pending visual updates are now checked again automatically when no other scheduled event will prompt a redraw, helping ensure changes appear on screen.
    • These checks become less frequent over time if an update remains pending, and existing scheduled events retain priority.
    • When the display is up to date, the app avoids scheduling unnecessary checks.

…nd no deadline exists

AboutToWait joins the app deadline array (hover/animation/bell/capture/
kitty/coalesced/timers/parked/shell-exit/selection/surface-retry/hidden
repair) and answers set_wait() when all of them are None. A frame can
still be owed at that point - a rejected stale-atlas frame keeps
pending_full_redraw and arms no timer, and a plugin scene revision can
advance after the tick presented - so the loop parked in ControlFlow::Wait
with nothing to wake it. That is the reported 'unresponsive until I click'
and the deterministic CI hang where a lost redraw left the arm empty.

Runtime: present_owed() is the single retained-damage predicate (shared
with hidden_retained_work) plus the plugin scene revision, false right
after a committed present and always false while hidden (the occlusion
gate's repair wake owns that).

App: PresentNudge arms now + 50 ms when a frame is owed and no other
deadline is armed, doubling to a 500 ms ceiling, never overriding or
shortening an existing deadline, and clearing the instant the present
drains. No watchdog timeout was widened; a stuck present still reaches
the no-present detector.

Refs #2830
@Xuepoo Xuepoo added this to the v0.0.32 milestone Nov 2, 2026
@Xuepoo Xuepoo added fix Bug fix P0 Priority: highest area:runtime Area: runtime orchestration labels Nov 2, 2026
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
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: 1e295cbb-f890-4f2f-bf46-a07d013f98ae
Commits

Reviewing files that changed from the base of the PR and between bd410d0 and 601a8b4.

Files selected for processing: 3
  • crates/bitty-runtime/src/runtime/present.rs
  • crates/bitty-terminal/src/terminal_app.rs
  • crates/bitty-terminal/src/tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

The runtime now reports whether a visible surface has pending presentation work. TerminalApp uses a bounded wake nudge when work is owed and no other deadline exists. Existing deadlines are preserved. Tests cover owed-work detection and wake scheduling.

Changes: Presentation wake scheduling

Layer / File(s) Summary
Detect owed presentation work
crates/bitty-runtime/src/runtime/present.rs
The runtime centralizes retained-work checks and adds present_owed for visible surfaces. Tests cover retained redraw work, idle frames, new output, and hidden-surface repair behavior.
Schedule terminal wake nudges
crates/bitty-terminal/src/terminal_app.rs, crates/bitty-terminal/src/tests.rs
TerminalApp combines the runtime’s owed-work status with existing deadlines. When work is owed without another deadline, it schedules a checked wake with a 50 ms initial delay and a 500 ms cap. Tests cover backoff, reset, and deadline preservation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant EventLoop
  participant TerminalApp
  participant Runtime
  EventLoop->>TerminalApp: AboutToWait
  TerminalApp->>Runtime: Query present_owed
  Runtime-->>TerminalApp: Return owed status
  TerminalApp->>EventLoop: Set WaitUntil deadline
Loading

Possibly related issues

Merge Risk: Minimal · up to 601a8

This change adds a bounded wake so a frame left owed with no other deadline is retried instead of waiting for external input. No concrete merge-blocking defect remains. The author notes the original long-uptime freeze was not reproduced and a long soak test is still open.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the fix and its trigger: a bounded wake is armed when presentation damage is retained and no deadline exists. The changeset adds a PresentNudge that schedules a 50 ms to 500 ms bounded…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the fix and its trigger: a bounded wake is armed when presentation damage is retained and no deadline exists. The changeset adds a PresentNudge that schedules a 50 ms to 500 ms bounded wake in AboutToWait when a frame is owed and no other deadline is armed, and adds present_owed() in the runtime. The title matches the main change. The ticket prefix and the conventional commit prefix are present and do not affect the assessment.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 7 functions across 2 files. (1 skipped: 1 too large.)

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • 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 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 verification (bitty-guard-cron tick, independent of the implementer)

Verified on head 601a8b4877cc0632ad1a94353bd9d0f015329cfe.

Scope matches the remaining in-scope item of bitty#2830 (PR #2834 already landed
instrumentation + soak + self-heal; the owner's issue comment pinned the
lost-redraw-with-empty-deadline-array mechanism):

  • Runtime::retained_present_work() becomes the single "damage retained"
    definition; hidden_retained_work() now delegates to it instead of duplicating
    the predicate, so the occlusion gate and the new nudge cannot drift apart.
  • New Runtime::present_owed() is false while hidden (the repair wake owns that
    state) and false after a committed present, so an idle surface still arms
    nothing — the PB-7 zero-periodic-wakeup posture is preserved by construction,
    and there are two dedicated tests pinning it (an_idle_surface_owes_nothing_after_its_present,
    a_hidden_surface_is_covered_by_the_repair_wake_not_the_nudge).
  • PresentNudge::arm never overrides an existing deadline and never returns
    now; it doubles 50 ms -> 500 ms and clears when the present drains, so a stuck
    frame self-heals at 2 Hz instead of spinning or parking. Unrepresentable
    now + delay fails closed to plain Wait.
  • The AboutToWait arm is the only production wiring point, and the wiring test
    asserts on recorded loop-control operations (no Wait when a frame is owed, a
    future and bounded deadline when it is).

Test honesty spot-check: the runtime test builds the state through the real
reject_stale_atlas_frame path rather than a synthetic flag, and the child
reported the red proof (removing only the wiring fails
an owed frame must never be handed plain Wait).

CI on this exact SHA: 18/18 required checks pass — Quality gates (1)/(2), MSRV
1.85, Linux X11 (xvfb), Linux Wayland, both compat matrices, macOS ARM64, Windows,
Supply chain, CodeQL, CodeRabbit, extension pin drift, VM tier (PR), M1 and Compat
release aggregates. VM tier (main) / VM tier (nightly ARM64) are the usual
conditional skips. Note the X11 leg finished in 15m50s, i.e. the job that used to
hang for 18 minutes to the job timeout now completes.

Not a blocker but recorded: Refs #2830 is correct — the long-duration soak
campaign acceptance bullet stays open, and the original field freeze was never
reproduced, so this closes the lost-wakeup class rather than claiming a root
cause.

Merge decision: green required checks + this verification; merging as a P0 runtime
fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:runtime Area: runtime orchestration fix Bug fix P0 Priority: highest

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant