Skip to content

GPU: atomic adaptive PSO wait budget and non-blocking pipeline library saves - #275

Open
wbkepler wants to merge 2 commits into
Marvisak:mainfrom
wbkepler:gpu/pso-hitch-and-library-save
Open

wbkepler wants to merge 2 commits into
Marvisak:mainfrom
wbkepler:gpu/pso-hitch-and-library-save

Conversation

@wbkepler

Copy link
Copy Markdown
Contributor

Summary

Eliminates mid-gameplay 500 ms PSO wait freezes and periodic 20-second pipeline-worker stalls while raising early-warmup capacity:

  • pipeline/make.rs:
    • Replaces non-atomic FRAME/WAITED_US accounting with a lock-free packed AtomicU64 FrameBudget (reserve + same-frame refund) so concurrent recording threads cannot collectively overshoot the frame wait budget or corrupt newer frames.
    • Moves from a single global Condvar to per-Pending wait_lock/wait_done wakeups.
    • Uses an adaptive default budget (500 ms for warmup frames < 60, 8 ms in steady state) with an explicit VICTORY_PSO_WAIT_MS (0..=5000 ms) override.
  • pipeline/library.rs:
    • Offloads periodic save(false) onto a dedicated low-priority background saver thread reusing its serialization buffer (pre-sized outside library.lock()).
    • Holds library.lock() strictly for ID3D12PipelineLibrary1::Serialize, skips rewriting host-pipelines.bin when only early-pipelines.txt changed, and performs unique-temp atomic write+rename with cleanup on error outside all locks (restoring dirty counters on failure).
    • Keeps shutdown save(true) synchronous via FIFO SaveAck, and raises EARLY_MAX from 8,192 to 65,536.
  • Adds 4 unit tests in victory-gpu covering concurrent 8-thread budget reservation/refund/frame isolation, VICTORY_PSO_WAIT_MS parsing/clamping and adaptive defaults, early-list recording/dedup up to 65,536, and atomic-write overwrite + temp-file cleanup on rename error.

Verification

  • cargo clippy --workspace --all-targets — passed (zero new warnings)
  • cargo clippy -p victory --features diagnostics --all-targets — passed
  • cargo test --workspace — passed
  • cargo xtask policy — passed (151 files ok)

…y saves

Eliminate mid-gameplay 500 ms PSO wait freezes and periodic 20-second
pipeline-worker stalls while raising early-warmup capacity:

- pipeline/make: replace non-atomic FRAME/WAITED_US accounting with a
  lock-free packed AtomicU64 FrameBudget (reserve + same-frame refund) so
  concurrent recording threads cannot overshoot the frame wait budget or
  corrupt a subsequent frame's budget; move from a single global Condvar
  to per-Pending wakeups so unrelated background compiles do not wake
  waiting threads.
- pipeline/make: use an adaptive default budget (500 ms during the first
  60 warmup frames for boot/menu/one-shot init passes, 8 ms in steady
  state) with an explicit `VICTORY_PSO_WAIT_MS` (`0..=5000`) override.
- pipeline/library: offload periodic saves onto a dedicated low-priority
  background saver thread reusing its serialization buffer (pre-sized
  outside `library.lock()`), hold `library.lock()` only for `Serialize`,
  skip rewriting `host-pipelines.bin` when only the early list changed,
  perform atomic unique-temp write + rename with cleanup on error outside
  all locks, keep `save(true)` synchronous on shutdown, and raise
  `EARLY_MAX` from 8,192 to 65,536.
- tests: add unit tests for concurrent budget reservation/refund/frame
  isolation, `VICTORY_PSO_WAIT_MS` parsing/clamping and adaptive defaults,
  early-list recording/dedup above 8,192 up to 65,536, and atomic-write
  temp-file cleanup on rename failure.
@ifBars

ifBars commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

I compiled a deterministic CPU-only test against the FrameBudget implementation from f7730115. A recording thread can read frame 100, get descheduled, then enter reserve(100, ...) after another thread has already reserved frame 101. Because reserve resets the state on every differing tag, the stale reservation moves the tag back to 100. The next frame-101 caller then gets a second full budget.

