d3d12: finish CompileActivity before checkpointing and retry deferred cache snapshots #1756

Open
github-bot wants to merge 2 commits from github-bot/gh-1756 into main AGit
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 11:20 UTC · original
IlyassRS3:fix/startup-cache-checkpoint-race → main · +172 −32 · 6 files · 2 commits · open

Item ID: RT-STARTUP-CACHE-CHECKPOINT-RACE
Claim: #1608
Addresses finding: #1608 (LEONIDA_STARTUP_CACHE_CHECKPOINTS=1 wrote nothing during a 200 s run reaching world start)

Root cause

Two bugs in runtime/shims/d3d12_vulkan_device.cpp prevented startup cache checkpoints from saving during active world-start compilation bursts:

  1. maybe_checkpoint(cache) ran while CompileActivity still held device_.active_compiles >= 1: both PipelineState::build_compute() (lines 8038, 8091) and PipelineState::build() (lines 8202, 8386) kept CompileActivity activity(device_.active_compiles) alive across maybe_checkpoint(cache). When the build ran on a submitting or PipelineWorkers thread, the PipelineCompiler worker woke up before the caller returned, saw active_compiles != 0, and skipped save_session_pipeline_cache().
  2. Deferred checkpoints still burned the 120-second cooldown: whenever a checkpoint job was skipped because active_compiles != 0 or has_compile_waiter() (either before save_session_pipeline_cache() at line 8110 or after the size query at line 1348), maybe_checkpoint() unconditionally pushed next_checkpoint out by another 120,000 ms (2 minutes). A single deferral at t = 120 s pushed the next attempt to t = 240 s — past the world-start crash at ~195–200 s, leaving the cache directory empty.

Changes

  • runtime/src/pipeline_cache_store.h:
    • Added CheckpointOutcome (saved, deferred, skipped) and portable atomic CheckpointSchedule (try_claim, complete, abort_claim). Deferred checkpoints and queue-submission aborts stay immediately eligible on the next compile completion instead of burning default_checkpoint_interval_ms (120 s); saved and skipped (empty/over-cap/I/O error) advance the deadline by the full interval with saturation below the in_flight sentinel.
  • runtime/shims/d3d12_pipeline_checkpoint.h:
    • Added idempotent CompileActivity::finish() (with acq_rel ordering) so callers can release their active-compile count before queueing a checkpoint while keeping RAII cleanup on early returns.
  • runtime/shims/d3d12_vulkan_device.cpp:
    • Replaced raw next_checkpoint atomic with CheckpointSchedule checkpoint_schedule.
    • In build_compute(), publish pipeline_.pipeline, unlock variants_mutex_, and call activity.finish() before maybe_checkpoint(cache); in build(), call activity.finish() before maybe_checkpoint(cache).
    • Updated save_session_pipeline_cache() to return CheckpointOutcome (returning deferred if active_compiles or has_compile_waiter() became active during the size query) and wired maybe_checkpoint() to checkpoint_schedule.complete(..., outcome).
  • runtime/test/pipeline_cache_store_test.cpp:
    • Added test_checkpoint_schedule() covering due-time gating, in-flight coalescing, deferred immediate retry, abort_claim, saved/skipped 120 s cooldown, and near-UINT64_MAX saturation.

Verification

  • AI-assisted: yes
  • GPUs tested: none (developed on macOS without Windows SDK or Vulkan SDK)
  • Tested locally:
    • clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/pipeline_cache_store_test.cpp: PASS.
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/pipeline_cache_store_test.cpp: PASS.
    • python3 -I scripts/check_no_game_data.py runtime/src/pipeline_cache_store.h runtime/shims/d3d12_pipeline_checkpoint.h runtime/shims/d3d12_vulkan_device.cpp runtime/test/pipeline_cache_store_test.cpp: PASS.
    • python3 -I tests/test_text_write_line_endings.py: 3/3 OK.
  • Not compiled/executed locally: runtime/shims/d3d12_pipeline_checkpoint.h and runtime/shims/d3d12_vulkan_device.cpp are Windows/Vulkan shims and rely on Windows CI / a retail boot run with LEONIDA_STARTUP_CACHE_CHECKPOINTS=1.
**@⁠IlyassRS3** on GitHub · 2026-11-25 11:20 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756) `IlyassRS3:fix/startup-cache-checkpoint-race` → `main` · +172 −32 · 6 files · 2 commits · open Item ID: `RT-STARTUP-CACHE-CHECKPOINT-RACE` Claim: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 Addresses finding: https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608 (`LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` wrote nothing during a 200 s run reaching world start) ## Root cause Two bugs in `runtime/shims/d3d12_vulkan_device.cpp` prevented startup cache checkpoints from saving during active world-start compilation bursts: 1. **`maybe_checkpoint(cache)` ran while `CompileActivity` still held `device_.active_compiles >= 1`**: both `PipelineState::build_compute()` (lines 8038, 8091) and `PipelineState::build()` (lines 8202, 8386) kept `CompileActivity activity(device_.active_compiles)` alive across `maybe_checkpoint(cache)`. When the build ran on a submitting or `PipelineWorkers` thread, the `PipelineCompiler` worker woke up before the caller returned, saw `active_compiles != 0`, and skipped `save_session_pipeline_cache()`. 2. **Deferred checkpoints still burned the 120-second cooldown**: whenever a checkpoint job was skipped because `active_compiles != 0` or `has_compile_waiter()` (either before `save_session_pipeline_cache()` at line 8110 or after the size query at line 1348), `maybe_checkpoint()` unconditionally pushed `next_checkpoint` out by another 120,000 ms (2 minutes). A single deferral at `t = 120 s` pushed the next attempt to `t = 240 s` — past the world-start crash at `~195–200 s`, leaving the cache directory empty. ## Changes - **`runtime/src/pipeline_cache_store.h`**: - Added `CheckpointOutcome` (`saved`, `deferred`, `skipped`) and portable atomic `CheckpointSchedule` (`try_claim`, `complete`, `abort_claim`). Deferred checkpoints and queue-submission aborts stay immediately eligible on the next compile completion instead of burning `default_checkpoint_interval_ms` (120 s); `saved` and `skipped` (empty/over-cap/I/O error) advance the deadline by the full interval with saturation below the `in_flight` sentinel. - **`runtime/shims/d3d12_pipeline_checkpoint.h`**: - Added idempotent `CompileActivity::finish()` (with `acq_rel` ordering) so callers can release their active-compile count before queueing a checkpoint while keeping RAII cleanup on early returns. - **`runtime/shims/d3d12_vulkan_device.cpp`**: - Replaced raw `next_checkpoint` atomic with `CheckpointSchedule checkpoint_schedule`. - In `build_compute()`, publish `pipeline_.pipeline`, unlock `variants_mutex_`, and call `activity.finish()` before `maybe_checkpoint(cache)`; in `build()`, call `activity.finish()` before `maybe_checkpoint(cache)`. - Updated `save_session_pipeline_cache()` to return `CheckpointOutcome` (returning `deferred` if `active_compiles` or `has_compile_waiter()` became active during the size query) and wired `maybe_checkpoint()` to `checkpoint_schedule.complete(..., outcome)`. - **`runtime/test/pipeline_cache_store_test.cpp`**: - Added `test_checkpoint_schedule()` covering due-time gating, in-flight coalescing, deferred immediate retry, `abort_claim`, saved/skipped 120 s cooldown, and near-`UINT64_MAX` saturation. ## Verification - **AI-assisted**: yes - **GPUs tested**: none (developed on macOS without Windows SDK or Vulkan SDK) - **Tested locally**: - `clang++ -std=c++20 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined runtime/test/pipeline_cache_store_test.cpp`: **PASS**. - `clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/pipeline_cache_store_test.cpp`: **PASS**. - `python3 -I scripts/check_no_game_data.py runtime/src/pipeline_cache_store.h runtime/shims/d3d12_pipeline_checkpoint.h runtime/shims/d3d12_vulkan_device.cpp runtime/test/pipeline_cache_store_test.cpp`: **PASS**. - `python3 -I tests/test_text_write_line_endings.py`: **3/3 OK**. - **Not compiled/executed locally**: `runtime/shims/d3d12_pipeline_checkpoint.h` and `runtime/shims/d3d12_vulkan_device.cpp` are Windows/Vulkan shims and rely on Windows CI / a retail boot run with `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1`.
Incorporate @DadaCap's RTX 5080 retail boot findings (#1608#issuecomment-7161936928)
into #1756 so startup checkpoints actually persist compiled pipelines before a
world-start crash:
- Lower default checkpoint initial delay and post-save interval from 120 s to 30 s,
  with a 5 s retry backoff when deferred (CheckpointSchedule).
- Submit checkpoints at priority 1 (behind priority-0 awaited first-use draws/
  dispatches, ahead of speculative warm-up builds keyed by SPIR-V byte size).
- Narrow PipelineCompiler::has_compile_waiter() to priority-0 awaited jobs only
  and drop the cross-thread active_compiles gate on checkpoints (vkGetPipelineCacheData
  is thread-safe against concurrent vkCreate*Pipelines and takes ~7-28 ms).
- Update docs/d3d12_vulkan.md and runtime/test/pipeline_cache_store_test.cpp.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:03:48 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-25 11:20 UTC · original · reviewed

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-25 11:20 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#pullrequestreview-6056680588) · **reviewed** Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
Author
Owner

@⁠DadaCap on GitHub · 2026-11-25 12:10 UTC · original

Thanks for taking this from the stall finding. I had prepared a change for the same code, so here is what I measured (RTX 5080, NVIDIA 621.24, Windows 11, main 237deb64c plus a few open pull requests; details in this finding). I won't open a competing pull request. I have read #1756 at f32c1abcc but not run it.

The release of CompileActivity before the checkpoint and the retry without the 120 s penalty both look right to me. Three things your branch keeps were each enough to stop a save here:

  1. First attempt at 120 s. On this machine that is inside the world-start builds.
  2. Queue priority SIZE_MAX. The checkpoint waits behind every speculative warm-up build (about 900 programs). In a 140 s run it was never tried.
  3. "Nothing active, nothing queued". With 1 and 2 changed and a short retry, 19 and 22 attempts in two runs were all skipped. Your early finish() removes the caller's own build from that count, but builds on other threads and queued speculative jobs still defer it. save_session_pipeline_cache repeats the check after the size query.

