Skip to content

perf(gpu): list threads' lookups without shared locks (VICTORY_PLACED_SEEN, VICTORY_VIEWS_SHARDED, VICTORY_SHADOW_SHARDED) - #331

Open
PiloteCode wants to merge 1 commit into
Androtim:mainfrom
PiloteCode:pr/list-lookups
Open

PiloteCode wants to merge 1 commit into
Androtim:mainfrom
PiloteCode:pr/list-lookups

Conversation

@PiloteCode

Copy link
Copy Markdown

Summary

The threads that translate list calls (VICTORY_THIN) spend much of their time in short lookups that return the same answer draw after draw, behind locks every one of them takes. Even uncontended, taking a shared RwLock for reading writes its cache line, which then moves between cores on every read. Three cuts, each with its own switch (on unless 0; diagnostics builds can switch each inside a run with VICTORY_AB):

  1. VICTORY_PLACED_SEEN: resource::texture_at (a Mutex over a BTreeMap of 64-byte keys, taken for every view of placed memory a draw reads) is answered from a small per-thread table first. Safe because PLACED_TEXTURES is append-only (a texture made for a place and description is kept for the run); a comment on the table now says so.
  2. VICTORY_VIEWS_SHARDED: the table of every view (descriptor::VIEWS) is read under one of 16 cache-line-padded locks chosen by the reading thread; a writer takes all of them in order. Same exclusion as one RwLock; a thread that reads again while reading reuses its first lock (no writer can wedge between). views_read/views_write keep their try-first-then-count-the-wait shape (ReadMostly::try_write added for that).
  3. VICTORY_SHADOW_SHARDED: the same for the host copies' tables shadow::BUFFERS and shadow::LOOSE.

The three are in our fork's play defaults since 1 Dec.

Changes

  • crates/victory-gpu/src/listcpu.rs (new): the switches, ReadMostly<T> (+ try_read/try_write), Remembered<K, V, N>, hash_words; tests (concurrent readers under both lock modes while the switch flips, never seeing a half write; try-lock behaviour; memo correctness).
  • crates/victory-gpu/src/resource.rs: texture_at -> texture_at_seen / texture_at_table; test a_remembered_placed_texture_is_the_tables (skips without a host device, as the neighbouring test does).
  • crates/victory-gpu/src/descriptor.rs: VIEWS as OnceLock<ReadMostly<Views>>; views_read/views_write.
  • crates/victory-gpu/src/shadow.rs: BUFFERS, LOOSE as ReadMostly; .read()/.write() call sites without unwrap_or_else (poisoning handled inside).
  • crates/victory-gpu/src/lib.rs: mod listcpu;. host.rs untouched.

Rig Specs Tested On (our fork, not this tree)

  • CPU: Intel i9-14900KF (32 logical processors); also held to 12 logical processors (6-core stand-in)
  • GPU & VRAM: RTX 5090 32 GB; 12 GB card-budget stand-in at 1080p for the 12-thread run
  • System RAM: 128 GB; OS: Windows 11; driver not recorded

Run Settings & Profile

  • Method: in-run A/B with VICTORY_AB (7-8 switches, 10 s phases in a mixed order, 56 phases at the busiest place of a saved game), drift fitted; list threads' processor time per phase from the per-thread CPU counters
  • Runs: big-lcpu-2 and big-lcpu-5 (32 threads), big-lcpu-4 (12 threads, 1080p)

Measurements & Verification

Switch List threads' CPU, 32 threads (of 255 ms/frame) List threads' CPU, 12 threads (of 209) Frame median, 32 threads Frame median, 12 threads
PLACED_SEEN -6.6 +- 1.6 ms/frame -3.4 +- 1.6 -0.7 +- 0.5 ms +0.2 +- 0.3 ms
VIEWS_SHARDED -4.1 +- 1.6 -5.5 +- 1.7 +0.1 +- 0.5 -0.5 +- 0.3
SHADOW_SHARDED -5.4 +- 1.5 -4.7 +- 1.6 -0.4 +- 0.5 -0.8 +- 0.3
  • Together about 16 ms of list-thread processor time a frame less on 32 threads and 14 on 12; the frame's median about -1 ms either way (sum of the three). p90 and slowest 1 % unchanged within error (one exception: SHADOW_SHARDED slowest 1 % +3 +- 4 ms, not resolved). Pictures compared at fixed points: the same.
  • MiniVI has no per-thread CPU counters in its A/B lines; the effect should show in its thin_ms (list calls translated by threads of ours per frame) line.
  • Automated checks on this branch (rebased on main 3230974; offline, --locked, toolchain 1.98.1-msvc):
    • cargo clippy --workspace --all-targets --locked -- -D warnings
    • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
    • cargo test (not run by us on this tree)
    • cargo xtask policy (not run; files stay far below the 640 KiB limit)

