Skip to content

Runtime: preserve D3D12 fence rewinds across CPU and GPU signals (D3D-472) - #4577

Open
gabrielsteglich wants to merge 914 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/d3d12-fence-rewind
Open

gabrielsteglich wants to merge 914 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/d3d12-fence-rewind

Conversation

@gabrielsteglich

Copy link
Copy Markdown
Contributor

Claimed as D3D-472 in the coordination issue.

Depends on: #4224

What and why

The Vulkan layer used one monotonically increasing timeline for each D3D12 fence. After Signal(4) on a fence at 10, it still reported 10 and released a new Wait(8) before the producer supplied the data. A CPU signal could also be deferred behind an outstanding GPU signal.

  • Track the logical fence value separately from each Vulkan queue’s progress tickets. CPU signals take effect immediately and GPU signals publish on completion. A satisfied wait stays satisfied, and later waits use the current fence value.
  • Carry the producer’s Vulkan ticket into GPU waits, including after a CPU signal relays completed GPU work. Preserve accepted work when a consumer queue is released and forward waits when a held tile mapping is a no-op or is rejected. Runtime: preserve queue order for sparse buffer tile mappings #4224 supplies deferred tile mapping.
  • Keep the existing dispatcher and cancel losing ANY registrations. A deterministic regression covers two D3D12 queues that share a Vulkan queue but use separate progress semaphores.

The fence changes are in e9715504. The branch includes #4224’s bc15a8bb for the sparse-queue integration.

Tested

Windows 11 Pro build 26300, MSVC 19.44.35229, Windows SDK 10.0.26100.0, Vulkan SDK 1.4.363.0, RelWithDebInfo. NVIDIA GeForce RTX 3090, driver 621.01. Vulkan validation enabled, with implicit layers disabled.

  • Full CTest: 139 passed, 8 skipped, 1 disabled, 0 failed. Nine focused fence, queue and sparse tests passed with no Vulkan VUID or synchronization-hazard messages.
  • Fence timing and event tests matched native D3D12 on the RTX 3090 and WARP. These cover 10 → 4 → 12, events registered before and after the rewind, CPU 15 → 20 while GPU 10 is pending, and COPY signaling 4 while DIRECT waits for 8.
  • Queue handover matched every readback in 373 Vulkan-layer cases and 371 native D3D12 cases. On the unchanged baseline fence code, the new COPY/DIRECT case released DIRECT early and returned 512 incorrect words.
  • Mock tests cover shared-queue completion order, device loss, ANY cancellation, and sparse waits carried through rejected mappings and consumer queue destruction.

Checklist

  • Synthetic tests only. No game data, keys, or decryption.

AI-assisted (OpenAI Codex).

# Conflicts:
#	docs/design.md
# Conflicts:
#	docs/character_skeleton.md
# Conflicts:
#	docs/design.md
# Conflicts:
#	docs/design.md
ItsNotRexed and others added 6 commits November 22, 2026 18:52
- replay_cpu_bench: ItsNotRexed#3693 moved a draw's render targets and vertex buffers into Draw::views (D3D-391); the bench
  builds a DrawViews block instead of writing the old inline arrays.
- xgameruntime_user_test links file_system.cpp, which now defines rt::fs::game_dir that xgameruntime.cpp calls.
- check_sparse_queue_family: a vkCreateInstance refused because the api_dump/validation layer is not installed is
  the documented "layer absent" skip (77), not a failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This reverts commit 718f105, reversing
changes made to 9aa16b2.
Defer reserved-buffer tile updates and copies alongside held command batches and signals. Keep sparse backing alive, resolve source mappings at submission order, and carry waits past no-op or rejected binds.

Compare all tile readbacks with native D3D12 for CPU and COPY queue signals, and test wait forwarding with a fake incomplete Vulkan producer.
- test_bary_fallback: ItsNotRexed#3647 (BUILD-1046) made a missing input folder exit 2 with "does not exist"; the test from
  ItsNotRexed#1379 still expected exit 1.
- test_format_decode_branch: the f16 reference uses the interpreter's pinned half_to_float (a NaN half widens to
  the canonical quiet NaN) instead of struct's '<e', whose NaN payload changed in Python 3.14 (CPython gh-130317).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@Kam471 Kam471 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.

Built the five targets at e9715504 on Windows 11, RTX 5070 Ti, RelWithDebInfo, and ran each: exit 0 for all.

  • d3d12_fence_timing_test: NVIDIA GeForce RTX 5070 Ti: COPY fence value 4, DIRECT after Wait(8) completed early 0; WARP: CPU fence 10 -> 4 -> 12, old event retained 1, new event set early 0; WARP: CPU signals 15 -> 20, queued signal then 10, old event retained 1, new event set early 0; WARP: COPY fence value 4, DIRECT after Wait(8) completed early 0.
  • d3d12_queue_handover_test: Vulkan layer 373 cases, every one exact; host D3D12 371 cases, every one exact; COPY rewound 10 -> 4; DIRECT waited for 12 and read the exact texture and buffer.
  • vk_fence_dispatcher_sync_test: stable queue scan, latched waits, CPU rewind, re-entrant cancel(), mark_device_lost() wake and DEVICE_LOST drain all ok.
  • vk_sparse_queue_order_test: deferred no-op and rejected mappings preserve GPU waits (the two expected held tile mapping failed when it was released lines are printed).
  • d3d12_buffer_tiles_test: 12 full tiles match across all readbacks on the held-batch CPU-signal and copy-queue-signal paths.

git diff --check clean. The numbers match the PR body (373/371, and the baseline early-release case is covered).

Two coordination notes:

  1. The branch carries #4224 (bc15a8bb), which is still open (MERGEABLE). That dependency is declared and works here, but #4577 can only land after #4224, and merging it before would bring the sparse-mapping commit with it.
  2. #4557 and #4570 also edit runtime/src/vulkan_backend.h around the execute/Signal paths, and #4557 edits runtime/test/d3d12_queue_handover_test.cpp; all three need a rebase/fresh run whichever lands first.

@justr4mzi

Copy link
Copy Markdown
Contributor

Verified PR #4577 on Windows 11 (25H2 26200.9974) / AMD Radeon RX 6700 XT (gfx1031, Adrenalin 26.11.2, Vulkan 1.4.315, MSVC 19.44.35230.0, Vulkan SDK 1.4.363.0) at head e9715504:

  • Build: configured Ninja RelWithDebInfo cleanly and built all five targets ([19/19], exit 0).
  • CTest (standard & LEONIDA_VK_VALIDATION=1):
    • Standard: 5/5 passed (12.06 s): vk_fence_dispatcher_sync (0.44 s), d3d12_queue_handover (7.86 s), d3d12_buffer_tiles (0.90 s), d3d12_fence_timing (2.33 s), vk_sparse_queue_order (0.05 s).
    • LEONIDA_VK_VALIDATION=1: 5/5 passed (10.32 s): vk_fence_dispatcher_sync (0.26 s), d3d12_queue_handover (7.64 s), d3d12_buffer_tiles (0.44 s), d3d12_fence_timing (1.94 s), vk_sparse_queue_order (0.02 s).
  • Direct AMD RX 6700 XT runs under LEONIDA_VK_VALIDATION=1 (0 Vulkan validation errors, exit 0 for all 5):
    • d3d12_fence_timing_test.exe: standalone Vulkan, native AMD RX 6700 XT D3D12, and WARP all matched on CPU rewinds (10 -> 4 -> 12), queued signal rewinds (15 -> 20, queued then 10), and cross-queue COPY rewind 4 / DIRECT after Wait(8) (completed early 0).
    • d3d12_queue_handover_test.exe: COPY rewound 10 -> 4; DIRECT waited for 12 and read the exact texture and buffer on both Vulkan layer (373 cases passed) and Host D3D12 (AMD Radeon RX 6700 XT, 371 cases passed), plus never-signaled fence teardown without hanging.
    • vk_fence_dispatcher_sync_test.exe: device: AMD Radeon RX 6700 XT (validation on), dispatcher re-entrant/device-loss tests + logical fence: stable queue scan, latched waits, CPU rewind and device loss ok.
    • vk_sparse_queue_order_test.exe: Sparse queue order: deferred no-op and rejected mappings preserve GPU waits.
    • d3d12_buffer_tiles_test.exe: 12 full tiles match across all readbacks on Vulkan replay and Native D3D12 (original order, held batch CPU Signal, held batch copy-queue Signal).
  • CTest registration, docs & hygiene:
    • tests/test_ctest_registration.py: 4/4 OK (0.422s).
    • python -I -m unittest discover -s tests -p "test_docs*.py": 20/20 OK (19.040s).
    • scripts/check_no_game_data.py & git diff --check upstream/main...HEAD: clean (0).