What worked here, as a local experiment: first attempt at 30 s, priority 1 (ahead of the warm-up, behind builds that something waits for), yielding only when a priority 0 job is queued, again 30 s after a save and 5 s after a deferral. The save itself is short: 22 MiB took 7.3 ms to fill and 2.3 ms to publish, 77 MiB took 27.7 ms and 8.2 ms, so waiting for an idle moment gains little. With it, builds found in the cache went from 35 of 892 (no cache yet) to 617, 714 and 781 of about 1,000 over the next three runs, all of which crashed. Upstream's schedule saved nothing in any of my runs.

Would you like to take points 1 to 3 into this pull request? If you'd rather keep it to the race, I can send them as a follow-up with Depends on: #1756, and I can also run your branch here for a retail result.

AI-assisted (Claude Code).

**@⁠DadaCap** on GitHub · 2026-11-25 12:10 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7162018923) Thanks for taking this from the stall finding. I had prepared a change for the same code, so here is what I measured (RTX 5080, NVIDIA 621.24, Windows 11, `main` 237deb64c plus a few open pull requests; details in [this finding](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608)). I won't open a competing pull request. I have read #1756 at f32c1abcc but not run it. The release of `CompileActivity` before the checkpoint and the retry without the 120 s penalty both look right to me. Three things your branch keeps were each enough to stop a save here: 1. **First attempt at 120 s.** On this machine that is inside the world-start builds. 2. **Queue priority `SIZE_MAX`.** The checkpoint waits behind every speculative warm-up build (about 900 programs). In a 140 s run it was never tried. 3. **"Nothing active, nothing queued".** With 1 and 2 changed and a short retry, 19 and 22 attempts in two runs were all skipped. Your early `finish()` removes the caller's own build from that count, but builds on other threads and queued speculative jobs still defer it. `save_session_pipeline_cache` repeats the check after the size query. What worked here, as a local experiment: first attempt at 30 s, priority 1 (ahead of the warm-up, behind builds that something waits for), yielding only when a priority 0 job is queued, again 30 s after a save and 5 s after a deferral. The save itself is short: 22 MiB took 7.3 ms to fill and 2.3 ms to publish, 77 MiB took 27.7 ms and 8.2 ms, so waiting for an idle moment gains little. With it, builds found in the cache went from 35 of 892 (no cache yet) to 617, 714 and 781 of about 1,000 over the next three runs, all of which crashed. Upstream's schedule saved nothing in any of my runs. Would you like to take points 1 to 3 into this pull request? If you'd rather keep it to the race, I can send them as a follow-up with `Depends on: #1756`, and I can also run your branch here for a retail result. AI-assisted (Claude Code).
Author
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 12:18 UTC · original

Thank you @⁠DadaCap for those RTX 5080 retail measurements (#1608#issuecomment-7161936928) — folded all three points into this PR at 90506453e (rebased on main 0d80bc5df):

  1. 30 s initial & post-save interval, 5 s deferred retry (CheckpointSchedule: default_checkpoint_interval_ms = 30000, default_checkpoint_retry_ms = 5000).
  2. Priority 1 (checkpoint_priority = 1) in maybe_checkpoint(), behind priority-0 awaited first-use draws/dispatches and ahead of speculative compute warm-up builds (keyed by SPIR-V byte size >= 20).
  3. Yield only to priority-0 waiters: narrowed PipelineCompiler::has_compile_waiter() to jobs_.begin()->first == 0 and removed the active_compiles block from the checkpoint path (keeping CompileActivity::finish() before maybe_checkpoint() so teardown accounting stays exact; vkGetPipelineCacheData is thread-safe against concurrent vkCreate*Pipelines).
  4. Updated docs/d3d12_vulkan.md and runtime/test/pipeline_cache_store_test.cpp (re-verified locally under ASan/UBSan and -O2).

If you have a chance to test 90506453e on a retail boot, that would be awesome!

**@⁠IlyassRS3** on GitHub · 2026-11-25 12:18 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7162202414) Thank you @⁠DadaCap for those RTX 5080 retail measurements (#1608#issuecomment-7161936928) — folded all three points into this PR at `90506453e` (rebased on `main` `0d80bc5df`): 1. **30 s initial & post-save interval, 5 s deferred retry** (`CheckpointSchedule`: `default_checkpoint_interval_ms = 30000`, `default_checkpoint_retry_ms = 5000`). 2. **Priority 1 (`checkpoint_priority = 1`)** in `maybe_checkpoint()`, behind priority-0 awaited first-use draws/dispatches and ahead of speculative compute warm-up builds (keyed by SPIR-V byte size `>= 20`). 3. **Yield only to priority-0 waiters**: narrowed `PipelineCompiler::has_compile_waiter()` to `jobs_.begin()->first == 0` and removed the `active_compiles` block from the checkpoint path (keeping `CompileActivity::finish()` before `maybe_checkpoint()` so teardown accounting stays exact; `vkGetPipelineCacheData` is thread-safe against concurrent `vkCreate*Pipelines`). 4. Updated `docs/d3d12_vulkan.md` and `runtime/test/pipeline_cache_store_test.cpp` (re-verified locally under ASan/UBSan and `-O2`). If you have a chance to test `90506453e` on a retail boot, that would be awesome!
Author
Owner

@⁠DadaCap on GitHub · 2026-11-25 12:34 UTC · original

Retail result for 90506453e on the RTX 5080 (NVIDIA 621.24, Windows 11), merged with main 0d80bc5df, #1662 and our 674, 1694, 1705, with LEONIDA_STARTUP_CACHE_CHECKPOINTS=1 (and, for an unrelated test, host image copy off): it saves. 16 snapshots in 540 s, the file went from 123 MiB at the start to 183 MiB part way through, while speculative builds were still queued. Builds in that run: 1,083 found in the cache, 243 not. The run was still in the story load when it was stopped, so it does not show a save before a crash, which is the case this is for. Thank you for folding in the three points. AI-assisted (Claude Code).

**@⁠DadaCap** on GitHub · 2026-11-25 12:34 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7162561590) Retail result for `90506453e` on the RTX 5080 (NVIDIA 621.24, Windows 11), merged with `main` 0d80bc5df, #1662 and our 674, 1694, 1705, with `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` (and, for an unrelated test, host image copy off): **it saves.** 16 snapshots in 540 s, the file went from 123 MiB at the start to 183 MiB part way through, while speculative builds were still queued. Builds in that run: 1,083 found in the cache, 243 not. The run was still in the story load when it was stopped, so it does not show a save before a crash, which is the case this is for. Thank you for folding in the three points. AI-assisted (Claude Code).
Author
Owner

