GPU: keep persistent workers in texture::in_parallel so thread_local SCRATCH survives across submissions, and coalesce subresource spans #2786
No reviewers
Labels
No labels
accessibility
area: build
area: formats
area: gpu
area: loader
area: runtime
area: shader
bug
documentation
duplicate
enhancement
good first issue
gpu: amd
gpu: intel
gpu: nvidia
help wanted
host: wine
invalid
out of scope
question
request
run report
triage: confirmed
triage: has patch
triage: merge candidate
triage: needs info
triage: needs rebase
triage: needs work
triage: proposed close
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/Marvisak--VIctory!2786
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2786"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@RVZO6 on GitHub · 2026-11-25 20:23 UTC · original
RVZO6:rvzo/texture-refresh-pool→main· +377 −24 · 1 files · 1 commits · openClaimed in #1633: #1633
Summary
Fixes a performance bug in
crates/victory-gpu/src/texture.rs(+377/-24including unit tests and benchmark) wherein_paralleldefeated8f2a6f1'sthread_local! SCRATCHcache:texture::in_parallel:8f2a6f1introducedthread_local! SCRATCHspecifically to avoid allocating, zero-filling, and faulting a fresh texture read buffer on every refresh ("129,000 faults in a frame, run placed1"). However,in_parallelspawned ephemeral OS threads viastd::thread::scopeon everyrefresh_allanddescriptor::make_readcall, immediately destroying each worker thread and freeing itsthread_local! SCRATCHwhen the scope exited.Replacing
std::thread::scopewith a persistentParallelPool(up to 3 persistent workers + the calling thread = 4 max, matching the existingavailable_parallelism / 4cap) keeps each thread'sSCRATCHbuffer warm across submissions and removes per-submission OS thread creation/teardown. Contended or nested calls run inline to guarantee deadlock freedom; a RAII wait guard guarantees worker completion before return/unwind and propagates panics cleanly.Staging::refresh_now:merge_spans()sorts and merges overlapping or adjacent[a, b)touched subresource byte intervals before callingcopy_mapped, so each covered byte is read once instead of issuing separate calls for adjacent or partially overlapping subresources.Measured on
13f91ca(--release texture::tests::bench_in_parallel_scratch_reuse, median of 3×40 batches, 4 threads, 8× 2 MiBScratchbuffers)std::thread::scope(13f91ca)1.620 ms/batchParallelPool0.059 ms/batchNot a duplicate of
texture::in_parallelormerge_spansincrates/victory-gpu/src/texture.rs.Verification
windows-latestMSVC + WARP SM 6.6 CI (both clippy-D warningsprofiles,xtaskpolicy 6/6,victory-gpu198/198 includingparallel_pool_reuses_worker_scratch_and_handles_reentrancy_and_panicsandmerge_spans_coalesces_overlapping_and_adjacent_intervals): https://github.com/RVZO6/VIctory/actions/runs/45693633259AI-assisted: T3 Code (Antigravity, gemini-4-neon)
@kotekompotek on GitHub · 2026-11-25 20:40 UTC · original
Right diagnosis: thread_local Scratch died with the scoped threads each submission, so scratch was reallocated every frame - a persistent pool keeps it warm. The *const closure shim to workers is the standard non-'static handoff; the key invariant is run() never returns while a worker could still touch the closure, which the Drop join covers. merge_spans coalescing overlapping+adjacent intervals before the copy is a clean win. The panic/reentrancy test is the right coverage for a worker pool.
@oni-swr on GitHub · 2026-11-25 20:57 UTC · original
Independent WARP/CPU verification of head
d5f361504c40c3849c7d4ea941bcf1a6cd1f48a1merged cleanly ontoorigin/main13f91caee25f2fdf2c062be5f7a27f058e51cbca.Environment: Windows 11 x64, WARP/CPU only (
VICTORY_WARP=1,VICTORY_D3D12_WARP=1), no physical GPU, no game files; Windows SDK 10.0.26100.0 x64dxil.dll1.8.2502.11.Tests (
cargo test --no-fail-fast): victory-gpu: 197 passed, 0 failed, 2 ignored (baseline 195 passed, 1 ignored; +2 new tests, +1 ignored benchmark). The baseline's first run showedframe::tests::waits_end_on_ticks_and_count_framesfailing once and passing on the rerun (known flaky, see TEST-FRAME-WAITS); the new pool test passed 5/5 repeated runs.Negative control: changing
a <= spans[write].1to<inmerge_spansmakesmerge_spans_coalesces_overlapping_and_adjacent_intervalsfail; restored afterwards.Clippy:
cargo clippy -p <affected crates> --all-targets -- -D warningsclean (exit 0).fmt:
cargo fmt --checkis not clean onorigin/mainitself (891 diff hunks across many files); this PR: 890 hunks (-1).Review: I read the pool's claim/generation/remaining handshake, the
WaitGuarddrop ordering, the try_lock inline fallback for re-entrant/contended calls, and panic propagation; found no race or soundness problem. Merged spans only read each byte once, same bytes as before. The pool threads are never joined outside tests (static, process-lifetime), which seems acceptable. Diff contains no game files, dumps, shader names or retail hashes.AI disclosure: this verification was done by Claude Code (Claude Sonnet 5.5).
@fuzeofficlal on GitHub · 2026-11-25 21:13 UTC · original
Reviewed and benchmarked
d5f36150on Windows 11 (RTX 5090 + WARP) againstmain(13f91ca).Code review
try_lock()falls back cleanly to inline execution on concurrent/re-entrant calls (no deadlock);WaitGuard::dropblocks untilst.remaining == 0before returning or unwinding, ensuring the stack*const Joboutlives all worker accesses; both worker and caller paths wrap work incatch_unwind, advancejob.next = job.non panic, and re-throw viaresume_unwindafterdrop(guard)without poisoning the pool.Scratch::drop's existingKEEP = 32 MiBcap, retained scratch stays bounded (~128 MiB max);merge_spansdropsa >= bempties, sorts, and merges overlapping/adjacent[a, b)intervals cleanly.Verification & same-machine
--releasebenchmark (rustc 1.98.1MSVC)VICTORY_D3D12_WARP=1,--features diagnostics): 200 passed, 0 failed (texture::tests4/4, includingparallel_pool_reuses_worker_scratch_and_handles_reentrancy_and_panicsandmerge_spans_coalesces_overlapping_and_adjacent_intervals).--features diagnostics):195 passed, 2 failed(only the 2 pre-existing RTX 5090 >1M heap-cap baselines;texture::&descriptor::host::tests::a_*8/8 passed).cargo clippy --locked -p victory-gpu --all-targets -- -D warnings(default &diagnostics): 0 warnings;cargo xtask policy: 184 files ok; clean 4-waygit merge-treewith#2784,#2785,#2787.texture::tests::bench_in_parallel_scratch_reuse(--release, 3-run median × 40 batches, 4 threads × 8 × 2 MiB):0.524 ms/batch(13f91cathread::scope) ->0.009 ms/batch(58.2× / -98.3%).@Marvisak on GitHub · 2026-11-25 23:25 UTC · original
Automated triage for the maintainers.
The diagnosis checks out:
texture::in_parallelonmainspawns scoped threads on every call, so thethread_local!Scratchbuffer thatStaging::refresh_nowrelies on is dropped each time. This PR replaces the scoped threads with a persistent pool (ParallelPool, at most 3 workers plus the caller). AWaitGuardwaits for the workers before the stack-held job goes out of scope, and panics are passed back to the caller. A newmerge_spanscopies overlapping or adjacent subresource spans once instead of skipping only exact duplicates. I read the generation/claimed/remaining handshake and found no race. Points for the maintainer: this adds about 200 lines of hand-written unsafe synchronisation; a second caller that arrives while the pool is busy now runs single-threaded, wheremaingave it its own threads; and the speedup is from a synthetic benchmark, not from frame times in the title. CI passes.This is a recommendation for a maintainer to look, not an approval.
Generated by Claude Code
@Dukestar69 on GitHub · 2026-11-26 03:11 UTC · original · approved these changes
Tested merged onto
origin/main(63bcca4) on Windows 11 x64:cargo test -p victory-gpu --lib texture::: 4 passed, 0 failed, 1 ignored (including newparallel_pool_reuses_worker_scratch_and_handles_reentrancy_and_panics).cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.cargo xtask policy: 191 files ok.Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
@fuzeofficlal on GitHub · 2026-11-26 11:47 UTC · original · approved these changes
Reviewed and verified
d5f36150on Windows 11 (Ryzen 9 9950X, RTX 5090, WARP,VICTORY_D3D12_DEBUG=1).ParallelPool(crates/victory-gpu/src/texture.rs:490-715) is sound across lifetimes, re-entrancy, and panics:run_lock.try_lock()falls back to inline execution on concurrent or nested calls, avoiding deadlocks._run->job->guard) ensuresWaitGuard::dropwaits untilst.remaining == 0before the stackJobor closurefcan be dropped on either normal return or unwind.run_jobcatches worker/caller panics, stops remaining work (job.next.store(job.n, Relaxed)), and re-throws viaresume_unwindafterdrop(guard)without poisoning the pool.max_parallel_threads() - 1(at most 3 workers), andScratch::drop's existingKEEP = 32 MiBlimit bounds retained scratch memory across workers.merge_spans(texture.rs:907-925) drops empty spans and merges only overlapping or adjacent (a <= spans[write].1)[a, b)intervals, covering the exact same bytes without bridging uncommitted gaps, whilecopy_mappedhandles unmapped pages cleanly via its 64 KiB / 4 KiB fallback.Verification:
cargo xtask policy(184 files ok) andcargo clippy -p victory-gpu --tests -- -D warnings(default and--all-features): clean.texture::testspassed 5/5 repeated runs (4/4 each) anddraw::tests11/11 passed.VICTORY_D3D12_DEBUG=1and WARP +VICTORY_D3D12_DEBUG=1(--features diagnostics):texture::tests4/4 anddraw::tests11/11 passed on both adapters with zero Debug Layer errors.cargo test --release -p victory-gpu --lib texture::tests::bench_in_parallel_scratch_reuse -- --exact --ignored --nocapture):scoped=0.621 ms/batchvspooled=0.014 ms/batch(43.08x speedup).View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.