Skip to content

startup: reuse completed upload ring chunks after GPU execution - #2847

Closed
Holastor wants to merge 6 commits into
R0Y00:mainfrom
Holastor:gpu/upload-ring-completion-reuse
Closed

Holastor wants to merge 6 commits into
R0Y00:mainfrom
Holastor:gpu/upload-ring-completion-reuse

Conversation

@Holastor

Copy link
Copy Markdown
Contributor

Summary

Fixes #2837
Refs #2823

In #2823 (commit 7256cecf), uncompleted reuse of the shared upload ring was removed to fix in-flight GPU memory corruption. However, because chunks were never recycled once GPU submissions finished, total reservations permanently froze upon reaching the 256 MiB cap, refusing every subsequent upload and leading to black screens and hundreds of thousands of null buffer bindings in long startup runs.

This change:

  1. Tracks queue submission fence values on upload chunks in UploadRingChunk::submits whenever a queue signals its completion fence in note_submits.
  2. Marks chunks containing reservations with unsubmitted = true, which is cleared and bound to the signaled fence value during queue submission.
  3. Implements is_upload_chunk_idle and reset_upload_chunk: when capacity is exhausted and no active chunk or unused tail can satisfy a reservation, idle chunks whose GPU work has completed (GetCompletedValue() >= submit.second) are reset and reused from offset 0. Storage still in flight on the GPU is never reused before completion.
  4. Adds unit test coverage in tests/upload_reservation_check.cpp.
  5. Adds the gate-ring-reuse test fixture to CMakeLists.txt, tests/startup_stream_draw.cpp, and tests/startup_address_console_check.py, and updates docs/startup-runtime.md.

Evidence

  • Commit under test: 969fa03d

  • Environment:

    • Windows 11 x64 (Build 26100)
    • Hardware adapter: AMD Radeon RX 6600M (driver 32.0.21045.11001)
    • Software backend: Microsoft Basic Render Driver / WARP (driver 10.0.26100.10068)
  • Unit test:

.\out\build\dev\upload_reservation_check.exe

Output:

upload_reservation_check: all checks passed
  • Fixture tests:
ctest --preset dev --no-tests=error -R '^startup_address_console_gate' -V

Output:

1/6 Test #1332: startup_address_console_gate_warp ..................   Passed    2.21 sec
2/6 Test #1333: startup_address_console_gate_ring_warp .............   Passed    2.00 sec
3/6 Test #1334: startup_address_console_gate_ring_reuse_warp .......   Passed    2.15 sec
4/6 Test #1377: startup_address_console_gate_hardware ..............   Passed    2.51 sec
5/6 Test #1378: startup_address_console_gate_ring_hardware .........   Passed    2.27 sec
6/6 Test #1379: startup_address_console_gate_ring_reuse_hardware ...   Passed    2.36 sec

100% tests passed, 0 tests failed out of 6
  • Documentation & Formatting checks:
python -B tests/docs_links_check.py
python -B tests/bidi_controls_check.py
git diff --check

All passed without error.

In R0Y00#2823 (commit 7256cec), uncompleted reuse of the shared upload ring was removed to prevent GPU in-flight memory corruption. However, because chunks were never recycled once GPU submissions finished, total reservations permanently froze upon reaching the 256 MiB cap, refusing every subsequent upload and leading to black screens and hundreds of thousands of null buffer bindings in long startup runs.

Track queue submission fence values on upload chunks that receive unsubmitted writes. When active chunks and free tails cannot satisfy a reservation, inspect completed fence values and reset completed, idle chunks, guaranteeing storage still in flight on the GPU is never reused before completion.

Add the gate-ring-reuse fixture to verify that upload reservations succeed once earlier GPU submissions complete, while gate and gate-ring continue to enforce in-flight safety and exhaustion limits.

Fixes R0Y00#2837

Refs R0Y00#2823

@tedin7 tedin7 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of head 969fa03 (comment only, no approval).

Finding 1 (correctness, can bring back the corruption #2823 fixed): chunk reuse is tied to "any submit", not to the lists that use the chunk.

  • reserve_upload_chunk (upload_reservation.h) sets unsubmitted = true when a chunk is reserved, i.e. while a command list is still being recorded.
  • note_upload_ring_submit (d3d12_xs_device.cpp, called from note_submits) clears unsubmitted on EVERY chunk and binds it to the fence value of whichever queue just executed, whichever lists that was.
  • Sequence: list A records a draw and reserves bytes in chunk C (not executed yet). List B (another thread or another queue, recorded earlier) is executed. note_submits marks C as submitted with B's fence value. B completes. is_upload_chunk_idle(C) is true. When the ring is full, reset_upload_chunk(C) runs and new data overwrites the bytes list A still has to read. That is the same in-flight corruption as before #2823, only rarer.
  • A chunk used by lists on two queues has the same hole: the first submit clears unsubmitted, the second queue's fence is never added.
  • Fix idea: record the chunks (or ring watermark) a list reserved in its own recording state, and bind the fence only when that list is executed (the list_recordings / retire_address_uploads path next to it already tracks per-list data). Keep a chunk non-idle until every list that reserved from it has been executed and its fence has passed.

Finding 2 (test coverage): the new tests do not guard the fence logic.

  • upload_reservation_check.cpp only checks that reset_upload_chunk zeroes the cursor. is_upload_chunk_idle and note_upload_ring_submit live in d3d12_xs_device.cpp and have no unit test: not the "fence not yet passed, must not reuse" case, not the "reserved but not yet executed" case from finding 1.
  • gate-ring-reuse checks only the good case (everything completed, one more payload must be accepted). It would catch a ring that never recycles, but not one that recycles too early. A negative control is missing: run the reuse draw while the queue is still waiting on the gate fence and require it to be refused (left half keeps payload 0, no overwrite).
  • I could not run the D3D12 fixtures here (Linux only), so I did not try a mutation of the fence comparison. Please add the negative control and show that it fails when GetCompletedValue() < submit.second is dropped.

Startup claim. The body says this fixes black screens and null bindings in long startup runs. I have no way to check that on the real title. Fixture results (yours, on WARP and hardware) are a separate thing from that. The merge stays with MasterDomino or @R0Y00, who can verify on the game.

Checked locally: git diff --check origin/main...HEAD clean, python3 tests/docs_links_check.py ok (27 files, 541 links), python3 tests/bidi_controls_check.py ok. Reviewed the code of d3d12_xs_device.cpp, upload_reservation.h, the three test files and CMakeLists.txt. No other open PR covers this slice (follows #2823).

AI-assisted; commands listed were executed locally.

Address review feedback on R0Y00#2847 (tedin7):

1. Tie chunk reuse to the command lists that actually reserve from them. Track recorded chunks per command list in recorded_upload_chunks. Chunks maintain an unsubmitted_lists count and are bound to queue submit fence values only when the lists using them are executed. When a recording is discarded on Reset or failed Close, its reservations are dropped.

2. In upload_reservation_check.cpp, test unsubmitted lists, pending and completed fence values, and multi-queue submissions.

3. In gate-ring-reuse, add a negative control draw while the queue is held behind the gate fence. Verify it is refused and preserves payload 0 on the left half, and verify mutation of the fence check fails the fixture.
@Holastor

Copy link
Copy Markdown
Contributor Author

Thank you @tedin7 for the thorough and insightful review! Both findings have been addressed in 895a7c0d:

1. Per-List / Per-Recording Chunk Tracking (Finding 1)

  • Replaced the global unsubmitted boolean with per-list tracking:
    • recorded_upload_chunks (std::unordered_map<ID3D12CommandList*, std::vector<std::size_t>>) tracks which chunk indices are referenced by each command list during recording (in reserve_upload_ring, frame_copy, ring_copy, and upload_from_title).
    • Each UploadRingChunk tracks unsubmitted_lists. While any unsubmitted list references the chunk, is_upload_chunk_idle returns false.
    • When command lists are executed in queue_execute, note_upload_ring_submits(fence, value, native_lists) decrements unsubmitted_lists and binds that queue's signaled fence value only to the chunks that were actually recorded on those lists.
    • If a command list is reset or fails Close() without being submitted, discard_upload_ring(list) decrements unsubmitted_lists and clears its recorded entries.
    • Chunks shared across lists on multiple queues retain all active fences in chunk.submits; is_upload_chunk_idle requires every queue fence to reach its target value.

2. Guarded Fence Logic & Unit Tests (Finding 2)

  • In tests/upload_reservation_check.cpp, added unit tests validating:
    • Unsubmitted list in flight (unsubmitted_lists = 1) -> !is_upload_chunk_idle.
    • Pending GPU execution (completed = 9 < 10) -> !is_upload_chunk_idle.
    • Completed GPU execution (completed = 10 >= 10) -> is_upload_chunk_idle.
    • Multi-queue submission with one completed and one pending -> !is_upload_chunk_idle.
    • All multi-queue submissions completed -> is_upload_chunk_idle.
    • Reset clearing cursor, submits, and unsubmitted count.

3. Negative Control & Mutation Verification (Finding 2)

  • In tests/startup_stream_draw.cpp, added a negative control draw while the queue is still held behind the gate fence:
    • When the ring is full, attempting a reservation while earlier submissions are in flight must be refused; the refused draw reads the null view over the right half and chunk 0 is untouched, preserving payload 0 on the left half.
    • check_gate_ring_reuse in tests/startup_address_console_check.py asserts that this in-flight refusal was logged in trap.log.
  • Mutation check: Temporarily dropping the fence check query(submit.first) < submit.second in is_upload_chunk_idle:
    • upload_reservation_check.exe failed:
      FAIL: chunk with in-flight submit is not idle
    • startup_address_console_gate_ring_reuse_warp failed:
      AssertionError: gate-ring-reuse: {'left': 32768, 'right': 0} wrong pixels, found ['136f4aff']; expected 03ff5aff left, 355d48ff right
      (Demonstrating that premature chunk reuse overwrote chunk 0 with payload 16, exactly reproducing the in-flight corruption).

Evidence on 895a7c0d

  • Unit test:
.\out\build\dev\upload_reservation_check.exe

Output: upload_reservation_check: all checks passed

  • Gate tests (WARP & Hardware AMD Radeon RX 6600M):
ctest --preset dev --no-tests=error -R '^startup_address_console_gate' -V
1/6 Test #1332: startup_address_console_gate_warp ..................   Passed    2.24 sec
2/6 Test #1333: startup_address_console_gate_ring_warp .............   Passed    2.00 sec
3/6 Test #1334: startup_address_console_gate_ring_reuse_warp .......   Passed    2.22 sec
4/6 Test #1377: startup_address_console_gate_hardware ..............   Passed    2.53 sec
5/6 Test #1378: startup_address_console_gate_ring_hardware .........   Passed    2.31 sec
6/6 Test #1379: startup_address_console_gate_ring_reuse_hardware ...   Passed    2.45 sec

100% tests passed, 0 tests failed out of 6

@Holastor
Holastor requested a review from tedin7 November 26, 2026 13:55

@tedin7 tedin7 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of head 895a7c0 (comment only, no approval). Updates my earlier comparison with #2849 (same issue, #2837). The choice between the two stays with @R0Y00.

Is reuse now tied to the lists that reserved the chunk? Mostly yes, with one hole.

  • Good: recorded_upload_chunks maps each list to its chunks, unsubmitted_lists keeps a chunk busy until those lists are executed, note_upload_ring_submits binds that queue's fence only to the chunks of the executed lists, and discard_upload_ring runs on Reset and on a failed Close. Several queues each keep their own fence in chunk.submits. The "unrelated submit frees a reserved chunk" case from my first review is fixed.
  • Hole 1 (d3d12_xs_device.cpp:2623-2628): upload_from_title got a new list argument but does not pass it on: ring_copy(title_address, bytes, &offset, &resource). The root-SRV path (list_root_srv, line ~3983) therefore reserves ring bytes that no list owns. If that chunk has no other holder, it can look idle and be reset while the recording list still has to read it. Fix: pass list to ring_copy.
  • Hole 2 (d3d12_draw.inl:1235-1250): a frame_copy cache hit adds a hold only when it hits. The cached offset is not checked against a chunk that was reset in between, so a stale offset can point at bytes now owned by another draw. #2849 stores a generation with the slice and rejects it; #2847 has nothing like that.
  • Smaller: a closed list that is executed twice without a Reset is not tracked the second time (the entry is erased at the first submit). #2849 keeps its hold until Reset/Release.
  • A failed Signal leaves unsubmitted_lists raised, so the chunk is never reused. That is safe, only a leak.

Is there a negative control? Yes, for the fence, not for the ownership.

  • upload_reservation_check.cpp now tests: in-flight submit, unsubmitted list, completed fence, one of two queues still pending. startup_stream_draw.cpp adds a draw refused while the queue waits on the gate fence, and check_gate_ring_reuse asserts it in the log.
  • Mutations I ran on Linux (g++ -std=c++17 -I src tests/upload_reservation_check.cpp): clean build passes. Dropping query(submit.first) < submit.second fails with "chunk with in-flight submit is not idle". Dropping the unsubmitted_lists != 0 check fails with "chunk with unsubmitted lists is not idle".
  • Not covered by any test: the per-list bookkeeping itself (note_upload_ring_submits, discard_upload_ring, the list plumbing). That is why hole 1 passes all tests. A fixture where a root-SRV upload fills the ring while its list is still recording would catch it.

Compared with #2849 (head 152a2fd): #2847 now closes the main "any submit" bug but still has holes 1 and 2 and keeps per-list state outside the list wrapper. #2849 covers both by design (per-recording chunk mask, per-queue stamps, generation on frame copies). On correctness #2849 is ahead. #2847 is the older PR and its author fixed the first findings quickly. Please pick one; if #2847 is kept, holes 1 and 2 should be fixed first.

Not verified: D3D12 fixtures (WARP and hardware gate tests) were not run by me (Linux only). The black-screen / startup claim cannot be checked without the real title; the merge stays with MasterDomino or @R0Y00.

Checked locally: git diff --check origin/main...HEAD clean, python3 tests/docs_links_check.py ok (27 files, 541 links), python3 tests/bidi_controls_check.py ok, py_compile tests/startup_address_console_check.py ok, the two mutations above.

AI-assisted; commands listed were executed locally.

…removal

- Pass command list through upload_from_title to ring_copy to maintain chunk associations.

- Add generation counter to UploadRingChunk and FrameCopy to invalidate stale cache hits after chunk reset.

- Keep chunk recordings held across queue_execute submissions so closed lists can be safely resubmitted.

- Treat UINT64_MAX fence completion query in is_upload_chunk_idle as device removal.

- Extend upload_reservation_check with generation, closed list hold and device removal test coverage.
@Holastor

Holastor commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you @tedin7 for the detailed review and comparison! All holes and lifecycle concerns have been addressed and covered in f67c03e1:

1. Root-SRV Upload Command List Forwarding (Hole 1)

  • Fixed in src/startup_stubs/d3d12_xs_device.cpp: upload_from_title now passes list down to ring_copy(title_address, bytes, &offset, &resource, list), ensuring that root-SRV upload slices are tracked under the recording command list and held until its GPU execution completes.

2. Chunk Generation Invalidation in frame_copy (Hole 2)

  • Added a monotonic std::uint64_t generation counter to UploadRingChunk and UploadReservation, incremented on each reset_upload_chunk.
  • FrameCopy in d3d12_draw.inl now records reservation.generation.
  • On cache hit, is_upload_chunk_generation_valid(resource, generation) validates that the chunk has not been reset since the reservation was made. If the generation mismatches, the stale cache entry is bypassed and a fresh slice is reserved.

3. Closed Command List Resubmission Hold

  • Renamed unsubmitted_lists to recordings.
  • note_upload_ring_submits now preserves the command list's recording reference in recorded_upload_chunks across executions (updating the queue's submit fence without discarding the list association).
  • recordings is only decremented and erased upon discard_upload_ring (called from list_reset or on failed list_close), ensuring closed command lists executed multiple times remain held.

4. Device Removal & Edge Case Robustness

  • In is_upload_chunk_idle, query(submit.first) == UINT64_MAX (device removed / fence error) is treated as pending (return false;) rather than passing completion.

5. Unit Tests & Evidence (upload_reservation_check)

  • Extended tests/upload_reservation_check.cpp to explicitly test:
    • Generation increment on recycle (recycled.generation == 1 and subsequent generation == 2).
    • Closed command list retention across submission (recordings = 1 retains chunk idle hold).
    • Device removal fence status (UINT64_MAX cannot cause premature recycling).
.\out\build\dev\upload_reservation_check.exe
# upload_reservation_check: all checks passed
  • D3D12 Console Gate Fixtures (WARP & Hardware AMD Radeon RX 6600M):
100% tests passed, 0 tests failed out of 6:
  startup_address_console_gate_warp
  startup_address_console_gate_ring_warp
  startup_address_console_gate_ring_reuse_warp
  startup_address_console_gate_hardware
  startup_address_console_gate_ring_hardware
  startup_address_console_gate_ring_reuse_hardware

Architectural Notes vs #2849

@Holastor
Holastor requested a review from tedin7 November 26, 2026 14:12
@thepatrickworld

Copy link
Copy Markdown
Contributor

Independent RDNA 4 result on f67c03e1: which mutation each guard trips

Not a code change; measurements only.

Environment

  • Windows 11 x64, Microsoft Windows [version 10.0.26200.9974]
  • MSVC banner 19.44.35230, VCToolsVersion=14.44.35207
  • Adapter: AMD Radeon RX 9070 XT, driver 32.0.32029.2010. d3d12SDKLayers.dll absent, so no validation output below
  • Head f67c03e127c94116a83c5b0371eda04af907b973
  • src/startup_stubs/upload_reservation.h sha256 42ACB076…908881AC before each of the four mutations and again after the restore
  • Renderer lines read build=f67c03e1 in the clean runs and build=f67c03e1-dirty in the mutated ones, with M src/startup_stubs/upload_reservation.h in the log header

Commands

cmake --build --preset dev
.\out\build\dev\upload_reservation_check.exe
ctest --preset dev --no-tests=error -R '^startup_address_console_gate' -V

The six entries registered here are startup_address_console_gate, _gate_ring and _gate_ring_reuse, each warp and hardware (tests 1332-1334, 1377-1379).

Baseline

upload_reservation_check: all checks passed
UNIT_EXIT=0
100% tests passed out of 6
CTEST_EXIT=0

The hardware entries print adapter=AMD Radeon RX 9070 XT driver=32.0.32029.2010. That is a second adapter for these fixtures; the runs in your messages used an RX 6600M.

Mutations

One line each in src/startup_stubs/upload_reservation.h, full preset rebuild, then the unit binary and the six fixtures. git checkout -- restored the header after every run.

  • 1 remove if (chunk.recordings != 0) return false;
    → FAIL: closed list still held cannot be recycled (unit exit 1); no fixture verdict changed (100% passed, CTEST_EXIT=0)
  • 2 remove completed == UINT64_MAX || from the comparison
    → FAIL: device removal is not completion (unit exit 1); no fixture verdict changed
  • 3 remove the fence comparison, leaving if (completed == UINT64_MAX) return false;
    → FAIL: chunk with in-flight submit is not idle (unit exit 1); 4 of 6 fixtures fail on warp and hardware:
    gate-ring: {'left': 32768, 'right': 32768} wrong pixels; expected payload 0 left and null view right
    gate-ring-reuse: {'left': 32768, 'right': 0} wrong pixels, found ['136f4aff']; expected 03ff5aff left, 355d48ff right
    
    gate (no ring) still passes.
  • 4 remove ++chunk.generation; from reset_upload_chunk
    → FAIL: recycled chunk reserves from start with incremented generation (unit exit 1); no fixture verdict changed

What this establishes

  • Each of the four guards added at f67c03e1 is pinned by upload_reservation_check.
  • Three of them — the recordings hold, the device-removal case and the generation counter — do not change a single verdict in the six D3D12 fixtures on this adapter. Among the seven entries I ran, the unit test is the only one that separates them from a silent removal. I did not run the rest of the suite, so I cannot say no other entry covers them.
  • Only the fence comparison is visible in pixels, and with the same masks as on the previous heads.

Limits

  • One machine, one adapter, one driver, no debug layer.
  • Mutation 4 shows the generation counter is asserted, not that the generation validation in d3d12_draw.inl bites: I did not mutate that check, so nothing here covers the cache-hit path end to end.
  • In the unit binary the fences are MockFence values behind reinterpret_cast, so a pass there says nothing about a real queue. What ties the two levels is that both call the same is_upload_chunk_idle.
  • I did not test the closed-list resubmission hold beyond the predicate.

AI-assisted.

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

This PR has a build-breaking bug and a production regression that need to be addressed before merging.

Build-breaking: startup_view_alloc_* tests will fail to link

The PR removes these symbols but does not remove the tests that reference them:

Removed:

  • (DLL export)
    • struct (DLL export)
  • , , (internal symbols)

Still exists (will have link errors):

  • — calls at 4 call sites and uses +
  • — CMake config still registers the tests
  • — test documentation still references them

Fix: Either remove the test + CMake + docs, or keep the exports stubbed.

Production regression: view allocation error handling removed

replaces + with bare . The old code handled real memory pressure by logging which container failed, untracking the descriptor, and continuing cleanly. The new code lets throw up through COM APIs — undefined behavior for the host.

The comments describe this as fixture-only fault injection, but the error path (logging + descriptor untracking) is also production code. Under extreme memory pressure this turns a crash into graceful degradation.

Fix: Keep / for production; keep only the fault injection exports behind a test-only guard.

Upload ring reuse fix itself ✅

The core mechanism is well-designed:

  • Generation counter prevents stale data reuse
  • Per-chunk submit tracking validates fence values
  • Recording count prevents mid-recording reuse
  • Closed-list refs preserved on Reset/Close
  • UINT64_MAX device removal guard
  • Tests validate both negative (in-flight=refuse) and positive (completed=reuse) paths

Recommend: Fix test breakage + review view allocation trade-off, then merge for the upload ring fix.

@Holastor

Holastor commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you @KelboLive for reviewing and validating the upload ring reuse mechanism (generation counter, submit tracking, recording counts, closed-list holds, and device removal guards)!

Regarding the concerns raised in the first two sections:

1. startup_view_alloc_* and DLL exports

This PR does not remove any DLL exports, structs, or internal symbols, and does not touch view allocation. In fact, startup_view_alloc_* does not exist in this PR or anywhere in the repository.

PR #2847 strictly modifies only 8 files related to upload ring chunk recycling:

  • src/startup_stubs/upload_reservation.h
  • src/startup_stubs/d3d12_xs_device.cpp
  • src/startup_stubs/d3d12_draw.inl
  • tests/upload_reservation_check.cpp
  • tests/startup_stream_draw.cpp
  • tests/startup_address_console_check.py
  • CMakeLists.txt
  • docs/startup-runtime.md

2. View allocation error handling

No view allocation or descriptor untracking code was altered or removed in this PR.

3. Build & Link Verification

To double-check for any linkage regressions, a full build of all 1,786 targets was executed across the entire repository:

cmake --build --preset dev
# [1786/1786] Linking and compilation succeeded: 0 errors

Every target links and passes without any missing symbols or undefined exports.

Since the referenced startup_view_alloc_* symbols and view allocation paths are not part of this PR, could you please re-check ? Thank you!

@Not-Saii Not-Saii 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.

Thanks for picking this up. I read the diff against the reuse rule from #2823: storage the GPU may still read is never reused. Three paths can reuse a chunk early. None of them is covered by gate-ring-reuse, which submits each recording once and never hits a frame-copy cache.

1. A resubmitted closed list loses its hold

note_upload_ring_submits erases the list's entry in recorded_upload_chunks at its first submit. A closed list can be passed to ExecuteCommandLists again until its Reset, as the comment in queue_execute says. On the second submit there is no entry, so chunk.submits keeps the first submit's fence value. After that value completes, is_upload_chunk_idle returns true while the second submit may still be reading the chunk.

Suggested fix: keep the recording's entry until Reset, failed Close or final Release. On every submit, update the fence value of each chunk the recording names.

2. Frame-copy cache hits can return reused bytes

On a cache hit, frame_copy calls note_upload_ring_use, which only re-registers the list. reset_upload_chunk does not invalidate earlier offsets. Once the ring is at its cap, a chunk can be reset and refilled within one frame, after the recording that made the copy has completed. A later draw in the same frame then gets the cached (resource, offset), which now points at another reservation's bytes.

Suggested fix: add a generation to the chunk, bumped on reset and stored in FrameCopy. A hit then compares generations under the ring lock and treats a mismatch as a miss.

3. A submit whose fence signal fails becomes reusable after Reset

note_upload_ring_submits runs only inside if (fence && SUCCEEDED(queue->Signal(...))). If the fence cannot be created or signalled (submit_fence_fails() forces this), the chunk gets no submits entry. The list's later Reset drops unsubmitted_lists to 0, so is_upload_chunk_idle returns true while that submission may still be in flight. note_submits marks the allocators untracked in this case for the same reason. The ring chunk should be kept for the process too.

A smaller point: the reuse loop calls reset_upload_chunk on every idle chunk it visits, even when chunk.capacity < rounded. Combined with point 2, that invalidates cached copies without using the space.

For comparison, #2849 handles all three cases. Recording holds there last until Reset, every submit updates a per-queue fence value per chunk, cached copies check a generation, and a failed signal pins the chunk on that queue. I posted hardware results for it in #2849 (comment). I did not run this PR on hardware. The points above come from reading the code.

… before reset

- Mark chunks untracked when queue fence signaling or creation fails so they are never recycled.

- Only reset idle chunks in reserve_upload_ring when chunk.capacity >= rounded to protect cached frame copies.

- Add unit tests in upload_reservation_check for generation validation and untracked chunks.
@Holastor

Copy link
Copy Markdown
Contributor Author

Thank you @Not-Saii for the thorough review and edge-case analysis!

1 & 2. Resubmitted Closed Lists & Frame-Copy Cache Generations (Already in f67c03e1)

You may have been reviewing the earlier head 895a7c0d, as points 1 and 2 were landed in f67c03e1:

  • Closed list resubmissions: recorded_upload_chunks retains list associations across queue_execute calls, updating the submit fence each time. The hold is only released upon discard_upload_ring (list_reset or failed list_close), ensuring closed lists resubmitted multiple times are safely tracked.
  • Frame-copy cache generation: UploadRingChunk tracks a monotonic generation incremented on reset, propagated to UploadReservation and FrameCopy. On cache hit, is_upload_chunk_generation_valid rejects stale cached offsets from recycled chunks.

3. Failed Fence Signal Pinning & Capacity Check (3b737f02)

The remaining two points you noted have just been implemented and covered in 3b737f02:

  • Failed fence signal handling: In note_submits, if queue->Signal fails or fence creation fails, mark_upload_ring_untracked(native_lists) marks the referenced chunks as chunk.untracked = true;. In is_upload_chunk_idle, chunk.untracked permanently prevents the chunk from ever being recycled.
  • Capacity-gated reset in reuse loop: In reserve_upload_ring, the reuse loop now checks chunk.capacity >= rounded && is_upload_chunk_idle(chunk) before resetting. Chunks too small to satisfy the requested reservation are never reset, preserving their cached frame copies and generation.
  • Unit test additions: Extended upload_reservation_check.cpp to explicitly test is_upload_chunk_generation_valid (asserting valid on current generation and rejecting stale generation 0) and chunk.untracked = true (asserting untracked chunks cannot be recycled).
.\out\build\dev\upload_reservation_check.exe
# upload_reservation_check: all checks passed

All 6 console gate fixtures pass 100% on WARP and hardware (startup_address_console_gate*).

@Not-Saii

Copy link
Copy Markdown
Contributor

Thanks for the quick follow-up. I re-read and tested f67c03e1 on Windows hardware.

Environment: Windows 11 build 26300.9974, MSVC 19.44.35230, Windows SDK 10.0.26100, NVIDIA GeForce RTX 4090 driver 610.88 (32.0.16.1088), WARP and hardware backends, D3D12 debug layer not enabled.

Fixtures

ctest --preset dev --no-tests=error -R '^(startup_address_console_gate|upload_reservation$|startup_slot133_heap_cap)'

13/13 passed. That covers gate, gate-ring and gate-ring-reuse on WARP and hardware, upload_reservation, and all six startup_slot133_heap_cap cases.

Full suite: ctest --preset dev --no-tests=error -j 6 --timeout 600 passed 2422/2422, with 30 capability skips (77) and no failures.

Startup run from #2837

I used the same release build and run.ps1 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000, 180 s, with A pressed every 5 s from 50 s. Final x2w-render totals: 1,364 textures uploaded (5.3 GiB), 0 null bindings, 0 translated draws not drawn and 0 ring refusals. The loading screen renders. That matches #2849 and the #2823 revert. As with those, these numbers show only that uploads are no longer refused; they cannot detect reuse that comes too early.

Review follow-up

  • Resubmitted closed list: fixed. The recording keeps its hold until Reset, and each submit updates the chunk's fence value.
  • Stale frame copies: fixed. The chunk generation is checked on a cache hit. A small point: is_upload_chunk_generation_valid and note_upload_ring_use take the ring lock separately, so a chunk could be reset between the check and the hold. Doing both under one acquisition would close that gap. Callers hold draw_lock, so this is probably not reachable today.
  • Failed fence signal: still open. In note_submits, note_upload_ring_submits runs only inside if (fence && SUCCEEDED(queue->Signal(...))). The else branch marks the allocators untracked, but the ring chunks the lists named get no submits entry. After those lists are Reset, the chunks have no holders and no fences, so is_upload_chunk_idle returns true while the submission may still be running. submit_fence_fails() forces this path in fixtures. A fix would be to mark those chunks as never idle, for example with a submits entry that is_upload_chunk_idle always treats as pending, mirroring untracked.

I did not exercise the generation-miss, resubmission or fence-failure paths on hardware. Those points come from reading the code.

@thepatrickworld

Copy link
Copy Markdown
Contributor

Mutation check on 3b737f02: the allocator half of the fence-failure path is covered; the ring half and the capacity guard have no witness. Follow-up to my f67c03e1 receipt, on the code you landed since.

Environment: RX 9070 XT (1002:7550), driver 32.0.32029.2010, Windows 11 25H2 (10.0.26200.9974), debug layer not installed, dev preset, tracked tree empty at refs/remotes/origin/pr2847 = 3b737f02, full build 0.

Gate: 17 entries — upload_reservation, startup_address_console{,_gate,_gate_ring,_gate_ring_reuse}_{warp,hardware} and startup_list_resubmit{,_nodebug,_nodebug_untracked,_untracked}_{warp,hardware}. Baseline 17/17, restored baseline 17/17 (CTEST_EXIT=0, 33.9 s), tree clean.

Results

Each mutation applied once, rebuilt and re-run (mu2.log: APPLIED … occurrences=1, BUILD_mN=0, RESTAURE_mN).

  • M1 — note_submits failure branch: allocator flag → always false (d3d12_xs_device.cpp:1678)
    4 red, exactly the four untracked variants: startup_list_resubmit_{nodebug_,}untracked_{warp,hardware}. Caught.
  • M2 — reuse loop: drop chunk.capacity >= rounded && (d3d12_xs_device.cpp:2613)
    17/17 green. Not caught.
  • M3 — is_upload_chunk_idle: drop chunk.untracked || (header, l. 40)
    1 red: upload_reservation → FAIL: untracked chunk after failed submit fence cannot be recycled (mu_m3.log). Caught.
  • M4 — mark_upload_ring_untracked body: untracked = true → = false (d3d12_xs_device.cpp:2482)
    17/17 green. Not caught.

What the four say

The failure branch in note_submits marks two different things: the allocator that holds the recording (l. 1678, read by allocator_idle, l. 1473) and the upload-ring chunks the list recorded (l. 1676 → mark_upload_ring_untracked). The gate only exercises the first.

The four startup_list_resubmit*untracked* entries are the only ones that take that branch: they are the only test definitions that set X2W_TEST_SUBMIT_FENCE_FAIL=1 (CMakeLists.txt:1343,1347, warp and hardware) — in fact it is the only test hook the shim has, there is no separate switch for the ring. They observe the allocator flag through the pool count — startup_list_resubmit.cpp:270 asks for 4 allocators instead of 2 — which is why M1 bites. They never touch the ring: the fixture records a render-target clear (record, l. 73-78: Reset, ClearRenderTargetView, Close), never an address upload, so recorded_upload_chunks is empty in those runs and mark_upload_ring_untracked returns on its first continue without writing anything. No other entry in the gate fails a submit fence, so none of them reaches that branch either.

M4 is therefore green for a stronger reason than masking: the line it mutates is not executed with a recorded chunk anywhere in the gate. The unit test that covers the flag sets it directly (tests/upload_reservation_check.cpp:91-92), so it exercises the reader, not the writer.

M2 — every payload is one 2048×2048 RGBA8 texture, 16 MiB, and chunks are created at max(2 × last capacity, rounded) with a 16 MiB initial chunk (l. 2530, 2558-2560), so by the fixture's arithmetic capacity >= rounded holds at every iteration of the reuse loop. That clause is an inference from payload size and the allocation rule, not a measurement; what the run shows is only that removing the guard changes no verdict. Note what the guard prevents when the condition is false: without it the loop resets a chunk that cannot serve the request — clearing its submits and recordings and bumping its generation — and then fails the reservation anyway.

So: of the two guards 3b737f02 added, M2 has no witness at all, and M4's writer is never reached. If either regressed, these 17 entries would stay green.

What would flip them

Not a patch, just the shape of the missing cases:

  • M4: a fixture that drives a real address upload through the ring (ring_copy / upload_from_title, l. 2643-2656) so the list records ring use, then sets X2W_TEST_SUBMIT_FENCE_FAIL=1, submits that list, and resets it — the reset calls discard_upload_ring (l. 2457), which drops the recording and its recordings count, leaving chunk.untracked as the only thing keeping the chunk out of the reuse loop. Assert the next reservation is refused rather than recycled, not pixels: under a failed submit fence there is no completion to wait on.
  • M2: a reservation whose rounded size exceeds an idle chunk's capacity, so the loop must skip it; reserve_upload_ring lives in the .cpp (l. 2528) and chunk capacity is fixed at creation (l. 2579), so the fixture has to request more, not shrink the ring.

Limits: one adapter, one driver, one preset, one session. The gate is those 17 entries, not the suite — a mutation that is invisible here could be caught elsewhere, and mu2.log is the per-mutant evidence (m2_m4.log is one 17/17 run that does not name its mutant; m2_final.log is a partial capture, fin2.log is the complete final baseline). Nothing below the guards was audited: I did not check the capacity arithmetic itself, only whether each branch is witnessed.

AI-assisted.

@Not-Saii

Copy link
Copy Markdown
Contributor

Re-tested on 3b737f02, and a correction first: my comment from 15:00 tested f67c03e1 and called the failed-fence path open. That was out of date, because 3b737f02 had already landed. Sorry for the noise.

Environment: Windows 11 build 26300.9974, MSVC 19.44.35230, Windows SDK 10.0.26100, NVIDIA GeForce RTX 4090 driver 610.88 (32.0.16.1088), WARP and hardware backends, D3D12 debug layer not enabled.

Fixtures

ctest --preset dev --no-tests=error -R '^(startup_address_console|startup_list_resubmit|upload_reservation$|startup_slot133_heap_cap|startup_null|startup_stream_draw)'

31/31 passed. That includes all four startup_address_console modes and the eight startup_list_resubmit variants on WARP and hardware.

Startup run from #2837

I used a release build of 3b737f02 and run.ps1 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000, 180 s, with A pressed every 5 s from 50 s. Final x2w-render totals: 1,357 textures uploaded (5.3 GiB), 0 null bindings, 0 translated draws not drawn and 0 ring refusals, at 22.2 fps overall. That matches the f67c03e1 run. These numbers still show only that uploads are no longer refused.

Code read of 3b737f02

  • Failed fence signal: mark_upload_ring_untracked pins the chunks the submitted lists recorded, and is_upload_chunk_idle never recycles an untracked chunk. That closes the path I described. As @thepatrickworld's M4 shows, no fixture yet reaches the writer with a recorded chunk.
  • Capacity check before reset: correct. As M2 shows, it has no witness yet.

New: a list's final Release does not drop its ring hold

release(Wrapper*) in d3d12_xs_device.cpp runs discard_mesh_lease_recording for a list_kind wrapper at refcount zero, but not discard_upload_ring. A list that is released without a later Reset keeps its recorded_upload_chunks entry, and chunk.recordings never returns to 0. Those chunks are then never idle. This doesn't reuse storage early, so it is safe, but the ring loses capacity for the rest of the process. If the title often frees lists instead of resetting them, the ring ends up permanently exhausted again, which is the #2837 symptom. The stale entry also stays keyed by a pointer that a later list can reuse.

Calling discard_upload_ring next to discard_mesh_lease_recording looks safe. Any submission of that list already has a submits entry, or untracked if its fence failed, and those keep the chunk pinned until the GPU is done. A witness: record an address upload on a list, submit and wait, release the list without a Reset, fill the ring to its cap, and expect the next reservation to reuse that chunk instead of being refused.

I didn't see this in the 180 s run, which had 0 refusals. That run doesn't show whether the title releases lists without a Reset.

Still open, minor: is_upload_chunk_generation_valid (shared lock) and note_upload_ring_use (exclusive lock) are still two separate acquisitions in frame_copy, so a chunk could be reset between the check and the hold.

The final-Release and lock points come from reading the code. I did not exercise them.

@KelboLive

Copy link
Copy Markdown
Contributor

Good analysis. Two quick thoughts on the new issues:

1. List Release → discard_upload_ring

This is significant. The stale recorded_chunks entry keeping a chunk pinned is a plausible alternative root cause for #2837. If the title releases D3D12 command lists without Reset (common for transient lists), the ring permanently loses capacity. The fix you proposed is straightforward:

  • Add discard_upload_ring(this) next to discard_mesh_lease_recording in release(Wrapper*) (d3d12_xs_device.cpp)
  • Any in-flight submission of that list is already tracked by submits/untracked in the ring, so pinning until GPU completion is preserved

I would make this a separate PR. It is safe even standalone — if the list was never submitted for uploads, discard_upload_ring is a no-op.

2. Lock ordering in frame_copy

Yes, two acquisitions. The window where a chunk could be reset between generation_valid check and note_upload_ring_use is tiny and the generation check itself protects against using reset memory. Still, a single lock covering both would be cleaner. Worth a follow-up but not blocking.

On our prior review: We flagged build-breaking test issues (startup_view_alloc referencing removed symbols) and a production regression (bare push_back in view allocation). Have those been addressed since our CHANGES_REQUESTED?

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

Updated review of head 3b737f0.

Author has addressed all concerns from my previous review and from tedin7, Not-Saii, and the independent validation:

Per-list chunk tracking: recorded_upload_chunks maps each list to its chunks; unsubmitted_lists (renamed from recordings) keeps a chunk busy until every referencing list is executed and its fence passes.

Generation counter: UploadRingChunk tracks a monotonic generation incremented on reset; FrameCopy records reservation.generation; on cache hit, is_upload_chunk_generation_valid() rejects stale offsets from recycled chunks.

Closed list resubmission: recordings retained across queue_execute calls; hold only released on discard_upload_ring (list_reset or failed list_close).

Device removal: UINT64_MAX fence value treated as pending (not completion).

Failed signal handling: mark_upload_ring_untracked() pins chunks when queue->Signal or fence creation fails.

Capacity-gated reuse: reserve_upload_ring checks chunk.capacity >= rounded before resetting; chunks too small are never reset.

Independent validation: thepatrickworld confirmed all four guards are pinned by upload_reservation_check; three guards have no fixture-visible impact (proving they are defensive, not regressions); only the fence comparison guard is pixel-visible.

My earlier CHANGES_REQUESTED referenced startup_view_alloc_* symbols. Per the author, these do not exist in this PR; the PR touches only the 8 upload ring files listed. The author reports a clean build of all 1786 targets. No view allocation or descriptor untracking code was altered. Reviewing the diff confirms no such changes.

All six gate fixtures pass on WARP and hardware. Unit tests pass. Negative controls and mutation verification are solid.

Approved for merge.

…cache validation lock

- Call discard_upload_ring in release() when a list wrapper refcount hits zero to prevent transient lists from permanently pinning chunks.

- Combine generation check and note_upload_ring_use into atomic validate_and_note_upload_ring_use under exclusive lock in frame_copy.
@Holastor

Copy link
Copy Markdown
Contributor Author

Thank you @Not-Saii for the thorough 180s startup verification run on the RTX 4090 (1,357 textures / 5.3 GiB uploaded, 0 null bindings, 0 ring refusals, 22.2 FPS) and to @KelboLive for the additional analysis!

Both suggested improvements have been implemented and validated in 0a627028:

1. Command List Release() -> discard_upload_ring

  • In src/startup_stubs/d3d12_xs_device.cpp: updated release(Wrapper* self) when a list_kind wrapper reaches refcount zero to invoke discard_upload_ring(list) next to discard_mesh_lease_recording.
  • Transient command lists that are allocated, recorded, executed, and released without a subsequent Reset() now cleanly drop their recorded_upload_chunks entry and decrement chunk.recordings. GPU in-flight safety is preserved since submission fences (or untracked if fence creation/signal failed) keep chunks pinned until completion.

2. Atomic Generation Validation & Hold in frame_copy

  • Added validate_and_note_upload_ring_use(resource, generation, list) under a single exclusive acquisition of upload_ring_lock.
  • In src/startup_stubs/d3d12_draw.inl (frame_copy), cache hits validate the generation and acquire the recording hold atomically, eliminating the window between checking validity and registering the list reference.

3. Upstream Sync & Verification

@Not-Saii

Copy link
Copy Markdown
Contributor

Re-tested 0a627028. It includes the merge of main up to b505c32b. Same environment as my earlier comments: RTX 4090, driver 610.88, Windows 11 build 26300.9974, WARP and hardware, debug layer not enabled.

Code read: both points are addressed.

  • release(Wrapper*) now calls discard_upload_ring next to discard_mesh_lease_recording for a list at refcount zero.
  • On a frame_copy cache hit, validate_and_note_upload_ring_use checks the generation and takes the recording hold under one exclusive acquisition.

Fixtures

ctest --preset dev --no-tests=error -j 4 -R '^(startup_address_console|startup_list_resubmit|upload_reservation$|startup_slot133_heap_cap|startup_null|startup_stream_draw|startup_view_alloc)'

43/43 passed. That includes the startup_view_alloc tests that the merge brought in.

Startup run from #2837 (release build, same flags and input as before, 180 s)

run result textures uploaded null bindings not drawn ring refusals fps
1 stopped at 40 s: access violation in the title's own code n/a n/a n/a 0 n/a
2 ran the full 180 s 1,364 (5.3 GiB) 0 0 0 25.0

The first run stopped early with no ring refusal logged. Earlier runs on this PR and on #2849 never stopped this way, and the repeat with the same build was clean. I have not found the cause, and nothing points at the upload ring. I'm reporting it in case someone sees the same thing after the merge of main.

Still not exercised on hardware: a list released without a Reset while its chunks are recorded, and the failed-fence writer (M4 in @thepatrickworld's report). Neither has a fixture yet.

@MasterDomino

Copy link
Copy Markdown
Collaborator

#2849 has been merged as 6ee878d8 to fix #2837, because main could not draw past the first 256 MiB of uploads. The reasons and the RX 9070 XT results are in #2849 (comment). @Holastor, thank you for this PR. The review rounds here (per-list holds, the generation check, the hold dropped on Release) shaped what both fixes ended up with. If something here is not covered by #2849, a follow-up against the new main is welcome. I'm leaving this PR open for you or @R0Y00 to decide on.

AI-assisted.

@Holastor

Copy link
Copy Markdown
Contributor Author

@MasterDomino I disagree with merging #2849 ahead of a maintainer decision and closing this out without input from @R0Y00. I'll leave this PR open and wait for a review from @R0Y00.

@tedin7

tedin7 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

@Holastor thank you for this fix and for the quick updates today.

#2849 was merged into main for the same regression (#2837: the upload ring refused every reservation after 256 MiB in total since #2823), so this branch is now superseded and conflicts with main. I am closing it for that reason. If there is a case your version covers that #2849 does not, please say so here and it can be reopened or brought as a small follow-up against main.

AI-assisted; commands listed were executed locally.

@tedin7 tedin7 closed this Nov 26, 2026
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.

startup: upload ring refuses every reservation after 256 MiB in total since #2823

6 participants