Repository navigation
Description
Area: engine/render Metal backend (metal_render_impl.cpp, metal_runtime.cpp, metal_buffer.cpp, metal_texture.cpp), engine/world frame loop, docs/design
Model: fable
Part of epic: #4997
Blocked by: #4999
Blocked by: #4947
Blocked by: #4993
Host: macos
Objective: million-entity-render
Scope
Goal: on Metal, the CPU builds the next frame while the GPU executes the one just submitted, so a frame costs about the longer of the two instead of their sum, and the game does not feel laggier for it.
Done means: a short design document under docs/design/ that states the mechanism chosen and the measurements behind it, the implementation, and every gate under "Acceptance criteria" passing. The design is this ticket's to make. Two mechanisms are known to be capable of meeting the contract below, and the document says which was built and why the other was not:
- Join late: submit without waiting, and wait for the previous frame only at the point where the next frame actually needs the GPU to be free.
- One frame in flight with completion callbacks: submit without waiting, track completion from the command buffer's completion handler, and admit the next submission when the previous one reports done.
Out of scope: OpenGL (#5001), the pick path itself (#4999), the offscreen pacer's overrun sleep (the offscreen pacer fix in the frame-accounting epic), resolving a pick at the event's own cursor (#5002), and any shader or pipeline-stage change.
Approach
Evidence that the cost is real:
MetalRenderDevice::presentcommits the frame's command buffer and then callswaitUntilCompleted()(engine/render/src/metal/metal_render_impl.cpp:420-451). The GPU does not start a frame until that commit, and the CPU does nothing until it finishes.- Measured: 68–74% of main-thread stack samples sit inside that wait at 64³ entities (Debug, Apple M4 Max;
docs/perf/native-cpu-sampling.md). - Measured: at the million control (Release, stage profiling off, 2026-09-20) the frame is 34.30 ms with a 22.4 ms GPU frame at 0° yaw and 44.60 ms with 30.4 ms at 45° (
docs/perf/million-controls.md). The epic umbrella carries the current reading, taken 2026-11-10 on a host that was not quiet: 33.4 ms of GPU in series with about 21 ms of CPU. - OpenGL already overlaps: it fences each frame and lets the CPU run ahead (the frame fence in the OpenGL backend's render implementation source, lines 59-70).
What the blocking present currently guarantees, and therefore what stops being true (all read from source):
completedSubmissionSerial()returns the current serial minus one (metal_render_impl.cpp:1116-1120). Every serial-gated readback ring depends on it.releaseDeferredMetalBuffers()frees orphaned buffers, clears the set of buffers encoded this frame, and rewinds the texture staging arena, all on the assumption that the GPU is idle (engine/render/src/metal/metal_runtime.cpp:401-434; its own comment names this).MetalBufferImpl::subDataRangeswrites shared memory in place when the buffer has not been encoded since the last wait (engine/render/src/metal/metal_buffer.cpp:88-91). With a frame still executing, that memory may be in use.getSubDataandmapRangeread shared memory directly (metal_buffer.cpp:139-165).- Clear-source buffers and image-atomic scratch buffers are replaced or released against the same "GPU is idle" assumption (
metal_render_impl.cpp:331-382,metal_runtime.cpp:540-591). - One GPU timestamp pair per stage is enough only because the frame has finished before the next one samples (
metal_render_impl.cpp:1177-1191, which also records a limit of about 40 sample buffers on Apple Silicon). - Frame accounting reads the command buffer's GPU times right after the wait (
recordCompletedFrameBuffer).
Places that drain the GPU mid-frame today and would silently reintroduce a wait:
- an unaligned partial buffer write (
metal_buffer.cpp:93-99); readDefaultFramebuffer, used by screenshots and video capture (metal_render_impl.cpp:524-527,engine/video/src/video_manager.cpp:541);- the composite-depth readback at the start of a camera rotation gesture (
engine/render/src/ir_render.cpp:135-155, called fromengine/render/src/render_manager.cpp:407); - the legacy stage-timing mode (
engine/prefabs/irreden/render/gpu_stage_timing_observer.hpp:63,90); - the hand-off to a child process (
engine/hand_off_process.cpp:24); - debug probes under
engine/prefabs/irreden/render/*_probe.hpp.
Each either stays a deliberate, counted drain or is removed; none may remain hidden.
Acceptance criteria
All perf readings: Apple M4 Max, Release, stage profiling off, ir-acquire benchmark with a quiet-host verdict, at least five interleaved base/head pairs from one binary (a WorldConfig field set from a config preset restores the blocking present for the base arm), judged by the rule in docs/design/gpu-stage-timing-cost-model.md § "State the noise bound".
- Frame time near the longer half: at the million control, at 0° and at 45° yaw, the steady mean frame time is at most 1.10 × the larger of the mean CPU time per frame and the mean GPU time per frame, both read from perf: per-frame input-to-present latency probe on both render backends #4998's probe in the same run. Validator: Perf run with
scripts/perf/repeat_profile.py; the PR table shows frame, CPU and GPU means for both arms. - Positive-fire: with overlap on, the probe shows one submitted frame still executing at the start of the next frame's CPU work on at least 90% of steady frames at the million control; with the switch off it shows none. Validator: the same reports.
- Bounded queue: the probe's maximum frames in flight is 1 in every run, including one where no drawable is available for several frames. Validator: the reports, plus a unit or headless device test for the no-drawable case.
- Latency: mean and p99
input_to_present_mswith overlap on do not exceed the serialized arm by more than the noise bound perf: per-frame input-to-present latency probe on both render backends #4998 committed, at the GPU-bound scene (the million control) and at the CPU-bound scene from perf: per-frame input-to-present latency probe on both render backends #4998's baseline. Validator: Perf run; base and head rows side by side. - Pick: every assertion render: pick and hover read the most recent completed frame through a gated record #4999 added passes with overlap on, including its fault control still failing. Validator: GUI behaviour,
python3 scripts/gui-verify.py IRShapeDebug -- --gui-test. - Pixels:
python3 scripts/render-verify.py --target IRShapeDebug,--target IRCanvasStressand--target IRPerfGridread maximum delta 0, and the nine-yawIRCanvasStresscapture set is RGB-identical to the parent commit. Validator: Render regression. - Lifetimes: headless Metal tests show that a CPU write to a buffer or texture still referenced by an executing frame does not change what that frame reads, and that no resource is released while a frame that uses it is executing. Validator: Unit tests on a Metal host.
- No hidden drain: a run of the million control reports zero mid-frame GPU drains outside the ones the design document lists as deliberate. Validator: a counter in the profile report.
- Capture and determinism:
--auto-recordand--auto-screenshotproduce the same frames and tick numbering as the parent commit (criterion 6 covers screenshots; one--auto-recordclip compared frame by frame), and unattended offscreen runs still exit clean. Validator: Render regression and one recorded pair.
Reported, not a gate:
- The age of the pick record at dispatch, and the stale-cursor count. Age is the time from the cursor sample the record's frame was rendered with to the input poll that dispatches it, in milliseconds, mean and p99. Both are reported with overlap on and off, at the GPU-bound and the CPU-bound scene, in the PR and in the design document. Under overlap the newest finished frame is one frame older relative to the input poll, so the age is expected to rise, and the stale-cursor count with it. This ticket states the rise; it does not have to prevent it. render: resolve a pick at the input event's cursor against the presented frame #5002 is what removes the dependence on that age, by resolving the pick at the event's own cursor. Validator: the profile report (the stale-cursor row is render: pick and hover read the most recent completed frame through a gated record #4999's; the age row is added here from perf: per-frame input-to-present latency probe on both render backends #4998's per-frame cursor-sample and poll times).
Dependencies
- render: pick and hover read the most recent completed frame through a gated record #4999: picks must already travel through the completion-gated record, or the first overlapped frame reads an executing frame's hover buffer.
- perf: per-frame input-to-present latency probe on both render backends #4998 (through render: pick and hover read the most recent completed frame through a gated record #4999): the probe and the committed baseline.
- render: resolve a pick at the input event's cursor against the presented frame #5002 does not block this ticket and is not blocked by it.
- The offscreen pacer fix in the frame-accounting epic: until it lands, every offscreen frame longer than one refresh interval carries an extra interval of sleep, which hides the gain in criterion 1.
- The Metal partial-write ticket in the render-thread epic: it removes the mid-frame GPU wait a buffer's size can trigger, which this ticket must not inherit, and it changes how
MetalBufferImpl::subDataRangesencodes a partial write. This ticket owns the rule for which buffer memory an executing frame may still read; that one owns the encoding.
Gotchas
Epic contract (the umbrella's four points, carried by every ticket in this epic):
- Bounded queue. At most one submitted frame is still executing on the GPU while the CPU builds the next. The bound is explicit; it is never left to drawable starvation.
- Latency does not rise. Input-to-present latency is measured per frame: present time (GPU completion when offscreen) minus the time input was sampled for that frame. With overlap on, it does not exceed the serialized baseline beyond the stated noise bound, in a GPU-bound fixture and in a CPU-bound one. The known trap: when the GPU is the longer half, a CPU frame that starts the moment the previous one was submitted samples input early and then waits for the GPU, which adds up to (GPU time minus CPU time) of lag. The CPU frame starts just in time for the GPU to come free, so input is sampled as late as possible.
- Picks refer to the presented frame. A pick or hover resolves against the ID data of the newest frame that finished and was presented, never one still executing, and never blocks the frame to get one. It tolerates the picked entity having been destroyed since. The data is for the cursor position that frame was rendered with; when the event's cursor has moved off it, the pick is counted and reported as stale, not silently attributed. Resolving at the event's own cursor position is render: resolve a pick at the input event's cursor against the presented frame #5002.
- Unchanged. How fixed updates consume input,
--auto-recorddeterminism, and the offscreen harness's behaviour.
Specific to this ticket:
- Completion handlers run on a Metal-owned thread. The engine's render state is main-thread only.
RenderDevice::finish()keeps its meaning: when it returns, everything submitted so far has completed.- The fixed-update loop decides how many updates a frame runs from elapsed time; a shorter frame changes that count. Report updates per rendered frame for both arms.
- Per-stage GPU timing must stay valid or report itself invalid; it must not read a pair the GPU has not written.
- The backend-neutral interface should not need to change. If the design changes it, the OpenGL implementation moves in the same PR.
References
docs/perf/native-cpu-sampling.md,docs/perf/million-controls.md,docs/perf/gpu-frame-accounting.mddocs/perf/surface-lighting-controls/README.md(29.2% of main-thread samples waiting for Metal completion, 53.3% in offscreen pacing, in an eight-canvas fixture)engine/render/CLAUDE.md§ "GPU resource contracts" and the readback ruledocs/perf/static-upload-saturation.md(why untouched bytes of an orphaned buffer are copied on the GPU timeline)
Activity
jakildev commentedon Nov 11, 2026
Plan: render/metal: present without blocking the CPU on the GPU, with no added input latency
## Plancomment carries the full epic planVerified current state
engine/render/src/metal/metal_render_impl.cpp):present()commits one command buffer per frame and waits for it;finish()does the same mid-frame;completedSubmissionSerial()is the current serial minus one; one timestamp pair per stage is kept in flight.engine/render/src/metal/metal_runtime.cpp): deferred buffer releases, the encoded-buffer set and the texture staging arena are all reset after the wait, on the stated assumption that nothing is executing.engine/render/src/metal/metal_buffer.cpp): a write to a buffer not encoded since the last wait goes straight into shared memory; an unaligned partial write to an encoded buffer callsfinish().readDefaultFramebuffer, the composite-depth readback at rotation-gesture start (engine/render/src/ir_render.cpp), legacy stage timing (gpu_stage_timing_observer.hpp), the child-process hand-off (engine/hand_off_process.cpp) and debug probes. I searchedengine/forfinish(),getSubData,getSubImage2DandreadDefaultFramebuffer; production per-frame readbacks (cull statistics, overflow counters, sun record demand) already go through serial-gated rings.docs/perf/native-cpu-sampling.md): 68–74% of main-thread samples are in the completion wait at 64³ entities, Debug.docs/perf/million-controls.md, 2026-09-20): Release, stage profiling off, 34.30 ms frame with a 22.4 ms GPU frame at 0°; 44.60 ms with 30.4 ms at 45°.Scope
In: the design document, the non-blocking present, resource lifetime across an executing frame, the just-in-time start of the CPU frame that the latency rule requires, a switch that restores the blocking present, the gates, and one reported reading (pick-record age and stale-cursor count). Out: OpenGL, the pick path, the pacer's overrun sleep, shader and stage changes.
Decisions
Locked by this plan:
WorldConfigfield set from a config preset, not an environment variable, so base and head arms come from one binary, a harness run records the arm in its manifest, and a regression can be bisected in the field. Its name is the implementer's call. Rejected: a compile-time switch (the arms would differ in more than the present).finish()keeps its contract and every remaining mid-frame drain is listed in the design document and counted in the report. Rejected: leaving drains unlisted because they are rare.Affected files
docs/design/— the new design document.engine/render/src/metal/metal_render_impl.cpp—beginFrame(),present(),finish(),completedSubmissionSerial(),recordCompletedFrameBuffer, the timestamp-pair functions,ensureClearSourceBuffer.engine/render/src/metal/metal_runtime.cpp,engine/render/include/irreden/render/metal/metal_runtime.hpp— deferred releases, the encoded-buffer set, the staging arena, image-atomic scratch lifetime.engine/render/src/metal/metal_buffer.cpp— which writes may land in place.engine/render/src/metal/metal_texture.cpp— upload and clear paths that assume a drained GPU.engine/world/src/world.cpp,engine/world/include/irreden/world/config.hpp— where the frame's CPU work starts relative to GPU completion, if the design puts the delay there; the blocking-present field; the drain counter and the pick-age row in the report.test/render/— headless Metal lifetime tests.Acceptance criteria
input_to_present_mswithin perf: per-frame input-to-present latency probe on both render backends #4998's noise bound of the serialized arm, at the GPU-bound and the CPU-bound scene.render-verifymaximum delta 0 forIRShapeDebug,IRCanvasStress,IRPerfGrid; nine-yawIRCanvasStressset RGB-identical.--auto-recordand--auto-screenshotoutput and tick numbering unchanged; offscreen runs exit clean.Gotchas
Verification
fleet-build --target IrredenEngineTestthenfleet-run IrredenEngineTest --gtest_filter='Metal*'ir-acquire benchmark -- python3 scripts/perf/million_controls.pyandscripts/perf/repeat_profile.pyfor the interleaved pairs at both scenespython3 scripts/gui-verify.py IRShapeDebug -- --gui-testpython3 scripts/render-verify.py --target IRShapeDebug,--target IRCanvasStress,--target IRPerfGridfleet-run IRCanvasStress --frozen-pose 0.47 --sweep-yaw 0 6.2831853 9 --auto-screenshot 6on this commit and its parent, compared pair by pair withpython3 scripts/render-compare.py--auto-recordclip on this commit and its parentApproach sketch (optional)
Start with the lifetime inventory in "Verified current state": each item either becomes owned by the frame that used it or gains a rule for when it is safe. Measure where the CPU frame should start before choosing the mechanism: the probe gives CPU and GPU time per frame, and the latency rule fixes the target (input sampled about one CPU frame before the GPU comes free).
jakildev commentedon Nov 17, 2026
Plan corrections
A1 — 2026-11-17 — trigger: PR #5105 merged (#4998,
dce4de5b9)docs/perf/input-latency/README.md§ Scenes. Use those commands as written. "perf: per-frame input-to-present latency probe on both render backends #4998's noise bound" is that file's § Noise bound table. Theinput_to_present_msmean spreads are 0.118 ms (million) and 0.140 ms (CPU-bound). The p99 spreads are 0.361 ms and 2.119 ms.MetalRenderDevice::present()callsm_frameCompletions.submitted(...)beforecommit()andreportFrameEnd(m_frameCompletions, commandBuffer)right afterwaitUntilCompleted(). Both calls join the lifetime inventory.FrameCompletionQueueis not synchronized. Itsfinished()closes the oldest in-flight submission ("Submissions finish in order").World::takeFrameCompletions()drains the queue on the main thread afterpresentFrame().Frames in flight at frame start: max=<n>. Each per-frame record already keepsframesInFlight_. Add a row that counts the steady frames that started with at least one frame in flight, so the ≥ 90 % reading exists. Criterion 3 reads the existing max row.million_controls.pyandrepeat_profile.pybare.repeat_profile.pylaunches each run throughfleet-run, andir-runtakes the benchmark lease for every--auto-profilerun. An outerir-acquire benchmark -- …hold makes every nested run run inside it, so no run prints aQUIET=verdict. The body's "ir-acquire benchmarkwith a quiet-host verdict" is each run's own lease and itsQUIET=guardedline.ir-acquire benchmark -- python3 scripts/perf/million_controls.pyline in### Verification. Everything else is additive.commandBufferSpansfrom--- GPU frame timing ---(the GPU start to GPU end of the frame's command buffers) beside the probe's two halves.submit_to_present_msas GPU time because "the pipeline is serialized". Once a frame is still executing when the next one is committed, that interval also holds the wait behind it, so it is no longer the GPU half.docs/perf/input-latency/README.md: § Scenes and § Noise bound. "CPU is the probe'sframe_start_to_submit_msmean and GPU itssubmit_to_present_msmean". "The pipeline is serialized." "Each run's own quiet guard held (QUIET=guarded), which is the verdict the benchmark lease gives."4303d18ae:engine/render/src/metal/metal_render_impl.cpp,engine/render/include/irreden/render/input_latency.hppandengine/profile/src/profile_report.cpp.docs/agents/BUILD.md: "ir-runwraps …--auto-profileinir-acquire benchmark". "A run nested under anir-acquirethat still holds its verb … runs inside that hold".jakildev commentedon Nov 17, 2026
Plan corrections
A2 — 2026-11-17 — trigger: PR #5115 merged (#4999,
683701acd)The pick ring is one of "every serial-gated readback ring".
TRIXEL_TO_FRAMEBUFFER::endTickcallsRenderManager::publishMouseTrixelPick. It copiesHoveredEntityIdBufferinto aGpuReadbackRingslot (m_presentedPickRing, 8 slots) tagged withsubmissionSerial().RenderManager::mouseTrixelPickdrains the slots atcompletedSubmissionSerial()and reads each one withgetSubData.completedSubmissionSerial()is the serial minus one (this plan, first### Verified current statebullet).MetalRenderDevice::copyBufferSubData's no-command-buffer branch.metalCommandBuffer()is null, itmemcpys the source into the destination at once. Its comment states the assumption: "No command buffer yet, so no queued work can touch either side."beginFrame()leaves the command buffer null whennextDrawable()returns null. So in criterion 3's no-drawable run, the pick publish takes this branch on every starved frame.Criterion 5's validators. The assertions render: pick and hover read the most recent completed frame through a gated record #4999 added are four
IRShapeDebug --gui-testshots:newest_completed_pick_frame:PICK_FRAME_CURRENT, 30 frames;settled_cursor_is_current:PICK_STALE_CLEAR, 30 frames;same_batch_move_press_is_stale:PICK_STALE_SEEN;destroyed_entity_is_filtered:PICK_ENTITY_EMPTY.The unit tests are
PresentedPick*. The fault control ispython3 scripts/gui-verify.py IRShapeDebug -- --gui-test --config-preset configs/presented-pick-previous.lua, which setspresented_pick_previous_completed_test_fault = true. With overlap on, it must still failnewest_completed_pick_frame. On PR render: gate mouse picks on completed frames (#4999) #5115 it readcurrent=0/30.Criterion 10's stale-cursor row is
Stale pick input ticks: <n>under--- Input latency ---. It is counted once per INPUT tick.683701acd:engine/render/src/render_manager.cpp,render_manager.hpp,system_trixel_to_framebuffer.hppendTick,profile_report.cpp,creations/demos/shape_debug/main.cppinitHoverParityFixture,configs/presented-pick-previous.lua, and the PR's evidence table.683701acd:engine/render/src/metal/metal_render_impl.cppcopyBufferSubData,beginFrame()andpresent().memcpy".## Approach: "What the blocking present currently guarantees, and therefore what stops being true".### Approach sketch: "each item either becomes owned by the frame that used it or gains a rule for when it is safe".jakildev commentedon Nov 17, 2026
Host pin corrected: this task was claimable on no host
The scout's cached record for this issue read
needs_host: macandneeds_gl_host: trueat 2026-11-17T22:20Z. The first comes from the**Host:** macosline. The second came from one context bullet that cited the OpenGL backend's render-implementation file by path: the scout's backstop treats a cited file under theopengl/source directory as a GL-only edit. With both set, the macOS host refused the task at the GL gate and every GL host refused it at the macOS pin, so it was never dispatched (the dispatcher log has no launch for it). Its blockers #4947, #4993 and #4999 are all closed.I reworded that one bullet so it names the file in prose instead of by path. Nothing else in the body changed: scope, decisions and acceptance criteria are as approved. The tool gap is filed as #5147.
— opus-architect, on the owner's fleet check
jakildev commentedon Nov 18, 2026
Live Codex worker iteration preserved as WIP in #5161, head
af82b8975. Task 5000 is not complete. The PR contains the implementation, all 30 final guarded measurements, exact-parent capture proof, and a row for every acceptance criterion. Review and merge remain blocked.Human action required: wake the macOS display and keep the logged-in Aqua session available for validation. The clean-parent command
fleet-jobs start render-verify -- --all --record-control --tracker 4904 --json-out build/metal-overlap-render-parent.jsonreachedCoreGraphics online=1 awake=0 NSScreen=1; the engine will discover 0 monitors, with later scenes exiting 69. Job20261118T023223Z-render-verify-3913a0has a terminalfailed exit=1; the head comparison and a planned complete 0° recheck were not launched after that result.Continuation also requires sequencing behind #4994 / PR #5100: the overlap gate returned exit 3 with conflicts in
metal_runtime.hpp,render_device.hppandmetal_render_impl.cpp. The WIP PR carriesfleet:awaiting-infraandParked-until: #4994. After sequencing and restoring the display, rebuild, obtain the exact merge-base render control, compare the head, and investigate the preserved 0° latency/overlap failures. Waking the display does not establish that the performance failures will pass.Blocked-operation record:
ps -p 61797 -o pid,ppid,commreturnedoperation not permitted; not retried, and no foreign process or lease was modified.fleet-jobs start render-verify -- --all --record-control --tracker 4904 --json-out /private/tmp/fleet-pool-1/metal-overlap/render-parent.jsonreturned exit 2,--json-outvalue not allowed. The documentedbuild/destination was used once instead, producing the terminal job above.Issue moved from
fleet:queuedtofleet:needs-humanunder role-worker step 8b. Claim and reservation are being released; no different task was discovered or claimed. Runtime/model: Codex / GPT-6. Human merge authority preserved.