Skip to content

vulkan: a barrier that keeps an image's layout adds no tracker journal entry, and tests for the journal (VK-TRACKER-NO-COPY) - #1284

Open
DadaCap wants to merge 6 commits into
ProjectLeonida:mainfrom
DadaCap:vk-tracker-undo
Open

DadaCap wants to merge 6 commits into
ProjectLeonida:mainfrom
DadaCap:vk-tracker-undo

Conversation

@DadaCap

@DadaCap DadaCap commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: VK-TRACKER-NO-COPY

Narrowed on 2026-11-25. This pull request replaced the copy of the whole LayoutTracker per submission with an undo journal. #1723 merged the same journal into main, so after merging main (its version taken in both files) only the part it does not have is left: 7 net lines in vulkan_replay.h and the tests.

What

  • A change to the layout an image already has adds no journal entry. to_attachment and the texture barrier in emit_commands called LayoutTracker::set even when every piece already had the new layout. With the journal open, the first such call per image and submission copies that image's entry (two allocations). They now call set only when a piece really changes, or for a discard. The barrier itself is still recorded. initialize() updates the tracker itself for an image's first use.
  • Tests for the journal, which main has none of: begin/rollback/commit (a changed layout put back, a second change keeping the first note, an image tracked since begin forgotten again, a forgotten image brought back, commit keeping the change), and a same-layout barrier or attachment reuse allocating nothing while still recording its barrier.

Tests

RTX 5080, NVIDIA 621.24, Windows 11, VS 18 RelWithDebInfo, head 8532369 (main 0d80bc5 merged in): ctest without the tests that match present|window|splash|pad|xinput|movie (they open windows): 423 of 423 pass, replay_texture_barrier_test among them. Not run: those excluded tests, other GPUs, Linux, a retail boot of this head.

AI-assisted (Claude Code).

🤖 Generated with Claude Code

…s changes back (VK-TRACKER-NO-COPY)

execute_now copied the whole LayoutTracker for every submission, so that a
failed one leaves the layouts as they were: two heap allocations per tracked
image for each ExecuteCommandLists, whatever the lists touch. On a retail
boot's loading screen that copy took most of the submitting thread.

LayoutTracker::begin() now notes what an image had before its first change,
rollback() puts it back and commit() drops the notes; execute_now changes the
device's tracker under tracker_mutex_, which it already held around the copy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@akimfomin

Copy link
Copy Markdown
Contributor

I tested an allocation case on the exact PR head c74f8f38340f91218b16b31926a12e240f7f91f3. A barrier that keeps the current image layout still needs to order memory. Enhanced texture-barrier replay and attachment reuse nevertheless call LayoutTracker::set() and copy the old layout vector into the undo journal even when the tracker already has the required state.

The patch below uses the layouts those two paths already read. Both synchronization calls still run, and discard and layout changes still update the tracker. The allocation regression fails twice on the unmodified PR head and passes with the patch. The new test checks the emitted access scopes and rollback for a mixed-mip range.

On a synthetic CPU-only replay with 8,192 tracked images and 32 touched per submission, the parent 6261ca91, this PR, and the follow-up made 16,385 → 64 → 0 allocations for the unchanged-layout case. All three emitted all 32 barriers. Across nine rotating rounds, the median was 3.57 → 1.62 µs from the PR head to the follow-up. For real layout changes plus rollback, both made 64 allocations and medians were 3.67 → 3.65 µs. Those figures cover the mock CPU replay on Windows with Clang 23.1.6, not GPU or title performance.

Four standalone CPU tests passed (replay_texture_barrier, replay_readback_stages, replay_copy_offset, replay_khr_as_copy_postbuild). PortBridge preflight looked for related tracker work before this check. Codex (GPT-6 family) assisted with the patch and tests.

Patch against the exact PR head, including the reproduction
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index c8bcd4d..0ec4c39 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -2322,6 +2322,7 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf
     const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate);
     auto pieces = current(tracker, a.id, range, layout);
     initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker);
+    bool layout_changed = false;
     for (const auto& piece : pieces) {
         if (piece.layout == layout) {
             // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier.
@@ -2330,8 +2331,9 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf
         }
         image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout,
                       VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages);
+        layout_changed = true;
     }
-    if (tracker) tracker->set(a.id, range, layout);
+    if (tracker && layout_changed) tracker->set(a.id, range, layout);
 }
 
 } // namespace detail
@@ -3674,7 +3676,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
             if (pieces.size() > few.size()) many.resize(pieces.size());
             VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data();
             std::uint32_t barrier_count = 0;
+            bool layout_changed = discard;
             for (const auto& piece : pieces) {
+                layout_changed |= piece.layout != new_layout;
                 VkImageMemoryBarrier2& b = barriers[barrier_count++];
                 b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2};
                 b.srcStageMask = src.stages;
@@ -3694,7 +3698,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
             dependency.imageMemoryBarrierCount = barrier_count;
             dependency.pImageMemoryBarriers = barriers;
             vk.pipeline_barrier2(command_buffer, &dependency);
-            if (tracker) tracker->set(id, range, new_layout);
+            // Same-layout barriers still order memory, but leave nothing to journal.
+            if (tracker && layout_changed) tracker->set(id, range, new_layout);
         } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
             if (p.skip) continue;
             const VulkanAccess state = vulkan_access(d3d12_state::render_target, false);
diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp
index 8639b9b..49db7a4 100644
--- a/runtime/test/replay_texture_barrier_test.cpp
+++ b/runtime/test/replay_texture_barrier_test.cpp
@@ -68,6 +68,12 @@ void VKAPI_CALL record_barrier2(VkCommandBuffer, const VkDependencyInfo* info) {
         g_barriers.push_back(info->pImageMemoryBarriers[i]);
 }
 