@⁠3L1A5-1 on GitHub · 2026-11-25 13:39 UTC · original

Tested 90506453e (both commits cherry-picked onto main 98c2f7777) on native Windows 11 26300, RTX 2060 SUPER 8 GB (Turing, no Resizable BAR), NVIDIA 617.14, 16 GB RAM. Retail boot with LEONIDA_STARTUP_CACHE_CHECKPOINTS=1 and LEONIDA_DEVICE_FAULT=1 (identical in both runs). Each run was 600 s: past the landing prompt into the story load (session state 0xd at 170 s), and stopped by my time guard, not a crash.

  • Checkpoints work here. Run A started with no session file. It wrote 19 checkpoints, the first at about 30 s and then about every 30 s, growing from 1.1 MB to 87.8 MB. On main without this PR, the folder stayed empty in all four of my earlier runs.
  • The warm run gains nothing on the slow builds. Run B loaded the 87,768,274-byte file. All slow builds (≥ 2 s) in both runs are compute library/lib_cs_* programs:
    • 45 programs are slow in both runs. Their build times sum to 169.1 s in A and 168.3 s in B.
    • Over the whole run, A had 50 slow builds (183.5 s) and B had 66 (244.2 s).
    • B's checkpoints stayed at 87,768,274 bytes for 18 writes, then grew to 93.9 MB.
  • So the saving side is fixed. On this NVIDIA driver, though, the library compute pipelines don't hit in the cache from the previous run. That matches the observation in CLHelper's release of PIPELINE-SEED-LIBRARY on #1608. I haven't found out why yet.

AI-assisted: yes

**@⁠3L1A5-1** on GitHub · 2026-11-25 13:39 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7164092319) Tested `90506453e` (both commits cherry-picked onto `main` `98c2f7777`) on native Windows 11 26300, RTX 2060 SUPER 8 GB (Turing, no Resizable BAR), NVIDIA 617.14, 16 GB RAM. Retail boot with `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` and `LEONIDA_DEVICE_FAULT=1` (identical in both runs). Each run was 600 s: past the landing prompt into the story load (session state `0xd` at 170 s), and stopped by my time guard, not a crash. - **Checkpoints work here.** Run A started with no session file. It wrote 19 checkpoints, the first at about 30 s and then about every 30 s, growing from 1.1 MB to 87.8 MB. On `main` without this PR, the folder stayed empty in all four of my earlier runs. - **The warm run gains nothing on the slow builds.** Run B loaded the 87,768,274-byte file. All slow builds (≥ 2 s) in both runs are compute `library/lib_cs_*` programs: - 45 programs are slow in both runs. Their build times sum to 169.1 s in A and 168.3 s in B. - Over the whole run, A had 50 slow builds (183.5 s) and B had 66 (244.2 s). - B's checkpoints stayed at 87,768,274 bytes for 18 writes, then grew to 93.9 MB. - So the saving side is fixed. On this NVIDIA driver, though, the library compute pipelines don't hit in the cache from the previous run. That matches the observation in CLHelper's release of PIPELINE-SEED-LIBRARY on #1608. I haven't found out why yet. AI-assisted: yes
Author
Owner

@⁠DadaCap on GitHub · 2026-11-25 13:41 UTC · original

@⁠3L1A5-1 a data point against a general NVIDIA miss: on an RTX 5080 with NVIDIA 621.24 the library compute programs do hit a session file from the previous run. With LEONIDA_TRACE_PIPELINE_COMPILE=1, a run that loaded a 268 MB file had 1,416 library builds with hit=1 (147 of them over 600 KB of SPIR-V) and 138 with hit=0. All 75 that were slow (2 s or more) in the run before and slow again were ones that run could not save, because it was over the 256 MiB limit (7163972744); your 88 MB file is far below that, so that is not your cause. If you can, one run with the trace on would show whether the driver reports hit=0 or hits that are slow. Two things that cost me hits: entries written with LEONIDA_DEVICE_FAULT=1 miss without it and the reverse, and a retranslated shader. AI-assisted (Claude Code).

