Skip to content

D3D12.X: batch used-pipelines.txt writes off the bind lock - #2635

Open
Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-pso-async-batch-used-writes
Open

Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-pso-async-batch-used-writes

Conversation

@Decodere

@Decodere Decodere commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What is in it

Part of #2508
Part of #1833

pso_async::used::note() (crates/xcl/src/hle/d3d12x/pso_async.rs) previously ran synchronous create_dir_all, OpenOptions::open, and unbuffered writeln!(f, "{key:016x}") syscalls while holding the global used::now mutex on the title's command-recording / bind thread (Pending::note_use, called from resolve and resolve_wait_for). During world-load pipeline bursts, every newly used pipeline serialized bind threads behind disk I/O.

Changes (3 files: crates/xcl/src/hle/d3d12x/pso_async.rs, crates/xcl/src/host.rs, crates/xcl/src/eh.rs):

  • Extracted used::Journal backed by a single lightweight writer thread (xcl-pso-used), Mutex<JournalState>, wake_cv, and flushed_cv.
    • Journal::note(key) performs zero filesystem syscalls on the caller thread or under the state mutex: it inserts into seen, appends to pending (continuing to queue keys while fallback_path is set even if writer spawn failed), and notifies wake_cv only on empty-to-nonempty (1) and burst-threshold (64) transitions. used::note(0) returns early before used::get(), avoiding OnceLock initialization and startup I/O on zero keys.
    • writer_loop coalesces bursts up to 25 ms (draining immediately at 64 unique keys), moves pending into in_flight (in_flight, in_flight_seq, in_flight_fallback_written) under the state lock before dropping it for I/O, lazily creates parent directories (only when absent) and opens used-pipelines.txt, performs a single batched write_all + flush, then clears in_flight and advances completed_seq = completed_seq.max(batch_seq). I/O failures clear the cached handle and never panic or break in-memory deduplication.
    • Kept if cfg!(test) isolated from the user's cache file (Journal::in_memory, with a test-only XCL_TEST_USED_STATIC_PATH env hook for subprocess exit verification) and left counts() un-flushed (present.rs calls it on PresentX).
  • Bounded initial lock and I/O paths, plus lossless accounting for batches already owned by the writer (addressing @Prime1997's #2572 review, @luckyteagirl's exit-flush review, and @KDenKC's follow-up review):
    • Added MAX_USED_FILE_BYTES = 16 MiB and read_used_bounded(path, max_bytes) in used::init_from_path and earlier_used_keys(), trimming any truncated tail back to the last newline so an oversized or truncated file cannot stall startup or parse a partial hex key.
    • Added lock_until(mutex, deadline) (try_lock loop with poison recovery, sleeping up to 1 ms slices until deadline) and poison recovery across all journal locks so Journal::flush_bounded(timeout) bounds both initial and post-fallback state-mutex acquisition and never deadlocks if another thread is suspended or wedged holding state during termination.
    • Journal::flush_bounded(timeout) accounts for writer-owned in_flight batches as well as pending: when timed out (e.g., xcl-pso-used blocked on the Windows loader lock during ExitProcess) or stopped, it drains both unwritten in_flight keys and pending keys to fallback_path and advances completed_seq only when append_to_path succeeds (restoring in_flight_fallback_written and pending on transient fallback failure, and leaving both untouched without advancing completed_seq when fallback_path is None).
    • Journal::shutdown(&self) flushes pending keys and joins xcl-pso-used through a shared &'static reference (Drop delegates to shutdown()), then drains any remaining unwritten in_flight (e.g., mid-batch writer panic where StopGuard marks writer_stopped) and pending keys to fallback_path.
    • Registered CRT atexit(on_process_exit) -> used::shutdown() when used::init_from_path initializes the file-backed static journal, wired pso_async::shutdown_used() on normal loader::run_main return in crates/xcl/src/host.rs, wired bounded pso_async::flush_used_bounded(500 ms) on the XCL_RUN_SECONDS watchdog thread before real::end_title(0) so a wedged writer cannot hang the watchdog, and wired pso_async::flush_used_bounded(100 ms) into crates/xcl/src/eh.rs::hk_nt_terminate_process alongside crate::log::flush().
  • Pure-CPU unit & subprocess tests in pso_async::used_tests:
    • used_note_does_not_block_on_slow_writer
    • used_burst_coalesces_writes_and_deduplicates_keys
    • used_flush_drop_lazy_file_and_io_error_are_graceful
    • used_static_once_lock_flushes_on_process_exit (normal / exit / explicit / bounded subprocess exit paths)
    • used_flush_bounded_timeout_and_spawn_failure_fallback_are_sound
    • used_flush_bounded_respects_timeout_when_state_lock_is_held
    • used_flush_bounded_persists_writer_in_flight_batch_and_preserves_non_fallback_pending (file-backed in-flight-only timeout, in-flight + pending timeout with monotonic completed_seq, non-fallback preservation, and mid-batch writer panic shutdown() recovery)
    • used_bounded_read_caps_oversized_file_on_line_boundary

Tested

  • hardware (GPU + driver, CPU), Rust version, debug / release: NVIDIA GeForce RTX 4060 (8 GB, driver 621.14, 32-lane waves), Intel Core i5-11400F (6C/12T, 32 GB RAM), Windows 11, DXC 1.9.2609.5, rustc 1.100.0, debug + release
  • cargo clippy --all-targets -- -A clippy::approx_constant: 0 new warnings or errors across all 3 modified files (pso_async.rs, host.rs, eh.rs)
  • Debug WARP (XCL_ADAPTER=warp, XCL_WARP=1): cargo test -p xcl --lib -- hle::d3d12x::pso_async:: --test-threads=4 --nocapture -> 22 passed, 0 failed, 0 ignored (3/3 consecutive runs, 0.79 s each, 0 skipped)
  • Release RTX 4060 targeted:
    • cargo test --release -p xcl --lib -- hle::d3d12x::pso_async:: --test-threads=4 --nocapture -> 22 passed, 0 failed, 0 ignored (3/3 consecutive runs, 0.78–0.79 s, 0 skipped)
    • cargo test --release -p xcl --lib -- hle::d3d12x::bind:: --test-threads=4 --nocapture -> 8 passed, 0 failed, 0 ignored
    • cargo test --release -p xcl --lib -- eh:: --test-threads=4 --nocapture -> 6 passed, 0 failed, 0 ignored
  • cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture: 1443 passed, 0 failed, 47 ignored across 37 workspace test targets (SKIPPED GPU tests/subcases: wave64-only GPU tests on 32-lane RTX 4060, 3 per-lane wave32 driver-refused subcases, heap_window_out_of_memory_falls_back_to_the_switch_form without XCL_HEAP_WINDOWS=1, pso_measurement_compiles_an_exact_synthetic_record without Windows Developer Mode, and 3 debug-layer tests without d3d12SDKLayers.dll)

Regression run

main:

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1571 (PresentX 1571)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13975 MB

PR:

xcl-smoke v1
commit: 3dca5a093dabd45f7933132694ef8be4e00df71f
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1554 (PresentX 1554)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14003 MB

Not tested

  • Retail title mid-world-load PSO burst micro-benchmarks (the 60 s smoke run covers startup/intro/menus) and abrupt external TerminateProcess from outside the process (which bypasses user-mode hooks and atexit).
  • Host-gated skipped GPU tests listed above (native wave64 GPUs, D3D12 debug layer SDK, XCL_HEAP_WINDOWS=1, driver-cache-disabled PSO measurement), non-Windows / Wine hosts, and the 47 #[ignore] tests.

AI use

  • Google Antigravity (Gemini 4 Neon) — authored the batched used::Journal writer, bounded initial lock/I/O paths (read_used_bounded, lock_until, XCL_RUN_SECONDS bounded flush), writer in-flight batch tracking and panic/timeout fallback recovery, process-exit flush/shutdown wiring (atexit, host::host_main, eh::hk_nt_terminate_process), unit and subprocess regression tests, and verification runs.

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

Used is held in a static OnceLock, so its Journal::Drop (which joins and drains the worker) does not run on ordinary process exit. After note() returns, the writer can wait up to COALESCE_WINDOW (25 ms) before opening/writing used-pipelines.txt; if the title exits during that window, those last-used keys are lost. The old synchronous path appended them before returning. Could the normal shutdown path explicitly flush/join this journal, and could a subprocess test record a key then exit without dropping a local Journal? The current drop test only covers a stack-owned journal.

@sage-sage

Copy link
Copy Markdown

Test report: passes on NVIDIA. Exact head bd9b4008 (its base is current main b49be18, so head = merged).

Tested

  • RTX 4080 SUPER (driver 621.40), Ryzen 5 7600X, Windows 11 26H2 build 26300.10075, rustc 1.100.0 MSVC, DXC 1.9.2602.17 (Windows SDK 10.0.26100), debug build
  • cargo test --workspace -- --test-threads=4: 1438 passed, 0 failed, 47 ignored; the three new used_tests pass
  • SKIPPED (29 lines, the same as on main on this machine): 21 wave64 tests (NVIDIA is wave32 only), 3 per-lane wave32 f16/f32 forms (refused), 3 D3D12 debug layer (d3d12SDKLayers.dll not installed), 1 no heap windows, 1 pso_measurement_compiles_an_exact_synthetic_record (Developer Mode off)

Not tested

  • No game, so not the timing on a real first-bind burst.

Claude Code (Claude Opus 5.5) ran the tests and wrote this report.

@Decodere
Decodere force-pushed the fix-pso-async-batch-used-writes branch from bd9b400 to ad798f3 Compare November 26, 2026 05:18
@Decodere

Copy link
Copy Markdown
Contributor Author

@luckyteagirl Great catch — pushed ad798f3b addressing static OnceLock<Used> exit persistence across all Windows exit paths:

  • Wrapped Journal::writer in Mutex<Option<JoinHandle<()>>> so Journal::shutdown(&self) flushes pending keys and joins xcl-pso-used through the static reference (Drop delegates to shutdown()), and registered CRT atexit(on_process_exit) when used::init_from_path initializes the file-backed journal.
  • Wired pso_async::shutdown_used() into host::host_main on normal return and XCL_RUN_SECONDS (right before real::end_title(0) suspends threads / terminates), and wired pso_async::flush_used_bounded(100 ms) into eh::hk_nt_terminate_process alongside log::flush() with a direct-append fallback to used-pipelines.txt if xcl-pso-used is blocked on the Windows loader lock during a fast ExitProcess.
  • Added used_static_once_lock_flushes_on_process_exit (subprocess test with a 60 s coalesce window, no local Journal drop) covering normal process return (atexit), Win32 ExitProcess (eh::install_crash_handler + std::process::exit(0)), explicit shutdown_used(), and flush_used_bounded() (reproduced failing-first on bd9b4008, now 18/18 passing on WARP and RTX 4060). Thanks for the review!

@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Source review of head ad798f3b, no run. Two small things in the journal, both low impact today:

  1. completed_seq can go backwards (pso_async.rs, writer_loop: completed_seq = batch_seq). The writer takes batch 1 (batch_seq = 1) and is slow in write_batch. Meanwhile a new key arrives (enqueued_seq = 2), and flush_bounded times out, appends it itself and sets completed_seq = 2. The writer then finishes and stores 1. With pending empty and completed_seq < enqueued_seq, a later flush() waits forever. Today flush() is only called from tests, and the exit path is flush_bounded (with a timeout) followed by shutdown, which still joins. So this is a latent hang, not a live one. g.completed_seq = g.completed_seq.max(batch_seq); closes it.
  2. The spawn-failure fallback never has keys to write. with_sink sets writer_stopped = true when the thread fails to spawn, and note() returns early on writer_stopped. Nothing reaches pending, so the "or failed to spawn" branch in flush_bounded writes nothing and the run's keys are silently not recorded. If keys should survive that case, note() could still push while fallback_path is set.

Not tested: no build or run of this head on our side.

AI use: Gemini (Antigravity) did a first-pass review; Claude Code (Claude Opus 5.5) checked both points against the source at ad798f3b and wrote this.

@Decodere
Decodere force-pushed the fix-pso-async-batch-used-writes branch from ad798f3 to 24e584c Compare November 26, 2026 06:56
@Decodere

Copy link
Copy Markdown
Contributor Author

@KDenKC Good catches on both points — pushed 24e584ca addressing both:

  1. Monotonic completed_seq: writer_loop now stores g.completed_seq = g.completed_seq.max(batch_seq), so a slow batch completing after a timed-out flush_bounded() fallback drain can never regress completed_seq below enqueued_seq.
  2. Spawn-failure fallback: Journal::note() now continues queuing keys while fallback_path.is_some() even if writer_stopped is set, and Journal::shutdown() also drains any remaining pending keys to fallback_path so both flush_bounded() and shutdown() persist keys if xcl-pso-used fails to spawn.
  3. Added used_flush_bounded_timeout_and_spawn_failure_fallback_are_sound covering both cases; re-verified release WARP & RTX 4060 pso_async:: (19/0/0), full release workspace (1440/0/47), and paired 60 s RTX 4060 smoke (1582 frames, 60 60 60, 0 removals/crashes).

@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Checked at 24e584ca: writer_loop stores completed_seq.max(batch_seq), and note() keeps queuing while a fallback_path exists. Both points are addressed, thanks @Decodere.

AI use: Claude Code (Claude Opus 5.5) checked the source and wrote this.

bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order.

The worker-start fallback concept was adapted from xcl-dev#2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal.

Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable.

Assisted-by: Codex (GPT-5.6-sol)
@Prime1997 Prime1997 mentioned this pull request Nov 26, 2026
Move used-pipelines.txt directory creation, lazy file open, formatting,
and disk writes out of the used::note bind mutex onto a lightweight
background writer thread (`xcl-pso-used`) with 25 ms burst coalescing
(immediate drain at 64 keys), deterministic `Journal::flush()`, and
bounded, lossless process-exit persistence.

- Bound initial lock and I/O paths: cap initial `used-pipelines.txt`
  reads in `used::init_from_path` and `earlier_used_keys` to 16 MiB on a
  clean newline boundary (`read_used_bounded`), restore the `key == 0`
  early return before `used::get()` in `used::note`, bound `flush_bounded`
  initial and post-fallback state-mutex acquisition via `lock_until` with
  poison recovery across journal paths, and use bounded
  `flush_used_bounded(500 ms)` on the `XCL_RUN_SECONDS` watchdog thread in
  `host.rs` before `real::end_title(0)` while keeping `shutdown_used()` on
  normal game return and `atexit`.
- Account for batches already owned by the writer thread: track the
  writer's active `in_flight` batch (`in_flight`, `in_flight_seq`,
  `in_flight_fallback_written`) in `JournalState` until `write_batch`
  finishes so timed-out `flush_bounded` drains (e.g., `ExitProcess`
  loader-lock stalls via `eh::hk_nt_terminate_process`) and mid-batch
  writer panic `shutdown()` persist both in-flight and queued keys to
  `fallback_path` without losing keys or falsely advancing `completed_seq`
  (and leave both intact when no `fallback_path` is configured or restore
  them on transient fallback write failure).
