Skip to content

D3D12.X: skip clean sparse Map readbacks and track buffer copies/clears - #3217

Open
fixgep wants to merge 1 commit into
xcl-dev:mainfrom
fixgep:fix/sparse-map-skip-clean-readback
Open

fixgep wants to merge 1 commit into
xcl-dev:mainfrom
fixgep:fix/sparse-map-skip-clean-readback

Conversation

@fixgep

@fixgep fixgep commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Skip redundant synchronous GPU readbacks on clean sparse Map ranges after certifying exact 64-byte chunks once (with XCL_MAP_SYNC=1 escape hatch), while tracking buffer copies/clears (CopyBufferRegion, CopyResource, ClearUnorderedAccessView*, ResolveQueryData) and invalidating clean certification across all potentially untracked GPU submissions.

Note on PR size: out of +1747 / -91 total lines, 1015 lines are dedicated unit and GPU regression tests covering sub-page and partial-chunk boundaries, multi-queue races, copy/clear/query write tracking, non-indexed DrawInstanced UAV writes, and atomic fast-paths (+730 / -91 production lines + 2 README.md lines). Certification and full invalidation are kept in one PR so no partial skip lands without complete invalidation coverage.

What is in it

  • Exact 64-byte chunk certification (sparse.rs): readback_now_step certifies only full 64-byte chunks actually transferred and verified clean against sent hashes when no overlapping async readback is pending and all untracked submits have settled; partial-chunk reads and unprobed neighbor chunks remain synchronous. Added XCL_MAP_SYNC=1 escape hatch (README.md) and MAP_SYNC_READBACKS / MAP_SYNC_SKIPPED counters in the periodic sparse windows: log.
  • Tracked sparse buffer writes (list_x.rs, real.rs): Records CopyBufferRegion, CopyResource, and ClearUnorderedAccessViewUint/Float writes into sparse console buffers, and integrates #3393's query_result_bytes per-query sizing in resolve_query_data_x (marking the list untracked if note_copy_into cannot track the target).
  • Complete GPU-writer invalidation (bind.rs, list_x.rs, real.rs, sparse.rs): Added note_untracked_gpu_write to bind::draw_instanced (console vtable slot 12) so non-indexed draws writing to UAVs/stream-out invalidate certified chunks, alongside DrawIndexedInstanced, Dispatch, DispatchMesh, ExecuteIndirect, ExecuteBundle, texture copies/resolves/clears, replayed/unknown lists, split KickoffX segments, and in-flight independent queues. Audited real.rs and bind.rs for hooked CopyTiles, AtomicCopyBufferUINT/64, WriteBufferImmediate, and raytracing (DispatchRays, BuildRaytracingAccelerationStructure, CopyRaytracingAccelerationStructure) paths — none of those are hooked on command lists.
  • Hot-path overhead elimination (sparse.rs, list_x.rs, real.rs):
    • SPARSE_BUFFERS_ACTIVE (AtomicBool) fast-path: note_untracked_gpu_write and begin_submission return in a single relaxed atomic load without touching LISTS when no sparse/shadowed/view console buffers exist (lists created before sparse activation remain conservatively untracked if sparse activates later).
    • Lock-free DIRTY_LISTS direct-mapped atomic cache in list_x.rs: repeated draws on an already-dirty command list skip the LISTS mutex; cleared on create/reset/release.
    • Conditional queue Signal in UntrackedSubmitTracker::finish: skips fence allocation and native_queue_signal on submit until tracked sparse writes (prepare_after_execute) or a sparse Map probe/certification arms it.
  • Tests (sparse.rs, list_x.rs, bind.rs): Added unit and GPU tests for clean-probe skip, XCL_MAP_SYNC=1, pending async overlap, sub-page / partial-chunk boundaries, multi-queue in-flight blocking, late compute and non-indexed DrawInstanced UAV writes after a clean probe, SPARSE_BUFFERS_ACTIVE / DIRTY_LISTS fast-paths, and unarmed queue Signal skipping.

Tested

  • Hardware: NVIDIA GeForce RTX 3060 + WARP (XCL_ADAPTER=warp), Windows x64, rustc 1.100.0 (0ef1bc386 2026-11-09)
  • Builds (0 new compiler warnings):
    • cargo build -j 4 --workspace: passed
    • cargo test -j 4 --workspace --no-run: passed
    • cargo build -j 4 --release -p xcl: passed
  • Targeted tests on RTX 3060 (--test-threads=1):
    • cargo test -j 4 -p xcl --lib hle::d3d12x::sparse::tests -- --test-threads=1: 149 passed, 0 failed, 1 ignored (0 SKIPPED)
    • cargo test -j 4 -p xcl --lib hle::d3d12x::list_x::tests -- --test-threads=1: 108 passed, 0 failed, 0 ignored (0 SKIPPED)
    • cargo test -j 4 -p xcl --lib hle::d3d12x::bind::tests -- --test-threads=1: 117 passed, 0 failed, 0 ignored (1 SKIPPED: two_pass_binds_set_the_shared_view_heap, opt-in XCL_HEAP_WINDOWS=1)
  • Targeted tests on XCL_ADAPTER=warp (--test-threads=1):
    • cargo test -j 4 -p xcl --lib hle::d3d12x::sparse::tests -- --test-threads=1: 149 passed, 0 failed, 1 ignored (5 pre-existing GPU/tiled-tier-2 SKIPPED; all new sparse Map certification and DrawInstanced UAV tests ran and passed)
    • cargo test -j 4 -p xcl --lib hle::d3d12x::list_x::tests -- --test-threads=1: 108 passed, 0 failed, 0 ignored (0 SKIPPED)
    • cargo test -j 4 -p xcl --lib hle::d3d12x::bind::tests -- --test-threads=1: 117 passed, 0 failed, 0 ignored (1 SKIPPED: two_pass_binds_set_the_shared_view_heap)
  • Real-title readback stats (60 s smoke run on title 3c290c16): sparse windows: 4096 submits, 1370 MB of CPU writes uploaded, 474 ms spent, 13388 tiles mapped, map sync 0 readbacks/0 skipped — this title reads sparse memory via persistent pointers rather than Map read ranges, and the atomic fast-paths kept throughput parity (1676 vs 1666 frames shown, 61 60 60 presents/2s).

Regression run

xcl-smoke v1
commit: 6bfb5c5153ccc23517daf30aa1071ddb0fadb53c
gpu: NVIDIA GeForce RTX 3060
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1666 (PresentX 1666)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15171 MB
xcl-smoke v1
commit: e6fdb91916e0753ef20cadeb1951011fa0917015
gpu: NVIDIA GeForce RTX 3060
title: 3c290c16
seconds: 60
exit: 0x0
frames shown: 1676 (PresentX 1676)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 18694 MB

Not tested

  • Full cargo test --workspace suite on this rebased commit (only targeted sparse::tests, list_x::tests, and bind::tests were run on RTX 3060 and WARP).
  • A retail title that actively issues repeated ID3D12Resource::Map read-range calls on sparse buffers (covered by the GPU regression tests in sparse::tests).

AI use
Antigravity (Google Deepmind, Gemini) rebased the branch onto upstream/main (#3393), audited GPU write hooks, implemented the DrawInstanced invalidation fix, atomic fast-paths, and regression tests, and ran the builds, targeted tests, and paired smoke runs.

@andrewDoing

Copy link
Copy Markdown
Contributor

On a GeForce RTX 5070 (driver 616.92), I reproduced stale mapped bytes on 760a932668dbf7c081d5ce0debd4ce13cb9871d8 when a compute shader writes after the first clean Map probe.

I extended the PR's sparse GPU test harness. A tracked native copy initialized 128 bytes to 0x3a and its readback updated the CPU shadow. The first 64-byte Map synchronization performed one readback and marked the page probed. A second clean synchronization correctly skipped. A native compute dispatch then wrote 0xa1b2c3d4 at offset 0 and 0xb0a3d2c5 at offset 60. I waited for its title-queue fence on the CPU before checking the same 64 bytes.

Map synchronization after dispatch New readbacks Word at 0 Word at 60
Default 0 0x3a3a3a3a 0x3a3a3a3a
XCL_MAP_SYNC=1 on the same page 1 0xa1b2c3d4 0xb0a3d2c5

All 14 interior words retained 0x3a3a3a3a. The stock test with the shader write before the first Map passed on this adapter. This fixture calls the internal synchronization routine used by resource Map and checks the actual CPU shadow. It bypasses the guest COM wrapper.

A clean probe establishes agreement at that point. Elision on subsequent Maps also needs evidence that no intervening submission could have written the page.

@andrewDoing

Copy link
Copy Markdown
Contributor

A second native RTX 5070 control on 760a932 shows that submission invalidation alone would leave a stale-read case. The compute dispatch and fence both completed before the first Map. The dispatch wrote DWORDs at offsets 0 and 60 in a 4 KiB page initially filled with 0x3a. There were no further guest submissions.

  1. Default Map of bytes [64,128) performed one synchronous readback and classified the whole page as clean. Repeating that Map skipped the readback.
  2. Default Map of [0,64) also skipped the readback and returned sixteen 0x3a3a3a3a words.
  3. Forced synchronous Map of [0,64) returned the expected 0xa1b2c3d4 and 0xb0a3d2c5 at the endpoints, with all fourteen interior words unchanged.

readback_now_locked transfers the requested subrange, while finish_probes sets a per-page bit. A clean certificate would need to cover the actual bytes being reused, including partial chunks. For the earlier late-write case, a submission-generation scheme also needs to account for pending independent queues, split KickoffX segments and replayed/unknown lists. Conservatively keeping readback enabled whenever those conditions are uncertain would retain baseline visibility. Synthetic native compute/readback fixture using the production sparse Map helper, with AI assistance from OpenAI Codex.

@fixgep
fixgep force-pushed the fix/sparse-map-skip-clean-readback branch from 760a932 to b4fdc7a Compare November 28, 2026 21:50
@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:memory Virtual/physical memory, arenas, VRAM budget, UMA gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-pr-check Failing the PR description check (CONTRIBUTING.md) and removed needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Nov 28, 2026
@andrewDoing

Copy link
Copy Markdown
Contributor

I retested both sparse Map cases on revised head b4fdc7ac1b9a07f5c6bfa2d7821c4eacdbc37964 with a GeForce RTX 5070, driver 616.92. Both still return stale bytes by default.

Sequence Default Map of [0,64) Same range with XCL_MAP_SYNC=1
Clean Map, then fenced UAV write at offsets 0 and 60 0 readbacks, both words stayed 0x3a3a3a3a 1 readback, 0xa1b2c3d4 and 0xb0a3d2c5
Fenced UAV write first, then clean Map of [64,128) on the same page, then Map of [0,64) 0 readbacks, both words stayed 0x3a3a3a3a 1 readback, same two expected words

All 14 untouched words matched in both runs. The stock UAV-write-before-first-Map control passed when its first Map covered the written words.

On this revision the tracked copy used the async after-submit preparation and drain. After each native compute dispatch, the fixture invoked the production sparse after-submit hook with empty tracked-copy and immediate ranges, as appropriate for a shader-only write. The hook returns immediately on empty ranges. The CPU waited for the title fence before inspecting the shadow. The Map fixture used the production readback step through its test wrapper. The synthetic fixture bypasses guest COM dispatch and does not measure game performance.

AI use: OpenAI Codex adapted the fixtures to this revision, ran the native comparisons, and drafted the report.

@Kalmarv

Kalmarv commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

merge-check
base: fa20459
head: b4fdc7a
merge: clean (trial merge fced91e8b82aed785ea481674bd3f13c1bb1a0a8, local, not pushed; README.md and real.rs auto-merged)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 (XCL_DXC_DIR = DXC 1.9.2609) -> 2611 passed, 4 failed, 49 ignored; SKIPPED: 26, the usual set (21 no wave64 on this 32-lane GPU, 3 per-lane f16/f32 forms refused, 2 no heap windows). All six new tests passed: clamp_console_buffer_write_clamps_and_rejects_overflow, sparse_buffer_writes_are_recorded_for_copy_and_clear, tracked_write_probes_once_then_skips_clean_sync_readbacks, untracked_compute_shader_uav_write_is_detected_and_stays_synchronous, decommit_clears_probed_and_untracked_bits_on_page_and_tile_reuse, xcl_map_sync_forces_synchronous_readback_on_clean_probed_pages. The 4 failures are environmental, not this PR: launcher_directory_with_only_xcl_copy_warns_self (OS error 112, "not enough space on the disk") and pls_quota::disk_free_space_ex_reports_pls_quota ("test requires 1 MiB of host space") hit a moment when the shared machine's disk filled up (it had 124 GB free again minutes later), and gpu_two_pass_cache_e2e::two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs failed in both its runs ("stale-mesh:" and a (3, 2, 1) vs (3, 2, 2) count), a known load flake of that driver-cache test. All three targets passed when rerun alone on the same merge (cargo test -p xcl --test gpu_two_pass_cache_e2e --test launcher_e2e --test pls_quota -> 1 + 7 + 1 passed, 0 failed).
review: blocking: a clean probe makes later shader writes invisible to Map. The first Map of a page reads it back and compares it with what was uploaded. If it's unchanged, the page is marked probed, and every later Map of it skips the readback unless a tracked readback overlaps (has_pending_readback_overlapping) or XCL_MAP_SYNC=1 is set. probed is cleared only on decommit. "Tracked" means the list's sparse_writes: CopyBufferRegion, CopyResource, CopyTextureRegion into a buffer, CopyMemory, fills, WriteBufferImmediate, ResolveQueryData, and (new here) the two UAV clears. Draws and dispatches that write a sparse buffer through a UAV are not in that list, and readback_after_execute doesn't cover them; on main they come back only because readback_now always copies the range. So once a page's first Map finds it clean, any later UAV write from a shader never reaches the CPU on Map. The PR's own untracked_compute_shader_uav_write_is_detected_and_stays_synchronous covers only the other order (GPU write before the first Map, so the probe sees it and marks the page untracked). I ran the reverse order on the trial merge with the test below (a copy of that test with the first Map moved before the dispatch): the first Map leaves probed=1 untracked=0, then after the dispatch the second Map does 0 synchronous readbacks and the CPU word stays 0x0 instead of 0xA1B2C3D4. The PR's two tests passed in the same run, which is cargo test -p xcl --lib -- nvrev_uav_write untracked_compute_shader_uav tracked_write_probes_once --test-threads=1 -> 2 passed, 1 failed. Possible fixes: clear probed for pages under a UAV a submitted draw or dispatch could write (or record such UAV ranges in sparse_writes), or keep the readback by default and make the skip opt-in until shader writes are tracked. Smaller notes: clamp_console_buffer_write was inserted between note_copy_into and its doc comment, so that doc now attaches to the helper; clear_uav notes the whole buffer (u64::MAX) even when rects limit the clear, which is safe (it over-reads).
performance: not measured. I didn't do a title run because the result above already decides the verdict; on main every Map of a sparse buffer pays the synchronous readback this PR removes, and that saving is real once the skip only covers pages nothing untracked can write.
verdict: not yet
hardware / tool and model: NVIDIA GeForce RTX 5070 Ti 16 GB (driver 610.74, wave32 only), AMD Ryzen 9 9950X, Windows 11 build 26200; rustc 1.99.0, debug test profile, DXC 1.9.2609 via XCL_DXC_DIR. Claude Code, Claude Opus 5.5: merge, build, suite, the extra test and full-diff review; this report.

The reverse-order test (added inside sparse.rs's mod tests, next to untracked_compute_shader_uav_write_is_detected_and_stays_synchronous)
    #[test]
    fn nvrev_uav_write_after_a_clean_probe_reaches_the_next_map() {
        let _lock = MAP_SYNC_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        if crate::gpu::recomp::dxc::location().is_err() {
            crate::gpu::recomp::runner::skip_test("no DXC");
            return;
        }
        unsafe {
            let Some(mut h) = TestSparseHarness::new(1, PAGE) else { return };
            let hlsl = r#"
RWByteAddressBuffer u0 : register(u0);
cbuffer C : register(b0) { uint val; };
[RootSignature("RootConstants(num32BitConstants=1, b0), UAV(u0)")]
[numthreads(1, 1, 1)]
void main() { u0.Store(0, val); u0.Store(60, val ^ 0x11111111u); }
"#;
            let dxil = crate::gpu::recomp::dxc::compile(hlsl, "main", "cs_6_6", &[]).expect("DXC compile");
            let rs: ID3D12RootSignature = h.dev.CreateRootSignature(0, &dxil).unwrap();
            let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() };
            let pso: ID3D12PipelineState = h.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap();
            let gpu_va = h.reserved.as_ref().unwrap().GetGPUVirtualAddress();
            let dispatch_uav = |h: &mut TestSparseHarness, word: u32| {
                h.run_title_list(|l, dst| {
                    l.ResourceBarrier(&[TestSparseHarness::transition_barrier(dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
                    l.SetComputeRootSignature(&rs);
                    l.SetPipelineState(&pso);
                    l.SetComputeRoot32BitConstant(0, word, 0);
                    l.SetComputeRootUnorderedAccessView(1, gpu_va);
                    l.Dispatch(1, 1, 1);
                    l.ResourceBarrier(&[TestSparseHarness::transition_barrier(dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]);
                });
                h.sync_title_to_sparse();
            };
            // the first Map, before any GPU write: the page probes clean
            h.state.readback_now_for_test(h.base, 64);
            eprintln!("nvrev: after first Map probed={} untracked={}", h.state.mapped[&h.base].probed & 1, h.state.mapped[&h.base].untracked & 1);
            dispatch_uav(&mut h, 0xA1B2_C3D4);
            let rb = map_sync_readbacks();
            h.state.readback_now_for_test(h.base, 64);
            let got = (h.base as *const u32).read_volatile();
            eprintln!("nvrev: second Map sync readbacks +{} word {got:#x}", map_sync_readbacks() - rb);
            assert_eq!(got, 0xA1B2_C3D4, "a UAV write after a clean probe must reach the next Map");
        }
    }

@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:amd-test Needs a test report or merge-check on an AMD GPU needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU and removed needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:amd-test Needs a test report or merge-check on an AMD GPU needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Nov 29, 2026
@fixgep
fixgep force-pushed the fix/sparse-map-skip-clean-readback branch from b4fdc7a to 9635736 Compare November 29, 2026 06:43
@andrewDoing

Copy link
Copy Markdown
Contributor

Retested the two previously failing 5070 cases on 96357362628faf37349a6dae3f8c4772d0a472e9. Both are fixed in these controls (RTX 5070, driver 616.92).

  • Late UAV write: The first Map certified bytes [0,64), and the identical second Map skipped the copy. After a fenced compute dispatch wrote offsets 0 and 60, the next default Map performed one readback and returned both new values.
  • Disjoint ranges: The dispatch and fence completed before the first Map. Reading [64,128) certified only that chunk, and repeating it skipped the copy. Reading [0,64) then performed one readback and returned both new values.

In each case the default result matched the subsequent forced readback (XCL_MAP_SYNC=1) on all 16 DWORDs: 0xa1b2c3d4 and 0xb0a3d2c5 at the endpoints, with the 14 intervening words still 0x3a3a3a3a. On the previously tested b4fdc7ac both default reads had skipped and returned stale bytes.

I used the saved native fixtures with the production list_x::begin_submission / finish_submission hooks around execution of the actual unregistered D3D12 compute-work command list on its queue. The sparse test state shared the tracker used by those hooks, and Map used the existing readback-step wrapper. These results cover that submission route and the two reported stale reads; guest COM recording and independent queues were outside this retest.

AI disclosure: OpenAI Codex adapted and ran the fixtures and drafted this report.

@Aniseto

Aniseto commented Nov 29, 2026

Copy link
Copy Markdown

Ran the sparse readback and list tracking tests at 96357362 on an NVIDIA Blackwell desktop part.

System

  • GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders), driver 32.0.16.2140 (621.40)
  • CPU: Intel Core i5-12400F, 64 GB RAM
  • OS: Windows 11 Pro build 26200 x64
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5
  • Build: debug

Results

  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::sparse::tests -- --test-threads=1: 147 passed, 0 failed, 1 ignored.
  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::list_x::tests -- --test-threads=1: 104 passed, 0 failed, 0 ignored.

What this adds
Both groups pass on hardware the description lists as untested (NVIDIA Blackwell / RTX 5070). They cover late compute UAV writes after a clean probe, sub-page probes ahead of dirty prefixes, pending independent queues and submission classification. The author ran them on an RTX 3060; this is the first Blackwell datapoint, on driver 32.0.16.2140. These are synthetic tests, not a title run.

Not tested
A retail title, a paired smoke run, the full workspace suite, AMD and Intel GPUs, native wave64 hosts, Wine, release profile, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - ran the commands above on this machine and wrote this report; no game data was used.

@jsalzy

jsalzy commented Nov 30, 2026

Copy link
Copy Markdown

The red CI on 9635736 is not from this PR. Its four failures (shaders::pipeline_library::tests::builder_deduplicates_names_and_atomically_replaces_output, graphics_pipeline_round_trips_through_serialized_library, mesh_pipeline_round_trips_through_serialized_library, and shaders::warm_library::tests::cold_publish_makes_an_unchanged_corpus_reusable) are the test race that #3221 fixed on main (merged Nov 29, 16:18 UTC, after this run); its commit message names this PR's base, beeb81b. This PR touches none of those files. A rebase onto main should turn CI green; the PR check will then want a new xcl-smoke block on the new head.

AI use: Claude (Claude Opus 5.5) matched the CI log against main's history; checked and posted by me.

@fixgep
fixgep force-pushed the fix/sparse-map-skip-clean-readback branch from 9635736 to 7300a37 Compare November 30, 2026 14:04
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head 7300a37, diff read, not a merge-check; conflicts with main, PR description red: its smoke block names 9635736):

  • Some GPU writes are never tracked, so a skipped readback can return stale data. A readback can be skipped only if every GPU write to that memory is seen. The console DrawInstanced hook (bind.rs ~4068, vtable slot 12) never calls note_untracked_gpu_write, while the indexed draw (~4099), dispatch (~4756), DispatchMesh (~3337), ExecuteIndirect (~3486) and the two-pass flush (~2361) do. A list whose only GPU write to a sparse buffer is a non-indexed draw (pixel-shader UAV or stream output) counts as clean. begin_submission (list_x.rs ~2138) then doesn't bump the epoch, and the next Map of a certified chunk (sparse.rs ~5789) returns stale bytes. Main is safe only because every Map reads back. Not hooked either (unverified whether titles use them): CopyTiles into a buffer, AtomicCopyBufferUINT/UINT64, the PC WriteBufferImmediate, and the raytracing calls.

  • ResolveQueryData sizes: the PR records 8 or 88 bytes (list_x.rs ~7039), too short for PIPELINE_STATISTICS1 and SO_STATISTICS. Main fixed those in D3D12.X: track exact per-query byte sizes in ResolveQueryData #3393 (query_result_bytes), and that's one of the conflict hunks; the other is set_test_console_buffer in real.rs.

  • New default-path cost, unmeasured:

    • Every CopyBufferRegion, CopyResource, footprint CopyTextureRegion and UAV clear into a sparse buffer is recorded (note_copy_into, ~2107) and copied back after submit, whether or not the title ever Maps it. CopyResource and the clears record the whole buffer.
    • Every draw and dispatch takes the global LISTS mutex.
    • Nearly every submit gets an extra Signal (sparse.rs ~221).

    Meanwhile any draw submit invalidates all certified chunks, and snapshot (~246) needs every tracked queue idle, so the saving in a running game may be near zero. Nothing counts skips in a title (MAP_SYNC_READBACKS is read by tests only).

  • Size: +1498/-89, about 840 of it tests, with no reason given for passing 800. A split:

    1. the refactor with no behaviour change (readback_now_step, readback_ranges_checked, the harness);
    2. recording sparse copies and clears, using main's query_result_bytes, with the copy-back cost measured;
    3. classifying untracked writes, plus a counter of Maps that could be skipped, without using it;
    4. the skip itself, opt-in until DrawInstanced and the writers above are covered.

Fine: the epoch / fence tracker is ordered right (a submit is in flight from before ExecuteCommandLists until its fence). Partial chunks are never certified, and decommit clears the bits. Unknown, PC, replayed, KickoffX-split and bundle lists count as untracked. The two stale reads Kalmarv and andrewDoing reported are fixed, and XCL_MAP_SYNC=1 restores the old behaviour. It will conflict with #1385, #1740 and #1847, which rewrite readback_now_locked.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@Foniass

Foniass commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Triage (#1607) – head e6fdb91

No open or merged PR skips clean sparse Map readbacks or adds XCL_MAP_SYNC/UntrackedSubmitTracker.
list_x::note_untracked_gpu_write now returns before the LISTS mutex when no sparse buffer is active (sparse_buffers_active) or the list is already marked (DIRTY_LISTS), so the hot-path concern is addressed. At ~1840 changed lines in one commit it is well over the size limit; the write tracking in list_x and the certification/skip in sparse could be separate PRs.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

Skip redundant synchronous GPU readbacks on clean sparse Map ranges after certifying exact 64-byte chunks once (with XCL_MAP_SYNC=1 escape hatch), while checking pending async readback overlap and recording CopyBufferRegion, CopyResource, and ClearUnorderedAccessView writes into sparse console buffers.

Certify only full 64-byte chunks actually transferred and verified clean (leaving partial chunks and unprobed neighbor chunks synchronous), and invalidate clean certification via a submission epoch and per-queue fence tracker across any potentially untracked GPU submission (draws, dispatches, bundles, indirects, non-buffer texture copies, replayed or unknown lists, split KickoffX segments, and in-flight independent queues).

Assisted-by: Antigravity (exact model name not provided to the agent)
@fixgep
fixgep force-pushed the fix/sparse-map-skip-clean-readback branch from 7300a37 to e6fdb91 Compare December 1, 2026 19:27
@fixgep

fixgep commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @Foniass — all points are addressed in e6fdb919 (rebased onto main 6bfb5c51):

  • Missing DrawInstanced / GPU writers: Added super::list_x::note_untracked_gpu_write(this) to bind::draw_instanced (console vtable slot 12) plus both a unit test (bind::tests::draw_instanced_marks_tracked_list_untracked_and_respects_fast_paths) and an end-to-end GPU regression test (sparse::tests::late_draw_instanced_uav_write_after_clean_probe_does_not_skip) verifying a non-indexed VS UAV write after a clean probe invalidates certification. Audited real.rs and bind.rs for CopyTiles, AtomicCopyBufferUINT/64, WriteBufferImmediate, and raytracing (DispatchRays, BuildRaytracingAccelerationStructure, CopyRaytracingAccelerationStructure) — none of those are hooked on command lists.
  • #3393 query_result_bytes: Rebased onto main and adopted query_result_bytes(ty) in resolve_query_data_x while preserving the note_untracked_gpu_write fallback when note_copy_into returns false.
  • Hot-path overhead (LISTS mutex & extra Signal):
    • Added SPARSE_BUFFERS_ACTIVE (AtomicBool) so note_untracked_gpu_write and begin_submission return in one relaxed atomic load without locking LISTS when no sparse/shadowed/view console buffers exist (lists created before sparse activation stay conservatively untracked via clean_tracking_armed if sparse activates later).
    • Added a lock-free direct-mapped DIRTY_LISTS atomic cache in list_x.rs (cleared on create/reset/release) so repeated draws on an already-dirty list skip LISTS.
    • UntrackedSubmitTracker::finish now skips fence allocation and native_queue_signal until armed by tracked sparse writes (prepare_after_execute) or a sparse Map probe/certification (sparse::tests::untracked_submit_skips_queue_signal_until_armed).
  • PR size: Of +1747 / -91 lines, 1015 lines are dedicated unit/GPU regression tests (+730 / -91 production lines); certification and full invalidation are kept together so no partial skip lands without full invalidation coverage.
  • Smoke run & stats: Updated Regression run with paired 60 s xcl-smoke blocks on 6bfb5c51 (1666 frames) and e6fdb919 (1676 frames, 0 crashes/removals, map sync 0 readbacks/0 skipped across 4096 sparse submits on 3c290c16), and verified pr_check.py passes cleanly.

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

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:memory Virtual/physical memory, arenas, VRAM budget, UMA gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants