Skip to content

GPU: maintain shadow-buffer coherency for directly indexed SRVs - #185

Closed
aycow wants to merge 22 commits into
Marvisak:mainfrom
aycow:fix/direct-indexed-buffer-coherency
Closed

aycow wants to merge 22 commits into
Marvisak:mainfrom
aycow:fix/direct-indexed-buffer-coherency

Conversation

@aycow

@aycow aycow commented Nov 24, 2026 •

Copy link
Copy Markdown

Status

The prior draft head a6367ba integrated desplmfao's Wine fix and cross-shadow batching, preserving original commits 9e94c21 and 9131c10. The same-reservation fallback check and PR description also credit desp's per-allocation and never-committed handling from #515 that informed 481fb1a.

Cross-shadow batching

The combined tree passed 16 selected tests each on AMD Radeon Graphics, NVIDIA RTX 5070 Laptop and WARP with Agility SDK 1.620.2, the D3D12 debug layer and full GPU-based validation. Separate deterministic checks passed with batching both enabled and disabled. They cover older journal readers on overlapping shadows, pending GPU writes and copyback, reservation recommit, and observing a post-sample write in the next refresh.

On desplmfao's Proton workload, write-watch time was 776 ms on 1efd438, 662 ms after the Wine fix, and 22 ms with both changes. Frame time stayed within run-to-run spread. In separate AMD Windows synthetic runs, host preparation per 80 submissions was 3.061 → 1.344 ms for dense views, 3.205 → 4.119 ms for sparse views that fit one shared span, and 3.313 → 3.581 ms for gapped views that fell back. Exact-head title validation and a matched Linux preparation breakdown remain open. Synthetic methodology and profiling branch · Review tests

A later matched warm-cache RTX 5080 Proton run toggled only shared spans on the same binary. Sharing reduced write-watch queries from 111,891 to 3,650 and watch time from 684 to 23.1 ms per world frame. Direct-SRV preparation was 2,391 → 2,052 ms and submission preparation was 2,439 → 2,350 ms. Frame time was 2,800 → 2,700 ms, alongside about 10% fewer direct ranges, so the run leaves overall frame-time impact unresolved. The contributor is profiling reservation lookups separately. Matched Proton report

The subsequent reservation-cache draft attributes roughly 1.8–2.3 s per sampled Proton world frame to reservation queries. Its locked per-pass cache produced a small preparation difference in the short runs. The cross-frame version still needs an ownership proof for commit state. An independent synthetic review observed a cached zero committed count after a native commit and before its mapping notification, while a fresh query saw 65,536 committed bytes. The draft remains separate. A separate diagnostics-only fixture tested the contributor's mapped-view hint without caching commitment or bypassing per-shadow refresh. For two learned mapped views and one private reservation, native Windows reservation queries fell from three to one. A same-address remap and an injected stale hint both preserved the refreshed bytes. There is no Proton timing result for this hint. Reproduction and coordination

Independent in-game A/B on 1efd438

The testers held their respective stacks, settings and inputs fixed across 53e36e7 plus #202 compatibility and 1efd438. These results compare revisions of this PR.

Tester and system World frame time Direct-SRV preparation Write-watch calls per frame
GamingRipperDoc, RX 9070 XT, Windows 10 22H2 2,777 → 850–1,567 ms 1,846 → 400–739 ms 779,083 → 90,000–124,000
EricPlayZ, RTX 2070 Super, Windows 11 1,999–3,300 → 1,300–1,900 ms 1,488–1,649 → 299–315 ms 721,000–832,000 → 49,000–60,000

The AMD baseline contributed one comparable steady window. The NVIDIA run had one sample per build and differed in submissions per frame. Both reports still ended in device removal. GamingRipperDoc independently ran 78 Windows 10 tests with app-local Agility enabled, including the two binding regressions, and 77 with it disabled. AMD and Windows 10 report · NVIDIA report

On the fork PR's RTX 5080 Proton stack, the Wine fix reduced watch calls from 147,000 to 116,000 per frame. Its 2.9 to 2.6 s frame interval was within run spread. The combined revision passed the synthetic direct-SRV suite on AMD Radeon Graphics, RTX 5070 Laptop and WARP with Agility SDK 1.620.2 and full GPU-based validation, plus the Windows private/mapped-reservation classification tests. Exact-head title and Wine retests remain open. Wine test and measured stack

Earlier implementation and synthetic results

EricPlayZ identified three amplification mechanisms in the NVIDIA run and supplied the original implementation. His clean commit was kept with its original authorship on the local test branch, and the draft revision credits him as co-author. The two linked branches were compared against c6bf7df. The measured stack was used to verify the configuration, including PR #202 and its local allocation, shader, and title changes. Performance report · Clean commit · Measured stack

Changes in 53e36e7

  • Cache merged ranges for live buffer SRVs. Descriptor writes, copies, replacements, and retiring or reusing a native allocation invalidate the affected entries. Commands retain bound heaps and captured resources for their required lifetimes.
  • Use emitted shader metadata when it proves fixed or finitely bounded buffer SRV slots, or establishes that there are no direct buffer SRVs. Unknown indexing still refreshes all live candidates. CPU writes between submissions remain visible.
  • Keep exact watched byte coverage and group queries for dense ranges. Split failed watch probes across Windows reservations and publish each successful observation to the shared journal. Recheck exact reserved extents, retain valid watched bytes around them, and exclude pending GPU write ranges from refresh.
  • Invalidate watched coverage when supported XMem mappings and guest VirtualAlloc or VirtualFree calls change the backing pages. The allocation wrappers preserve flags and LastError.

Synthetic performance

AMD, 320 submissions with four lists each. The stable heap contains 8,192 live descriptors and 1,024 merged ranges per submission over 128 MiB of title memory. It models 2,621,440 slot visits, 327,680 range visits, and 21.46 GB of logical direct requests. The fixture checks the shader result, pending GPU copybacks, committed data, and hole contents.

Revision Fully mapped mixed wall time Fragmented mixed wall time Fragmented direct fill
c6bf7df 2.040 s 17.829 s 10.92 GB
c6bf7df + #202 2.027 s 5.405 s 10.92 GB
EricPlayZ 0dd303b 2.130 s 14.648 s 10.76 GB
EricPlayZ 0dd303b + #202 1.944 s 5.050 s 10.76 GB
Revised 1.664 s 4.031 s 1.30 GB

Fully mapped baseline and clean-patch times are medians of three. Fragmented and revised timings are single samples. Fragmented preparation fell from 17.392 s at c6bf7df to 3.307 s in the revision. Repeated zero fills fell from 9.87 GB to zero. Composing the latest revision with #202 in a scratch worktree produced identical bytes and outputs and took 4.163 s in one fragmented sample. #202 substantially accelerated the original sparse fallback. PR #202

Once the heap cache was warm, unrestricted indexing did zero repeated slot enumeration or sorting in this fixture. A separate fixed-slot control visited 320 slots across 320 submissions and filled 20.97 MB. The unrestricted mapped case still fills 10.42 GB where ordinary CPU memory has no dirty signal. Fragmented ranges still require 545,280 instrumented write-watch queries in the instrumented fixture, 327,040 failed bulk-read attempts, and mapping checks. The in-game cost of those paths remains to be measured.

Correctness and validation

  • The clean patch returned stale 19 when the title wrote 500 to a committed 4 KiB island following a reserved prefix within a 64 KiB tracking page. The revised regressions exercise this layout and verify that a clean watched refresh retains live bytes without recopying holes.
  • The suite preserves the six original correctness regressions and covers partial commit, decommit and recommit, reserved and populated transitions, section remaps, registered address reuse, pending GPU bytes, mixed reservations, and two shadows observing one journal after a later query fails.
  • AMD Radeon Graphics, NVIDIA RTX 5070 Laptop GPU, and WARP each completed the focused suite with Agility SDK 1.620.2, the D3D12 debug layer, and full GPU-based validation with resource-state tracking. The active InfoQueue callback reported no errors.
  • The final workspace run passed 300 tests, or 307 with GPU diagnostics, with seven ignored in each run. Workspace checking, Clippy, and asset policy passed. Clippy and repository-wide formatting report existing issues.
  • Existing copyback behavior across a remap while writes are pending and the snapshot gap/overlap cases identified in GPU: copy-back puts back only what shaders wrote, in two more cases #261 remain separate. Direct NT and Ex allocation APIs and deferred MEM_RESET discards are outside the guest notification path. PR #261

PR #393's conventional batching and mapped guard fast path are complementary. PR #420 tracks selections for rebuilt root descriptor tables. This revision's completeness proof concerns emitted resource-heap handles. Both upstream patches and the measured title stack remain separate. PR #393 · PR #420

The next in-game comparison should hold the integration stack, title scene, and timing options fixed. Please include completed frames before any device removal, submission and heap counts, direct requested and filled bytes, and the top refreshed ranges.

AI-assisted with OpenAI Codex.

Earlier results through c6bf7df

Reproduction

VIctory schedules shadow-buffer refreshes for known vertex, index, root, and conventional table bindings. A shader can select a directly indexed heap slot without going through those paths. In a synthetic Shader Model 6.6 test on upstream 35b054e, the real VIctory descriptor and shadow path returned 13 after the title CPU changed its value to 500. The patched path returned 500 with the same recorded list and descriptor. A separate fixed-index test covers the first use of a descriptor that has never gone through a conventional table.

Implementation

  • Keep sparse metadata for populated buffer SRV slots. A recorded list retains the native heap, and submission looks up the slots then so descriptor writes, copies, and replacements made before submission are visible.
  • Materialize deferred buffer SRVs and merge overlapping ranges per native shadow after deferred title writes and before submitting GPU work. Refresh those ranges with the existing dirty-page and pending-write logic. The code retains the captured native resources until the queue has finished.
  • Guard resource-backed descriptor generations during CPU refresh so released views cannot copy from reused title memory. Preserve the existing copyback path for tracked writes. The regression suite also checks descriptor replacement after recording, title heap release before resubmission, resource release and address reuse, and a native copy producer ordered ahead of the SRV reader in one submission.
  • The chosen combination is descriptor metadata, existing dirty tracking, and a scan once per bound heap per submission. The translator retains binding information for conventional resources, while a directly indexed shader can compute the slot from GPU data. Populated SRV slots therefore set the conservative bound.

Validation

Check Result
cargo test --workspace 270 passed, 4 ignored. With GPU diagnostics, 275 passed and 4 ignored
cargo clippy --workspace --all-targets Completed with existing warnings, also with the GPU diagnostics feature
cargo fmt --all -- --check Existing formatting differences, 168 upstream hunks and 167 on this branch
cargo xtask policy and git diff --check Passed

DXC-compiled synthetic tests ran on AMD Radeon Graphics, NVIDIA GeForce RTX 5070 Laptop GPU, and Microsoft WARP. Each adapter reported Shader Model 6.6 and passed all five functional regressions. AMD also passed all five without diagnostics and ran the benchmark. A temporary local adapter selection forced the NVIDIA device. See the performance follow-up for the current debug-layer and GPU-based validation results.

Synthetic AMD benchmark

64 submissions with a one-million-slot heap, 1,024 populated overlapping SRV slots over 32 shadows, and one CPU-dirtied 64 KiB page per submission.

Metric Upstream 35b054e Patched
Final shader value 13 (stale) 563
SRV slots inspected across all submissions 0 65,536
Merged shadow ranges 0 2,048
Bytes refreshed / copied back 0 / 0 4,194,304 / 0
Refresh CPU time 0 ms 34.565 ms
Total submission preparation 0.099 ms 35.001 ms
Wall time 27.358 ms 56.553 ms

The patched run visits 1,024 slots and merges them to 32 ranges per submission. A follow-up clean submission copies zero bytes. For 1,024 populated slots, the estimated metadata and peak snapshot payload total about 72 KiB, before tree and allocator overhead. This is a payload estimate rather than a process memory measurement.

Performance follow-up

The follow-up is c6bf7df. On 83963c5, the 12.21 MB attributed to direct SRVs is already included in the 23,025.1 MB aggregate. The aggregate also includes conventional shadow fills and requested lengths for deferred CPU copies and upload fills. The aggregate measures software-accounted logical bytes. Snapshots contribute to overall submission preparation, while texture operations and post-fence copyback have separate counters. Contributor A/B report

An end-to-end AMD test confirmed one way a small direct refresh can produce substantial conventional traffic. The direct SRV read four bytes from an ordinary private reservation adjacent to a 16 MiB write-watched reservation. Both views used the same native shadow. The failed write-watch probe previously disabled tracking for the entire shadow, so later clean conventional ranges copied in full. The correction keeps the fallback local to the affected pages and preserves the fast path when an initially unclassified shadow fits in a single committed private region. It retains dirty-page tracking, pending GPU writes and the existing copyback behavior. Diagnostics now report conventional requested and filled bytes, allocation and watch activity, snapshots, copyback, and descriptor materialization. The top conventional ranges include failed probes for the same shadow.

Same AMD descriptor fixture Pre-fix Corrected
Direct bytes copied 4 4
Conventional bytes copied across four clean submissions 64 MiB 0
Conventional bytes copied after one CPU write 16 MiB 64 KiB
Clean-submit wall time, single sample 8.167 ms 0.626 ms
Shader values, direct and after CPU write 27 / 500 27 / 500

The larger AMD fixture uses a 262,144-slot heap, 24,576 populated slots over 192 shadows, four lists per submission, and 1,920 dispatches per 12-submission sample. It revisits 294,912 slots and 221,184 merged ranges per sample. The mixed clean/dirty samples filled 145.9/147.2 MB on both builds, with 84.6/85.4 MB conventional and 61.3/61.8 MB direct. Preparation measured 390.8/394.0 ms before and 380.3/370.2 ms after in single samples. Clean all-watched submissions filled zero bytes. All-unwatched samples filled 291.9 MB on both builds. The warmed control with direct refresh scheduling omitted filled 84.6/85.4 MB and retained stale direct data after a CPU write. Both builds allocated 24 MiB of native shadows during setup. Timed native shadow allocations were zero.

AMD Radeon Graphics, NVIDIA RTX 5070 Laptop GPU, and WARP each passed the five original correctness tests and the new mixed-reservation regression with the D3D12 debug layer and GPU-based validation with resource-state tracking active. We used an app-local Microsoft Agility SDK 1.620.2 test build. The allocation, watched-range, and benchmark measurements above are synthetic. With VICTORY_PC_DXC set, run cargo test -p victory-gpu --features diagnostics directly_indexed_srv_unwatched_range_preserves_watched_refreshes -- --nocapture --test-threads=1 for the focused case. Set VICTORY_COH_MIXED_BENCH=1 and filter to directly_indexed_srv_mixed_heap_benchmark for the larger fixture.