Limits

…s remembered by thread, views' and host copies' tables read under per-thread lock shards (VICTORY_PLACED_SEEN, VICTORY_VIEWS_SHARDED, VICTORY_SHADOW_SHARDED)
@Androtim

Androtim commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Read-only security & triage review on 11322318 (external author PiloteCode — awaiting manual owner approval per repository security allowlist policy; not built/executed locally and not auto-merged):

  • Security / Supply-Chain / Clean-Room: Clean. Touches only crates/victory-gpu/src/{descriptor.rs,lib.rs,listcpu.rs,resource.rs,shadow.rs} (+515/-58); no Cargo.toml, build.rs, .github/workflows/, binaries, shell/network calls, or clean-room violations. Note custom unsafe sharded RwLock wrapper (listcpu.rs) + VirtualAlloc test — warrants careful soundness review on approval.
  • Architecture note: High-value lock-contention removal (VICTORY_PLACED_SEEN, VICTORY_VIEWS_SHARDED, VICTORY_SHADOW_SHARDED, default-on with =0 kill-switches). Needs manual owner approval to run CI + plain---release A/B verification.

@Androtim

Androtim commented Dec 2, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers (not an approval).

Verdict: needs-work · CI (check): pending

Review Summary

The overall idea—eliminating shared cache-line bouncing on resource::PLACED_TEXTURES, descriptor::VIEWS, and shadow::BUFFERS/LOOSE—is well-motivated and PLACED_TEXTURES is indeed append-only on main (resource::texture_at has no side effects on hit outside diagnostics-only PLACED_RAW/PLACED_TWINS). The VirtualAlloc usage flagged in crates/victory-gpu/src/resource.rs is benign (PAGE_READWRITE test allocation inside a_remembered_placed_texture_is_the_tables, matching the neighboring test).

However, there is a concrete deadlock bug in ReadMostly::read that is also directly exercised by the new unit test:

Blocking Issue

  1. Recursive std::sync::RwLock::read() deadlock under writer contention (crates/victory-gpu/src/listcpu.rs)
    • ReadMostly::read tracks re-entrancy in HELD so that when depth > 0, a nested read() picks the same shard lock (first) and calls self.locks[at].0.read() a second time.
    • std::sync::RwLock is not recursively read-lockable when a writer is waiting: both Windows SRWLOCK (AcquireSRWLockShared) and Linux futex-based std::sync::RwLock block new shared readers once an exclusive writer is queued on that lock.
    • Sequence: Reader holds locks[at] (depth == 1) → Writer blocks in locks[at].0.write() → Reader calls ReadMostly::read() again (depth == 1, same at) → Reader blocks in locks[at].0.read() behind Writer → deadlock. (try_read in descriptor::views_read similarly returns None and falls through to lock.read(), deadlocking.)
    • tests::readers_never_see_a_write_half_done_whichever_lock_they_take directly triggers this by running 6 reader threads doing nested let pair = PAIR.read(); let again = PAIR.read(); against 2 writer threads doing 20,000 PAIR.write() calls (cargo test was not run on this branch per the PR description).

