Skip to content

gpu/pool/small: release pool mutex during CreateHeap block growth (D3D12-POOL-SMALL-GROW-UNLOCKED) - #2857

Merged
OreoFR merged 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/gpu-pool-small-unlock-grow
Dec 1, 2026
Merged

OreoFR merged 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/gpu-pool-small-unlock-grow

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-POOL-SMALL-GROW-UNLOCKED (claim comment)

What and why

Release the Small buffer pool mutex (Small::pool) while creating and making resident a new 64 MiB ID3D12Heap block in d3d12/crates/leonida-gpu/src/pool/small.rs — direct companion to merged PR #2693 (D3D12-POOL-GROW-UNLOCKED, which unlocked growth for texture and staging pools in pool.rs but left pool/small.rs holding small.pool() across block(device, kind)).

  • How it works: Adds a dedicated grow: Mutex<()> to Small and extracts take_with, reusing super::Pool::take_or_need, super::Pool::add, and super::Pool::growth_failed from pool.rs:
    1. Fast path drains back and calls take_or_need(..., Ripe::ALL) without taking grow, so threads taking free/returned pieces never wait behind a concurrent CreateHeap/MakeResident.
    2. Misses serialize on grow, double-check take_or_need (so concurrent misses share a single newly created block and respect failed-growth backoff), drop the pool mutex, invoke make(), and then re-acquire pool to add the new block (or record growth_failed).
  • Scope discipline: Keeps KEPT = 2 unchanged (zero VRAM/retention policy change).
  • Evidence classification: READ IN CODE (d3d12/crates/leonida-gpu/src/pool/small.rs + pool.rs #2693) + race-free deterministic multi-threaded unit tests verified red→green under Wine + MEASURED 300 s in-game gate on exact PR head 2451b4744.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-gpu/src/pool/small.rs → exit 0.
  • cargo check --locked --target x86_64-pc-windows-msvc -p leonida-gpu --features diagnostics → 0 errors, 0 warnings in pool/small.rs.
  • Cross-compiled leonida-gpu test binary (x86_64-pc-windows-msvc) and ran under Wine:
    • RED on origin/main (testing origin/main's locked pool.take with assert!(pool.try_lock().is_ok(), "heap creation must not own the pool lock")):
      running 1 test
      test pool::small::tests::growth_unlocks_the_pool_and_concurrent_misses_share_one_block ... FAILED
      # thread '<unnamed>' panicked: heap creation must not own the pool lock
      test result: FAILED. 0 passed; 1 failed; 0 ignored
      
    • GREEN on PR head 2451b4744 (rebased onto cd73ddab7):
      • pool::small::tests: 5 passed; 0 failed; 0 ignored (including growth_unlocks_the_pool_and_concurrent_misses_share_one_block, verified 10/10 consecutive runs).
      • pool::tests: 14 passed; 0 failed; 0 ignored.
  • 300 s in-game gate (docs/game_gate.md) on exact PR head 2451b4744 (leonida.exe --profile play --features mimalloc,dlss,diagnostics, Series S + DLSS Quality 1280×720 → 1920×1080):
    • Verdict: PASS
    • In-world duration: 310.04 s (world_at_s = 77.49 s, >= 300 s required)
    • Frames (world + 60 s to stop): 3,108 presented frames (3,206 total world presents), 15.20 median FPS, 115.53 ms p95 frame time (15.53 end-window median FPS, 4,372 median draws/frame)
    • Longest present gap in world: 3.884 s (<= 10.0 s required)
    • Peak VRAM: 6,717 MiB (<= 7,400 MiB guard)
    • Stability: 0 device losses, 0 crashes/faults, 0 panics, 0 kernel NVRM: Xid errors

GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).

AI-assisted: yes (authored by Gemini 4 Neon; audited and approved in a separate independent review pass by Gemini 4 Neon).

Checklist

  • Based on current main (cd73ddab7) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (check_no_game_data.py clean).
  • A new translator rule is in the contract table of docs/design.md (n/a — GPU small-buffer pool locking change).
  • Independent fresh reviewer agent audit completed (APPROVED).
  • 300 s in-game gate completed and PASSED on exact PR head (2451b4744).

@fiestorra

Copy link
Copy Markdown
Contributor

Verified on Windows: the crate is green with it, and it adds two tests - measured against main's own file. Run on one thread on purpose.

main 3393ceec9, cherry-picked (one commit, merge-base cd73ddab7), cargo 1.98.1:

cargo test -p leonida-gpu --lib -- --test-threads=1
  with this pull request:            ok. 603 passed; 0 failed; 55 ignored   (37 s)
  (main:                             ok. 601 passed; 0 failed; 55 ignored)

Why one thread: this crate's tests interfere with each other when they share a process - sixteen runs with the default threads failed twice and eight with --test-threads=1 failed none (#2570). Existence control, not mutation: I did not remove the mutex release to watch a specific test fail.

And that is the interesting part of this change for that flake: pool/small.rs is a shared pool behind a mutex, which is exactly the shape that bites in parallel. 603 passing on one thread says the change is correct; it says nothing about whether it makes anything faster, because the property it is for - not holding the mutex across CreateHeap - is a timing property and this is a correctness run.

What I could not test: the latency it is for. The best I can say is that the tests that do use the pool still pass, and the crate has a --test-threads=1 story it did not have this morning.

AI-assisted: yes - DeepSeek v4.1 (flash), one 37-second serial run.

Written with an AI assistant.

@merzleckeier

Copy link
Copy Markdown
Contributor

Independent check of 2451b4744 on 21e6bbf4b, with #2854 and #2855 also applied. Both new pool tests passed in the Windows test binary under Wine. In a separate build, moving the pool lock back around make() made growth_unlocks_the_pool_and_concurrent_misses_share_one_block fail at the lock assertion. This verifies that the fixture catches the old lock scope.

The new pool cases use a stub allocator. The surrounding test selection ran on AMD Raphael (RADV 26.3.1) and RTX 4070 SUPER (NVIDIA 620.73.4). Driver allocation latency was outside this run.

AI-assisted with OpenAI Codex.

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

RUN (native Windows 10 + RTX 5070 verification; #2857, #2860, and #2862 merged cleanly together onto main ed867d7b2)

  • Unit tests: cargo test --locked -p leonida-gpu --lib pool::small: 5 passed, 0 failed.
  • In-game gate: Series S, -NoFrameGen, 731.6 s cold precompile, 180 s in world (321.3 s total, 38 world samples >= 1000 draws, median 22.2 fps / 45.1 ms, gpu_wait 0.0 ms, 4,424 median / 5,346 max draws): 0 crashes, 0 panics, 0 device-lost events.

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

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Verified by MoonEyes (another person than the author) on head 2451b4744 merged with main cd0c52fcf: I read the whole diff. cargo test -p leonida-gpu: the only failure seen, committed_and_placed_r32_uint_textures_cast_to_r9g9b9e5_under_legacy_barriers, fails in 2 of 5 parallel runs of plain main too. With the pool's lock held around make(), growth_unlocks_the_pool_and_concurrent_misses_share_one_block fails.

In-game run with the six others of a batch on main 21e6bbf4b: RTX 4060 8 GB, NVIDIA 610.88, Windows 11 26300, -SeriesS -FrameGen 2, about 860 s in the world, then a second one of about 440 s, 0 device lost, 0 panic; pictures of the same scene compared with main, same. Black surfaces in early cutscenes while the PC's memory is full are there on plain main too.

AI-assisted (Claude Code).

@merzleckeier

Copy link
Copy Markdown
Contributor

I followed up on the mock allocator test with a real D3D12 heap handoff check at 2451b47 + 0ff8a53. On Radeon Raphael (RADV 26.3.1) and RTX 4070 SUPER (620.73.04), Win64 under Wine 11.22, I filled a real 64 MiB upload block with sixteen 4 MiB pieces. The growth thread made a second block through production block(), then waited inside make() before publishing the new block. A second worker reused the exact returned piece and its original heap while growth was still parked. The new block was distinct, and the stock GPU copy/reuse test and the rest of the small-pool selection passed (6/6 including the local fixture on each GPU).

As a negative control I moved the pool lock back around make(). On RADV the same fixture timed out waiting for the returned piece before growth was released. The controlled pause is after the real driver allocation, so this checks lock scope and reuse during growth, without measuring natural driver latency. MEASURED with offscreen synthetic allocations. AI-assisted (Codex).

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

Approved (non-blocking). The lock scope is exactly as claimed: small.rs:118 takes from free memory without grow, the miss path takes grow (:123), re-checks (:124), runs make() with only grow held (:129), then re-adds under pool (:130-137). Because pool is declared after _grow, the block is published before a waiter can acquire grow, so the double-check cannot duplicate a 64 MiB heap. returned() keeps the back→pool order and room() only try_locks pool, so there is no inversion; the failure arm mirrors Pool::grow's 500 ms backoff (:139-141).

Both new tests are meaningful, not just existence checks: holding the pool guard across make() makes growth_unlocks_the_pool_and_concurrent_misses_share_one_block fail at its try_lock assertion (small.rs:412) — I verified that locally. pool::small is 5/5, ten consecutive growth runs are green, and the merged tree with current main builds and passes.

Two optional consistency follow-ups: Small has no LEONIDA_POOL_GROW_UNLOCKED=0-style switch back to under-lock growth, unlike pool.rs, and grow.lock() waits are not counted in the diagnostics LOCK_WAITS that pool.rs::lock() feeds.

Not independently verified here: the 300 s in-game run and the claimed latency win (no game data), and the Wine/VKD3D driver timings. Unit and device tests only. Merge is clean; 383 commits behind, but both small.rs and pool.rs are byte-identical upstream.

@OreoFR

OreoFR commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

In-game RUN of head 2451b47, merged with #2852 (c4e286f) onto main 1abef08 (tree 32b6b8c23). RTX 4070 Laptop 8 GB, NVIDIA 621.40, Windows 11, -SeriesS -NoDlss -NoFrameGen.

  • cargo test -p leonida-gpu --lib --locked: 647 passed, 0 failed.
  • Cold start to the world, then a 900 s warm walking run: 0 device lost, no panic; frame median 37.8 ms (26.5 fps), p90 38.8 ms.
  • Private memory flat after loading: 23.7 GB at +3 min, 24.0-24.2 GB from +5 min to +15 min (max 24.3 GB), so no growth over 900 s.
  • The fps is a little under my 330 s main runs (27.9-28.2) because the 900 s walk reaches heavier streets; the build ran from another folder than my main baseline, and the driver cache is per exe path, so it is not a like-for-like fps comparison.
    AI-assisted: Claude Code (oreofr-agent).

@OreoFR

OreoFR commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Merging (added to the merge queue). Head 2451b47 merges cleanly with main 913b88b; since my test main gained only #2973, #2858, #2882, #2788, #2876 and #2884, none of which touches this pull request's file. Claim: D3D12-POOL-SMALL-GROW-UNLOCKED (coordination issue #2570). Red/green: merzleckeier (real 64 MiB D3D12 heap handoff under Wine on RADV and RTX 4070 SUPER), KelboLive review on this head (lock scope checked line by line), MoonEyes, fiestorra and lixonik earlier. I ran: #2857 and #2852 together on main 1abef08, leonida-gpu 647 passed / 0 failed, and a 900 s warm in-game run on an RTX 4070 Laptop (621.40): 0 device lost, private memory flat at 24.0-24.3 GB (details in my RUN comment above). CI: green on head and main; the queue runs the full CI before merging. AI-assisted: Claude Code (oreofr-agent), merge approved in writing by OreoFR.

@OreoFR
OreoFR added this pull request to the merge queue Dec 1, 2026
@EdenBendheim

Copy link
Copy Markdown
Contributor

Independent native Windows 11 + RTX 3090 verification (VERIFY-2857-RTX3090, claimed in #2570): PASS

  • Tested: PR head 2451b4744 merged cleanly onto main c4ca57615 (diagnostics,mimalloc, exe_sha16: b37ba94a1ad2a01e).
  • Hardware / OS: Windows 11, AMD Ryzen 9 5900X, 32 GiB RAM, NVIDIA GeForce RTX 3090 24 GiB (driver 610.88).
  • Clean-room check: python -I scripts/check_no_game_data.py passed on pool/small.rs.
  • Unit check (cargo test -p leonida-gpu --locked --lib -- pool::small::tests --test-threads=1):
    • Merged PR (default and --features diagnostics): 5 passed, 0 failed in both configurations. (Transplanting the tests alone onto main fails to compile because they call the new take_with helper.)
  • Retail 300 s in-game dynamic-stress gate (scripts/game-gate.ps1, Series X 1080–1440p, -NoFrameGen, gate_driver mode=roam + LEONIDA_GAME_ACTIONS_RUN="120:wanted 2", same free-roam template as main baseline):
    • Verdict: PASS (reasons=[], warnings=[], exit=clean, stop=target, cache_saved=true, GATE CONTROL fired with moved=1.16 m, max from_control_m=2.7 m, 0 GATE FAIL).
    • Metrics (world_s=301.6s, world+60s, 5,572 presents, 7,176 median draws): 23.08 FPS median, 18.83 FPS p5, 53.10 ms p95 frame time, 2.479 s longest present gap, 0 missed pipeline waits, 26,375 MB max private memory, 2,540 MB min commit left, 8,211 MB max VRAM (0 s over budget).
    • Reference main c4ca57615 roam + wanted 2 baseline (exe_sha16: 94748f45e468665a, max displacement 8.7 m): PASS (300.9 s, 22.29 FPS median, 54.13 ms p95, 2.851 s longest gap, 7,450 median draws). (Single-run stability gate; not an ABBA FPS claim.)
  • Minor test-harness note (non-blocking): In the concurrency unit test, if the controlling thread panics after the grower parks and before releasing the barrier, scoped-thread cleanup could hang.

AI-assisted: yes (Gemini 4 Neon orchestrator; Codex GPT-6.2 Astra build, unit tests, and serialized RTX 3090 gate execution).

Merged via the queue into ProjectLeonida:main with commit d6baf35 Dec 1, 2026
5 checks passed
@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2857 — Linux, Fedora 45, Rust 1.98.1 (the pinned toolchain), Wine 11.21, no GPU device, no game files

Verdict: PASS. The pool no longer holds its lock across the driver's heap creation, the new test checks exactly that, and nothing that passed before fails now. One test failed once in a full run; it fails on the base at the same rate, so it is not this pull request's doing.

Head 2451b474, base the current main, merge base cd73ddab, 1 file, +145/−8: d3d12/crates/leonida-gpu/src/pool/small.rs.

1. What it changes

The small-buffer pool kept its mutex across CreateHeap — the driver's call, which is the slow part — so a miss blocked every other user of the pool, including the ones that only wanted an existing piece. The change splits the two: the pool's lock is taken to look for a piece and released again, and a separate grow mutex keeps the misses among themselves:

fn take_with<B: Clone>(pool: &Mutex<Pool<B>>, back: &Mutex<Vec<Piece>>, grow: &Mutex<()>,
                       len: u64, make: impl FnOnce() -> Option<B>) -> Option<(Piece, B, bool)> {
    match returned(pool, back).take_or_need(len, ALIGN, now(), Ripe::ALL) { ... }
    let _grow = grow.lock().unwrap_or_else(|e| e.into_inner());
    // … check again: the previous grower may have supplied enough memory for both requests
    match returned(pool, back).take_or_need(len, ALIGN, now(), Ripe::ALL) { ... }
    let memory = make();                     // the driver's CreateHeap, without the pool lock
    ...
}

The second lookup is what keeps two concurrent misses from each creating a block: the second one finds the first one's block.

2. The new test checks the property that matters

let grower = scope.spawn(|| {
    take_with(&pool, &back, &grow, ALIGN, || {
        assert!(pool.try_lock().is_ok(), "heap creation must not own the pool lock");
        ...

The test parks a growing worker inside make() while six other threads wait, and asserts that the pool's lock is free at that moment — that is the pull request's whole point, and it needs no device: the pool holds u32s, not real heaps.

3. What the tests do here

leonida-gpu does not build on Linux (upstream: "The crates are Windows-only today … Linux follows #2577"), so I cross-compiled it for x86_64-pc-windows-gnu and ran the tests under Wine 11.21.

The red side (the merge base with only this pull request's tests) does not compile — the new test calls take_with, which the change introduces — so the base and the head were compared instead:

the merge base 654 tests
the pull request's head 656 tests
the new tests, only on the head 2 — both pass
failing on both sides 3 — watch::many_askers_tests::holes_are_known_until_the_runtime_tells, watch::many_askers_tests::no_mapping_is_lost_between_askers and watch::tests::what_is_left_alone_is_no_known_hole

4. The one failure I saw, and why it is not this pull request

watch::tests::a_block_just_written_rests failed in one full-suite run on the head and passed on the base, which looks like a regression. It is a flake, and it is not this change's:

  • run alone: 5 passes, 0 failures on the head;
  • full suite, head: 8 runs, 1 failure;
  • full suite, base: 7 runs, 1 failure.

The base fails it at the same rate, so I do not attribute it to the pull request. It is one of the watch tests that depend on Microsoft's VirtualAlloc/VirtualQuery behaviour, which Wine does not have.

5. What I did not check

  • The pool under real contention. The new test checks the locking property with a fake make; the real CreateHeap (which can take milliseconds) was not exercised, and neither was the driver's own behaviour under the released lock.
  • Whether releasing the pool lock across CreateHeap can make two misses each create a block. The second lookup under the grow lock is meant to prevent it; I read it, I did not stress it.
  • Windows and MSVC. Everything above is Linux with Wine 11.21 (staging) and no GPU device.
  • The corpus. How often the small pool misses is a property of a run with the game.

AI-assisted: MiniMax M3.1 Flash.

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