Skip to content

d3d12-gpu: fix parallel unit test races in watch, descriptor, and pool - #2854

Open
lixonik wants to merge 3 commits into
ProjectLeonida:mainfrom
lixonik:fix/leonida-gpu-parallel-test-flakes
Open

lixonik wants to merge 3 commits into
ProjectLeonida:mainfrom
lixonik:fix/leonida-gpu-parallel-test-flakes

Conversation

@lixonik

@lixonik lixonik commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claim: D3D12-GPU-TEST-PARALLEL-FLAKES (#2570 (comment))

Fixes the three process-global parallel test races in leonida-gpu reported in #2570 (where cargo test -p leonida-gpu --lib flaked under default parallel test threads while passing under --test-threads=1).

Root causes & fixes

  1. watch::tests (d3d12/crates/leonida-gpu/src/watch.rs)

    • nothing_is_guarded_between_our_forgetting_it_and_its_unmapping and writes_to_views_are_not_lost called UnmapViewOfFile before dropping Remapping, returning the virtual address to Windows while g.changing still listed its block as left_alone. Any concurrent test whose MapViewOfFile / VirtualAlloc2 reused that address skipped guarding or lost published(...). Ended the remapping window before UnmapViewOfFile.
    • drop_views called title_memory_remapped instead of title_memory_unmapping, leaving stale VIEWS bitmap bits behind after unmapping. Switched drop_views to title_memory_unmapping.
  2. descriptor::tests (d3d12/crates/leonida-gpu/src/descriptor.rs)

    • records_copied_as_bytes_are_made_at_the_next_sync raced with the 4 ms background "leonida-heap-sync" thread and concurrent test submissions calling sync_heaps() over process-global SHADER_HEAPS, causing assert!(!host.made(5)) to observe an early mirror. Added a #[cfg(test)] TEST_SYNC_LOCK around sync_heaps() and held it across the raw copy + pre-sync assertion.
  3. pool::Reclaim / texture::alias_cast_tests (d3d12/crates/leonida-gpu/src/pool.rs)

    • Reclaim::release returned a pooled piece without removing the released ID3D12Resource raw pointer from RECENT or UNSEEN. When a subsequent committed texture reused that COM pointer within 1 second, pool::fresh falsely reported true, failing assert_eq!(pool::fresh(&copy.texture), false) in committed_and_placed_r32_uint_textures_cast_to_r9g9b9e5_under_legacy_barriers. Stored raw: usize in Reclaim and cleared RECENT and UNSEEN via forget_released(raw) on final release.
    • Added unit test released_texture_pointer_is_not_kept_in_recent_or_unseen and COM last-reference drop regression test dropping_last_pooled_texture_reference_forgets_recent_and_unseen (allocates a 32x32 RGBA8 placed texture via pool::texture, holds two COM references, confirms entries remain after dropping the first reference, and confirms RECENT and UNSEEN are cleared after dropping the final reference triggers Reclaim::release).

Verification

  • Before (main ad7c62edb, 8 parallel runs): watch::tests::other_memory_at_a_guarded_address_keeps_its_protection and watch::tests::what_is_put_in_beside_the_guards_is_told_at_every_view panicked on parallel run 2/8.
  • Red/green for dropping_last_pooled_texture_reference_forgets_recent_and_unseen (at bce4a898b):
    • Without forget_released(gone.raw) in Reclaim::release: 0 passed; 1 failed (panicked on post-drop RECENT assertion).
    • With forget_released(gone.raw) restored:
      • cargo test --locked -p leonida-gpu --lib dropping_last_pooled_texture_reference_forgets_recent_and_unseen -- --nocapture: 1 passed, 0 failed.
      • cargo test --locked -p leonida-gpu --features diagnostics --lib dropping_last_pooled_texture_reference_forgets_recent_and_unseen -- --nocapture: 1 passed, 0 failed.
      • cargo test --locked -p leonida-gpu --lib pool::: 20/20 consecutive parallel runs passed.
      • cargo test --locked -p leonida-gpu --lib -- --skip depth_bounds_pipeline_loads_and_filters_draws (default thread count): 17/18 parallel runs passed (601 passed, 0 failed, 55 ignored each); run 18/20 hit an unrelated watch::port7_tests::no_write_is_lost_with_port_7 + watch::tests::what_is_put_in_beside_the_guards_is_told_at_every_view parallel flake.
    • (depth_bounds_pipeline_loads_and_filters_draws fails deterministically on Windows 10 inbox D3D12 without Agility SDK; tracked in d3d12-gpu: drop unused SM 6.6 root signature flags in depth_bounds test #2855.)

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (driver 621.40, Windows 10 Pro 22H2 build 19045, Ryzen 9 5950X 16C/32T)

AI-assisted: Antigravity (plus separate read-only reviewer subagent)

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Your claim is there (D3D12-GPU-TEST-PARALLEL-FLAKES, #2570 (comment)), but the description does not name it. Could you add the ID and that link, so the merge checklist finds it?

One small thing while reading the diff: TEST_SYNC_LOCK sits between the doc comment of sync_heaps and the function, so those lines now document the static.

This one changes pool.rs outside the tests, so it is in the in-game run I have queued on an RTX 4060.

AI-assisted (Claude Code).

@Kal0s-design

Copy link
Copy Markdown
Contributor

Independent Windows check, A/B over repeated runs: 99ed48337 merged onto current main 653f60d37 (no conflict, 1b2be1bfc) against main itself. Native Windows 11, MSVC x64, Rust 1.98.1. I built the leonida-gpu lib test binary once per side (debug, default parallel test threads) and ran each whole suite 40 times back to back, alternating nothing else.

runs with a failure tests that failed
main 653f60d37 4 / 40 watch::tests::what_the_kernel_writes_through_is_not_guarded_for_another_view, watch::tests::kernel_reads_into_guarded_blocks_after_opening, watch::tests::a_write_is_reported_at_every_checked_view (one per run; one run's name wasn't captured)
main + this PR 0 / 40 none

So the watch cross-test interference reproduces on main here (about 1 run in 10), and with this PR it doesn't show in 40 runs. On another day I also saw descriptor::tests::records_copied_as_bytes_are_made_at_the_next_sync fail once in 9 runs on a branch, which is the second race this PR addresses. It didn't come up in these 40 main runs, so I can't add a count for it.

GPUs tested: n/a (unit tests). AI-assisted: yes.

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@MoonEyes Thanks for catching both!

  • Added the claim ID (D3D12-GPU-TEST-PARALLEL-FLAKES) and link to the PR description.
  • Moved TEST_SYNC_LOCK above sync_heaps's doc comment so those doc lines stay attached to pub(crate) fn sync_heaps(), and re-verified records_copied_as_bytes_are_made_at_the_next_sync.

@Kal0s-design Thanks for the independent 40-run Windows 11 A/B verification (4/40 -> 0/40)!

AI-assisted: Antigravity

@enlight3d

Copy link
Copy Markdown
Contributor

RUN (independent run on Windows, #2854 head 99ed483, merged locally into main 3393cee with git merge --no-ff, no conflicts. The head still merges cleanly into main bf30e25. CI on the head: change-scope, check, linux-python-and-viewer, no-game-data and semantic-tests all pass.)

Commands, in d3d12/, target x86_64-pc-windows-msvc, toolchain 1.98.1, all with --locked, at low priority. cargo test -p leonida-gpu --lib --no-run of main and of the merge; then the two test binaries were run alternately, each with the default thread count (32 here, no --test-threads), as cargo test -p leonida-gpu --lib runs them:

  • Default build, 32 runs each side: main 31 clean, 1 failure (watch::tests::what_the_kernel_writes_through_is_not_guarded_for_another_view, watch.rs:6010, left Some([..]), right Some([])); merge 32 clean (602 passed / 0 failed / 55 ignored, the extra test being the new one). So no new failure, and the one parallel failure seen on main is a watch test. The flake rate here is low (1 in 32 on main), so these runs alone cannot prove the fix; the two tests named in the body did not fail on main in 32 runs here.
  • --features diagnostics build, 10 runs each side: main 2 clean, merge 2 clean. timeline::record::tests::global_stall_routing_retains_spans_waits_wakes_and_sent_fences_without_stacks fails in parallel on both sides (main 7 of 10, merge 8 of 10, record.rs:2325, no "synthetic stall span"): a parallel race this pull request does not touch. descriptor::tests::records_copied_as_bytes_are_made_at_the_next_sync, which this pull request fixes, failed once on main and never on the merge.
  • Red, by assertion: forget_released emptied (fn forget_released(_raw: usize) {}), the new test kept: released_texture_pointer_is_not_kept_in_recent_or_unseen fails on its first assertion (!RECENT...any(|r| r.0 == raw), pool.rs:1295). Green after restoring: 1 passed.
  • What that test does not cover: it calls forget_released directly. With the call taken out of release (let _ = gone.raw;), the whole suite still passes (602 / 0 / 55, one run). So no test checks that the last release of a pooled texture really forgets it; a test that makes a pooled texture, drops it and then asks fresh for its pointer would.
  • Lock order, read through pool.rs (RECENT, UNSEEN, TEXTURES): RECENT and UNSEEN are private to pool.rs. They are taken in fresh, made_now, begun_before, forget_released and the new test, and each guard covers only work on its own list of numbers (under UNSEEN, made_now also calls host::submissions(), which reads two atomics). No other lock is taken and no COM object is released while either is held, and the two are never held together (made_now drops RECENT before it takes UNSEEN; forget_released takes one, then the other). In release, the TEXTURES guard is a temporary dropped at the end of its statement, before forget_released. So both stay leaf locks: no reversed order and no re-entry is possible. A caller that holds some other lock when it drops the last reference to a pooled texture only adds an edge into these two leaf locks, which cannot close a cycle.
  • descriptor.rs: TEST_SYNC_LOCK and its use in sync_heaps are #[cfg(test)], so a normal build does not change. But the new static sits between the doc comment of sync_heaps and the function: that whole doc block (including the LEONIDA_HEAP_SYNC=0 line) now documents TEST_SYNC_LOCK, and sync_heaps has no doc comment in a normal build. Moving the static above that block would fix it. python -I tools/d3d12_switches.py --check d3d12/docs/switches.md is still clean on the merge.
  • cargo clippy -p leonida-gpu --all-targets, default and --features diagnostics, on main and on the merge: the same warnings on both sides (69 and 68 locations, counting those the command reports in leonida-shader and leonida-lua), none new.
  • Not covered here: the game. forget_released now runs at every last release of a pooled texture (a scan of RECENT, the textures made in the last second, under its lock).

Since this run the head moved to eab9e2a, which only moves TEST_SYNC_LOCK above the doc comment of sync_heaps (5 lines in descriptor.rs): that fixes the doc point above and changes nothing else tested here.

Machine: Windows 11 Pro 26300, i9-13900K, 64 GB, RTX 3090 24 GB, NVIDIA 621.40, Rust 1.98.1.

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

One thing before a merge, from enlight3d's check and confirmed by reading: taking the call of forget_released out of release leaves the whole suite green, since the new test calls the function directly. Could you add a test that drops the last reference of a pooled texture (or a Reclaim) and fails without that call? The rest reads fine: the locks are leaves and the entry goes before the address can be reused.

AI-assisted (Claude Code).

@merzleckeier

Copy link
Copy Markdown
Contributor

I tested the requested last-reference regression at eab9e2ab + #2884 on b3910e5e. The fixture makes a real 32×32 RGBA8 placed texture through pool::texture, requires that pooled allocation to succeed, and holds two COM references. It checks that both tracking entries exist initially and after the first drop. After dropping the last reference, it checks that HELD has returned to its original count and both RECENT and UNSEEN no longer contain the key.

Device under Wine 11.22 With the PR With only forget_released(gone.raw) removed from release
AMD Raphael / RADV 26.3.1 returned pool piece, both entries cleared returned pool piece, both entries remained
RTX 4070 SUPER / 620.73.04 returned pool piece, both entries cleared returned pool piece, both entries remained

That gives a red/green test through COM destruction without relying on pointer reuse. The separate full diagnostics runs with #2884 kept the same eight non-target Wine failures seen with #2884 alone. All three combined runs passed the new stock bookkeeping test and the timeline-record tests. Win64 MSVC target, Rust 1.98.1, synthetic inputs. MEASURED, AI-assisted (Codex).

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@MoonEyes Added pool::tests::dropping_last_pooled_texture_reference_forgets_recent_and_unseen in bce4a898b:

  • Allocates a real 32x32 RGBA8 placed texture via pool::texture, holds two COM references, verifies RECENT and UNSEEN stay populated after dropping the first reference, and verifies both entries are cleared when dropping the final reference triggers Reclaim::release.
  • Red/green: Removing forget_released(gone.raw) from Reclaim::release fails the test (0 passed; 1 failed); restoring it passes (1 passed under both default features and --features diagnostics, and 20/20 parallel runs of pool::).

@merzleckeier Thanks for testing the last-reference drop path independently as well!

@DIGITALWORLD-PL

Copy link
Copy Markdown

For comparison with the test-only lock in this PR, we tested an alternative for records_copied_as_bytes_are_made_at_the_next_sync on Windows with a GeForce RTX 5090 (driver 621.01).

We paused a competing synchronization round after it had taken the dirty page for slot 5 and before it published the host descriptor. Under that forced interleaving, the original test failed 6/6 runs at assert!(host.made(5)) after its own sync_heaps() returned. With our patch, the test passed 6/6 runs under the same schedule: three with the helper thread and three with inline synchronization.

Our one-file patch checks the fresh slot before the raw copy, submits a closed command list through Host::execute_sync_internal, and checks publication after it returns. The experiment exercised CPU-side descriptor publication on the RTX-backed D3D12 device. We tested the original code and our patch; we have not run this experiment against #2854's TEST_SYNC_LOCK implementation.

AI-assisted testing and independent review with OpenAI Codex (GPT-6.2 Astra).

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The strongest hunk is drop_views → title_memory_unmapping — open/remapped never cleared clean, PUBLISHED or VIEWS, so a freed address kept stale state; that is a deterministic leak, not a race. The descriptor lock is real too: my parent-commit A/B caught assert!(host.made(5)) failing 1/60 full-suite runs, and the head is 0/40. One correction: the body describes that race backwards — the observed failure was the post-sync assert seeing false because another sync had consumed the write-watch reset, not !made seeing an early mirror. Same root cause, opposite direction.

Two nits in pool.rs:

  1. Call forget_released(gone.raw) before lock(&TEXTURES).give(...) (:713-714). As written, a texture created at the same COM address in that gap can have its fresh RECENT/UNSEEN entry wiped by the release. The mechanism is right (wrapper reuse is independent of the 2.5 s piece REST), just the order.
  2. The new tests are not hermetic: dropping_last_... asserts on process-global RECENT/UNSEEN after freeing a COM object (a parallel pool test landing on the same wrapper address re-adds raw), and released_texture_pointer_... calls note_unseen(..., 10, 5) (:1295), whose retain evicts every other UNSEEN entry with begun <= 5. Low probability, but this is a flake PR.

The watch reorder (:5190) is not covered: reverting it leaves the whole 602-test suite green. That is acceptable for a race, but please don't count it as tested — it removes the specific window where the address is back with Windows while guards().changing still makes left_alone() skip guarding; the residual window between drop(changing) and UnmapViewOfFile is argued, not closed.

Mutation coverage otherwise holds: dropping forget_released from release fails the new test at pool.rs:1345, and dropping just UNSEEN.remove fails both. Merge is clean against current main; a local merge builds and passes 635/0/59 despite the 384-commit gap. #2896 is complementary (different hunks), but note #2908's require_host() sweep would leave the new pool.rs:1313 test on the old silent form.

@Neutron-0

Neutron-0 commented Dec 1, 2026 •

Copy link
Copy Markdown

Verified on Windows 11, Rust 1.98.1, no GPU and no game files.

The fix is shown to be needed, by reverting only the source the change touches. The pull request's own new test pool::tests::dropping_last_pooled_texture_reference_forgets_recent_and_unseen passes on the head bce4a898b, and fails when the one line the fix adds to Reclaim::release is taken out of the head's d3d12/crates/leonida-gpu/src/pool.rs (forget_released(gone.raw);), with the rest of the head untouched:

result
the head bce4a898b test result: ok. 1 passed; 0 failed
the head with that one line removed test result: FAILED. 0 passed; 1 failed

That test builds a real 32x32 RGBA8 texture, keeps a second COM reference so the first drop does not release it, drops the last reference, and then checks that the raw pointer is gone from both RECENT and UNSEEN - so it does cover the wiring, not only the helper.

The other new test covers less than its comment says. pool::tests::released_texture_pointer_is_not_kept_in_recent_or_unseen passes on the head, and it still passes with that same line removed: it calls forget_released(raw) itself rather than releasing anything, so it tests the helper and not the path that calls it. Its doc comment ("Releasing a pooled texture clears its raw pointer from RECENT and UNSEEN") describes the other test. Not blocking - the second test covers the wiring - but the comment overstates what is checked.

What the parallel runs showed. The whole leonida-gpu test binary was run in parallel, with the shape the report uses (cargo test -p leonida-gpu --lib --features diagnostics -- --skip depth_bounds_pipeline_loads_and_filters_draws), so that the other test threads are there to contend. This was done three times, twenty runs on the head and forty on the base:

runs
the head bce4a898b 20 passed, 0 failed
the base 7fbcd456e 33 passed, 7 failed

The seven failures on the base were in four different tests, and only one of them is named in the report:

texture::alias_cast_tests::committed_and_placed_r32_uint_textures_cast_to_r9g9b9e5_under_legacy_barriers
  panicked at crates\leonida-gpu\src\texture.rs:5664:17
  assertion `left == right` failed: left: true, right: false
  (the pool race this pull request fixes: assert_eq!(pool::fresh(&copy.texture), false) reading true)   [3 runs]

watch::tests::what_the_kernel_writes_through_is_not_guarded_for_another_view
  panicked at crates\leonida-gpu\src\watch.rs:6010:9
  assertion `left == right` failed: left: Some([42241094]), right: Some([])
  (the second guard() query expected the block to be free, and it was still guarded)                     [1 run]

watch::tests::a_block_guarded_before_we_were_told_of_its_view_can_be_written
  panicked at crates\leonida-gpu\src\watch.rs:5343:9
  assertion failed: !writable(at) && !writable(at + ...)                                                 [1 run]

timeline::report::tests::real_waits_are_recorded_with_who_ended_them
  panicked at crates\leonida-gpu\src\timeline\report.rs:1459:9
  assertion `left == right` failed: left: None, right: Some(20124)                                      [2 runs]

The two watch failures are in the file this pull request changes, under names the report does not list. The report names watch::tests::nothing_is_guarded_between_our_forgetting_it_and_its_unmapping and watch::tests::writes_to_views_are_not_lost; the ones that actually fired here are what_the_kernel_writes_through_is_not_guarded_for_another_view and a_block_guarded_before_we_were_told_of_its_view_can_be_written. The first is the same shape the report describes - a view's address reused by another thread while this thread's guard state still listed the block, so the second guard() query found the block still guarded by somebody else - and the pull request's watch.rs change (ending the remapping window before UnmapViewOfFile returns the address to Windows, and title_memory_unmapping where title_memory_remapped was called) is aimed at exactly that window. Both of these tests should be named in the report, because they are the ones that failed here.

The timeline failure is a different race, in a file this pull request does not touch, and its cause is known. crates/leonida-gpu/src/timeline/report.rs:1459 is not covered by this pull request, and neither by #2884 (which fixes the ROLLING.dropped_contention counter in timeline/record.rs). The assertion reads left: None, so there was no wait of 10 ms or more to attribute at all: the test spawns the thread that is to wait on the mutex, sleeps a fixed 20 ms and then releases the lock, and under the load of the whole binary running in parallel the new thread sometimes has not reached the lock by then. It is filed as a separate finding: in #2570, because cargo test --workspace on main is red at random when it fires. Note the shape of the four pull requests: #2854 fixes the pool and watch races, #2884 fixes the timeline/record.rs race, and the timeline/report.rs race is a fourth one that nobody has taken.

A note on the rates. A race that fires in one run out of ten does not fire in every set of ten, so the difference between the head and the base here is seven failures in forty against none, not a clean per-test verdict for each of the races. The deterministic control above is what shows the change is needed; the parallel runs show the suite is not yet clean.

Not checked: the descriptor race in this pull request (it needs the same contention and did not fire in these sixty runs); the GPU crates under a real adapter (no GPU device here).

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.

8 participants