Code review of LogicalFence / QueueProgress / FenceWaitDispatcher / VulkanQueue::submit looks sound: collecting completed GPU signals under the same mutex as host Signal, preserving 物理 VkQueue FIFO prefix ordering (completed_prefixes_), and publishing pending_ transactionally with vkQueueSubmit avoids lost wakeups and VkSemaphore monotonicity violations cleanly.

AI-assisted (Gemini, Antigravity).

@Flyander Flyander 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.

The per-physical-queue prefixes preserve ordering within one Vulkan queue, but the final publication loop still treats pending_ insertion order as completion order across distinct queues. D3D12 allows a fence to be rewound and specifies that when signals race across queues, the value from the last Signal to complete remains. Please preserve or explicitly serialize that cross-queue completion order and add a deterministic regression.

Comment thread runtime/src/vulkan_backend.h Outdated
const auto prefix = std::find_if(completed_prefixes_.begin(), completed_prefixes_.end(),
[physical](const auto& entry) { return entry.first == physical; });
if (prefix != completed_prefixes_.end() && i <= prefix->second) {
publish_locked(signal.value, signal.point, ready);

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.

[P2] Preserve completion order across different physical queues. If pending_ contains Q1 Signal(10) followed by Q2 Signal(4), and Q2 completes first while Q1 completes last, a poll that sees both timeline counters complete publishes 10 then 4 here and leaves completed_ == 4. D3D12 requires the last completing signal to win, so the expected value is 10 (and a new Wait(8) must not be released from the stale 4 state). The prefix calculation proves ordering only within one VkQueue; it gives no ordering between Q1 and Q2. Please preserve that ordering or serialize these signals, with a deterministic two-queue regression. Microsoft documents the rewind/race rule: https://learn.microsoft.com/en-us/windows/win32/direct3d12/user-mode-heap-synchronization

ItsNotRexed and others added 2 commits November 22, 2026 22:07
Merges that each passed alone but clash together:
- v_cmp_class_f64: the earlier cmp_class_f64 (685d16e) (operand-form checks, test_cmp_class_f64) and the later f64 branch
  in cmp_class both handled the opcode; f64 goes to cmp_class_f64 again, f16 stays in cmp_class.
- rdna2spirv CLI tests: spirv-as/spirv-val now run in the output folder with the staging file's bare name, so
  the test doubles resolve it against cwd; assemble_spirv decodes the output only when it is bytes. (The doubles
  had been writing .spirv-*.tmp files into the repository root.)
- ps_w64 fixtures (TEST-722): an 18th fixture (ps_w64_a_discard) landed; its killed lanes export nothing and
  keep the clear value.
- first_light: a run without an OBJ removes mesh.bin, and harness_env reads manifest["files"]; batch_glb's stats
  name failures and dropped textures; run_gpu_tests reports a frame never written as a missing readback
  (TEST-837).
- make_game TRANSLATION_SOURCES and runtime.yml's paths include spirv_opt.py and report_paths.py (and
  wave64_emulate_opt.py), which the translator imports.