Non-blocking Notes

  • ReadMostly::try_write (crates/victory-gpu/src/listcpu.rs) heap-allocates a Vec::with_capacity(SHARDS + 1) on every call (including every descriptor::views_write). A stack array (e.g., [Option<RwLockWriteGuard<'_, ()>>; SHARDS + 1] or MaybeUninit) avoids the allocation.
  • shard() uses MINE.with(...) instead of try_with, unlike HELD.try_with(...) in ReadMostly::reader/Drop, which can panic if accessed during TLS teardown.
  • Several read-only helpers in crates/victory-gpu/src/shadow.rs (stale_pages, windows, window_use, memory, spans, window_cover) still call LOOSE.write() (pre-existing on main), which now acquires 17 write locks instead of 1; switching them to LOOSE.read() would avoid stalling list threads.
  • Remembered::at assumes N is a power of two <= 1 << 24; a const assertion in Remembered::new would enforce that invariant.

To change the verdict:

  1. Fix the recursive-read deadlock in ReadMostly (either support true re-entrant reads without re-acquiring a writer-preferring std::sync::RwLock—e.g. via a recursive-read-safe lock primitive or atomic per-shard reader counts—or disallow/remove nested reads if callers never nest them, and update readers_never_see_a_write_half_done_whichever_lock_they_take accordingly).
  2. Run cargo test (including listcpu::tests::readers_never_see_a_write_half_done_whichever_lock_they_take and resource::tests::a_remembered_placed_texture_is_the_tables) and ensure CI passes.
  3. Once green, this will still warrant a local real-GPU smoke/perf check on main since the three switches default to on and prior measurements were on a fork predating #222, #285, #287, and #322.

Generated with Antigravity CLI (agy).

@Androtim Androtim added triage: needs work Triage found bugs, missing tests, or requested changes area: gpu D3D12 host, descriptors, memory, or rendering labels Dec 2, 2026
@Androtim

Androtim commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Allowlist & Architect Deep Review (PiloteCode is now on the trusted allowlist; CI 46881376625 approved and audited):

Status: triage: needs work — CI 46881376625 Tests step hung > 5 min (live deadlock), confirming the re-entrant ReadMostly::read() self-deadlock bug in crates/victory-gpu/src/listcpu.rs:

  1. Blocking — Re-entrant ReadMostly::read() deadlock (listcpu.rs:245-282, 449-453):

    • Memory-safety / aliasing exclusion of UnsafeCell<T> + Send/Sync bounds + !Send ReadGuard (_held: RwLockReadGuard<'a, ()>) is sound (every writer takes all SHARDS + 1 locks in fixed order 0..=SHARDS).
    • However, std::sync::RwLock (both Windows SRWLOCK and Linux futex) is not recursively re-entrant when a writer is waiting on the same shard. Re-acquiring self.locks[at].0.read() while already holding it deadlocks if a writer queues on self.locks[at] in between. The unit test readers_never_see_a_write_half_done_whichever_lock_they_take exercises this directly (PAIR.read() nested inside PAIR.read() under 2 concurrent writers), causing the live CI hang.
    • Fix: Either make ReadMostly strictly non-reentrant (matching std::sync::RwLock, removing HELD and the nested PAIR.read() in the test after verifying no VIEWS/BUFFERS/LOOSE call site nests reads) or avoid re-acquiring the underlying RwLock while depth > 0 without allowing out-of-order early unlock.
  2. Additional architectural findings to fix in the same pass:

    • Read-only LOOSE.write() stalls (crates/victory-gpu/src/shadow.rs): stale_pages(), spans(), and diagnostics helpers (windows, window_use, memory, window_cover) still call LOOSE.write() for read-only iteration. With ReadMostly, each LOOSE.write() now acquires all 17 shard locks, stalling every recording thread unnecessarily. Switching those read-only sites to LOOSE.read() removes that contention.
    • Unmasked filler words in PLACED_SEEN (crates/victory-gpu/src/resource.rs:texture_at_seen): PLACED_TEXTURES is confirmed append-only, so caching This is sound today. However, texture_at_seen hashes and caches the raw *desc without zeroing filler words desc[1] and desc[13] (unlike texture_at_table), so stack-garbage variations in filler words will cause false misses and duplicate entries in the 1024-slot thread-local cache.
    • Minor: Avoid heap-allocating Vec::with_capacity(SHARDS + 1) on every ReadMostly::try_write(), and fix the a_remembered_placed_texture_is_the_tables eviction loop (currently calls texture_at_seen(..., &buffer), which returns None and never writes to PLACED_SEEN).

Once fixed and CI is green, this will need a plain --release A/B run on main (b0842d93+) before merge.

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

Labels

area: gpu D3D12 host, descriptors, memory, or rendering triage: needs work Triage found bugs, missing tests, or requested changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants