Repository navigation
[CTX-1711] fix(render): move Wayland swapchain acquire/present off the event-loop thread - #2907
Conversation
…r so the UI never waits on the compositor
…t ack-timing races
…it generations, wakeups and deadlines
…r a lost-ack frame
|
Warning Review limit reachedYou'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. View limit details
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. |
Xuepoo
left a comment
There was a problem hiding this comment.
Independent review — PR #2907
[CTX-1711] fix(render): move Wayland swapchain acquire/present off the event-loop thread
- Head reviewed:
e671d734338551d8d162bad4b1b4f5dbcc055245(based337031d, 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-threadwas 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 onlypresent_draw_list_colorcall site (crates/bitty-runtime/src/runtime/present.rs:7890) sits in theelsebranch afterif let Some(presenter) = self.presenter.as_mut()returns at:7866.GpuSurfaceBackend::present(crates/bitty-render/src/present.rs:187-206) is the sole caller ofpresent_draw_list_color_classified. - No lock is held across a driver call.
worker_loop(present.rs:677-698) takesslotonly for the predicate check pluscv.wait(which releases it), and never holdsacks/wakewhile a frame is being presented (push_ackat:549-566clones the waker out, drops the guard, then calls it). - Therefore
Presenter::submit(:1073-1101),drain_acks(:1107-1118),configure/resize(:1047-1066) andpause/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 onexit_cvwith a deadline, and only callsjoin()after the exit marker;Drop(:1208-1217) never joins.worker_main(:666-674) drops the backend beforemark_exited, both wrapped incatch_unwind, so a panicking surface destructor cannot postpone the exit signal (testa_panicking_backend_destructor_still_signals_exit). - Missed-wakeup safety:
stop/pausedare stored while holdingslot(:644-655) and consumers re-check under the same mutex, so no wake can be lost between the check andcv.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
Presentedack (apply_present_ackruntime/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 setpending_full_redraw = true; a dropped presented ack is only possible whenpending_presentwas already cleared (hide / resize / recovery), and each of those paths arms a full redraw of its own (present.rs:2348-2390retains it throughretained,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 tofullpastPRESENT_MAX_CARRIED_DAMAGE_RECTS = 16and absorbs contained rects; proven bydamage_union_collapses_to_full_past_the_cap. - Generation commit is precise:
PendingPresentcapturesprimary_generation/pane_generations/scene_revisionat collection time (:3687-3702,:7849-7852) andcommit_presentadvances exactly those, not the live values (:7469-7484), so output that arrived during the flight stays owed. Tested bypane_output_during_the_flight_is_not_marked_presentedandcommit_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_ackreturns early unlesspending.token == ack.token()(:7405-7411), andpending_presentis always the newest submission. StalePresentedand staleOutdatedacks are both asserted inert bya_stale_ack_cannot_commit_a_newer_pending_frame_or_arm_retry(:13235-13301), including thatsurface_retry_deadline()staysNone. commitonly onPresented:PresentOutcome::Presentedis the only arm reachingcommit_present(:7412-7421);Outdated/Lost/Timeout/Other/ErrorandPRESENT_NON_FRAME_TOKENnever commit.- #2570 chain preserved:
retry_attemptfires only aftersubmitreturned a token (:7836-7838);retry_armedonly fromfail_async_present(:7445-7446), i.e. after a real driver failure;retry_recoveredonly viaclear_surface_retryfromcommit_present(:7193-7198,:7466).a_successful_async_submission_does_not_double_the_retry_backoffcovers 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 freshWorkerSharedand a new generation, so a late return cannot touch the live worker's mailbox, gauges or ack ring (presenter_begin/presenter_endCAS on the packed generation,telemetry.rs:219-266). - Two separate budgets:
PRESENT_RECOVERY_LIMIT = 3(abandoned threads) andPRESENT_CREATION_FAILURE_LIMIT = 5(refused surfaces), so a failed factory does not consume the thread budget (recover: factory runs beforeabandon_worker).abandonedis pruned to live weak refs, so the vector is bounded by at most 3 live entries.creation_failures_do_not_charge_the_abandoned_worker_budgetandcreation_failure_budget_stops_surface_attemptsprove both. - "One stale frame presented on unblock" is handled:
abandoned_alive()is polled atPRESENT_ABANDONED_CHECK(1 s), and the >0 → 0 transition arms one corrective full repaint (:7239-7258), consumed by the next successful submit (:7846). Testan_abandoned_worker_exit_forces_a_correcting_frame. - Honest documentation of the leak: module docs
present.rs:27-30and:1174-1198state 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_surfaceon 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
cfggate:SurfaceTarget::display_server()(crates/bitty-platform/src/surface.rs:266-291) maps the raw handle toWayland | X11 | Other | Unknown, and the single call site isterminal_app.rs:4499. Non-Wayland, headless and pre-attach runs never construct aPresenter. - The synchronous path is untouched:
attach_gpustill 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), andresize/set_window_opacitykeep theirself.gpuarms (runtime/resize.rs:518-526,live_config.rs:385-392). - Platform gating of the new test is correct:
classify_display_servermatchesRawDisplayHandlevariants (available unconditionally inraw-window-handle = 0.6.2), whiledisplay_server_classifies_every_protocol_familyis#[cfg(unix)]because it constructsWaylandDisplayHandle/XlibDisplayHandlefrom 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) andPresentNudge::deadlineclamps 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()andsurface_extent()both read the same headless mirror, soplan == extentcannot fail unlesspresent_plan_extentitself regresses. The strong assertion — the extent of theDrawListactually handed to the worker — is not made (the fake only recordsgeneration/damage).- Two assertions in the same test read process-global telemetry (
bitty_render::telemetry::snapshot().resize, andpresenter_stuck_presents >= 1instuck_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_unionbuilds partial carries viaframe()(tests.rs:284), a shape production never produces and the production backend explicitly rejects — a valid unit test ofDamageCarry, 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:
- "the only configure on the UI thread is the initial one before ownership transfer" — false.
Presenter::spawn_gpu's recovery factory callscreate_surfaceandconfigure_with_opacityon the event-loop thread (present.rs:892-899), andrecover()runs it synchronously; the code's own doc at:872-875admits this. The Design paragraph should say "initial configure + recovery surface creation". - 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 isrecovery_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. - "
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, sohas_gpu()stays true); it becomes headless only once that worker is also inactive, which is what triggers the reattach path. The body also omitsPRESENT_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 nestedif let (Some(presenter), Some(extent)) = (...)atlive_config.rs:376is a single tuple pattern. - No const-eval-only
dead_codepattern: noconst _: ()assertions were added, and every newPRESENT_*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→Finishedwith no diagnostics.
Findings
-
Medium — a frame queued at the old extent can be presented into the reconfigured surface.
Presenter::resizeonly queues aConfigure(present.rs:1053-1066) andreflow_to_griddropspending_presentbut 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 aDrawListlaid 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 becausereflow_to_gridarmspending_full_redraw(resize.rs:528). Suggested fix: havequeue_configurewithrecord_resizedropslot.frame(the caller already re-arms a full redraw), or have the worker skip a taken frame whosedraw_list.plan.extentdiffers from the configured extent. -
Low — the recovery factory creates and configures a surface on the event-loop thread.
present.rs:892-899runs insiderecover(), whichpoll_presentercalls fromtick_atin 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). -
Low — the reattach path builds a whole
GpuContexton 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 inAboutToWait, 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". -
Low — the damage-carry union is unreachable in production and would be rejected if it were reached.
runtime/present.rs:7821always submitsDamageCarry::full(), andGpuSurfaceBackend::presentreturnsInvalidInputfor anything else (present.rs:190,:301-309). Somerge/add(:256-288) is exercised only by the fake backend, whosepresentaccepts 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. -
Nit —
set_window_opacityreports the mirror's alpha support on the unchanged-opacity early return.live_config.rs:374returnsself.surface.opacity_alpha_supported(), which for the async path is the headless mirror's unconditionaltrue(gpu.rs:1083), while the changed-opacity path correctly returnspresenter.alpha_supported()(:383). Only affects whether the "opacity unsupported" warning is emitted. -
Nit —
WorkerShared::stuckis write-only. Declared atpresent.rs:473, incremented at:1040, never read (the readable counter isPresenter::stuck_total+telemetry::presenter_stuck). Either publish or drop it. -
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 omittedPRESENT_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
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.rsaddsPresenter(UI handle) and a dedicatedbitty-presentworker. The worker owns aBox<dyn PresentBackend>; the productionGpuSurfaceBackendowns theSurfaceplusArc<GpuContext>and is the only code that callsget_current_texture/frame.present().submitnever waits. Replacing a queued frame mergesDamageCarry(up toPRESENT_MAX_CARRIED_DAMAGE_RECTS = 16; past that it collapses tofull = true). Every combined frame is already a full-surface composite, so replacement is lossless.VecDeque<PresentAck>(PRESENT_ACK_CAPACITY = 32, oldest dropped and counted). Outcomes are typed:Presented,Outdated,Lost,Timeout,Other,Error.generation << 32 | in_flight_since_ms; the watchdog seespresenter_in_flight,presenter_in_flight_since_ms,presenter_in_flight_ms,presenter_stuck_presents,presenter_recoveries,presenter_coalesced,presenter_acks_dropped.PRESENT_STUCK_BOUND(1500 ms) the runtime stops and drops the old handle (never joins), builds a freshSurface+ 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.presenter: Option<Presenter>pluspending_present; commit (generation, allocations, bands, scene report, retry clear) happens only on aPresentedack. Thesurfacebecomes a headless mirror for extent/opacity/theme queries; the only configure on the UI thread is the initial one before ownership transfer.shutdown_bounded(PRESENT_SHUTDOWN_BOUND)(250 ms) then detach;Runtime::shutdown_with_timeoutstops 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
arm_surface_retry->retry_armed->note_surface_present_failurechain.retry_attemptfires only after a successful submission,retry_recoveredonly on a committed ack; worker-sidepresent_ok/acquire classes come from the real driver call.present_plan_extentreads the mirrored extent;reflow_to_gridsends the configure message and rebuilds the mirror in the same step; the worker applies configure before the next acquire. Test assertsplan == surface extentandderive_scale == 1.0.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
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
drm_syncobj_timeline_wait_ioctl. Needs an owner-host check after merge.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.Summary by CodeRabbit
New Features
Bug Fixes
Diagnostics
Supersedes #2904, which GitHub closed when its head branch was renamed to
ctx-1711/fix-present-thread(naming convention). The branch is rebased ontoorigin/main(d337031d) and carries the same content plus the round-4 state-machine fixes; the independent review verdict on that content was APPROVE.