**@⁠DadaCap** on GitHub · 2026-11-25 13:41 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7164156157) @⁠3L1A5-1 a data point against a general NVIDIA miss: on an RTX 5080 with NVIDIA 621.24 the library compute programs do hit a session file from the previous run. With `LEONIDA_TRACE_PIPELINE_COMPILE=1`, a run that loaded a 268 MB file had 1,416 library builds with `hit=1` (147 of them over 600 KB of SPIR-V) and 138 with `hit=0`. All 75 that were slow (2 s or more) in the run before and slow again were ones that run could not save, because it was over the 256 MiB limit ([7163972744](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608)); your 88 MB file is far below that, so that is not your cause. If you can, one run with the trace on would show whether the driver reports `hit=0` or hits that are slow. Two things that cost me hits: entries written with `LEONIDA_DEVICE_FAULT=1` miss without it and the reverse, and a retranslated shader. AI-assisted (Claude Code).
Author
Owner

@⁠MoonEyes on GitHub · 2026-11-25 17:52 UTC · original

Small follow-up for this PR, if useful: a queue-order test for the priority change. Patch below, based on 90506453e.

  • pipeline_compile_order_test drives PipelineCompiler with no device: one blocking priority-0 job, 900 warm-ups (priority 20..919), then the checkpoint at checkpoint_priority. It checks that the checkpoint runs second, and that has_compile_waiter() only reports priority-0 jobs.
  • On this branch it passes. On main (fe1553456) with the checkpoint at SIZE_MAX, the same test fails: the checkpoint runs 902nd. That one constant is the only line I changed for main, since checkpoint_priority does not exist there. On main the has_compile_waiter() check fails too, independently of that line: main reports any queued job that is not SIZE_MAX, warm-ups included.
  • The patch also fixes the comment above PipelineCompiler in d3d12_pipeline_compile.h, which still says "an idle checkpoint runs last".
  • The PR description still says 120 s and "immediately eligible"; the code is now 30 s first checkpoint, 30 s interval, 5 s retry, priority 1.

I only ran this one test, not the full suite. Feel free to take the patch or drop it.

Patch (git format-patch, applies on this branch)
From 698a29bca0b46ff258fe63b74fddcc0f6b8404a9 Mon Sep 17 00:00:00 2001
From: MoonEyes <[email protected]>
Date: Wed, 25 Nov 2026 18:02:32 +0100
Subject: [PATCH] d3d12: test the compile queue order for the priority-1
 checkpoint

pipeline_compile_order_test drives PipelineCompiler with no device and no
game data: a blocking priority-0 job holds the worker, 900 warm-ups
(priority 20..919) and then the checkpoint are queued, and the checkpoint
must be the first job to run once the gate opens. With the old SIZE_MAX
priority it ran 902nd. A second case checks that has_compile_waiter() only
reports priority-0 jobs.

Also update the PipelineCompiler comment, which still said that an idle
checkpoint runs last.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
---
 runtime/CMakeLists.txt                       |   8 ++
 runtime/shims/d3d12_pipeline_compile.h       |   4 +-
 runtime/test/pipeline_compile_order_test.cpp | 143 +++++++++++++++++++
 3 files changed, 153 insertions(+), 2 deletions(-)
 create mode 100644 runtime/test/pipeline_compile_order_test.cpp

diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e9cb8d434..97d738fa3 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -3608,6 +3608,14 @@ if(TARGET Vulkan::Headers)
       target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8)
       add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test)
       set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300)
+      # Order of the compile queue, with no device: a checkpoint (priority 1) runs right behind an awaited build, ahead of
+      # 900 warm-ups. Header-only (PipelineCompiler), so it does not link the device library.
+      add_executable(pipeline_compile_order_test test/pipeline_compile_order_test.cpp)
+      target_link_libraries(pipeline_compile_order_test PRIVATE Vulkan::Headers)
+      target_compile_definitions(pipeline_compile_order_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
+      target_compile_options(pipeline_compile_order_test PRIVATE /W4 /permissive- /utf-8)
+      add_test(NAME pipeline_compile_order COMMAND pipeline_compile_order_test)
+      set_tests_properties(pipeline_compile_order PROPERTIES TIMEOUT 120)
       # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#.
       add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp
                      test/xmem_geometry_aliases_stub.cpp ${LEONIDA_TEST_CS})
diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h
index 191fce176..e444d37fd 100644
--- a/runtime/shims/d3d12_pipeline_compile.h
+++ b/runtime/shims/d3d12_pipeline_compile.h
@@ -85,8 +85,8 @@ struct CompileTrace {
 };
 
 
-// Demanded work has priority zero, speculative work is ordered by module size, and
-// an idle checkpoint runs last. No Vulkan call runs with the queue lock held.
+// Demanded work has priority zero, the cache checkpoint priority one, and speculative
+// work is ordered by module size. No Vulkan call runs with the queue lock held.
 //
 // Lifetime. A job names its owner (the PSO it builds, or the device for a cache checkpoint) and the device whose
 // Vulkan objects it uses, and holds no reference to either: a reference kept the device alive past the title's last
diff --git a/runtime/test/pipeline_compile_order_test.cpp b/runtime/test/pipeline_compile_order_test.cpp
new file mode 100644
index 000000000..ce98426f1
--- /dev/null
+++ b/runtime/test/pipeline_compile_order_test.cpp
@@ -0,0 +1,143 @@
+// Order of the pipeline compile queue (PipelineCompiler, shims/d3d12_pipeline_compile.h), with no device and no game
+// data. The worker takes the job with the smallest priority key: 0 is an awaited first-use build, the cache
+// checkpoint comes next (checkpoint_priority), and speculative warm-up builds are keyed by SPIR-V size (>= 20).
+// Cases:
+//   order    a blocking priority-0 job holds the worker, 900 warm-ups and then the checkpoint are queued: once the
+//            gate opens the checkpoint is the first job to run after it, not the 902nd (the old SIZE_MAX priority).
+//   waiter   has_compile_waiter() is false with only warm-ups and the checkpoint queued, true once a priority-0 job is.
+#include "../shims/d3d12_pipeline_compile.h"
+#include "../src/pipeline_cache_store.h"
+
+#include <cstddef>
+#include <cstdio>
+#include <mutex>
+#include <vector>
+
+#define EXPECT(condition) do { \
+    if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); ++failures; } \
+} while (0)
+
+namespace {
+
+using rt::d3d12::PipelineCompiler;
+
+constexpr int warmups = 900;
+constexpr int gate_id = -1;
+constexpr int checkpoint_id = 1000;
+constexpr int waiter_id = 1001;
+constexpr int marker_id = 1002;
+constexpr std::size_t checkpoint_priority = leonida::pipeline_cache_store::checkpoint_priority;
+
+int failures = 0;
+
+struct Event {
+    HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+    Event() = default;
+    Event(const Event&) = delete;
+    Event& operator=(const Event&) = delete;
+    ~Event() { CloseHandle(handle); }
+    void set() const { SetEvent(handle); }
+    bool wait(DWORD ms = 30000) const { return WaitForSingleObject(handle, ms) == WAIT_OBJECT_0; }
+};
+
+// Jobs append their id here as they run.
+struct Log {
+    std::mutex mutex;
+    std::vector<int> ran;
+    void add(int id) {
+        std::lock_guard lock(mutex);
+        ran.push_back(id);
+    }
+};
+
+// Holds the worker in a priority-0 job until open().
+struct Gate {
+    Event entered, opened, left;
+    Log& log;
+    Gate(PipelineCompiler& compiler, Log& l) : log(l) {
+        static const int owner = 0;
+        compiler.submit(&owner, nullptr, 0, [this] {
+            log.add(gate_id);
+            entered.set();
+            opened.wait(INFINITE);
+            left.set();
+        });
+        entered.wait();
+    }
+    void open() { opened.set(); }
+    ~Gate() {
+        opened.set();
+        left.wait();  // the job is out of this object before its events close
+    }
+};
+
+// Queues the warm-ups, then the checkpoint (the order the runtime meets them in, the checkpoint last).
+void queue_warmups_and_checkpoint(PipelineCompiler& compiler, Log& log) {
+    static const int owner = 0;
+    for (int i = 0; i < warmups; ++i)
+        compiler.submit(&owner, nullptr, 20 + std::size_t(i), [&log, i] { log.add(i); });
+    compiler.submit(&owner, nullptr, checkpoint_priority, [&log] { log.add(checkpoint_id); });
+}
+
+// Waits for the worker to run everything queued so far: a last-priority marker job.
+bool drain(PipelineCompiler& compiler, Log& log) {
+    static const int owner = 0;
+    Event done;
+    if (!compiler.submit(&owner, nullptr, SIZE_MAX, [&] { log.add(marker_id); done.set(); })) return false;
+    return done.wait();
+}
+
+std::size_t position(Log& log, int id) {
+    std::lock_guard lock(log.mutex);
+    for (std::size_t i = 0; i < log.ran.size(); ++i)
+        if (log.ran[i] == id) return i;
+    return SIZE_MAX;
+}
+
+}  // namespace
+
+int main() {
+    PipelineCompiler& compiler = PipelineCompiler::instance();
+    compiler.retain();  // the worker lives to the end of the test and is joined by release()
+
+    {  // order
+        Log log;
+        {
+            Gate gate(compiler, log);
+            queue_warmups_and_checkpoint(compiler, log);
+            gate.open();
+            EXPECT(drain(compiler, log));
+        }
+        const std::size_t at = position(log, checkpoint_id);
+        std::fprintf(stderr, "checkpoint ran at position %zu of %zu (0 is the gate)\n", at, log.ran.size());
+        EXPECT(log.ran.size() == std::size_t(warmups) + 3);
+        EXPECT(at == 1);  // right behind the gate, ahead of every warm-up
+        EXPECT(position(log, 0) == 2);  // the smallest warm-up follows
+        EXPECT(position(log, warmups - 1) == std::size_t(warmups) + 1);
+        EXPECT(position(log, marker_id) == std::size_t(warmups) + 2);
+    }
+
+    {  // waiter
+        Log log;
+        {
+            Gate gate(compiler, log);
+            queue_warmups_and_checkpoint(compiler, log);
+            EXPECT(!compiler.has_compile_waiter());  // speculative work and a checkpoint do not count
+            static const int owner = 0;
+            compiler.submit(&owner, nullptr, 0, [&log] { log.add(waiter_id); });
+            EXPECT(compiler.has_compile_waiter());
+            gate.open();
+            EXPECT(drain(compiler, log));
+        }
+        EXPECT(position(log, waiter_id) == 1);  // a demanded build still goes before the checkpoint
+        EXPECT(position(log, checkpoint_id) == 2);
+    }
+
+    compiler.release();
+    if (failures) {
+        std::fprintf(stderr, "pipeline_compile_order_test: %d failure(s)\n", failures);
+        return 1;
+    }
+    std::puts("pipeline_compile_order_test: ok");
+    return 0;
+}
-- 
2.42.0.windows.1

AI-assisted: yes (Claude Code wrote and ran the test)

**@⁠MoonEyes** on GitHub · 2026-11-25 17:52 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/1756#issuecomment-7170109909) Small follow-up for this PR, if useful: a queue-order test for the priority change. Patch below, based on 90506453e. - `pipeline_compile_order_test` drives `PipelineCompiler` with no device: one blocking priority-0 job, 900 warm-ups (priority 20..919), then the checkpoint at `checkpoint_priority`. It checks that the checkpoint runs second, and that `has_compile_waiter()` only reports priority-0 jobs. - On this branch it passes. On main (fe1553456) with the checkpoint at `SIZE_MAX`, the same test fails: the checkpoint runs 902nd. That one constant is the only line I changed for main, since `checkpoint_priority` does not exist there. On main the has_compile_waiter() check fails too, independently of that line: main reports any queued job that is not SIZE_MAX, warm-ups included. - The patch also fixes the comment above `PipelineCompiler` in `d3d12_pipeline_compile.h`, which still says "an idle checkpoint runs last". - The PR description still says 120 s and "immediately eligible"; the code is now 30 s first checkpoint, 30 s interval, 5 s retry, priority 1. I only ran this one test, not the full suite. Feel free to take the patch or drop it. <details><summary>Patch (git format-patch, applies on this branch)</summary> ``` From 698a29bca0b46ff258fe63b74fddcc0f6b8404a9 Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+[email protected]> Date: Wed, 25 Nov 2026 18:02:32 +0100 Subject: [PATCH] d3d12: test the compile queue order for the priority-1 checkpoint pipeline_compile_order_test drives PipelineCompiler with no device and no game data: a blocking priority-0 job holds the worker, 900 warm-ups (priority 20..919) and then the checkpoint are queued, and the checkpoint must be the first job to run once the gate opens. With the old SIZE_MAX priority it ran 902nd. A second case checks that has_compile_waiter() only reports priority-0 jobs. Also update the PipelineCompiler comment, which still said that an idle checkpoint runs last. Co-Authored-By: Claude Fable 5.2 <[email protected]> --- runtime/CMakeLists.txt | 8 ++ runtime/shims/d3d12_pipeline_compile.h | 4 +- runtime/test/pipeline_compile_order_test.cpp | 143 +++++++++++++++++++ 3 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 runtime/test/pipeline_compile_order_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e9cb8d434..97d738fa3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3608,6 +3608,14 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compile_teardown_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compile_teardown COMMAND d3d12_compile_teardown_test) set_tests_properties(d3d12_compile_teardown PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # Order of the compile queue, with no device: a checkpoint (priority 1) runs right behind an awaited build, ahead of + # 900 warm-ups. Header-only (PipelineCompiler), so it does not link the device library. + add_executable(pipeline_compile_order_test test/pipeline_compile_order_test.cpp) + target_link_libraries(pipeline_compile_order_test PRIVATE Vulkan::Headers) + target_compile_definitions(pipeline_compile_order_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pipeline_compile_order_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME pipeline_compile_order COMMAND pipeline_compile_order_test) + set_tests_properties(pipeline_compile_order PROPERTIES TIMEOUT 120) # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp test/xmem_geometry_aliases_stub.cpp ${LEONIDA_TEST_CS}) diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h index 191fce176..e444d37fd 100644 --- a/runtime/shims/d3d12_pipeline_compile.h +++ b/runtime/shims/d3d12_pipeline_compile.h @@ -85,8 +85,8 @@ struct CompileTrace { }; -// Demanded work has priority zero, speculative work is ordered by module size, and -// an idle checkpoint runs last. No Vulkan call runs with the queue lock held. +// Demanded work has priority zero, the cache checkpoint priority one, and speculative +// work is ordered by module size. No Vulkan call runs with the queue lock held. // // Lifetime. A job names its owner (the PSO it builds, or the device for a cache checkpoint) and the device whose // Vulkan objects it uses, and holds no reference to either: a reference kept the device alive past the title's last diff --git a/runtime/test/pipeline_compile_order_test.cpp b/runtime/test/pipeline_compile_order_test.cpp new file mode 100644 index 000000000..ce98426f1 --- /dev/null +++ b/runtime/test/pipeline_compile_order_test.cpp @@ -0,0 +1,143 @@ +// Order of the pipeline compile queue (PipelineCompiler, shims/d3d12_pipeline_compile.h), with no device and no game +// data. The worker takes the job with the smallest priority key: 0 is an awaited first-use build, the cache +// checkpoint comes next (checkpoint_priority), and speculative warm-up builds are keyed by SPIR-V size (>= 20). +// Cases: +// order a blocking priority-0 job holds the worker, 900 warm-ups and then the checkpoint are queued: once the +// gate opens the checkpoint is the first job to run after it, not the 902nd (the old SIZE_MAX priority). +// waiter has_compile_waiter() is false with only warm-ups and the checkpoint queued, true once a priority-0 job is. +#include "../shims/d3d12_pipeline_compile.h" +#include "../src/pipeline_cache_store.h" + +#include <cstddef> +#include <cstdio> +#include <mutex> +#include <vector> + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); ++failures; } \ +} while (0) + +namespace { + +using rt::d3d12::PipelineCompiler; + +constexpr int warmups = 900; +constexpr int gate_id = -1; +constexpr int checkpoint_id = 1000; +constexpr int waiter_id = 1001; +constexpr int marker_id = 1002; +constexpr std::size_t checkpoint_priority = leonida::pipeline_cache_store::checkpoint_priority; + +int failures = 0; + +struct Event { + HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr); + Event() = default; + Event(const Event&) = delete; + Event& operator=(const Event&) = delete; + ~Event() { CloseHandle(handle); } + void set() const { SetEvent(handle); } + bool wait(DWORD ms = 30000) const { return WaitForSingleObject(handle, ms) == WAIT_OBJECT_0; } +}; + +// Jobs append their id here as they run. +struct Log { + std::mutex mutex; + std::vector<int> ran; + void add(int id) { + std::lock_guard lock(mutex); + ran.push_back(id); + } +}; + +// Holds the worker in a priority-0 job until open(). +struct Gate { + Event entered, opened, left; + Log& log; + Gate(PipelineCompiler& compiler, Log& l) : log(l) { + static const int owner = 0; + compiler.submit(&owner, nullptr, 0, [this] { + log.add(gate_id); + entered.set(); + opened.wait(INFINITE); + left.set(); + }); + entered.wait(); + } + void open() { opened.set(); } + ~Gate() { + opened.set(); + left.wait(); // the job is out of this object before its events close + } +}; + +// Queues the warm-ups, then the checkpoint (the order the runtime meets them in, the checkpoint last). +void queue_warmups_and_checkpoint(PipelineCompiler& compiler, Log& log) { + static const int owner = 0; + for (int i = 0; i < warmups; ++i) + compiler.submit(&owner, nullptr, 20 + std::size_t(i), [&log, i] { log.add(i); }); + compiler.submit(&owner, nullptr, checkpoint_priority, [&log] { log.add(checkpoint_id); }); +} + +// Waits for the worker to run everything queued so far: a last-priority marker job. +bool drain(PipelineCompiler& compiler, Log& log) { + static const int owner = 0; + Event done; + if (!compiler.submit(&owner, nullptr, SIZE_MAX, [&] { log.add(marker_id); done.set(); })) return false; + return done.wait(); +} + +std::size_t position(Log& log, int id) { + std::lock_guard lock(log.mutex); + for (std::size_t i = 0; i < log.ran.size(); ++i) + if (log.ran[i] == id) return i; + return SIZE_MAX; +} + +} // namespace + +int main() { + PipelineCompiler& compiler = PipelineCompiler::instance(); + compiler.retain(); // the worker lives to the end of the test and is joined by release() + + { // order + Log log; + { + Gate gate(compiler, log); + queue_warmups_and_checkpoint(compiler, log); + gate.open(); + EXPECT(drain(compiler, log)); + } + const std::size_t at = position(log, checkpoint_id); + std::fprintf(stderr, "checkpoint ran at position %zu of %zu (0 is the gate)\n", at, log.ran.size()); + EXPECT(log.ran.size() == std::size_t(warmups) + 3); + EXPECT(at == 1); // right behind the gate, ahead of every warm-up + EXPECT(position(log, 0) == 2); // the smallest warm-up follows + EXPECT(position(log, warmups - 1) == std::size_t(warmups) + 1); + EXPECT(position(log, marker_id) == std::size_t(warmups) + 2); + } + + { // waiter + Log log; + { + Gate gate(compiler, log); + queue_warmups_and_checkpoint(compiler, log); + EXPECT(!compiler.has_compile_waiter()); // speculative work and a checkpoint do not count + static const int owner = 0; + compiler.submit(&owner, nullptr, 0, [&log] { log.add(waiter_id); }); + EXPECT(compiler.has_compile_waiter()); + gate.open(); + EXPECT(drain(compiler, log)); + } + EXPECT(position(log, waiter_id) == 1); // a demanded build still goes before the checkpoint + EXPECT(position(log, checkpoint_id) == 2); + } + + compiler.release(); + if (failures) { + std::fprintf(stderr, "pipeline_compile_order_test: %d failure(s)\n", failures); + return 1; + } + std::puts("pipeline_compile_order_test: ok"); + return 0; +} -- 2.42.0.windows.1 ``` </details> AI-assisted: yes (Claude Code wrote and ran the test)
This pull request has changes conflicting with the target branch.
  • docs/d3d12_vulkan.md
  • runtime/shims/d3d12_pipeline_compile.h
  • runtime/shims/d3d12_vulkan_device.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1756/head:github-bot/gh-1756'
git switch 'github-bot/gh-1756'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1756'
git switch 'github-bot/gh-1756'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1756'
git switch 'github-bot/gh-1756'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1756'
git switch 'main'
git merge --squash 'github-bot/gh-1756'
git switch 'main'
git merge --ff-only 'github-bot/gh-1756'
git switch 'main'
git merge 'github-bot/gh-1756'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.