This interleaving needs no timing-sensitive test:

let budget = FrameBudget::new();
let limit_us = 8_000;
assert_eq!(budget.reserve(101, limit_us), limit_us);
assert_eq!(
    (budget.reserve(100, limit_us), budget.reserve(101, limit_us)),
    (0, 0),
);

The current implementation returns (8000, 8000). The existing test exercises stale refunds. Could we also test stale reservations and have reserve return zero when the supplied tag precedes the active tag, accounting for the sentinel and wraparound?

@wbkepler

Copy link
Copy Markdown
Contributor Author

@ifBars Good catch — thanks for the deterministic repro!

Fixed in 96b2822:

  • FrameBudget::frame_tag now uses frame % NO_FRAME_TAG (keeping tags strictly in 0..NO_FRAME_TAG without colliding at NO_FRAME_TAG), and FrameBudget::reserve checks is_newer_tag(tag, cur_tag) via modular half-range distance (0 < diff < NO_FRAME_TAG / 2) before resetting the budget.
  • Stale tags preceding cur_tag (including across the NO_FRAME_TAG wraparound boundary) now return 0 without mutating the active frame's packed state.
  • Added stale_reservation_never_rewinds_active_frame_or_wraparound covering the reserve(101) -> reserve(100) / reserve(101) interleaving, partial-budget preservation, and NO_FRAME_TAG wraparound (cargo test -p victory-gpu --lib: 48 passed / 1 ignored, cargo clippy -p victory-gpu --all-targets, cargo xtask policy all passing).

Xeltax pushed a commit to Xeltax/VIcky that referenced this pull request Nov 24, 2026
# Conflicts:
#	crates/victory-gpu/src/pipeline/library.rs
Xeltax pushed a commit to Xeltax/VIcky that referenced this pull request Nov 24, 2026
…Marvisak#358 Marvisak#89 Marvisak#331 Marvisak#86 Marvisak#83 Marvisak#211 Marvisak#260 Marvisak#275)