- Keep `cfg!(test)` isolated from the user's cache file, tolerate I/O
  failures without panicking or breaking in-memory deduplication, and add
  regression tests covering bounded lock timeout, in-flight + pending
  fallback persistence, non-fallback preservation, mid-batch writer panic
  recovery, and line-boundary bounded reads.

Part of xcl-dev#2508
Part of xcl-dev#1833

Assisted-by: Google Antigravity (Gemini 4 Neon)
@Decodere
Decodere force-pushed the fix-pso-async-batch-used-writes branch from 24e584c to 3dca5a0 Compare November 26, 2026 15:03
@Decodere

Copy link
Copy Markdown
Contributor Author

Addressed @Prime1997's #2572 review item ("Bound initial lock/I/O paths and account for batches already owned by writer") in 3dca5a09:

  1. Bounded initial lock & I/O paths: Added MAX_USED_FILE_BYTES = 16 MiB and line-boundary read_used_bounded in used::init_from_path / earlier_used_keys(), restored if key == 0 { return; } before used::get() in used::note(), bounded Journal::flush_bounded initial and post-fallback state mutex acquisition via lock_until with poison recovery across journal locks, and switched the XCL_RUN_SECONDS watchdog in host.rs to flush_used_bounded(500 ms).
  2. Writer-owned in-flight batch accounting: Tracked active in_flight / in_flight_seq / in_flight_fallback_written in JournalState so timed-out flush_bounded calls and mid-batch writer-panic shutdown() persist both in-flight and pending keys to fallback_path, advancing completed_seq only on successful write (and preserving both untouched when fallback_path is None).
  3. Regression coverage: Added used_flush_bounded_respects_timeout_when_state_lock_is_held, used_flush_bounded_persists_writer_in_flight_batch_and_preserves_non_fallback_pending, and used_bounded_read_caps_oversized_file_on_line_boundary; re-verified with 3x debug WARP & 3x release RTX 4060 pso_async:: (22/0/0), 0 new clippy warnings, full release workspace (1443/0/47), and refreshed 60 s RTX 4060 smoke against b49be183 (1554 frames, 60 60 60, 14003 MB, 0 rem/crash).

bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order.

The worker-start fallback concept was adapted from xcl-dev#2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal.

Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable.

Assisted-by: Codex (GPT-5.6-sol)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 27, 2026
Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order.

The worker-start fallback concept was adapted from xcl-dev#2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal.

Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable.

Assisted-by: Codex (GPT-5.6-sol)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 27, 2026
Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order.

The worker-start fallback concept was adapted from xcl-dev#2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal.

Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable.

Assisted-by: Codex (GPT-5.6-sol)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 27, 2026
Retain sequenced keys when the journal worker cannot start or exits, and append them only after its file handle is gone at a flush boundary. Mark torn retry fragments invalid so they cannot become false preload ranks while complete retried keys keep their order.

The worker-start fallback concept was adapted from xcl-dev#2635 by Decodere, authored there with Google Antigravity (Gemini 4 Neon), and reworked for the integrated ordered journal.

Windows-GNU cargo check passed; focused tests could not link because x86_64-w64-mingw32-dlltool is unavailable.

Assisted-by: Codex (GPT-5.6-sol)
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.

4 participants