Skip to content

render/metal: key the render-pipeline cache by layout value, not address - #5050

Merged
jakildev merged 2 commits into
masterfrom
claude/4996-metal-pipeline-value-key
Nov 12, 2026
Merged

jakildev merged 2 commits into
masterfrom
claude/4996-metal-pipeline-value-key

Conversation

@jakildev

@jakildev jakildev commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • The Metal render-pipeline cache key is now a trivially copyable MetalRenderPipelineKey (metal_runtime.hpp): colour, depth and entity-id pixel formats, the blend setting, and a MetalVertexLayoutSignature (per attribute: format, offset, buffer index; plus attribute count and stride). Equality is defaulted and MetalRenderPipelineKeyHash reads only those fields. The cache is std::unordered_map<MetalRenderPipelineKey, MTL::RenderPipelineState *, MetalRenderPipelineKeyHash>. The per-draw std::string key and the descriptor-address input are gone.
  • MetalVertexLayoutImpl computes the signature once at construction and builds its MTL::VertexDescriptor from the signature, so the key and the descriptor cannot disagree. bind() passes the signature to setActiveMetalVertexLayout, and MetalVertexLayoutBinding carries it.
  • A new currentMetalRenderPipelineKey(blendingEnabled) builds the key from the bound target (including the entity-id attachment format) and the active layout. Each of the five draw functions changes one argument: getRenderPipelineState(currentMetalRenderPipelineKey(m_blendingEnabled), layout.vertexDescriptor_).
  • On a miss the pipeline descriptor is built from the key's own formats (the entity-id attachment comes from key.entityIdPixelFormat_, no longer a re-read of global state) and the live descriptor. The cache stores no descriptor pointer. The failure branch is untouched, for render/metal: report allocation, pipeline and command-buffer failures in every build type #4995.
  • The signature holds kMaxAttributes = kMaxVertexAttributes (16, vao.hpp): every layout the shared VertexLayout contract admits, the same cap the OpenGL backend asserts. A layout over that cap is refused at creation with an IR_ASSERT. The engine's layouts use at most 2.
  • MetalPipelineStateProvider::renderPipelineStateCount() is the narrowest accessor the cache tests need.

Test plan

  • fleet-build --target IrredenEngineTest: clean on head 3fc9f7529 (rebased onto master 369cb6b06)
  • fleet-run IrredenEngineTest --gtest_filter='MetalPipelineKey*': 8/8 pass; --gtest_filter='Metal*': 34/34 pass (includes MetalStickyUntrack* and MetalGpuComputeDispatchTest*)
  • Max-width layout: MetalPipelineKeyCacheTest.HoldsALayoutWithTheMostAttributesVertexLayoutAdmits builds a 16-attribute layout, checks every slot's format and offset plus the stride, and builds a pipeline state from it. Mutation with the cap set back to 8 (the test's static_assert disabled): FAILS (Engine assertion failed thrown). Restored: passes. The over-capacity case (RefusesALayoutTheSignatureCannotHold, now 17 attributes) passes.
  • Parent commit plus a count-only shim (the same renderPipelineStateCount() accessor added to the unchanged string-keyed cache), same cache tests: LayoutsWithEqualContentsShareOneState FAILS (cachedStateCount() is 2, expected 1). ReplacingALayoutWithEqualContentsBuildsNoNewState FAILS (2, expected 1). The other two pass on the parent.
  • cmake -DPROJECT_ROOT=$PWD -P cmake/run_header_checks_standalone.cmake: exit 0
  • python3 scripts/lint_comment_refs.py: exit 0
  • Render A/B on the final head, IRShapeDebug and IRCanvasStress: built master 369cb6b06 (the fork point) and captured its output as temporary references (render-verify --update-references --force), then checked out head 3fc9f7529, rebuilt (the log shows metal_runtime.cpp, metal_render_impl.cpp, metal_pipeline.cpp and metal_framebuffer.cpp recompiled), and ran render-verify against them. Both read max delta 0 (details in the evidence table). Committed references were restored afterwards; none are in this diff.

Acceptance evidence

Criterion Check run Observed
1. Two layouts with identical attributes leave one cache entry; the parent leaves two fleet-run IrredenEngineTest --gtest_filter='MetalPipelineKey*' on branch and on parent + count shim branch: [ OK ] MetalPipelineKeyCacheTest.LayoutsWithEqualContentsShareOneState; parent: [ FAILED ] ...LayoutsWithEqualContentsShareOneState: cachedStateCount() Which is: 2 vs 1
2. Layouts differing in one format, one offset or stride, and each differing colour / depth / entity-id format and blend setting, produce different keys same suite, MetalPipelineKey.EachFieldDistinguishesTheKey (pure key test; also buffer index and attribute count; all 10 variants are distinct in an unordered_set with the real hash) and MetalPipelineKeyCacheTest.EachBlendSettingHasItsOwnState (draws with blending off/on/off → 2 states) [ OK ] MetalPipelineKey.EachFieldDistinguishesTheKey, [ OK ] MetalPipelineKeyCacheTest.EachBlendSettingHasItsOwnState
3. The key is trivially copyable (compile-time check) and holds no address; equality and hash read only its fields Build (static_assert(std::is_trivially_copyable_v<MetalRenderPipelineKey>) in metal_runtime.hpp, repeated for the key and the signature in the test) + source review Builds clean. Members are three MTL::PixelFormat, a bool, and a signature of MTL::VertexFormat / uint32_t fields, with no pointer members. operator== is defaulted; MetalRenderPipelineKeyHash combines each field explicitly and never reads raw bytes or padding
4. Destroying and re-creating an identical layout ten times, drawing after each, leaves one cache entry same suite: ReplacingALayoutWithEqualContentsBuildsNoNewState (move-assigns a fresh layout 10×, the shape depth_tested_primitives.hpp's growth branch uses: replacement built before the old is released) and DestroyingAndRecreatingAnEqualLayoutBuildsNoNewState (scoped destroy-then-create 10×) both [ OK ] on branch; the replace variant fails on the parent (2 entries). The scoped variant passes on the parent too, because the allocator hands the freed descriptor's address straight back (the stale-address hazard in this issue's Scope)
5. A cache hit constructs no string: the lookup uses the value key directly Build (criterion 3's static_assert) + source review getRenderPipelineState calls m_renderStates.find(key) on the const MetalRenderPipelineKey & it is passed. currentMetalRenderPipelineKey returns the key by value from runtime fields. Nothing on the hit path builds a std::string, calls std::to_string, or allocates. The map's key type is the value struct
6. render-verify max delta 0 for IRShapeDebug and IRCanvasStress python3 scripts/render-verify.py --target IRShapeDebug and --target IRCanvasStress on head 3fc9f7529, against references captured from the fork-point build (master 369cb6b06) IRShapeDebug: all 158 checks PASS, all 151 pixel shots 100.0 0 inf (match %, max delta, PSNR), plus 7 structural checks PASS. IRCanvasStress: all 59 checks PASS, all 36 pixel shots 100.0 0 inf, plus 23 structural checks PASS

Plan departures

  • Plan § Verification runs render-verify against the committed references. On this host, master itself fails 19 of 148 IRShapeDebug checks against them, all yaw-180/270 shots, max delta 109–120 (the identical set and deltas appear on an unrelated branch's head run on this host). So the committed references cannot show a delta of 0 for anyone. Criterion 6 is graded on a base-vs-branch A/B instead: the fork-point build's captures are the references. The A/B ran after the final rebase, on the pushed head.
  • The signature also carries each attribute's buffer index (always 0 today) and the attribute count, matching the plan's "per attribute its format, offset and buffer index". The key struct names are MetalRenderPipelineKey / MetalVertexLayoutSignature / MetalVertexAttributeSignature.
  • The issue's criterion 4 is satisfied by two tests (replace-in-place and scoped destroy/create). Only the replace shape is reachable from tracked code today and fails on the parent.

Notes for reviewer

Closes #4996

🤖 Generated with Claude Code

@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: key the render-pipeline cache by layout value, not address

Verdict: needs-fix

The value-key approach is sound, and building the Metal descriptor from the same stored signature is a good way to keep the cache key and pipeline state aligned. Two issues still block this head.

Needs-fix

  • engine/render/include/irreden/render/metal/metal_runtime.hpp:32 / engine/render/src/metal/metal_framebuffer.cpp:38-45 — the new signature caps layouts at 8 attributes, but the shared VertexLayout contract permits 16 (engine/render/include/irreden/render/vao.hpp:13). In debug, a valid 9–16-attribute layout now throws; in IR_RELEASE, IR_ASSERT expands to nothing and the loop writes past the 8-element array. Size the signature to the engine's supported maximum (preferably tied to kMaxVertexAttributes) and cover the maximum supported layout so the Metal backend does not narrow the API or corrupt memory in release builds.
  • Acceptance criterion 6 is not established on the shipped tree. The PR's own Plan departures says both zero-delta A/B render runs happened before the rebase that produced current head d778c282dd77840ad53fa0331923bce40be61ef4. Re-run the base-vs-current-head IRShapeDebug and IRCanvasStress comparisons after the final amendment and record terminal zero-delta results.

Acceptance (issue #4996)

Criterion Grade Basis
Equal layouts share one state; parent leaves two met MetalPipelineKeyCacheTest.LayoutsWithEqualContentsShareOneState exercises the real draw path, and the evidence records the positive-fire parent failure.
Every layout/target/blend input distinguishes the key met MetalPipelineKey.EachFieldDistinguishesTheKey varies every named field and checks all variants in the real hashed container.
Key is trivially copyable, address-free, and field-based met The type contains only value fields, has defaulted equality, a compile-time assertion, and an explicit field hash.
Ten equal replacements/re-creations leave one state met Both replacement-before-release and scoped destroy/re-create cases run ten rounds and require one entry.
Cache hits construct no string met getRenderPipelineState directly calls m_renderStates.find(key) on the value-keyed map.
Current shipped head has max delta 0 for both render targets unmet The retained jobs succeeded, but both validated the pre-rebase tree rather than the current PR head.

Validation reviewed

  • Exact-head local build: fleet-jobs: 20261112T015552Z-build-21d153 succeeded exit=0.
  • Exact-head targeted run: MetalPipelineKey*, 7/7 passed.
  • git diff --check origin/master...HEAD: clean.
  • The current perf-gate, render-harness, and fleet-test failures reproduce on the exact base commit's workflows and are inherited; the Linux build was still in progress when this review was prepared.

Test plan the author should run before merge

  • Add and run a Metal test for a layout with exactly kMaxVertexAttributes attributes, plus the existing over-capacity case.
  • Rebuild and rerun MetalPipelineKey* after the capacity fix.
  • Rerun both base-vs-current-head render comparisons after the final commit.

🤖 Reviewed by Codex GPT-5 (review-pr skill)

Opus recheck not required (reviewed at opus class).

@jakildev jakildev added fleet:needs-fix Fleet reviewer found issues — author must address and removed fleet:reviewing-mac-pool-4 labels Nov 12, 2026
@jakildev jakildev removed the fleet:needs-fix Fleet reviewer found issues — author must address label Nov 12, 2026
jakildev and others added 2 commits November 11, 2026 21:16
The Metal render-pipeline cache keyed each state on a string built per
draw from the attachment formats, the blend flag and the address of the
layout's MTL::VertexDescriptor. A layout replaced with identical
contents got a fresh address and built a duplicate pipeline state on
the frame path; a later layout reusing a dead layout's address could be
handed a state built for different attributes; and every draw paid for
several heap allocations to build the key.

The key is now a trivially copyable MetalRenderPipelineKey: colour,
depth and entity-id formats, the blend setting, and a
MetalVertexLayoutSignature holding each attribute's format, offset and
buffer index plus the stride. The signature is computed once when a
layout is created, the descriptor is built from it, and the active
layout binding carries it to the draw. A cache hit hashes the value and
allocates nothing; a miss builds from the live descriptor and the key's
own formats, so the state always matches its key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The signature held 8 attributes while the shared VertexLayout contract
admits 16, so a valid 9-16 attribute layout threw in debug and wrote past
the array in release. kMaxAttributes now aliases kMaxVertexAttributes, and
a test builds a layout and pipeline state at exactly that width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jakildev
jakildev force-pushed the claude/4996-metal-pipeline-value-key branch from d778c28 to 3fc9f75 Compare November 12, 2026 06:36
@jakildev jakildev added fleet:changes-made Agent addressed human feedback — ready for human re-review and removed fleet:amending-mac-pool-4 labels Nov 12, 2026
@jakildev

Copy link
Copy Markdown
Owner Author

Addressed feedback (head 3fc9f7529, rebased onto master 369cb6b06):

  • Attribute cap. MetalVertexLayoutSignature::kMaxAttributes is now kMaxVertexAttributes (16, vao.hpp); the header includes vao.hpp to tie the two. Every layout the shared VertexLayout contract admits fits, so a 9–16-attribute layout neither throws in debug nor writes past the array in release. Over 16 is still refused by the IR_ASSERT, the same cap the OpenGL backend asserts.
  • Max-width test. New MetalPipelineKeyCacheTest.HoldsALayoutWithTheMostAttributesVertexLayoutAdmits: static_asserts the two caps are equal, builds a 16-attribute layout, checks each slot's format and offset plus the stride, and builds a pipeline state from the full-width descriptor (one cache entry). Mutation: with the cap back at 8 (and the static_assert disabled) it fails with Engine assertion failed; restored, it passes. The over-capacity case now uses 17 attributes and still throws.
  • Tests. MetalPipelineKey* 8/8 and Metal* 34/34 pass on the rebased head. Header checks, lint_comment_refs.py and git diff --check are clean.
  • Criterion 6 on the shipped tree. I rebased onto current master first (it had moved 4 commits, including render changes in render: fully sort overflow growth frames (#4959) #5020 / engine/voxel: run voxel-set position updates once per rendered frame #5046 and a metal_render_impl.cpp edit), then ran the A/B on the final head. Base: master 369cb6b06 built, captured as temporary references. Head: 3fc9f7529 rebuilt, with all four changed Metal sources recompiled. IRShapeDebug: all 158 checks PASS, 151/151 pixel shots 100.0 0 inf. IRCanvasStress: all 59 checks PASS, 36/36 pixel shots 100.0 0 inf. The first base canvas capture lost one pass to a 600 s GPU-lock timeout, so I re-ran the whole base capture cleanly (36 updated, no lock failures) before the head run. Committed references are restored and none are in the diff.
  • The PR body's summary, test plan, evidence row 6 and the Plan departures line about the pre-rebase A/B are updated.

— worker

@jakildev jakildev removed the fleet:changes-made Agent addressed human feedback — ready for human re-review label 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.

Re-review — render/metal: key the render-pipeline cache by layout value, not address

Verdict: approve

The amend resolves both prior findings. MetalVertexLayoutSignature::kMaxAttributes now aliases the shared 16-attribute contract, and the new max-width test builds a full descriptor and pipeline state while the 17-attribute case still exercises the refusal path. The render A/B evidence was also rerun against the current shipped head after the rebase.

Acceptance (issue #4996)

Criterion Grade Basis
Equal layouts share one state; parent leaves two met MetalPipelineKeyCacheTest.LayoutsWithEqualContentsShareOneState exercises two layouts through the draw path and requires one entry; evidence row 1 records the parent positive-fire failure with two.
Every layout, target-format, and blend input distinguishes the key met MetalPipelineKey.EachFieldDistinguishesTheKey varies each named key field in the real hashed container; EachBlendSettingHasItsOwnState covers the live draw path.
Key is trivially copyable, address-free, and field-based met Compile-time checks cover the key and signature; the key contains only value fields and the explicit hash reads those fields.
Ten equal replacements/re-creations leave one state met Both replacement-before-release and scoped destroy/re-create tests run ten draw rounds and require one entry; the replacement case positively fails on the parent.
Cache hit constructs no string met The cache is value-keyed and its hit path directly calls m_renderStates.find(key).
Current shipped head has max delta 0 for both render targets met Evidence row 6 pins head 3fc9f7529 and reports 158/158 IRShapeDebug checks plus 59/59 IRCanvasStress checks passing, with all 187 pixel shots at max delta 0.

Validation reviewed

  • Exact-head build: fleet-jobs: 20261112T064215Z-build-bc70bd succeeded exit=0.
  • Exact-head MetalPipelineKey*: 8/8 passed.
  • Exact-head Metal*: 34/34 passed.
  • git diff --check origin/master...HEAD: clean.
  • comment-refs, format-check, header-checks, instruction-refs, instruction-size, no-plan-files, and whitespace are green. fleet-tests, linux-build, perf-gate, and render-harness-tests were still pending when this review was posted, so they are not claimed as passing here.

Praise

  • Building the descriptor from the stored signature keeps the cache identity and the Metal state construction on one source of truth.
  • The max-width regression test directly locks the backend-neutral layout contract that the first pass found narrowed.

🤖 Reviewed by Codex gpt-5.6-sol at opus class (review-pr skill)

Opus recheck not required (reviewed at opus class).

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: key the render-pipeline cache by vertex layout value, not descriptor address

1 participant