Conflict in crates/victory-gpu/src/descriptor/host.rs: gpu-state (Marvisak#251)
moved the dynamic-slot search into free_table(); gpu-draw (Marvisak#86) bounds
the search by the heap's spare slots instead of DYNAMIC. free_table() works
over taken.len(), which is the spare count, so the helper is kept with
gpu-draw's spare-based cursor wrap. Both sides' tests kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
The tester tree (upstream main ffe310e plus its PRs, update 8; see its
INTEGRATION.md) ran 11-25 minutes in the world on an RTX 5070 without a
device removal. Where both sides carry the same PR (the wave64 stack
#223/#233/#320 with #439 and #180, #454, #336, #259, #331 and others), the
tester tree's newer head is taken; our own work and the PRs only we
merged are kept.

Conflicts, file by file:

- descriptor/host.rs: the tester layout (`spare`, the guard slot after the
  dynamic slots, `free_table`, the capped sampler heap). A capped view
  heap keeps `capped_reserve()` dynamic slots, now 2^18 by default (the
  tester measurement, and our 91fed158), still `VICTORY_DYNAMIC_SLOTS` in
  diagnostics builds; uncapped hosts keep our 2^19. Our slot statistics
  (TAKEN/PEAK/SHORT), the bindless plan cache (`CommittedRegions`,
  `timed_valid_title_address`, `timed_find`, `title_bounds`) and the
  revision triple are kept beside the tester's `guard_slot`.
- Buffer states: the tester tree's buffer-state tracker (#334: every list
  moves host copies of title memory between GENERIC_READ and
  UNORDERED_ACCESS and back to common before it closes) and depth twins
  (#469) are taken. #40's enhanced/legacy indirect barriers (the indirect
  prelude, `use_indirect_buffers`, the title buffer handoff mirrored in
  `host_barrier`) cannot share buffers with that tracker and are dropped;
  #40's argument checks (`byte_len`, exact spans, overflow-safe clamp
  shader, aligned counts) stay. `indirect::bound` and #282's
  `rectangles` go through `buffer_state`, and `indirect::execute` (#334)
  replaces `done`. #178's DXC fallback compiles both of our passes.
  Our segments (#387: `close` ends the segment, `close_native` closes a
  native list) carry the tracker: each native list returns its buffers
  to common and its twins to their depth targets, and each prelude also
  holds our texture uploads.
- shadow.rs: our write flow (`queue_write`, one `snapshot` after the
  batch's refreshes, `finish_writes`, the unchanged-page cache) with
  #261's copy-back that also gives the snapshot the title's bytes; its
  tests run through our flow.
- pipeline/make.rs: #275's per-frame budget and per-pipeline wake pair,
  with our compute waits (a dispatch waits for its pipeline, up to 20 s).
- pipeline/library.rs: the tester version (#347, #275's saver thread);
  our concurrent-write test kept. shader_cache.rs: our byte-returning
  cache API with #358's "translated, only not kept".
- draw.rs: #493's root SRV tables; where no table can stand in, our
  drop of a draw whose root view is unset or outside title buffers. Our
  refusal of a table offset past the capped heap stays.
- resource.rs: `HostTexture` has both our `staged` generation and the
  depth twin.
- Shaders: the tester's lower.rs for the wave64 stack, #160's image
  sampling (it covers our #73 and #136 sample forms) and #453/#587; kept
  from our side: #136's preference for an image or buffer use of a
  descriptor read as data and its `s_buffer_` arm, #422's nearest-even
  narrowing (also for #169's d16 loads and #453's interpolation), #452's
  spin-wait limit, #391's LDS limit, #302's spilled root arguments (now in
  `NativeProgram::translation_ir`), #136's PSV0 interpolation beside the
  tester's row harmonisation. split_tests.rs, lane_read_loop_tests.rs and
  docs/wave64-on-wave32.md are the tester versions (the same PRs at newer
  heads).
- Tests: #483's heap guard dwords filled in our GPU tests of #200
  (v_div_scale) and #437 (scalar loads from a raw view), which read
  through the guard slot otherwise; #334's debug-layer test passes an
  offset to our `indirect::bound`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
…ry at the same time

Head f821cb9 (TG0000). Conflicts in pipeline/library.rs: our imports
(Arc, mpsc for #275's saver thread) with #1000's Condvar; the load takes
#1000's form (the interface cloned out of the lock, a hold per name).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: crates/victory-gpu/src/pipeline/library.rs, crates/victory-gpu/src/pipeline/make.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

@r4tedx

r4tedx commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

A pointer and one observation, since this PR and #2111 change the same accounting in pipeline/make.rs.

What overlaps. On main, wait reads the frame's waited time before it waits and adds its own only afterwards, so recording threads that wait at the same moment each take the whole budget. Both PRs fix that. #2111 does only that (the waits of a frame end together, and the frame line prints the time draws waited for pipelines); it is on main 940d32f and merges cleanly. Its synthetic test, four threads on pipelines that are never made: the frame stands still 882 ms on main and 505 ms with the fix.

What is only here. The adaptive budget (500 ms for the first 60 frames, 8 ms after), VICTORY_PSO_WAIT_MS, a wake per pipeline instead of one for all, and the non-blocking library saves. This PR came first (24 Nov). It is on d2a4bae and conflicts with main. For the library half, #2129 now maps the file and stages the save.

One behavioural difference, from reading 96b2822. wait reserves all the budget that is left before it waits, and returns at once when it is granted nothing. So when two recording threads need a pipeline at the same moment, the first holds the whole budget and the second drops its draw immediately, even if its pipeline would be there a millisecond later; it can wait only after the first has refunded. In #2111 both wait until the frame's shared budget ends. I have not measured whether that matters in the title, and neither PR has a title run.

Suggestion. After a rebase, the parts unique to this PR sit on top of either accounting, so the two need not compete: this could keep the adaptive budget, the switch and the per-pipeline wake, and take the accounting from whichever the maintainers prefer. If they prefer this PR's accounting, #2111 can close. Either way a test with two threads waiting at once would pin the case above.

Nothing was run for this comment; I read the diff.

AI-assisted (Claude Code).

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants