Skip to content

[CTX-1711] fix(render): move Wayland swapchain acquire/present off the event-loop thread - #2907

Merged
Xuepoo merged 5 commits into
mainfrom
ctx-1711/fix-present-thread
Nov 5, 2026
Merged

Xuepoo merged 5 commits into
mainfrom
ctx-1711/fix-present-thread

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Priority: P0 | Area: render | Labels: fix,P0,area:render,area:runtime | Milestone: v0.1.0 | RFC: none | Task: CTX-1711

Refs #2830. The thorough fix for the live freeze: the event-loop thread no longer waits on the compositor at all.

Root cause this removes

On the Wayland + NVIDIA explicit-sync path the swapchain acquire/present waits on a compositor-owned DRM timeline fence with no timeout. When the surface is not composited (workspace switched away, or a stalled compositor), that wait lasted 17.49 s and 13.09 s on the owner's live process, and input, PTY pumping, plugin timers and compositing all share the thread, so the whole UI froze. The visibility gate cannot help the first frame: it can only close after a blocked present returns.

Design

  • bitty-render/src/present.rs adds Presenter (UI handle) and a dedicated bitty-present worker. The worker owns a Box<dyn PresentBackend>; the production GpuSurfaceBackend owns the Surface plus Arc<GpuContext> and is the only code that calls get_current_texture/frame.present().
  • UI -> worker: one bounded frame slot plus a latest-wins configure request under one mutex/condvar. submit never waits. Replacing a queued frame merges DamageCarry (up to PRESENT_MAX_CARRIED_DAMAGE_RECTS = 16; past that it collapses to full = true). Every combined frame is already a full-surface composite, so replacement is lossless.
  • Worker -> UI: bounded VecDeque<PresentAck> (PRESENT_ACK_CAPACITY = 32, oldest dropped and counted). Outcomes are typed: Presented, Outdated, Lost, Timeout, Other, Error.
  • Pause/resume are atomics; the worker checks pause before every acquire and requeues a frame taken while paused. A recovery preserves a closed visibility gate.
  • Stuck detection: lock-free telemetry packs generation << 32 | in_flight_since_ms; the watchdog sees presenter_in_flight, presenter_in_flight_since_ms, presenter_in_flight_ms, presenter_stuck_presents, presenter_recoveries, presenter_coalesced, presenter_acks_dropped.
  • Recovery: past PRESENT_STUCK_BOUND (1500 ms) the runtime stops and drops the old handle (never joins), builds a fresh Surface + worker through a factory and swaps generations. The abandoned worker only sees its own shared state and exits when its driver call returns. PRESENT_RECOVERY_LIMIT (3) caps abandoned workers; then the UI stays responsive headless until a presented ack resets the budget.
  • Runtime: presenter: Option<Presenter> plus pending_present; commit (generation, allocations, bands, scene report, retry clear) happens only on a Presented ack. The surface becomes a headless mirror for extent/opacity/theme queries; the only configure on the UI thread is the initial one before ownership transfer.
  • Shutdown: shutdown_bounded(PRESENT_SHUTDOWN_BOUND) (250 ms) then detach; Runtime::shutdown_with_timeout stops the presenter first.

Scope

Async only when SurfaceTarget::display_server().is_wayland(). X11/XWayland, macOS, Windows and every headless/test surface keep the synchronous path unchanged.

Invariants

Tests

Render (12): submit_never_waits_for_a_blocked_present, replacing_a_queued_frame_carries_the_damage_union, damage_union_collapses_to_full_past_the_cap, pause_prevents_acquire_and_resume_presents_the_latest_frame, stuck_detection_recovers_the_worker_and_the_old_one_exits, shutdown_with_a_blocked_worker_is_bounded, acknowledgements_are_bounded_and_keep_the_newest_outcome, configure_is_applied_before_the_next_acquire, a_present_failure_is_acked_with_its_class, a_worker_that_exits_is_reported_inactive_and_can_be_recovered, recovery_keeps_a_closed_visibility_gate_paused, recovery_budget_stops_surface_creation.

Runtime (9): tick_returns_while_a_present_is_blocked_and_input_keeps_flowing (includes PTY parsing and a 4 s notification-banner expiry during the block), a_failed_ack_arms_the_2570_retry_and_retains_the_frame, stuck_present_recovers_the_presenter_and_keeps_ticks_fast, hide_pauses_the_worker_and_reveal_resumes_it, resize_is_a_worker_message_and_keeps_the_2898_invariant, shutdown_with_a_blocked_presenter_is_bounded, an_ack_wakes_only_its_own_frame_token, stale_ack_for_a_replaced_frame_does_not_roll_state_back, a_spent_recovery_budget_stops_new_surfaces_and_keeps_the_ui_responsive.

Gates

cargo fmt --all -- --check                                  clean
RUSTFLAGS="-D warnings" cargo clippy -p bitty-render -p bitty-runtime -p bitty-terminal --all-targets   clean
cargo test -p bitty-render                                  574 passed
cargo test -p bitty-runtime                                 3448 passed, 8 ignored
cargo test -p bitty-terminal --bin bitty                    1384 passed
RUSTDOCFLAGS="-D warnings" cargo doc ... --no-deps          clean
cargo check --target x86_64-pc-windows-gnu --all-targets    clean

One pre-existing flake appeared once (ctl::tests::wm_automation_surface_tracks_split_layout, IPC request-count timing); it passed in the prior/following full runs and 3 isolated runs. No presenter code is on that path.

Not covered / residual risk

  • No live Wayland/NVIDIA run yet; the design removes the UI-thread acquire instead of imposing a timeout on drm_syncobj_timeline_wait_ioctl. Needs an owner-host check after merge.
  • Real-GPU recovery (a second Surface/swapchain for the same window while the old worker is blocked) is compile-verified and fake-tested only. The abandoned worker may present one stale frame when it unblocks, then exits.
  • macOS/Windows/X11 keep the synchronous path; macOS was not built locally (target not installed), the new code is platform-neutral.
  • Canonical docs sync is a separate repository/task.

Summary by CodeRabbit

  • New Features

    • Wayland displays now use off-thread frame presentation; other display servers retain synchronous presentation.
    • Frames can be coalesced, with updates committed after presentation completes.
    • Added display-server identification and presentation status reporting.
  • Bug Fixes

    • Presentation failures and stalled workers can trigger bounded recovery while preserving redraws.
    • Visibility changes, resizing, and shutdown are coordinated with the presenter.
  • Diagnostics

    • Crash and stall reports now include presentation activity, recovery, coalescing, and dropped-acknowledgement details.

Supersedes #2904, which GitHub closed when its head branch was renamed to ctx-1711/fix-present-thread (naming convention). The branch is rebased onto origin/main (d337031d) and carries the same content plus the round-4 state-machine fixes; the independent review verdict on that content was APPROVE.

@Xuepoo Xuepoo added this to the v0.1.0 milestone Nov 5, 2026
@Xuepoo Xuepoo added fix Bug fix P0 Priority: highest area:render Area: rendering area:runtime Area: runtime orchestration labels Nov 5, 2026
@coderabbitai

coderabbitai Bot commented Nov 5, 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 29 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: 4753f756-b869-407d-81d1-7296c9f71ed2
Commits

Reviewing files that changed from the base of the PR and between d337031 and e671d73.

Files selected for processing: 14

  • crates/bitty-platform/src/lib.rs
  • crates/bitty-platform/src/surface.rs
  • crates/bitty-render/src/gpu.rs
  • crates/bitty-render/src/lib.rs
  • crates/bitty-render/src/present.rs
  • crates/bitty-render/src/present/tests.rs
  • crates/bitty-render/src/telemetry.rs
  • crates/bitty-runtime/src/runtime.rs
  • crates/bitty-runtime/src/runtime/live_config.rs
  • crates/bitty-runtime/src/runtime/present.rs
  • crates/bitty-runtime/src/runtime/resize.rs
  • crates/bitty-terminal/src/crash_report.rs
  • crates/bitty-terminal/src/stall_watchdog.rs
  • crates/bitty-terminal/src/terminal_app.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 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 — PR #2907

[CTX-1711] fix(render): move Wayland swapchain acquire/present off the event-loop thread

  • Head reviewed: e671d734338551d8d162bad4b1b4f5dbcc055245 (base d337031d, mergeable)
  • Method: full read of the 14 touched files at the head SHA in a throwaway worktree (.worktrees/review-2907), plus local gates (commands and results at the bottom). No live Wayland/NVIDIA host was available to this reviewer, so the live-freeze claim is assessed from the tree, not from a reproduction.
  • The lane's own worktree ctx-1711-present-thread was not touched.

1. Thread/lifecycle safety — PASS

The event-loop thread never reaches the compositor on the acquire/present path.

  • No get_current_texture / frame.present() outside the worker: the only present_draw_list_color call site (crates/bitty-runtime/src/runtime/present.rs:7890) sits in the else branch after if let Some(presenter) = self.presenter.as_mut() returns at :7866. GpuSurfaceBackend::present (crates/bitty-render/src/present.rs:187-206) is the sole caller of present_draw_list_color_classified.
  • No lock is held across a driver call. worker_loop (present.rs:677-698) takes slot only for the predicate check plus cv.wait (which releases it), and never holds acks/wake while a frame is being presented (push_ack at :549-566 clones the waker out, drops the guard, then calls it).
  • Therefore Presenter::submit (:1073-1101), drain_acks (:1107-1118), configure/resize (:1047-1066) and pause/resume (:1028-1036) block the UI thread only for the few instructions the worker holds those mutexes — never for a driver call.
  • Shutdown is bounded and never joins a blocked worker: shutdown_bounded (:1179-1192) signals stop, waits on exit_cv with a deadline, and only calls join() after the exit marker; Drop (:1208-1217) never joins. worker_main (:666-674) drops the backend before mark_exited, both wrapped in catch_unwind, so a panicking surface destructor cannot postpone the exit signal (test a_panicking_backend_destructor_still_signals_exit).
  • Missed-wakeup safety: stop/paused are stored while holding slot (:644-655) and consumers re-check under the same mutex, so no wake can be lost between the check and cv.wait.
  • The two real UI-thread driver calls are by design and bounded to the failure path — see findings 2 and 3. They are not acquire/present, so the central invariant holds.

2. Frame/damage correctness — PASS (one ordering defect, finding 1)

  • A frame is committed only on a Presented ack (apply_present_ack runtime/present.rs:7392-7432 → commit_present :7460-7530). Every non-commit exit restores the damage: fail_async_present (:7441-7452), the inactive-worker branch (:7298-7341), and the stuck branch (:7347-7381) all set pending_full_redraw = true; a dropped presented ack is only possible when pending_present was already cleared (hide / resize / recovery), and each of those paths arms a full redraw of its own (present.rs:2348-2390 retains it through retained, runtime/resize.rs:528).
  • Replacement cannot lose pixels: the runtime always submits DamageCarry::full() (runtime/present.rs:7821), a full composite, and the backend refuses anything else (require_full_damage, present.rs:301-309). The bounded union (merge/add, :256-288) collapses to full past PRESENT_MAX_CARRIED_DAMAGE_RECTS = 16 and absorbs contained rects; proven by damage_union_collapses_to_full_past_the_cap.
  • Generation commit is precise: PendingPresent captures primary_generation/pane_generations/scene_revision at collection time (:3687-3702, :7849-7852) and commit_present advances exactly those, not the live values (:7469-7484), so output that arrived during the flight stays owed. Tested by pane_output_during_the_flight_is_not_marked_presented and commit_advances_the_captured_scene_revision_not_the_live_one.
  • Defect: a frame queued at the old extent can be presented after the resize Configure — see finding 1. Bounded to one frame.

