Repository navigation
render/metal: patch partial buffer writes in place instead of orphaning - #5057
Merged
Merged
Conversation
A partial subData / subDataRanges write to a buffer queued GPU work may still read used to allocate a whole new buffer and blit every untouched byte across. It is now staged in the frame arena and copied into the same backing in command order, so its cost follows the bytes written. Backings round up to whole words, so a buffer's size can no longer force the silent mid-frame wait; a genuinely unaligned range still waits, but it is counted. RenderDevice::deviceStats() reports the buffer-write counters (Metal counts, OpenGL reports unsupported), World records per-frame deltas and the peak GPU allocation in the profile report, and compare_perf_runs / repeat_profile read them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eader Keeps metal_runtime.hpp's include block and ProfileReport's tail clear of the open pipeline-key and light-occlusion PRs' edits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 12, 2026
jakildev
commented
Nov 12, 2026
jakildev
left a comment
Owner
Author
There was a problem hiding this comment.
Review — render/metal: patch partial buffer writes in place instead of orphaning
Verdict: approve
Praise
- The staging path preserves the essential ordering invariant: each range is blitted into the same backing in command order, the arena remains immutable until the existing GPU-drain boundary, and the destination is re-marked encoded so later CPU writes cannot jump ahead.
- Oversized chunks stay reusable without allowing small uploads to fragment them, while the existing idle-drain release policy remains intact.
RenderDeviceStats::supported_and the parser's optional state preserve the distinction between an unsupported backend and measured zeros.
Acceptance (issue #4993)
| Criterion | Result |
|---|---|
| Parent counters recorded | Met — both required fixtures and parent-behavior rows are quoted. |
| Positive-fire / zero steady allocations | Met — both fixtures stage patches and report zero steady partial-write allocations. |
| Ordering and preservation | Met — tests cover pre/post encoder visibility, GPU-owned gaps, overlap ordering, and full replacement. |
| Nine-byte aligned write avoids the wait | Met. |
| Unaligned-write positive control | Met. |
| Zero mid-frame waits in fixtures | Met. |
| Pixel equivalence | Met for this change: final-head comparisons are byte-identical to the parent. The 19 IRShapeDebug reference mismatches are inherited on the parent with identical rows, so they are not charged to this PR. |
| Frame time and peak allocation | Met — five interleaved pairs are reported for both fixtures; the head mean is lower in both lanes, and peak process allocation is reported for both arms. |
Validation
- Independent macOS build:
fleet-jobs: 20261112T074437Z-build-44230b succeeded exit=0forIrredenEngineTest. - Independent focused run: 40/40
PositionUploadTest*,MetalBufferPatch*, andMetalGpuComputeDispatchTest*tests passed. - Independent perf-script run: 165/165 tests passed.
- CI
perf-gateis red for the same inheritedlibjack.so/CXXABI_1.3.15linker failure present on currentmaster. The two red render-harness suites also reproduce locally in unchanged files (test_editor_screen_alignment.pyandtest_harness_dependency_contract.py); neither failure is in this diff. Remaining checks were still running when this review was written.
No additional author action is needed for the reviewed diff.
🤖 Reviewed by Codex (GPT-5 runtime; review-pr skill)
Opus recheck not required (reviewed at opus class).
6 tasks done
This was referenced Nov 12, 2026
Closed
This was referenced Nov 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
subData/subDataRangeswrite that covers only part of a buffer the GPU may still read is copied into the frame staging arena, and one blit copies each range into the same backing in command order. No new buffer, no GPU copy of the untouched bytes. Encoders created before the write read the old bytes; encoders created after it read the new ones. A full replacement still swaps the backing; an unencoded buffer is still written directly.reserveMetalStaging/stageMetalUpload). An upload larger than a standard 4 MiB chunk gets a retained power-of-two chunk, reused every frame; large chunks serve only large uploads, and idle chunks are released by the existing idle-drain rule. The arena is still rewound only after a GPU wait.RenderDevice::deviceStats()returnsRenderDeviceStats { supported_, bufferWrites_ }. Its first fields are the buffer-write counters: partial-write allocations and bytes, staged patches and bytes, full replacements, mid-frame waits. OpenGL reportssupported_ = false; render/metal: draw consecutive draws to one target in one render pass #4994 and render/metal: report allocation, pipeline and command-buffer failures in every build type #4995 add fields here.Worldrecords per-frame counter deltas and the peakprocessAllocatedBytes_. The report gains a--- Render device counters ---section (total, steady per frame, max per frame, peak GPU allocation).compare_perf_runs.pyparses it andrepeat_profile.pysummarises it across runs (device_counter_lines).subDataorphans the buffer, including.claude/rules/cpp-ecs.md(same line count, 6 bytes shorter).Test plan
fleet-run IrredenEngineTest --gtest_filter='PositionUploadTest*:MetalBufferPatch*:MetalGpuComputeDispatchTest*'→[ PASSED ] 40 tests.(final head, on master369cb6b06)fleet-run IrredenEngineTest→[ PASSED ] 3777 tests.(final head, on master369cb6b06)metal_buffer.cppfail 4 of 7 (EncodersBeforeTheWriteReadOldBytesAndAfterReadNew,AnAlignedPartialWriteToANineByteBufferIsStagedWithoutAWait,APatchLargerThanAStagingChunkAllocatesOnlyOnItsFirstFrame,PositionFlushStagesOnePatchIntoAnEncodedBuffer). The 3 that pass check contracts both versions share: overlapping patches, full replacement, unaligned wait.python3 -m unittest discover -p 'test_*.py'inscripts/perf→ OK, including the newDeviceCounterParserTestandDeviceCounterSummaryTestfleet-build --target format-changed;python3 scripts/lint_comment_refs.py→ok: 0 reference line(s)python3 scripts/lint_instruction_size.py: output identical to the parent's (its existing over-budget files only; this PR adds no lines to any instruction file)Acceptance evidence
All runs on the macOS (Apple Silicon, Metal) host. The branch was rebased twice while the evidence ran. Criteria 2–6, the
IRCanvasStressrender-verify and the nine-yaw set were re-run on the final head against master369cb6b06. Criterion 1, theIRShapeDebug/IRPerfGridrender-verify and criterion 8 were measured at fork3734b2700(the parent there is that commit). "Parent behaviour" counter rows come from the parent plus this PR's counter code alone, i.e. the orphan path, instrumented.IRCanvasStressand the million control, parent behaviourIRREDEN_BUILD_DIR=<parent+counters>/build-release python3 scripts/perf/repeat_profile.py --repeats 1 --target IRCanvasStress -- --auto-profile --profile-frames 300, same for--target IRPerfGrid -- --config-preset configs/perf/million-profiling-off.lua --yaw 0 --wave-freeze --no-overlay --pivot-origin --auto-profile 300IRCanvasStress:bufferPartialWriteAllocations 59575 199.444 205,bufferPartialWriteAllocatedBytes 24481819600 81606327.111 81608016,bufferMidFrameWaits 0 0.000 0. Million:bufferPartialWriteAllocations 2401 8.000 9,bufferPartialWriteAllocatedBytes 17727826816 59036832.000 75814048,bufferMidFrameWaits 0 0.000 0(columns: total, steady/frame, max/frame). The premise holds on both, so the bail path did not apply.fleet-run IRCanvasStress --auto-profile --profile-frames 300; the million control as above; headIRCanvasStress:bufferStagedPatches 60449 203.329 213,bufferPartialWriteAllocations 1 0.000 1(one 4 MiB arena chunk in warm-up, zero in the steady window). Million:bufferStagedPatches 2401 8.000 9,bufferPartialWriteAllocations 3 0.000 3(32 + 8 MiB chunks in warm-up, zero steady). Staged bytes per steady frame: 1.22 MB vs 81.6 MB orphaned (IRCanvasStress); 28.1 MB vs 59.0 MB (million).fleet-run IrredenEngineTest --gtest_filter='PositionUploadTest*:MetalBufferPatch*'[ OK ] MetalBufferPatchTest.EncodersBeforeTheWriteReadOldBytesAndAfterReadNew(an encoder before the write reads all0x11, one after reads the patch; same backing, no retired buffer; zero allocations on frame 2);PositionUploadTest.PendingBatchPreservesGpuOwnedGapsOK;MetalBufferPatchTest.OverlappingPatchesInOneFrameLeaveTheSecondsBytesOK;MetalBufferPatchTest.AFullReplacementSwapsTheBackingOnceOK (new backing, +1 retired, +1 full replacement);PositionUploadTest.PositionFlushStagesOnePatchIntoAnEncodedBufferOK (renamed fromPositionFlushOrphansAnEncodedBufferOnce)[ OK ] MetalBufferPatchTest.AnAlignedPartialWriteToANineByteBufferIsStagedWithoutAWait(midFrameWaits_unchanged,stagedPatches_+1, byte 8 preserved); fails on the parent (positive control above)[ OK ] MetalBufferPatchTest.AnUnalignedWriteWaitsExactlyOnceAndLandsItsBytes(offset 5:midFrameWaits_+1, no staged patch, bytes correct);PositionUploadTest.UnalignedSparseBatchWaitsAndPatchesInPlacealso asserts +1bufferMidFrameWaits 0 0.000 0onIRCanvasStressand on the million controlrender-verifymax delta 0 forIRShapeDebug,IRCanvasStress,IRPerfGrid; nine-yawIRCanvasStressRGB-identical to the parentpython3 scripts/render-verify.py --target <T> --no-buildin the head tree and in a parent worktree, thendiffof the per-shot rows (match %, max delta, PSNR against the same committed references);fleet-run IRCanvasStress --frozen-pose 0.47 --sweep-yaw 0 6.2831853 9 --auto-screenshot 6in both trees,cmp+render-compare.pyIRShapeDebug148 rows,IRCanvasStress59,IRPerfGrid21: every row identical head vs parent excepttext_sizes:text_size_sample(parent 99.9889 % / 60 in one run, head 100.0 / 0). Rerunning that capture twice in each tree gave four byte-identical PNGs (one md5), so the parent's row was a one-off nondeterministic run, not a head difference.IRCanvasStressandIRPerfGridread all PASS; of their 36 + 21 image rows every max delta is 0 exceptso3_wide_parity(32, identical on the parent). Pre-rebase (parentbf74784da) all 148/59/21 rows were identical. Nine-yaw set: 9 of 9 shots byte-identical to the parent (cmpsilent;render-compare.py:max_delta 0,match 100.0) atbf74784da, at3734b2700and at369cb6b06. At369cb6b06theIRCanvasStressrender-verify readsall 59 checks PASSwith all 59 rows identical to the parent's.ir-acquire benchmark; peak process GPU allocation for both armsir-acquire benchmark -- bash ab.sh: 5 pairs per fixture, order alternating per pair, each armrepeat_profile.py --repeats 1on its ownbuild-releaseIRCanvasStresssteady mean per pair, base→head: 10.96→10.62, 11.21→10.62, 11.11→10.14, 11.13→10.10, 11.19→9.94 ms; means 11.120→10.284 (ratio 0.925), paired delta −0.836 ms, sd 0.365, one-sided 95 % upper bound −0.488 ms. Million control: 31.38→29.09, 31.99→29.04, 33.22→30.15, 47.99→42.04, 53.48→60.24 ms. Pairs 4–5 are host-disturbed in both arms (p95 70–92 ms vs ~32–35 ms in pairs 1–3; other panes were running GPU work). Means 39.612→38.112 (ratio 0.962), paired delta −1.500 ms, sd 4.828, upper bound +3.10 ms; pairs 1–3 alone are −2.3 to −3.1 ms each. Head mean is below the base mean on both fixtures, so the criterion's ratio arm passes. A pre-rebase lease at parentbf74784daread million 44.626→41.810 ms (paired −2.816, upper bound −2.304) and canvas 22.000→21.586 (−0.414, upper bound −0.263). Peak process GPU allocation (GPU process allocation: peak=):IRCanvasStressparent 576,061,440 B, head 498,696,192 B; million parent 287,080,448 B, head 329,023,488 B (+40 MiB: the retained 32 + 8 MiB staging chunks the 28 MB/frame patch stream reuses).Plan departures
RenderDevice. They are a nestedBufferWriteStats bufferWrites_insideRenderDeviceStats, beside asupported_flag, so render/metal: draw consecutive draws to one target in one render pass #4994/render/metal: report allocation, pipeline and command-buffer failures in every build type #4995 add sibling structs without reshaping this one.Worldand written to the report (GPU process allocation: peak=…). The parent binary has no such row, so the parent arm's peak comes from the parent+counters build in criterion 1, which allocates exactly what the parent does.stageMetalTextureUploadis renamed tostageMetalUpload(its one caller,metal_texture.cpp, is updated), andOversizedTextureUploadUsesDeferredStagingbecomesOversizedTextureUploadReusesItsStagingAfterDrain: an oversized upload now reuses a retained chunk instead of a one-shot deferred buffer.system_voxel_to_trixel.hpp,system_update_joint_matrices.hpp,component_gpu_particle_pool.hpp,system_update_gpu_particles.hpp,gui_text_batch.hpp,ir_render.cpp,buffer.hpp). Thesystem_bake_sun_shadow_map.hpprebind comments are left as they are: a full write still swaps the backing, so rebinding after a patch stays correct.Notes for reviewer
engine/render/CLAUDE.md: changes without a visual effect need no captures), and criterion 7's evidence is byte identity against the parent.IRShapeDebugshots (yaw180/270 poses,lod_scene_return_yaw180, thesdf_baked_*yaw180/270 shots) fail against the committed references on this host on the parent too, with identical match/delta/PSNR rows. Many passing ShapeDebug rows also sit at a nonzero delta against those references on this host, so "max delta 0" is graded head-vs-parent.getSubData/mapRangeon the same buffer see the new bytes only once the submission completes, the same rule as for any GPU write. Every production reader reads a completion-gated copy (plan, Verified current state).fleet-pr-overlap --base master:VERDICT: overlap, every shared path trial-mergesclean(render: preserve per-light propagation falloff (#4967) #5036 1 path, render: upload only the changed ranges of the voxel record and active-mask buffers (#4991) #5039 7, lighting: bound light occlusion grid visits (#4992) #5042 3, render/metal: key the render-pipeline cache by layout value, not address #5050 3). The first trial merge conflicted with render/metal: key the render-pipeline cache by layout value, not address #5050 (metal_runtime.hppinclude block) and lighting: bound light occlusion grid visits (#4992) #5042 (ProfileReporttail). The second commit moved this PR's lines off both (a forward declaration in place of the include; the report fields beside the GPU frame-timing fields). Please check the semantic seam with lighting: bound light occlusion grid visits (#4992) #5042, which addslightOcclusionChunkStats_to the same report, and with render/metal: draw consecutive draws to one target in one render pass #4994/render/metal: report allocation, pipeline and command-buffer failures in every build type #4995, which extendRenderDeviceStats.engine/render/CLAUDE.md§ "GPU resource contracts" describesgpuMemoryStats()but notdeviceStats(). That file is already over its instruction-size budget, so this PR adds no line to it.Closes #4993
🤖 Generated with Claude Code