The reviewed diffs cover post-fence copyback (#124), profiling (#130), draw admission and resource retirement (#135), and null texture UAVs (#205). We reproduced the three conflict locations with #135. The correction's standalone branch merges cleanly with #124. The contributor's resolved integration and its detailed logs are still needed to measure how much of the 23 GB came from this mechanism. The broader benchmark retains direct scan and unwatched-range traffic.

Scope

Directly indexed UAV write detection and copyback, direct CBVs, and coherency between distinct native shadow resources for aliased title memory remain separate work. The patch reuses existing buffer dirty tracking and leaves native resource-state handoffs to producers. The GPU ordering test uses an explicit copy-to-SRV transition. Existing workspace coverage exercises physical-page remapping, while the new GPU fixtures cover ordinary and write-watched allocations. Title behavior and any connection to issue #71 remain unverified.

AI-assisted with OpenAI Codex.

Current main integration and preparation

68c8f20 preserves desplmfao's exact 4740e19 merge from fork #4 onto ffe310e. The subsequent change names an existing worklist type for strict Clippy. Both workspace Clippy configurations passed. On the contributor merge, AMD, NVIDIA, and WARP each passed eight focused shader readbacks with full GPU-based validation, a coherency bookkeeping check, and the binding/runtime checks. The later fork-tip shader handle typing change has its own scope.

Native Windows, AMD Radeon Graphics: five alternating fresh processes per allocation mode, debug build with validation off, 12 submissions and 1,920 dispatches per phase. Each phase visited 221,184 direct ranges. All readbacks matched.

Synthetic allocation pattern Clean CPU prep Dirty CPU prep Dirty direct-SRV prep
Mixed watched and ordinary allocations 127.384 ms 109.343 ms 88.180 ms
All watched allocations 89.728 ms 76.535 ms 64.057 ms

Clean direct-SRV timing includes building the range cache. The dirty phase reuses it. This comparison changes allocation types on the same commit and preserves the shared-span setting.

On the contributor's stock Wine server, the separate earlier lookup measurement was 2.3 s to 0.9 s with the view cache. On the patched Wine server, the cache comparison measured 46 to 26 ms per world frame in reservation queries. The two patched runs had 584 and 2,270 median draws per frame, so frame-time and cross-server comparisons are unresolved. The rebase keeps the existing live checks and leaves the fork #3 cache separate. Contributor Wine measurements

Disjoint conventional refreshes

20ff80e credits pablogonz12's report and keeps exact disjoint ranges through readiness and refresh. Only overlapping or touching requests for the same native shadow coalesce. Larger grouped write-watch observations can still be shared. The unrequested dirty gap stays available for a later reader.

The 174 MiB synthetic sparse case copied 182,452,224 bytes on 68c8f20 and 131,072 bytes on 20ff80e. On native Windows AMD, five alternating optimized runs with validation off put median CPU preparation at 19.387 and 0.038 ms, respectively. GetWriteWatch calls were one and two. Dense access copied 174 MiB with one query on both paths, with medians of 20.037 and 20.414 ms. AMD, NVIDIA and WARP passed full GPU-based validation for this fixture and the existing overlapping-shadow, pending-write, remap and partial-reservation cases. Both strict workspace Clippy configurations passed.

The contributor's exact 02a59cc and integration tip are still requested for source comparison. Report

CPU updates inside UAV-declared ranges

The synchronous branch snapshots UAV backing after conventional and direct SRV refreshes finish. The synthetic regression covers title data written after recording, a real GPU write, and a separate late CPU write. CBV and direct SRV values recovered from 11/13 to 43/43. Values 77 and 61 survived GPU copyback and the later CPU write. The focused case, coherency suite and shadow suite passed on AMD Radeon Graphics, NVIDIA RTX 5070 Laptop GPU and WARP with full GPU-based validation. Workspace Clippy passed with default and all features.

Credit to Kevin Pratap Sidhu for the original investigation and synchronous main fix. Earlier in-flight reads/writes require separate fence ownership in #595. Matched Proton and title material retesting are pending.

@DaviTostes

Copy link
Copy Markdown

Tested 83963c5 under Wine 11.22 + vkd3d-proton 3.1 on Arch Linux x86_64 (AMD RX 9060 XT, RADV 26.3.1), Windows build with cargo xwin ... --target x86_64-pc-windows-msvc and a native Microsoft d3dcompiler_47: pass, no regression.

No game data used.

@gw1337x

gw1337x commented Nov 24, 2026

Copy link
Copy Markdown

Tested in game on an RX 7800 XT (Windows 11 26200, 31.6 GB). Build: main at d2a4bae + #135 + #124 + #130 + this PR + #205. It merged with #135 with three small conflicts, all keeping both sides: HostHeap's Drop with Slots, bind's -> bool, and take_retired with refresh_direct_srvs.

In the world (opening cutscene) frame time went from about 0.8–1.1 s without this PR to about 6 s. Copies grew from about 300–450 MB per frame to about 23 GB per frame:

0.2 fps, 5937.0 ms/frame (5532.8 preparing: copies 5407.2 ms 23025.1 MB, textures 22.7 ms 176.3 MB; 226.0 on the GPU; 130.6 copying back 10.1 MB), 1843 draws/frame
direct SRVs per frame: 25579 slots, 18988 merged ranges, 12.21 MB copied, 16.41 ms preparing

The world picture stays black (only the intro card and subtitles show), as without this PR. So on this title the extra copies seem to come from the refreshes the PR triggers for directly indexed SRV slots, about 25k slots a frame, not from the direct-SRV copy itself, which is only 12 MB.

No device loss in about 3 minutes; I stopped the run.

@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

Thanks for the detailed A/B and conflict notes, @gw1337x. I’m tracing the gap between the 12.21 MB attributed to direct SRV refresh and the 23 GB of aggregate copying. Could you share the integration branch or exact commit SHAs for the two builds, along with the diagnostics flags you used? That will let me compare the actual conflict resolutions and counter definitions against the standalone PR.

If you have the logs for both builds, the adjoining copies-per-frame line and the top copied-from ranges would also help separate deferred copies from conventional shadow refreshes.

AntoninMichelq pushed a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 24, 2026
…ctly indexed SRVs) into the integration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
AntoninMichelq pushed a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 24, 2026
…t copy's elements a raw view) into the integration

The SRV's coherency range (PR Marvisak#185) is computed before the view is
rewritten; the 16-byte raw-start check stays on the in-element path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

@gw1337x I pushed c6bf7df to the existing PR. The synthetic GPU test now reproduces and fixes one path from a small direct refresh to large conventional copies. A 4-byte unwatched SRV disabled write watching for the rest of a mixed shadow. Four clean conventional submissions then copied 64 MiB. With the correction they copied zero, and a later CPU write still reached the shader after refreshing one 64 KiB page. AMD, NVIDIA, and WARP passed the correctness suite with the debug layer and full GPU-based validation active.

Could you repeat the opening cutscene A/B with 83963c5 and c6bf7df, holding the other PRs, conflict resolutions, build configuration, and diagnostics flags constant? The exact SHAs and the full copy lines from both runs would help attribute the 23 GB. The revised build also logs shadow traffic per frame and failed watch probes alongside the top conventional ranges.

AntoninMichelq pushed a commit to AntoninMichelq/VIctory-forkAMD that referenced this pull request Nov 24, 2026
Shader PRs 136, 163, 164, 160, 176, 193, 177, 180, 138, 139, 145, 154,
156, 157, 162, 166, 168, 169, 179, 200, 226 and 25.

Marvisak#193's runtime stride table is combined with the runtime PRs:
- descriptor/host.rs keeps Marvisak#135's retire-on-keep, dynamic pool and
  sampler cap, Marvisak#185's Slots (made + directly indexed SRVs) and Marvisak#206's
  raw fallback for structured views off their host copy's elements. The
  stride table still holds the title view's element stride: a raw view
  made by Marvisak#206 starts at the same byte (raw_window never rounds), so the
  shader's index * stride + offset reads the same bytes.
- Slots Marvisak#193 did not know about now write their stride: a directly
  indexed SRV (Marvisak#185) when its record changes, and make_null_kind's
  typed null views (0).
- draw.rs keeps bind() returning whether it bound (with the stride table
  root SRV set inside it) and the bounded indirect argument copy.
- pipeline/host.rs keeps the per-stage subobject stream; the stride
  table root parameter merges cleanly.
- depth_bounds_test's HostShader gains stride_table: false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
@ChruutvoLuzi

Copy link
Copy Markdown

In-game numbers from NVIDIA with c6bf7df, for the A/B asked above. RTX 4090, driver 621.01, Windows 11. d2a4bae with #205, #206, #189, #134, #123 and #89, then this PR at c6bf7df. It conflicts with #206 in buffer_srv; I computed the SrvRange from the view's own first element before #206 moves it into the host copy, which covers the same bytes. Diag build, VICTORY_D3D12_DRED=1, loop limit 1024, the opening of the first mission.

Without this PR With c6bf7df
World frame time 0.8 to 1.6 s 1.9 to 7.1 s
Copies per frame 140 to 440 MB 2.6 to 13.5 GB
direct SRVs per frame (not logged) 1.0 to 3.9 million slots, 0.23 to 1.07 million merged ranges, 21 to 86 GB requested, 2.9 to 13.3 GB filled, 1.4 to 6.3 s preparing (median 4.3 s)
World until 0x887A0006 60 to 100 s 6.5 min, about 60 world frames

So on this card, at c6bf7df the large copies are in the direct SRV refresh itself: it visits about a million slots per frame. The world reached about as many frames as without the PR before the device was removed; that removal is the hang in #71.

AI-assisted (Claude Code).

@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

@ChruutvoLuzi Thanks for running this comparison and sharing the direct SRV counters. The current head still has a scalability regression. Your data shows that descriptor enumeration and the subsequent range refreshes need investigation. The time until device removal increased, and the completed frame count was comparable.

Could you share the full copy and shadow traffic per frame lines for a few paired frames, the native submission count, the number of distinct view heaps if available, and any top refreshed ranges? The exact integration SHAs or conflict-resolution diff for #206 would also help reproduce the same descriptor ranges. I’m keeping the current commit in place while testing the redesign.

@EricPlayZ

Copy link
Copy Markdown

A/B on NVIDIA, as asked, plus what removed most of the remaining cost on this title.

Setup: RTX 2070 SUPER (driver 596.49), Ryzen 7 5700X, 48 GB, Windows 11 26100. Diagnostics build (--profile diag --features diagnostics), VICTORY_GPU_TIMING=1. Same save, same inputs, opening cutscene into the world. The base also carries a few unrelated local fixes, held constant across runs. Frame lines are the runtime's own fps, ms/frame reports, taken from the steady world frames (the first, cheaper world frames are left out).

Build World frame Direct-SRV refresh Copied / frame
refresh switched off (local diag switch, same build as the last row) 1.2–2.3 s n/a ~0.25 GB
83963c5 ~8 s ~6 s 13–19 GB
c6bf7df 6–12 s 5–8.7 s 9–11 GB
c6bf7df + the diff below + #202 2.2–3.0 s 1.1–1.2 s ~2 GB

On this title c6bf7df alone did not help: its new counters showed ~480–600k initial_pages per frame against ~7.5k dirty_pages. Three causes, each fixed in the diff:

  1. Partial pages never become current. copy_stale marks a page copied only when the refreshed range covers it whole. Most directly indexed views are smaller than a page, so their pages stayed "never copied" and were copied again on every submission. Shadow::update now rounds a refresh to whole pages when the memory may be watched, without crossing ranges shaders are writing. Where watching fails, only the requested bytes are copied, as before. refresh_direct_srvs also joins views whose pages touch: about 1M → about 240k update calls per frame.
  2. Ranges over many small allocations. The title's buffers span many adjacent 64 KiB allocations, and GetWriteWatch refuses a range that crosses an allocation, so the whole range fell back to a full copy. writes now asks such a range page by page.
  3. Reserved-only holes. The rest of the untracked bytes (4–5 GB a frame, mostly zeros through the unmapped-read path) were placeholder pages, reserved but not mapped. Page by page, such a page counts as unchanged and is remembered as a hole; it is reported written once it holds memory. title_memory_remapped (called by XMem's map and unmap) now also records the remapped pages as written. Mapped views keep the existing whole-range guard path.

The measured build also write-watched the title's own VirtualAlloc reservations. That made no measurable difference in its own A/B, so it is left out of the diff.

With these, untracked_filled_mb went from 4.5–5.5 GB to 0; what is left is pages watching reports as written (~31k a frame here). #202 (sparse copies) stacks with this: without it the same bytes took about 3x longer.

Tests: all of victory-gpu passes on this machine (60 with diagnostics, 55 without, GPU tests enabled via VICTORY_PC_DXC), serially and in parallel. New tests: whole-page refresh of small watched views (Shadow::update), a range over adjacent watched allocations, a range over watched pages and a hole, a remapped page reported written, a hole committed later not taken as unchanged, and a write found before an unwatched page kept in the journal. I checked that the first two fail without the change.

Existing assertions changed, and why:

  • directly_indexed_srv_unwatched_range_preserves_watched_refreshes expected direct_bytes == 4; the view's page is now copied whole once (PAGE).
  • In unwatched_subrange_does_not_disable_watch_elsewhere_in_shadow, the border refresh now asserts "at most one page refetched, then 0" rather than exact counts.
  • written_pages_are_reported_to_every_asker assumed an empty global journal for a fresh allocation. It failed depending on test order, because an earlier test's freed pages at the same address stay in the journal. It now compares only askings after its first.

Not measured here: AMD/WARP, Linux/Wine. The GPU device hang on this title (DXGI_ERROR_DEVICE_HUNG a few minutes into the world) happens with and without this PR.

AI-assisted (Claude Code); I reviewed and ran it as described above.

Diff against c6bf7df (326+/24−: watch.rs, shadow.rs, host.rs, coherency test)
diff --git a/crates/victory-gpu/src/descriptor/tests/coherency.rs b/crates/victory-gpu/src/descriptor/tests/coherency.rs
index 512d3ff..519e034 100644
--- a/crates/victory-gpu/src/descriptor/tests/coherency.rs
+++ b/crates/victory-gpu/src/descriptor/tests/coherency.rs
@@ -487,7 +487,9 @@ void main(uint3 id : SV_DispatchThreadID) {
     host.execute(&[&direct]);
     let direct_bytes = counter(C::DirectBytes) - before;
     assert_eq!(read(direct_result), 27);
-    assert_eq!(direct_bytes, 4);
+    // The view's page is copied whole (once): a page partly copied stays
+    // "never copied" and was copied again at every submission.
+    assert_eq!(direct_bytes, PAGE as u64);
 
     let before = counter(C::ConventionalBytes);
     let started = std::time::Instant::now();
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index a2b81b6..89aced2 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -1294,9 +1294,12 @@ fn refresh_direct_srvs(runs: &[&HostList]) -> Vec<(u64, crate::descriptor::host:
             if !live(*key) || range.address == range.end {
                 continue;
             }
+            // Views whose pages touch join: the refresh is by whole pages
+            // anyway (`Shadow::update`), and each range costs a lock and a
+            // write-watch query (~1 million small views per world frame).
             if let Some((shadow, _, end)) = &mut pending
                 && Arc::ptr_eq(shadow, &range.shadow)
-                && range.address <= *end
+                && range.address / crate::watch::PAGE <= end.div_ceil(crate::watch::PAGE)
             {
                 *end = (*end).max(range.end);
                 continue;
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 40a27cf..28b5a20 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -280,6 +280,17 @@ impl Shadow {
         if from >= to {
             return 0;
         }
+        // Whole pages where the memory may be write-watched: a page counts as
+        // copied only when a refresh covers all of it, so small views (the
+        // world's directly indexed ones, most under a page) left their pages
+        // "never copied" and were copied again at every submission. Where
+        // watching fails only the requested bytes are copied.
+        let need = (from, to);
+        let (from, to) = if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
+            (from, to)
+        } else {
+            ((from / PAGE * PAGE).max(start), (to.div_ceil(PAGE) * PAGE).min(end))
+        };
         let mut busy: Vec<(usize, usize)> = self
             .pending
             .lock()
@@ -296,21 +307,22 @@ impl Shadow {
             let (mut at, mut bytes) = (from, 0);
             for (a, e) in busy {
                 if a > at {
-                    bytes += self.update_free(at, a);
+                    bytes += self.update_free(at, a, need);
                 }
                 at = at.max(e);
             }
             if at < to {
-                bytes += self.update_free(at, to);
+                bytes += self.update_free(at, to, need);
             }
             return bytes;
         }
-        self.update_free(from, to)
+        self.update_free(from, to, need)
     }
 
     /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
-    /// shader writes.
-    fn update_free(&self, from: usize, to: usize) -> usize {
+    /// shader writes; `need` is the range asked for, all that is copied
+    /// when the memory is not write-watched.
+    fn update_free(&self, from: usize, to: usize, need: (usize, usize)) -> usize {
         let watched = self.watched.load(Ordering::Relaxed);
         if watched != NOT_WATCHED {
             if let Some((now, written)) = crate::watch::writes(from, to, true) {
@@ -324,6 +336,10 @@ impl Shadow {
                 }
                 return copied;
             }
+            let (from, to) = (from.max(need.0), to.min(need.1));
+            if from >= to {
+                return 0;
+            }
             #[cfg(feature = "diagnostics")]
             crate::copystat::watch_failed(self as *const Self as usize, to - from);
             // Views of a single shadow can cover distinct title allocations.
diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs
index 554745d..abd084a 100644
--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@ -58,12 +58,17 @@ struct Journal {
     written: BTreeMap<usize, u64>,
     /// Room for the kernel's answer.
     found: Vec<usize>,
+    /// Pages found reserved but not committed (no data; placeholders the
+    /// title maps physical pages into later): reported written once they
+    /// hold memory.
+    holes: BTreeSet<usize>,
 }
 
 static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
     asked: 0,
     written: BTreeMap::new(),
     found: Vec::new(),
+    holes: BTreeSet::new(),
 });
 
 /// The pages of `[start, end)` (whole pages) as last written, for pages
@@ -93,13 +98,33 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
             &mut granularity,
         )
     } != 0;
-    let guarded = if failed {
+    // Not one write-watched allocation: a view is guarded whole, as before.
+    // Otherwise the range is asked about page by page (allocations start on
+    // 64 KiB): the title's buffers span many of its small allocations, some
+    // reserved but not mapped yet, and copying such ranges whole was
+    // ~4-5 GB a world frame, mostly of unmapped holes.
+    let mut by_pages = Vec::new();
+    let guarded = if !failed {
+        Vec::new()
+    } else if let Some(pages) = guarded.then(|| guard(first * PAGE, last * PAGE)).flatten() {
         count = 0;
-        if !guarded {
-            return None;
-        }
-        guard(first * PAGE, last * PAGE)?
+        pages
     } else {
+        count = 0;
+        match by_page(j, first, last, guarded) {
+            Ok(pages) => by_pages = pages,
+            Err(pages) => {
+                // Pages asked about before one that cannot be: their writes
+                // are now cleared in the kernel, so the journal keeps them.
+                if !pages.is_empty() {
+                    j.asked += 1;
+                    for page in pages {
+                        j.written.insert(page, j.asked);
+                    }
+                }
+                return None;
+            }
+        }
         Vec::new()
     };
     #[cfg(feature = "diagnostics")]
@@ -110,7 +135,11 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
     }
     j.asked += 1;
     let now = j.asked;
-    let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
+    let pages = j.found[..count]
+        .iter()
+        .map(|&at| at / PAGE)
+        .chain(guarded)
+        .chain(by_pages);
     for page in pages.collect::<Vec<_>>() {
         j.written.insert(page, now);
     }
@@ -123,6 +152,72 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
     ))
 }
 
+/// The written pages of pages `[first, last)`, asked about one at a time
+/// (clearing what the kernel reports): a write-watched page as the kernel
+/// says, a view's as its guard says, a reserved page with no memory as
+/// unwritten (noted as a hole, written once it holds memory). `Err` with
+/// the written pages found before a page none of these covers.
+fn by_page(
+    j: &mut Journal,
+    first: usize,
+    last: usize,
+    guarded: bool,
+) -> Result<Vec<usize>, Vec<usize>> {
+    use windows_sys::Win32::System::Memory::{
+        GetWriteWatch, MEM_MAPPED, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
+    };
+    const WRITE_WATCH_FLAG_RESET: u32 = 1;
+    let mut written = Vec::new();
+    let mut answer = [0usize; PAGE / KERNEL_PAGE];
+    for page in first..last {
+        let mut count = answer.len();
+        let mut granularity = 0;
+        // SAFETY: the answer buffer holds `count` entries.
+        let watched = unsafe {
+            GetWriteWatch(
+                WRITE_WATCH_FLAG_RESET,
+                (page * PAGE) as *const _,
+                PAGE,
+                answer.as_mut_ptr().cast(),
+                &mut count,
+                &mut granularity,
+            )
+        } == 0;
+        if watched {
+            if count > 0 || j.holes.remove(&page) {
+                written.push(page);
+            }
+            continue;
+        }
+        // SAFETY: plain data filled in by the query.
+        let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+        // SAFETY: a valid out pointer of the right size.
+        let n = unsafe { VirtualQuery((page * PAGE) as *const _, &mut info, size_of_val(&info)) };
+        if n == 0 {
+            return Err(written);
+        }
+        if info.State == MEM_RESERVE {
+            j.holes.insert(page);
+            continue;
+        }
+        let filled = j.holes.remove(&page);
+        if guarded
+            && info.Type == MEM_MAPPED
+            && let Some(pages) = guard(page * PAGE, (page + 1) * PAGE)
+        {
+            if filled || !pages.is_empty() {
+                written.push(page);
+            }
+            continue;
+        }
+        if filled {
+            written.push(page);
+        }
+        return Err(written);
+    }
+    Ok(written)
+}
+
 /// Guarded blocks of view memory.
 const BLOCK: usize = PAGE;
 
@@ -249,6 +344,16 @@ pub fn title_memory_remapped(at: usize, len: usize) {
         g.protected.remove(&block);
         g.clean.remove(&block);
     }
+    drop(g);
+    // New contents: written, for every refresh that copied the pages before
+    // (taken after the guards: `writes` takes the journal first).
+    let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
+    j.asked += 1;
+    let now = j.asked;
+    for page in at / PAGE..(at + len).div_ceil(PAGE) {
+        j.written.insert(page, now);
+        j.holes.remove(&page);
+    }
 }
 
 /// Registers the handler that takes writes to guarded blocks, once, ahead
@@ -326,16 +431,20 @@ pub(crate) mod tests {
         } as usize;
         assert_ne!(p, 0);
         let (start, end) = (p, p + 4 * PAGE);
-        let (_, before) = writes(start, end, false).expect("watched");
-        assert!(before.is_empty());
+        // The journal outlives allocations: pages an earlier test wrote at
+        // this address may be listed, with older askings than this test's.
+        let (first, _) = writes(start, end, false).expect("watched");
+        let since = |pages: Vec<(usize, u64)>| -> Vec<(usize, u64)> {
+            pages.into_iter().filter(|&(_, w)| w > first).collect()
+        };
         // SAFETY: committed pages of ours.
         unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
         let (now, after) = writes(start, end, false).expect("watched");
-        assert_eq!(after, [(p / PAGE + 1, now)]);
+        assert_eq!(since(after), [(p / PAGE + 1, now)]);
         // Another asker after the kernel's bit was cleared still sees it.
         let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
         assert!(later > now);
-        assert_eq!(again, [(p / PAGE + 1, now)]);
+        assert_eq!(since(again), [(p / PAGE + 1, now)]);
         let mut plain = vec![0u8; PAGE];
         assert!(
             writes(
@@ -465,9 +574,10 @@ pub(crate) mod tests {
         assert_eq!(shadow.update(start, watched), watched);
         assert_eq!(shadow.update(start, watched), 0);
 
-        // A small view in the next allocation needs the CPU fallback. A large
-        // conventional view on the same shadow can still use write watching.
-        assert_eq!(shadow.update(second.0 as usize, 4), 4);
+        // A small view in the next allocation is copied as its whole page
+        // (guarded there). A large conventional view on the same shadow can
+        // still use write watching.
+        assert_eq!(shadow.update(second.0 as usize, 4), PAGE);
         let refreshed: usize = (0..4).map(|_| shadow.update(start, watched)).sum();
         eprintln!(
             "4-byte unwatched refresh, then 4 clean watched requests copied {refreshed} bytes"
@@ -487,10 +597,181 @@ pub(crate) mod tests {
             assert_eq!(word, 500);
         }
 
-        // A later fallback crossing into the watched allocation invalidates
-        // that page's generation without affecting the remaining pages.
-        assert_eq!(shadow.update(start + watched - 4, 8), 8);
-        assert_eq!(shadow.update(start, watched), PAGE);
+        // A later small refresh across the allocations' border refetches at
+        // most the border page of the watched allocation, then nothing.
+        assert!(shadow.update(start + watched - 4, 8) >= 8);
+        assert!(shadow.update(start, watched) <= PAGE);
         assert_eq!(shadow.update(start, watched), 0);
     }
+
+    /// Two adjacent allocations, the first write-watched, the second
+    /// write-watched if `watched`, each one page; kept reserved (the journal
+    /// remembers their pages).
+    fn neighbours(watched: bool) -> usize {
+        for _ in 0..16 {
+            // SAFETY: plain test reservations.
+            unsafe {
+                let span = VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS);
+                assert!(!span.is_null());
+                assert_ne!(VirtualFree(span, 0, MEM_RELEASE), 0);
+                let kind = MEM_RESERVE | MEM_COMMIT;
+                let a = VirtualAlloc(span, PAGE, kind | MEM_WRITE_WATCH, PAGE_READWRITE);
+                if a.is_null() {
+                    continue;
+                }
+                let second = span.cast::<u8>().add(PAGE).cast();
+                let b = VirtualAlloc(second, PAGE, kind | if watched { MEM_WRITE_WATCH } else { 0 }, PAGE_READWRITE);
+                if b.is_null() {
+                    VirtualFree(a, 0, MEM_RELEASE);
+                    continue;
+                }
+                return span as usize;
+            }
+        }
+        panic!("no two adjacent allocations");
+    }
+
+    #[test]
+    fn a_range_over_watched_allocations_is_asked_page_by_page() {
+        let p = neighbours(true);
+        let (start, end) = (p, p + 2 * PAGE);
+        let (before, _) = writes(start, end, false).expect("watched, page by page");
+        // SAFETY: committed pages of ours.
+        unsafe {
+            ((p + 8) as *mut u8).write(1);
+            ((p + PAGE + 8) as *mut u8).write(1);
+        }
+        let (now, after) = writes(start, end, false).expect("watched, page by page");
+        let after: Vec<_> = after.into_iter().filter(|&(_, w)| w > before).collect();
+        assert_eq!(after, [(p / PAGE, now), (p / PAGE + 1, now)]);
+    }
+
+    #[test]
+    fn a_write_found_before_an_unwatched_page_is_kept() {
+        let p = neighbours(false);
+        let (before, _) = writes(p, p + PAGE, false).expect("watched");
+        // SAFETY: a committed page of ours.
+        unsafe { ((p + 8) as *mut u8).write(1) };
+        // The second allocation is not watched: refused, as before.
+        assert!(writes(p, p + 2 * PAGE, false).is_none());
+        // The first page's write was cleared in the kernel by that asking;
+        // the journal still has it.
+        let (_, again) = writes(p, p + PAGE, false).expect("watched");
+        assert!(again.iter().any(|&(page, w)| page == p / PAGE && w > before));
+    }
+
+    /// Adjacent one-page allocations of the given `VirtualAlloc` kinds
+    /// (read-write where committed); kept reserved.
+    fn pages_of(kinds: &[u32]) -> usize {
+        for _ in 0..16 {
+            // SAFETY: plain test reservations.
+            unsafe {
+                let n = kinds.len() * PAGE;
+                let span = VirtualAlloc(std::ptr::null(), n, MEM_RESERVE, PAGE_NOACCESS);
+                assert!(!span.is_null());
+                assert_ne!(VirtualFree(span, 0, MEM_RELEASE), 0);
+                let mut made = Vec::new();
+                for (i, &kind) in kinds.iter().enumerate() {
+                    let at = span.cast::<u8>().add(i * PAGE).cast();
+                    let protect = if kind & MEM_COMMIT != 0 { PAGE_READWRITE } else { PAGE_NOACCESS };
+                    let p = VirtualAlloc(at, PAGE, kind, protect);
+                    if p.is_null() {
+                        break;
+                    }
+                    made.push(p);
+                }
+                if made.len() == kinds.len() {
+                    return span as usize;
+                }
+                for p in made {
+                    VirtualFree(p, 0, MEM_RELEASE);
+                }
+            }
+        }
+        panic!("no adjacent allocations");
+    }
+
+    const WATCHED: u32 = MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH;
+
+    #[test]
+    fn a_range_over_watched_pages_and_a_hole_is_tracked() {
+        let p = pages_of(&[WATCHED, MEM_RESERVE, WATCHED]);
+        let (start, end) = (p, p + 3 * PAGE);
+        let (before, _) = writes(start, end, false).expect("watched pages and a hole");
+        // SAFETY: committed pages of ours.
+        unsafe {
+            ((p + 8) as *mut u8).write(1);
+            ((p + 2 * PAGE + 8) as *mut u8).write(1);
+        }
+        let (now, after) = writes(start, end, false).expect("watched pages and a hole");
+        let after: Vec<_> = after.into_iter().filter(|&(_, w)| w > before).collect();
+        assert_eq!(after, [(p / PAGE, now), (p / PAGE + 2, now)]);
+    }
+
+    #[test]
+    fn a_remapped_page_is_written() {
+        let p = pages_of(&[WATCHED, MEM_RESERVE]);
+        let (before, _) = writes(p, p + 2 * PAGE, false).expect("tracked");
+        title_memory_remapped(p + PAGE, PAGE);
+        let (_, after) = writes(p, p + 2 * PAGE, false).expect("tracked");
+        assert!(after.iter().any(|&(page, w)| page == p / PAGE + 1 && w > before));
+    }
+
+    #[test]
+    fn a_hole_committed_later_is_not_taken_as_unchanged() {
+        let p = pages_of(&[WATCHED, MEM_RESERVE]);
+        assert!(writes(p, p + 2 * PAGE, false).is_some());
+        // Committed in place (not watched): no longer answerable.
+        // SAFETY: the reserved page of ours.
+        let at = unsafe { VirtualAlloc((p + PAGE) as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) };
+        assert!(!at.is_null());
+        assert!(writes(p, p + 2 * PAGE, false).is_none());
+    }
+
+    #[test]
+    fn small_refreshes_of_watched_memory_copy_whole_pages_once() {
+        if crate::host::host().is_none() {
+            return;
+        }
+        let size = 4 * PAGE;
+        // SAFETY: a fresh write-watched allocation, kept reserved (below).
+        let base = unsafe {
+            VirtualAlloc(
+                std::ptr::null(),
+                size,
+                MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
+                PAGE_READWRITE,
+            )
+        } as usize;
+        assert_ne!(base, 0);
+        // SAFETY: committed pages of ours. Touched first: reading a
+        // demand-zero page faults it in, which write watching reports.
+        unsafe { (base as *mut u8).write_bytes(0, size) };
+        crate::shadow::register(base, base as u64, size as u64);
+        let shadow = crate::shadow::find(base as u64, size as u64).unwrap();
+        // Small views (the world's directly indexed ones): eight in the
+        // first page, one in the third, none covering a page whole.
+        let views = [0, 64, 128, 1024, 4096, 8192, 16384, 32768, 2 * PAGE + 16];
+        let refresh = || -> usize { views.iter().map(|&at| shadow.update(base + at, 4)).sum() };
+        // First: the two pages, whole. They were "never copied" before, and
+        // a page only partly copied stayed so, copied again at every refresh.
+        assert_eq!(refresh(), 2 * PAGE);
+        assert_eq!(refresh(), 0);
+        assert_eq!(refresh(), 0);
+        // A title write brings back only its page, with the new bytes.
+        // SAFETY: a committed page of ours.
+        unsafe { ((base + 64) as *mut u32).write(500) };
+        assert_eq!(refresh(), PAGE);
+        let mut data = std::ptr::null_mut();
+        // SAFETY: the live shadow holds the refreshed word; no GPU work.
+        unsafe {
+            shadow.buffer.Map(0, None, Some(&mut data)).unwrap();
+            let word = data.cast::<u8>().add(64).cast::<u32>().read_unaligned();
+            shadow.buffer.Unmap(0, None);
+            assert_eq!(word, 500);
+        }
+        crate::shadow::unregister(base, base as u64);
+        // The allocation stays reserved: the write journal remembers its
+        // pages, and another test's allocation there would inherit them.
+    }
 }

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

@EricPlayZ Thanks for the controlled NVIDIA comparison and for posting the implementation. Your partial-page, split-allocation, and reserved-hole findings give us concrete cases to test against the draft. I’ll credit your findings and any code we bring in.

Could you share a fork branch or commit for the posted diff and the exact commit stack used for the run with #202? That would let me verify the patch and measure the changes separately. I’m checking partial commits within a 64 KiB tile, transitions from populated memory to holes, and pending GPU writes on AMD, NVIDIA, and WARP before integrating.

@EricPlayZ

Copy link
Copy Markdown

Branches on my fork:

What 04afafa holds, on main at d2a4bae:

  • Translate 64-bit texture atomics and follow proven shader branches #48 (56f0072), GPU: skip unmapped regions after a failed bulk read into host memory #202 (dcf6664), this PR at 83963c5 and then c6bf7df (merges e0714fa, 181cfea, ee0c950, 794308a).
  • Unrelated local commits, held constant across all the runs in the table:
    • 5b43506: diagnostics-only title byte patching. It was used to skip the title's own hang watchdog; no game bytes are in the repo.
    • 8e166d9 and 0076c12: guard handling for partially remapped and read-only view blocks.
    • de58539: the fault handler reuses the guard lock it already holds.
    • 3a823ed: image sample addressing in the translator.
  • b510007 → 04afafa: the work behind the diff, in the order I tried it.
    • Includes a write-watch memo, added in b510007 and dropped in cc6fdef (no gain).
    • Includes a diagnostic that classifies untracked copies (0b7b2ad).
    • Includes the VirtualAlloc write-watch change (e5b5359, no measurable effect on its own).

The 0dd303b diff equals 04afafa's watch.rs, shadow.rs and coherency-test changes, plus the host.rs join, minus the diagnostics and the VirtualAlloc change. One adaptation: in c6bf7df, title_memory_remapped has no end binding, so the journal loop uses (at + len).

The runs were NVIDIA only. I have not tested partial commits inside a 64 KiB tile or populated-to-hole transitions beyond the unit tests listed above (a hole committed later; a remap marking pages written).

@GamingRipperDoc

Copy link
Copy Markdown

AMD + Windows 10 data point for @EricPlayZ's diff, as the comment above asked ("Not measured here: AMD"). Short version: the write-watch cost went down as described, but frames did not get faster here, and the copy volume the frame line reports went up. One run, with caveats below.

Setup: Windows 10 22H2 19045.7846, RX 9070 XT (driver 32.0.32015.7029), Ryzen 9 9900X. Base main d2a4bae + #175 (Agility SDK, needed on Windows 10) + #336. Then this PR at c6bf7df (one conflict with #336 in draw.rs: #336 makes bind return bool, this PR makes it pub(crate); kept both) + the diff from the comment above (applied cleanly) + #202. Diag build, VICTORY_D3D12_DRED=1, driven with a pad into the first mission. cargo test -p victory-gpu: 56 passed (61 with diagnostics); VICTORY_PC_DXC not set here, so the GPU-backed tests may have been skipped.

Steady world frames, from the runtime's fps, ms/frame and copystat lines:

base (#175 + #336) + #185 + diff + #202
frame 0.8–1.2 fps (~900–1,200 ms) 0.5–0.8 fps (~1,270–1,970 ms)
copies in the frame line 450–615 ms, 230–365 MB 850–1,350 ms, 1.2–3.0 GB
watches (copystat) 9,805 per frame, 983 ms, 52.8 GB checked, 51.5 GB unchanged 120,962 per frame, 329–540 ms, 49–85 GB checked, ~97% unchanged
world lasted ~145 s ~133 s
how it ended freed-texture page fault the same

So the change does what it says for write-watching (about 12× more queries, each far cheaper, about half the time), but here the bytes copied per frame grew 5–10× and the frame got slower. My guess, not checked: the whole-page rounding (Shadow::update) copying full pages for small views where watching then doesn't cover the page. The per-range copied from lines don't account for the GB, so I can't say where it goes.

Caveats: one run each, and the two runs were at different moments (the summary I compared shows 202 submissions per frame in the base run, 22.7 in this one), so this is a direction, not a measurement. I didn't run without the diff (#185 + #202 alone), so I can't separate the diff's effect from #185's. Happy to run that A/B, or with a diagnostics switch you'd like, on this machine.

No game data used.

AI-assisted (Claude Code); I played the runs, and the logs were read with the model.

Cache stable descriptor ranges and narrow refreshes to shader-proven slots
while retaining the unrestricted dynamic fallback. Keep watched subranges
current without widening ordinary reads or crossing pending GPU writes.

Adapt EricPlayZ's reservation splitting and hole-handling correction.
Preserve live watch coverage on partially committed pages and invalidate
old generations on supported guest allocation and remap operations.

Co-authored-by: EricPlayZ <EricPlayZ@users.noreply.github.com>
@aycow

aycow commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

Thanks, @EricPlayZ, for isolating the three refresh costs and sharing both branches. I kept your original commit intact on a local test branch. The draft revision 53e36e7 credits you and adapts the reservation splitting and hole handling. The new regression covers a committed 4 KiB island after a reserved prefix, where the clean patch returned stale data.

On the matched AMD fragmented fixture, c6bf7df, your clean patch plus #202, and the revised build took 17.83 s, 5.05 s, and 4.03 s over 320 submissions. The revised build filled 1.30 GB of direct shadow data versus 10.92 GB on c6bf7df, with matching shader results and copybacks. The focused suite passed on AMD, NVIDIA, and WARP with full D3D12 GPU-based validation.

@EricPlayZ @ChruutvoLuzi @GamingRipperDoc, could one of you please run another controlled in-game A/B with 53e36e7 and your previous baseline, keeping the other PRs, settings, scene, timing options, and #202 status fixed? If possible, please include direct requested and filled bytes, preparation time, submission and unique heap counts, top refreshed ranges, and frames completed before any device removal. An independent Wine run would also help. I’ll keep this in draft while we wait for the in-game result.

@pablogonz12

Copy link
Copy Markdown
Contributor

@aycow Queued: a matched warm-cache Proton A/B on my RX 9070 XT, same stack, scene and frame window, toggling only 20ff80e. I'll post aggregate copied bytes, watch queries, preparation time, frame time, draw count, and whether both runs reach the same scene. Not tested yet: any of this; no numbers until it runs.

The CPU may change constants inside a broad UAV declaration during submission preparation. Refresh them before GPU execution and keep an accurate copyback baseline.

Reported-by: Kevin Pratap Sidhu <pratapkevin8@gmail.com>

Reference: KevinPratap@7a03753
@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

The synchronous branch now snapshots UAV-declared ranges after conventional and direct SRV preparation in f173d36. Credit to @KevinPratap for isolating the failure in #1322. In the recorded→submit test, the CBV/direct SRV readback changed from 11/13 to 43/43. It still returned the GPU write of 77 and preserved a later CPU write of 61. The focused case plus the coherency and shadow suites passed with full GBV on AMD Radeon Graphics, RTX 5070 Laptop and WARP. Both workspace Clippy configurations passed.

@pablogonz12 thanks for the public refs. I compared f9a8032 with 02a59cc and 20ff80e. Your corrected composition avoids bridging the distant requests while sharing observations across copies. This branch retains exact requested byte intervals; it does not import the #393 integration merge. The queued warm Proton A/B against 20ff80e remains useful for the sparse-range change. Please identify f173d36 separately if you also A/B the UAV correction. No title performance result is established here.

yourmomsbasement pushed a commit to yourmomsbasement/VIctory_Dev that referenced this pull request Nov 24, 2026
A page only partly inside a requested range was copied in part and never
marked as copied, so every later range in the same page copied it again.
With many small, unaligned ranges in the same pages (directly indexed SRVs
in Marvisak#185, close to a million per world frame) this came to about 11 GB of
copies per frame.

Widen each range to its first and last pages' bounds (within the buffer)
when no pending range overlaps what that adds, so the page is marked and
copied again only after the title writes to it. Next to a pending range
the old behaviour stays.

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

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

I checked the latest #595 7465030 against f173d36. The current #185 keeps the submission lock through direct refresh, the UAV snapshot, fence wait, and copyback. Individual slot locks are released after descriptor metadata is collected, so retaining the backing Arc does not freeze the native slot or the bytes a queued reader will see. The fix needs to select the latest generation at submission, retain that native slot and protect the refreshed backing span through the fence. Any blocking path needs to drop the shader-heap registry lock before waiting so lease retirement can make progress. No branch or draft change. The matched warm-cache preparation comparison and async ownership remain the two separate checks.

AI-assisted using Codex.

@pablogonz12

Copy link
Copy Markdown
Contributor

Not run yet: the matched warm-cache A/B you describe (only 20ff80e toggled, stack, scene and frame window held fixed, copies, watch queries, preparation time, frame time and draw count, both reaching the same scene) needs the GPU and is on my list for the next free slot. I will post the numbers here when it has actually run.

@Marvisak Marvisak closed this Nov 24, 2026
zhaibingye pushed a commit to zhaibingye/VIctory that referenced this pull request Nov 25, 2026
Keep the requested union through pending and completed preparation. Leave dirty gaps for later readers and retain one inline range for the common case.

Reproduces the copy amplification reported by pablogonz12 on Marvisak#185 (Marvisak#185 (comment)) and carries forward the range behavior from 20ff80e on the current unified journal.
qub3d2 pushed a commit to qub3d2/victory-fork that referenced this pull request Nov 25, 2026
Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.
DoubleD17 added a commit to DoubleD17/victory-fork that referenced this pull request Nov 25, 2026
Keep the union of overlapping and adjacent refresh ranges per shadow. Cover range normalization with CPU unit tests and preserve the WARP readback regression.

Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.
ZaneIceMaster11 pushed a commit to ZaneIceMaster11/victory-fork that referenced this pull request Nov 25, 2026
Keep the union of overlapping and adjacent refresh ranges per shadow. Cover range normalization with CPU unit tests and preserve the WARP readback regression.

Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.
RicerBoy pushed a commit to RicerBoy/DropItLikeItsHot that referenced this pull request Nov 25, 2026
Part of #32 (VIwork port).

Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.

(cherry picked from commit 0d22b3808d0e5413dd845c771de5d6977cfbdc20)

(cherry picked from commit 3cd984de3a3d6fc31e983e8120f941f5d6ad3565)
DoubleD17 added a commit to DoubleD17/victory-fork that referenced this pull request Nov 25, 2026
Keep the union of overlapping and adjacent refresh ranges per shadow. Cover range normalization with CPU unit tests and preserve the WARP readback regression.

Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.
lopesdevi pushed a commit to lopesdevi/victory-dedsec-gta that referenced this pull request Nov 25, 2026
Adapted from Aydan (aycow) in Marvisak/VIctory#1818.
Thanks to pablogonz12 for the original reproduction in Marvisak/VIctory#185.

(cherry picked from commit 0d22b3808d0e5413dd845c771de5d6977cfbdc20)
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.

10 participants