3. Ack ordering — PASS

  • Only the newest token may commit or arm the retry: apply_present_ack returns early unless pending.token == ack.token() (:7405-7411), and pending_present is always the newest submission. Stale Presented and stale Outdated acks are both asserted inert by a_stale_ack_cannot_commit_a_newer_pending_frame_or_arm_retry (:13235-13301), including that surface_retry_deadline() stays None.
  • commit only on Presented: PresentOutcome::Presented is the only arm reaching commit_present (:7412-7421); Outdated/Lost/Timeout/Other/Error and PRESENT_NON_FRAME_TOKEN never commit.
  • #2570 chain preserved: retry_attempt fires only after submit returned a token (:7836-7838); retry_armed only from fail_async_present (:7445-7446), i.e. after a real driver failure; retry_recovered only via clear_surface_retry from commit_present (:7193-7198, :7466). a_successful_async_submission_does_not_double_the_retry_backoff covers the "submit is not a failure" case.
  • Stuck recovery is decided after draining acks (:7223-7237), so a worker that finished just before the tick is not abandoned — a_queued_presented_ack_is_drained_before_the_stuck_decision.

4. Recovery path — PASS

  • Abandoned workers are never joined (recover :1134-1172, abandon_worker :1199-1205); each gets a fresh WorkerShared and a new generation, so a late return cannot touch the live worker's mailbox, gauges or ack ring (presenter_begin/presenter_end CAS on the packed generation, telemetry.rs:219-266).
  • Two separate budgets: PRESENT_RECOVERY_LIMIT = 3 (abandoned threads) and PRESENT_CREATION_FAILURE_LIMIT = 5 (refused surfaces), so a failed factory does not consume the thread budget (recover: factory runs before abandon_worker). abandoned is pruned to live weak refs, so the vector is bounded by at most 3 live entries. creation_failures_do_not_charge_the_abandoned_worker_budget and creation_failure_budget_stops_surface_attempts prove both.
  • "One stale frame presented on unblock" is handled: abandoned_alive() is polled at PRESENT_ABANDONED_CHECK (1 s), and the >0 → 0 transition arms one corrective full repaint (:7239-7258), consumed by the next successful submit (:7846). Test an_abandoned_worker_exit_forces_a_correcting_frame.
  • Honest documentation of the leak: module docs present.rs:27-30 and :1174-1198 state the worker is detached, not joined, and exits when its driver call returns. Accepted residual risk, correctly labelled.
  • Gaps: the reattach path performs a full GpuContext::initialize_for_surface on the loop thread and is missing from the "Not covered" list (finding 3); the PR-body wording about the recovery budget misdescribes the resulting state (check 7, item 3).

5. Scope discipline — PASS

  • Selection is a runtime classification, not a cfg gate: SurfaceTarget::display_server() (crates/bitty-platform/src/surface.rs:266-291) maps the raw handle to Wayland | X11 | Other | Unknown, and the single call site is terminal_app.rs:4499. Non-Wayland, headless and pre-attach runs never construct a Presenter.
  • The synchronous path is untouched: attach_gpu still takes the surface (runtime.rs:2746-2760), present_assembled_frame's non-presenter branch is byte-for-byte the old code (runtime/present.rs:7867-7948), and resize/set_window_opacity keep their self.gpu arms (runtime/resize.rs:518-526, live_config.rs:385-392).
  • Platform gating of the new test is correct: classify_display_server matches RawDisplayHandle variants (available unconditionally in raw-window-handle = 0.6.2), while display_server_classifies_every_protocol_family is #[cfg(unix)] because it constructs WaylandDisplayHandle/XlibDisplayHandle from the unix module.
  • Two behaviour changes do apply on every platform; both are equivalent or strictly defensive: Runtime::is_headless() is now !has_gpu() (runtime.rs:3496-3498, same truth table for the sync GPU / headless cases) and PresentNudge::deadline clamps a past instant (terminal_app.rs:139-150), which is a spin fix.

6. Test quality — PASS (two named weaknesses)

48 new tests (22 in bitty-render/src/present/tests.rs, 26 in runtime::present::async_present_tests), all runnable without a GPU/display server; all 48 pass locally. No tautological gate/self-check test found — every concurrency assertion is made against an independent artefact (a Gate counter, the fake backend's presented/built/alive counters, the calls log, or a distinct accessor such as last_presented_generation). Named weaknesses:

  • resize_is_a_worker_message_and_keeps_the_2898_invariant (runtime/present.rs:13092-13135) is partly circular: present_plan_extent() and surface_extent() both read the same headless mirror, so plan == extent cannot fail unless present_plan_extent itself regresses. The strong assertion — the extent of the DrawList actually handed to the worker — is not made (the fake only records generation/damage).
  • Two assertions in the same test read process-global telemetry (bitty_render::telemetry::snapshot().resize, and presenter_stuck_presents >= 1 in stuck_detection_recovers_the_worker_and_the_old_one_exits), while the suite runs in one process with parallel threads. Those lines can pass because a different test emitted the same counter, so they are non-specific rather than deterministic.
  • replacing_a_queued_frame_carries_the_damage_union builds partial carries via frame() (tests.rs:284), a shape production never produces and the production backend explicitly rejects — a valid unit test of DamageCarry, but not evidence about the shipping path (finding 4).

7. Claims vs reality — FAIL (documentation only)

Three statements in the PR body do not match the tree:

  1. "the only configure on the UI thread is the initial one before ownership transfer" — false. Presenter::spawn_gpu's recovery factory calls create_surface and configure_with_opacity on the event-loop thread (present.rs:892-899), and recover() runs it synchronously; the code's own doc at :872-875 admits this. The Design paragraph should say "initial configure + recovery surface creation".
  2. Test counts/names: the body lists 12 render tests and 9 runtime tests; the tree has 22 and 26. One listed name does not exist (recovery_budget_stops_surface_creation; the actual test is recovery_budget_stops_only_surface_creation_and_the_ack_resets_it). This is an undercount, not inflation — flagged only because the body is used as the review record.
  3. "PRESENT_RECOVERY_LIMIT (3) caps abandoned workers; then the UI stays responsive headless until a presented ack resets the budget" — the runtime is not headless in that state: the current worker keeps owning the surface and keeps receiving frames (is_active() is true, so has_gpu() stays true); it becomes headless only once that worker is also inactive, which is what triggers the reattach path. The body also omits PRESENT_CREATION_FAILURE_LIMIT = 5, a second budget that is implemented and tested.

Verified as claimed: the 17.49 s / 13.09 s freeze durations do have in-tree provenance (they are the watchdog fixtures at crates/bitty-runtime/src/hang_watchdog.rs:654, crates/bitty-terminal/src/stall_watchdog.rs:4384/4438/4469). The gate list is accurate for bitty-render/bitty-platform/bitty-runtime/MSRV (re-run locally, see below); the full per-crate test counts (574/3448/1384) were not re-run here, only the presenter modules.

8. MSRV 1.85 — PASS

  • No let-chains: grep -n "&& let " over every new file is empty; the nested if let (Some(presenter), Some(extent)) = (...) at live_config.rs:376 is a single tuple pattern.
  • No const-eval-only dead_code pattern: no const _: () assertions were added, and every new PRESENT_* constant is read from non-const code.
  • Verified by toolchain, not by inspection: cargo +1.85 check -p bitty-render -p bitty-platform -p bitty-runtime -p bitty-terminal --all-targets --offline → Finished with no diagnostics.

Findings

  1. Medium — a frame queued at the old extent can be presented into the reconfigured surface. Presenter::resize only queues a Configure (present.rs:1053-1066) and reflow_to_grid drops pending_present but not the frame already sitting in the presenter slot (runtime/resize.rs:510-517). The worker then takes frame and configure in the same iteration and applies the configure first (present.rs:697-725), so a DrawList laid out for extent A is painted into a surface configured for B: the newly exposed strip shows only the clear colour for one frame. This is new behaviour (the sync path cannot have a queued frame during a resize) and self-corrects on the next frame because reflow_to_grid arms pending_full_redraw (resize.rs:528). Suggested fix: have queue_configure with record_resize drop slot.frame (the caller already re-arms a full redraw), or have the worker skip a taken frame whose draw_list.plan.extent differs from the configured extent.

  2. Low — the recovery factory creates and configures a surface on the event-loop thread. present.rs:892-899 runs inside recover(), which poll_presenter calls from tick_at in both the inactive branch (runtime/present.rs:7313-7317) and the stuck branch (:7348-7355). It cannot hit the timeline wait, and the code documents it (present.rs:872-875), but the PR body's central Design sentence denies it (check 7, item 1). Either correct the sentence or move surface creation into the new worker (the worker could configure its own backend before its first acquire).

  3. Low — the reattach path builds a whole GpuContext on the event-loop thread and is not in the residual-risk list. terminal_app.rs:5104-5110 → try_attach_gpu → pollster::block_on(GpuContext::initialize_for_surface(..)) (:4500) runs in AboutToWait, rate-limited to one attempt per 5 s (PRESENT_REATTACH_RETRY). Adapter/device creation can take hundreds of ms, so the exhausted path can still produce a short UI stall — precisely the class this PR exists to eliminate. It only runs after three failed recoveries, so it does not gate merge; it does belong in "Not covered / residual risk".

  4. Low — the damage-carry union is unreachable in production and would be rejected if it were reached. runtime/present.rs:7821 always submits DamageCarry::full(), and GpuSurfaceBackend::present returns InvalidInput for anything else (present.rs:190, :301-309). So merge/add (:256-288) is exercised only by the fake backend, whose present accepts partial carries (tests.rs:224-253). The module doc's promise ("a future partial-frame path must merge rather than drop a superseded frame's damage", :209-216) is therefore not yet honoured by the only real backend — a partial path would fail closed with an error ack, not merge. Worth a one-line comment so the next author does not trust the union.

  5. Nit — set_window_opacity reports the mirror's alpha support on the unchanged-opacity early return. live_config.rs:374 returns self.surface.opacity_alpha_supported(), which for the async path is the headless mirror's unconditional true (gpu.rs:1083), while the changed-opacity path correctly returns presenter.alpha_supported() (:383). Only affects whether the "opacity unsupported" warning is emitted.

  6. Nit — WorkerShared::stuck is write-only. Declared at present.rs:473, incremented at :1040, never read (the readable counter is Presenter::stuck_total + telemetry::presenter_stuck). Either publish or drop it.

  7. Nit — PR-body facts to correct before this is used as the record: the render/runtime test counts (12/9 vs the real 22/26), the missing test name recovery_budget_stops_surface_creation, "the only configure on the UI thread", and the "stays responsive headless" description of the exhausted state (plus the omitted PRESENT_CREATION_FAILURE_LIMIT). See check 7.

Gates re-run by this reviewer

cargo test -p bitty-render --lib present::                       22 passed, 0 failed
cargo test -p bitty-runtime --lib async_present_tests            26 passed, 0 failed
cargo fmt --all -- --check                                       clean (exit 0)
RUSTFLAGS=-D warnings cargo clippy -p bitty-render -p bitty-platform -p bitty-runtime --all-targets
                                                                 clean
cargo +1.85 check -p bitty-render -p bitty-platform -p bitty-runtime -p bitty-terminal --all-targets
                                                                 clean

Not re-run by this reviewer: the full bitty-render/bitty-runtime/bitty-terminal suites (574/3448/1384), cargo doc, and the x86_64-pc-windows-gnu check. No live Wayland/NVIDIA run either — the design removes the UI-thread acquire rather than bounding the driver wait, so the owner-host check the body asks for is still the only evidence that the 17 s freeze is gone.

VERDICT: APPROVE

@Xuepoo
Xuepoo merged commit 1008890 into main Nov 5, 2026
20 checks passed
@Xuepoo
Xuepoo deleted the ctx-1711/fix-present-thread branch November 5, 2026 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:render Area: rendering 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