+void VKAPI_CALL record_memory_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
+                                      std::uint32_t count, const VkMemoryBarrier* barriers, std::uint32_t,
+                                      const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {
+    if (count == 1 && barriers[0].srcAccessMask && barriers[0].dstAccessMask) ++g_calls;
+}
+
 int failures = 0;
 void expect(bool ok, const char* what) {
     if (!ok) {
@@ -193,6 +199,59 @@ int main() {
         expect(tracker.layout(id, 1) == transfer_src && tracker.layout(id, 0) == mip0, "commit keeps the change");
     }
 
+    // Reusing a render-target layout still needs synchronization, but does not need an undo entry.
+    {
+        const VkImageSubresourceRange all_mips{VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1};
+        const VkImageSubresourceRange last_mip{VK_IMAGE_ASPECT_COLOR_BIT, mips - 1, 1, 0, 1};
+        tracker.set(id, all_mips, attachment);
+        tracker.begin();
+        tracker.set(id, last_mip, transfer_src);
+        tracker.rollback();  // warm the undo map's buckets before measuring
+
+        CommandList list;
+        expect(list.barrier(TextureBarrier{y::render_target, y::render_target, a::render_target, a::render_target,
+                                           l::render_target, l::render_target, id, all, 0}) &&
+                   list.close(),
+               "record a barrier that keeps the render-target layout");
+        PreparedList prepared;
+        expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare a same-layout barrier");
+        g_barriers.clear();
+        g_calls = 0;
+        tracker.begin();
+        const std::size_t before = g_allocations;
+        emit(prepared, cb, vk, &tracker);
+        const std::size_t allocations = g_allocations - before;
+        if (allocations) std::fprintf(stderr, "same-layout emit allocated %zu times\n", allocations);
+        expect(allocations == 0, "same-layout emit does not allocate an undo entry");
+        expect(g_calls == 1 && g_barriers.size() == 1 && g_barriers[0].oldLayout == attachment &&
+                   g_barriers[0].newLayout == attachment && g_barriers[0].srcAccessMask && g_barriers[0].dstAccessMask,
+               "same-layout emit still records one barrier with both access scopes");
+        tracker.set(id, last_mip, transfer_src);
+        tracker.rollback();
+        expect(tracker.layout(id, mips - 1) == attachment, "rollback restores a change after same-layout emit");
+
+        tracker.set(id, last_mip, transfer_dst);
+        g_barriers.clear();
+        tracker.begin();
+        emit(prepared, cb, vk, &tracker);  // the first mips agree; only the last actually changes
+        expect(tracker.layout(id, mips - 1) == attachment, "update reaches the first different mip");
+        tracker.rollback();
+        expect(tracker.layout(id, 0) == attachment && tracker.layout(id, mips - 1) == transfer_dst,
+               "rollback restores the different mip without changing the others");
+
+        tracker.set(id, last_mip, attachment);
+        const detail::PreparedDraw::Attachment target{image, id, all_mips};
+        vk.pipeline_barrier = record_memory_barrier;
+        g_calls = 0;
+        tracker.begin();
+        const std::size_t before_attachment = g_allocations;
+        detail::to_attachment(vk, cb, target, attachment, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
+                              VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, &tracker, false);
+        expect(g_allocations == before_attachment, "reusing an attachment does not allocate an undo entry");
+        expect(g_calls == 1, "reusing an attachment still orders its writes");
+        tracker.commit();
+    }
+
     if (failures) return 1;
     std::printf("replay_texture_barrier_test: OK\n");
     return 0;

A texture barrier or an attachment reuse whose pieces are already in the
wanted layout still orders memory, but called LayoutTracker::set() and so
copied the image's layouts into the undo notes for nothing.

Patch and test by akimfomin, from the review of the pull request: the two
paths use the layouts they already read. Discards and real layout changes
still update the tracker.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@DadaCap

DadaCap commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@akimfomin thank you, that is a real gap and the patch is right: initialize() sets the tracker itself for the pieces it moves out of UNDEFINED, so after it a piece that already has the wanted layout needs no set(), and a discard still counts as a change in the barrier path.

I applied your patch as it is (commit message credits you) and pushed it to this branch. On the new head, RTX 5080 (NVIDIA 621.24), Windows 11, VS 18 RelWithDebInfo: replay_texture_barrier_test (with your same-layout and mixed-mip cases), vk_command_replay_test, vk_queue_query_sync_test and d3d12_draw_test pass. Not run: the whole ctest set, other GPUs.

AI-assisted (Claude Code).

… change only, never of a release

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@DadaCap

DadaCap commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Merged current main (507029d1e) into the branch; no force-push.

Two conflicts, both with main's new release barriers (a piece released before it was ever used has nothing to order):

  • emit, texture barrier: main's continue for such a piece comes first, then this branch's layout_changed |= piece.layout != new_layout; after the loop main's if (barrier_count) stays and the tracker is told only of a real change, and never of a release: if (tracker && !release && layout_changed) tracker->set(...).
  • replay_texture_barrier_test: main's cases 3 and 4 run first (they go on from case 2), then the rollback and same-layout cases of this branch. The rollback case tracked image id 2 as "new", which main's cases now track already, so it uses an id of its own.

On the merged head, RTX 5080 (NVIDIA 621.24), Windows 11, VS 18 RelWithDebInfo: replay_texture_barrier_test, vk_command_replay_test (with main's case L), vk_queue_query_sync_test and d3d12_draw_test pass. Not run: the whole ctest set, other GPUs.

AI-assisted (Claude Code).

@akimfomin

Copy link
Copy Markdown
Contributor

DadaCap, PortBridge checked V2 layout-range coalescing on your exact ddda2857 head with 5959a09 in place. The context-refreshed patch preserves the undo journal and release path. In a synthetic CPU partial-release fixture it used 3 barrier records instead of 12, with identical per-cell layouts, synchronization scopes and call order. The tracker restored all original layouts on rollback and kept the committed subset through a later rollback. Both existing focused barrier and state-map tests passed in each arm.

Exact-head compatibility patch, test and logs. Separately, V2 on main b4b7756 passed native Vulkan synchronization validation on RTX 4070 Ti SUPER and matched all 699,040 texels. That fixture reduced 97 records to 13 in the same two enhanced calls. The public CPU matrix includes a mostly-undefined case that costs about 10.7% more. This can be a separate follow-up if useful. AI-assisted with Codex.

@DadaCap

DadaCap commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@akimfomin thank you for checking it on this exact head. The range coalescing is useful, and I would keep it a separate follow-up as you suggest: this pull request then stays the undo journal alone, and yours can be reviewed against its own numbers (3 records instead of 12, and the mostly-undefined case that costs 10.7 % more). If you open it, I will not write a competing one. AI-assisted (Claude Code).

@tiguan26 tiguan26 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving ddda285 (c74f8f3 + 5959a09 + the merge of main 507029d). Cross-built with clang-cl 19 + xwin and run under Wine 11.22 on llvmpipe (Mesa 25.2.8).

  • Full suite (312 tests) on the base 6261ca9, on c74f8f3 and on 5959a09: no test goes from pass to fail on either head. The failures are the known Wine/llvmpipe ones, identical on the base.
  • This head: the merge's net change against 507029d is still the three files of this PR. The one combined condition, tracker && !release && layout_changed, keeps #1055's rule that a release is never recorded next to this PR's skip for an unchanged layout. Every test either PR touches passes here: replay_texture_barrier, vk_command_replay, vk_queue_query_sync (its device-loss case is the failed-submission path), command_list, d3d12_com, d3d12_close_parity, d3d12_draw, and the other replay_* tests (16 of 16).
  • Code: every LayoutTracker method that changes entries_ (track, set, forget) calls note() first, and the rest are const. In execute_now the only return is before begin(), so every path after it reaches commit() or rollback() under tracker_mutex_. In to_attachment, skipping set() when nothing changed is safe because initialize() already records the pieces it moves out of UNDEFINED (tracker->set(id, piece.range, layout)).
  • Nit, not blocking: the copy also rolled back when something threw between begin() and the end (e.g. a bad_alloc from the vectors filled there). Now that leaves half-applied changes with noting_ set until the next begin(). A guard that rolls back unless commit() ran would keep that.

AI-assisted (Claude).

Conflicts with the depth UAV barrier work: the enhanced texture barrier keeps this
branch's tracker line (a barrier that keeps the layout notes nothing) and main's
finish_depth_uav_barrier after it; the test keeps this branch's rollback and
same-layout cases and main's depth_uav_barriers.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@DadaCap

DadaCap commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@tiguan26 thank you for the review and for the full-suite run. main moved under it right after (the depth UAV barrier work touches the same two places), so I merged main into the branch instead of rebasing: head is now 2c178819f, nothing force-pushed, the commits you reviewed are untouched.

The two conflicts and how they are resolved:

  • vulkan_replay.h, enhanced texture barrier: this branch's if (tracker && !release && layout_changed) tracker->set(...) and, after it, main's if (!release) finish_depth_uav_barrier(p, new_layout);.
  • replay_texture_barrier_test.cpp: this branch's rollback and same-layout cases, then main's depth_uav_barriers(cb).

On the merged head (MSVC, Windows 11): gta6rt builds; replay_texture_barrier_test, replay_clear_gate_test and typeless_rtv_test pass. Not run on this head: the full suite and a GPU run. AI-assisted (Claude Code).

@akimfomin

Copy link
Copy Markdown
Contributor

DadaCap, PortBridge refreshed the separate Vulkan range-coalescing follow-up we discussed. The pinned patch, fixtures, and results apply to current main 3f81d46a. A clean combination with your 2c178819 also passed the state-map, replay, geometry, and rollback checks. The partial-release case emits 3 records instead of 12, with the same per-cell scopes and layouts. All three ordered operations emit 5 instead of 14.

Across two paired CPU runs, large stripes went from 640 to 2 records and spent 42–47% less time in the partition routine. Almost-undefined ranges took 0.55–4.66% longer. The 8×32 checkerboard took 1.77% and 16.41% longer with noisy pairs. The earlier Vulkan run at b4b7756e matched 699,040 texels per arm on the RTX 4070 Ti SUPER and reduced 97 records to 13. The current native fixture builds. Execution on that revision is still open.

GitHub currently restricts participation in the coordination issue for this account, so the patch is available here for review. PortBridge ran the comparison. AI-assisted by Codex.

clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 25, 2026
… & journal LayoutTracker in place (#1742, #1284)

Ports and adapts two high-impact upstream fixes to eliminate world-entry render-thread stalls:

1. Unlocked pipeline compilation + per-slot pinning (adapted from ProjectLeonida/mandy#1742 by IlyassRS3, GPL-3.0):
   - Separates VulkanContext pipeline registration/lookup (pipeline_mutex_ leaf lock + per-slot pin counts and built-handle cache) from resource_mutex_.
   - Adds PipelineCompiles in vulkan_replay.h so VulkanQueue::execute_now() collects unbuilt compute/graphics pipelines on pass 0, retires pass-0 transient helper state, releases tracker_mutex_ and resource_mutex_, compiles unlocked (while only per-slot pins keep active PSOs alive), and re-prepares on pass 1 against current resources.
   - Zero extra passes or heap allocations on the warm path; preserves BvhBuildGate, StandinReason, pending_compile_pipeline(), and UAV barrier elision.

2. In-place LayoutTracker journaling (adapted from ProjectLeonida/mandy#1284 by DadaCap, GPL-3.0):
   - Adds begin()/commit()/rollback() epoch-based undo journaling to open-addressed LayoutTracker in vulkan_replay.h.
   - Mutates context_.tracker_ in place under tracker_mutex_ in VulkanQueue::execute_now() instead of deep-copying tens of thousands of live texture entries on every ExecuteCommandLists.
   - Same-layout barriers and attachment reuses allocate zero undo entries.

Verified: 12/12 Vulkan-validated CTests PASS (0 validation errors), check_no_game_data.py 0 violations.
… replaces ours; the same-layout skip and the tests stay

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DadaCap DadaCap changed the title vulkan: a submission changes the layout tracker in place instead of copying it (VK-TRACKER-NO-COPY) vulkan: a barrier that keeps an image's layout adds no tracker journal entry, and tests for the journal (VK-TRACKER-NO-COPY) Nov 25, 2026
@DadaCap

DadaCap commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Merged main in (head 8532369). #1723 brought the same undo journal, so this is now only the same-layout skip and the journal's tests; title and description updated. @tiguan26, your approval was for the larger version, so please look again if you have a moment. AI-assisted (Claude Code).

@tiguan26 tiguan26 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Rechecked 8532369 and approving the smaller version.

I merged it into current main (b9320a1) with no conflicts and cross-built the Windows runtime (clang-cl 19, xwin SDK), running under Wine 11.22 with llvmpipe. replay_texture_barrier_test passes with the PR. With main's vulkan_replay.h it fails both new checks ("same-layout emit allocated 2 times" and "reusing an attachment does not allocate an undo entry"), so the test catches the change. replay_clear_gate_test and replay_readback_stages_test still pass.

I also checked the one place this could lose state. In to_attachment, initialize() already writes the tracker for every UNDEFINED piece it transitions, so skipping the final set when no barrier changed a layout records nothing less. In the barrier path, discard and any piece whose layout differs both still set the flag.

AI-assisted (Claude).

@github-actions github-actions Bot added the needs rebase Conflicts with the base branch: rebase it on main label Nov 26, 2026
…arguments with the same-layout skip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwRYcpySx4P4ncQ3wD5
@OreoFR

OreoFR commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Merge test for the #2464 campaign on an 8 GB laptop (profile M), done for the author. Main ec91d69 was merged without conflict, in one tree together with #1705, #1694 and #1284, which touch different code. The numbers were recomputed from the raw logs. AI-assisted (Claude Code, Claude Opus 5.5).

RUN dada3 | 2026-11-27 | OreoFR | AI-assisted: Claude Code (Claude Opus 5.5)
BASE:        main ec91d695c + #1705 (abe3f2042) + #1694 (3768be502) + #1284 (7358f3261), merged cleanly | shaders: main translation + #2447 (one-lane) pack
MACHINE:     RTX 4070 Laptop 8 GB, laptop (profile M) | NVIDIA 621.40 | Windows 11 | 40 GB
RECIPE:      documented + DEVIATIONS: ASYNC_PIPELINES=1 ASYNC_MIN_BYTES=1048576 VALUE_WAIT_TIMEOUT_MS=30000 MAP_READBACK=1 DEVICE_TYPE=6 ARENA_MB=4095 DEVICE_FAULT=1
OS/DRIVER:   TdrDelay 60
TARGET:      regression check against regA (main ec91d695c, same recipe and caches) | PREDICTED: world reached, no loss
MEASURED:    world entry ~237 s (regA 223 s) | 0 device lost, 0 exceptions (regA 0 / 0) | gpu-stall lines 2 (regA 10)
END:         stopped by our script 56 s after world entry (t=293 s): the known display stop after world entry is the same on main
CACHES:      warm | RUN 1 of 1
VERDICT:     no regression seen (n=1)
  • replay_texture_barrier_test from this head: OK. Built against main ec91d69, it fails (FAIL: same-layout emit does not allocate an undo entry, FAIL: reusing an attachment does not allocate an undo entry, exit 1). The fix is shown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants