Skip to content

render/metal: patch partial buffer writes in place instead of orphaning - #5057

Merged
jakildev merged 2 commits into
masterfrom
claude/4993-metal-staged-buffer-patch
Nov 15, 2026
Merged

jakildev merged 2 commits into
masterfrom
claude/4993-metal-staged-buffer-patch

Conversation

@jakildev

Copy link
Copy Markdown
Owner

Summary

  • Metal partial writes patch in place. A subData / subDataRanges write 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.
  • The size of a buffer can no longer cause a wait. Backings are allocated in whole four-byte words (the logical size is unchanged), and the alignment test looks only at each non-empty range. A genuinely unaligned range to an encoded buffer still waits (widening it could overwrite bytes a queued shader owns), but it is now counted and logged once per buffer in non-Release builds.
  • The staging arena serves buffers and textures (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.
  • Backend-neutral device statistics. RenderDevice::deviceStats() returns RenderDeviceStats { 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 reports supported_ = 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.
  • Profile report. World records per-frame counter deltas and the peak processAllocatedBytes_. The report gains a --- Render device counters --- section (total, steady per frame, max per frame, peak GPU allocation). compare_perf_runs.py parses it and repeat_profile.py summarises it across runs (device_counter_lines).
  • Corrected every comment and rule that still said Metal subData orphans 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 master 369cb6b06)
  • fleet-run IrredenEngineTest → [ PASSED ] 3777 tests. (final head, on master 369cb6b06)
  • Positive control: the new tests built against the parent metal_buffer.cpp fail 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' in scripts/perf → OK, including the new DeviceCounterParserTest and DeviceCounterSummaryTest
  • fleet-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 IRCanvasStress render-verify and the nine-yaw set were re-run on the final head against master 369cb6b06. Criterion 1, the IRShapeDebug / IRPerfGrid render-verify and criterion 8 were measured at fork 3734b2700 (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.

Criterion Check run Observed
1. Phase 0 reading on record: partial-write orphans, orphaned bytes and mid-frame waits per frame, 300 frames of IRCanvasStress and the million control, parent behaviour IRREDEN_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 300 IRCanvasStress: 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.
2. Positive fire: staged patches per frame > 0 and partial-write allocations per frame = 0 where phase 0 saw orphans fleet-run IRCanvasStress --auto-profile --profile-frames 300; the million control as above; head IRCanvasStress: 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).
3. Ordering and preservation (unit tests, Metal host) fleet-run IrredenEngineTest --gtest_filter='PositionUploadTest*:MetalBufferPatch*' [ OK ] MetalBufferPatchTest.EncodersBeforeTheWriteReadOldBytesAndAfterReadNew (an encoder before the write reads all 0x11, one after reads the patch; same backing, no retired buffer; zero allocations on frame 2); PositionUploadTest.PendingBatchPreservesGpuOwnedGaps OK; MetalBufferPatchTest.OverlappingPatchesInOneFrameLeaveTheSecondsBytes OK; MetalBufferPatchTest.AFullReplacementSwapsTheBackingOnce OK (new backing, +1 retired, +1 full replacement); PositionUploadTest.PositionFlushStagesOnePatchIntoAnEncodedBuffer OK (renamed from PositionFlushOrphansAnEncodedBufferOnce)
4. A partial four-byte-aligned write to a 9-byte buffer takes the staged path; wait counter stays 0 same filter [ OK ] MetalBufferPatchTest.AnAlignedPartialWriteToANineByteBufferIsStagedWithoutAWait (midFrameWaits_ unchanged, stagedPatches_ +1, byte 8 preserved); fails on the parent (positive control above)
5. Positive control: an unaligned-offset write to an encoded buffer increments the wait counter by exactly one and produces the right bytes same filter [ OK ] MetalBufferPatchTest.AnUnalignedWriteWaitsExactlyOnceAndLandsItsBytes (offset 5: midFrameWaits_ +1, no staged patch, bytes correct); PositionUploadTest.UnalignedSparseBatchWaitsAndPatchesInPlace also asserts +1
6. Mid-frame waits from this path read 0 over 300 frames at both fixtures the criterion 2 runs bufferMidFrameWaits 0 0.000 0 on IRCanvasStress and on the million control
7. render-verify max delta 0 for IRShapeDebug, IRCanvasStress, IRPerfGrid; nine-yaw IRCanvasStress RGB-identical to the parent python3 scripts/render-verify.py --target <T> --no-build in the head tree and in a parent worktree, then diff of 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 6 in both trees, cmp + render-compare.py IRShapeDebug 148 rows, IRCanvasStress 59, IRPerfGrid 21: every row identical head vs parent except text_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. IRCanvasStress and IRPerfGrid read all PASS; of their 36 + 21 image rows every max delta is 0 except so3_wide_parity (32, identical on the parent). Pre-rebase (parent bf74784da) all 148/59/21 rows were identical. Nine-yaw set: 9 of 9 shots byte-identical to the parent (cmp silent; render-compare.py: max_delta 0, match 100.0) at bf74784da, at 3734b2700 and at 369cb6b06. At 369cb6b06 the IRCanvasStress render-verify reads all 59 checks PASS with all 59 rows identical to the parent's.
8. Steady frame mean not worse than the parent beyond the noise bound, 5 interleaved base/head pairs each, Release, ir-acquire benchmark; peak process GPU allocation for both arms ir-acquire benchmark -- bash ab.sh: 5 pairs per fixture, order alternating per pair, each arm repeat_profile.py --repeats 1 on its own build-release IRCanvasStress steady 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 parent bf74784da read 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=): IRCanvasStress parent 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

  • The plan wrote the statistics as "the buffer-write counters as its first fields" of a struct on RenderDevice. They are a nested BufferWriteStats bufferWrites_ inside RenderDeviceStats, beside a supported_ 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.
  • "Partial-write buffer allocations" counts every backing allocation made on behalf of a partial write. On the head those are only staging-arena chunk allocations (the orphan is gone), so criterion 2's zero is a steady-window reading: the arena's first-use chunks land in warm-up and appear in the total column.
  • Peak process GPU allocation is sampled at each frame end by World and 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.
  • stageMetalTextureUpload is renamed to stageMetalUpload (its one caller, metal_texture.cpp, is updated), and OversizedTextureUploadUsesDeferredStaging becomes OversizedTextureUploadReusesItsStagingAfterDrain: an oversized upload now reuses a retained chunk instead of a one-shot deferred buffer.
  • Comments in prefab files outside the plan's Affected files that stated the orphan behaviour as fact were corrected (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). The system_bake_sun_shadow_map.hpp rebind comments are left as they are: a full write still swaps the backing, so rebinding after a patch stays correct.

Notes for reviewer

Closes #4993

🤖 Generated with Claude Code

jakildev and others added 2 commits November 11, 2026 23:35
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>
@jakildev jakildev added fleet:author-claude Implementation last authored by Claude; route review to Codex fleet:authored-on-macos PR was authored and smoke-tested on macOS Metal backend labels Nov 12, 2026

@jakildev jakildev left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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=0 for IrredenEngineTest.
  • Independent focused run: 40/40 PositionUploadTest*, MetalBufferPatch*, and MetalGpuComputeDispatchTest* tests passed.
  • Independent perf-script run: 165/165 tests passed.
  • CI perf-gate is red for the same inherited libjack.so / CXXABI_1.3.15 linker failure present on current master. The two red render-harness suites also reproduce locally in unchanged files (test_editor_screen_alignment.py and test_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).

@jakildev jakildev added fleet:reviewing-mac-pool-2 fleet:approved Fleet reviewer approved — ready for human merge fleet:needs-windows-smoke PR needs windows-debug build + smoke-run validation and removed fleet:reviewing-mac-pool-2 labels Nov 12, 2026
@jakildev
jakildev added this pull request to stack #5077 November 12, 2026 11:10
@jakildev
jakildev merged commit 05f9108 into master Nov 15, 2026
10 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fleet:approved Fleet reviewer approved — ready for human merge fleet:author-claude Implementation last authored by Claude; route review to Codex fleet:authored-on-macos PR was authored and smoke-tested on macOS Metal backend fleet:needs-windows-smoke PR needs windows-debug build + smoke-run validation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

render/metal: patch partial buffer writes in place instead of orphaning the whole buffer

1 participant