Repo rules: stdout guard on six tools; encoding on two opens (gen_gdk_runtime_classes' helper is read_utf8);
newline on one write; anim_skeleton_match's joaat encodes like hashdict.joaat; test_feature_scan's new test is
listed with the others its globals() runner reaches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This reverts commit ce318cd, reversing
changes made to a78f170.
gabrielsteglich and others added 4 commits November 23, 2026 00:11
# Conflicts:
#	docs/runtime_imports.md
#	runtime/CMakeLists.txt
#	runtime/shims/xgameruntime.cpp
#	runtime/test/xmem_test.cpp
#	tools/rdna2spirv.py
- rdna2spirv: %fmt_size_tab (main's typed-load size table) registers its length and entry constants when a load
  first uses it; created at assembly, %c128 came after the OpTypeArray naming it and spirv-val refused
  buffer_store_format_d16 modules (test_u16_high_half).
- test_vs_packed_inputs matches main's wording of the same SHADER-644 rule ("mixed component types").
- test_mutations: the v_mul_legacy_f32 anchor follows the SHADER-340 flushes (it had stopped matching on main).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ItsNotRexed#2887 added the fixture to the M2 build; with no entry in OTHER_HARNESS the GPU suite reported it as
"no checker defined".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@itsonlysimbo

Copy link
Copy Markdown
Contributor

Tested 0429d4b9 merged onto main d0835dd9 (2 behind; merges cleanly) on RTX 4070, NVIDIA 621.14, Windows 11 (10.0.26300), MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363: pass.

  • d3d12_fence_timing, d3d12_fence_events, d3d12_fence_waiter, d3d12_queue_handover, d3d12_buffer_tiles, vk_fence_dispatcher_sync and the new vk_sparse_queue_order pass.
  • Those seven, rerun 20 times with ctest -j 4: 20/20 runs all pass.
  • ctest: 146 passed, 10 skipped, 0 failed; run_gpu_tests.py: 164/210 passed, 46 skipped, 0 failed, same as main d0835dd9.

AI-assisted (Claude Code).

#4576 (Report Vulkan pipeline statistics write failures). POSTED.

Tested b82cb5e4 on RTX 4070, NVIDIA 621.14, Windows 11 (10.0.26300), MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363: pass.

  • vk_pipeline_check_cli passes.
  • ctest: 144 passed, 10 skipped, 1 failed; run_gpu_tests.py: 164/210 passed, 46 skipped, 0 failed, same as main d0835dd9. d3d12_present failed once in this run; it fails the same way intermittently on main d0835dd9 on this machine (once in three full runs, 5/5 passes alone), so it is not from this change.

AI-assisted (Claude Code).

@0klavair

Copy link
Copy Markdown

Tested c7cc36bc (merged onto main 3eb4410b) on NVIDIA GeForce RTX 5060 (Blackwell), driver 621.01, Windows 11 23H2 22631.6199, MSVC 19.44 (VS 2022 Build Tools), Vulkan SDK 1.4.363: pass.

No game files. AI-assisted.

@Exopus-0x65f7ad0

Copy link
Copy Markdown

Tested c7cc36bc on Windows 11 (26300), RTX 5060 Ti / 621.14, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363.0, RelWithDebInfo, clean build with -DLEONIDA_LLVM_MC (translated-shader D3D12 gate tests included), full LEONIDA_VK_VALIDATION=1 ctest -j4: 162/162 passed, 0 VUIDs, 0 build errors. AI-assisted (Claude Code).

@Vonsek

Vonsek commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested c7cc36b on Windows 11 (MSVC BuildTools 2022, Ninja, RelWithDebInfo, -j 4; no Vulkan validation layer installed), one GPU at a time, device line confirmed: AMD Radeon RDNA2 iGPU (driver 26.10.1) and NVIDIA RTX 5080 (driver 616.92). Ran ctest -R "^(d3d12_buffer_tiles|d3d12_fence_timing|d3d12_queue_handover|vk_fence_dispatcher_sync|vk_sparse_queue_order)$" (the tests this PR changes): pass on both GPUs, 5/5 each. No game files.

AI-assisted.

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.

9 participants