watch: move guard/alias VirtualProtect outside GUARDS mutex and batch Bits/publish #3760
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3760"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by ScymicX on 2026-11-30T06:10:16Z.
What it changes
guard()previously held the globalGUARDSmutex across allVirtualProtect,elsewhere,uncommitted_end, and aliased-viewprotect_aliascalls, stalling concurrent refresh worker threads and any locked write-fault path behind OS page-table walks. In addition,writes_withallocated aVec<usize>and updatedPUBLISHEDpage by page on every guarded refresh.This PR moves both primary and aliased-view
VirtualProtectcalls outsideGUARDSand batchesBits/PUBLISHEDupdates per 64-block word (enabled by default;VICTORY_WATCH_UNLOCKED_PROTECT=0falls back to the existingguard+publishpath):PROTECT_GATE+PROTECTING):MAPPING -> Asking -> PROTECT_GATE -> GUARDS -> OPENED.guard_with_pub/protect_unlockedholdPROTECT_GATE.read()while runningelsewhere,uncommitted_end, andVirtualProtectoutsideGUARDS; mutators (title_memory_allocated,look_at_holes,writing,kernel_writing,title_memory_written,views_mapped,title_memory_splitting,title_memory_remapped,title_memory_unmapping,title_memory_freed,title_memory_made_real) takePROTECT_GATE.write().soft_runs(...)is read underGUARDSbefore dropping the lock so concurrenttitle_memory_made_realcannot be missed.PROTECTINGmarks in-flight primary and alias blocks before droppingGUARDS(with RAIIClearProtecting/ClearProtectingSliceguards). Fault handlers (on_write,opened_for_writing,came_back) spin briefly onwait_protecting, andopen_unlockedreturnsfalseifPROTECTINGis set so racing faults take the safe locked/settled path.GUARDSis released,restore_rwreverts its protection; for aliased blocks,pending_cleanre-verifies allall_others(g.protected,g.aliased,!failed_aliases,!OPENING,!PROTECTING || alias_to_vp_set,!BESIDE,!unsettled) before marking a blockclean.Bits::{ensure_piece, set_word, clear_word, set_all}and word-levelBlocks::{insert_all, diff_into}.BESIDE/OPENING/TOLD/PROTECTINGpiece lookups and cachedg.protected/g.clean/now_instantinguard_with_pub.publish_pairsavoids theVec<usize>allocation inwrites_withand updatesPUBLISHEDper 64-block word, only called whenguard_with_pubreportsany_publishable.How it was tested
v2026.11.28.01baseline).VirtualProtectrunning insideGUARDS,guard: GUARDS mutex waitsummed across worker threads reached 18.51 ms/frame.VirtualProtectoutsideGUARDS+ batchingBits/publish_pairsreducedguard: GUARDS mutex waitto ~2.8 ms/frame.cargo testpassed for the crates it touches: yescargo test --locked -p victory-gpu --lib watch:: -- --test-threads=1: 65 passed, 0 failed.cargo test --locked -p victory-gpu --lib watch::many_askers_tests: 10 passed, 0 failed (default ON) and 10 passed, 0 failed (VICTORY_WATCH_UNLOCKED_PROTECT=0).watch::many_askers_tests::no_write_to_resting_views_is_lost_between_askers: 30 consecutive runs, 0 failures (runs=30 fails=0).cargo clippy -p victory-gpu --no-deps --all-targets --lockedand--all-features: 0 warnings in touched/new code.cargo xtask policy --staged: passed.Checked for overlap
shadow.rslanding bitmap) and #3756 (watch.rslock-freeWRITTEN_EPOCHSjournal).Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Yoruiopz on 2026-11-30T09:42:48Z.
I reproduced an ownership regression on exact head
2789218a. In open_unlocked, OPENING.swap_on returns true when another fault already owns the bit. The combined early-return branch then clears that other opener's bit. A guard or a third fault can observe the still-active opening as idle. This branch is shared by both VICTORY_WATCH_UNLOCKED_PROTECT settings.The asset-free Windows fixture holds the first opener's claim on a real allocated block, exercises the competing fault entry, and checks that the first claim survives. It failed on the unmodified production logic and passed with this two-check correction. The correction leaves an existing claim alone and clears only a claim taken by the current caller when PROTECTING requires fallback.
All 66 watch tests passed with VICTORY_WATCH_UNLOCKED_PROTECT=1 and again with 0.
Preliminary in-game comparison
I built the exact PR head plus the small ownership correction as a single locked Windows diagnostics executable. Same RTX 5070 Laptop, copied porch checkpoint, warm cache, Series S with DLSS Ultra Performance and frame generation off. Only VICTORY_WATCH_UNLOCKED_PROTECT changed.
I used three corresponding host reports around 17–28 seconds after the world entered, with roughly 5,200 draws per frame in both modes. These numbers are medians of those reports.
The enabled session lost Windows foreground shortly after two screenshots confirmed the expected porch pose, so the longer camera-qualified comparison and frame-time percentiles are incomplete. Both modes still show the separately tracked porch arm artifact. The aggregate lock time measures worker contention and is separate from wall-clock frame time.
Series X with 2x DLSS FG
I tested the corrected guard code on the same .05 base with the explicit 1080p startup fix and #3811, using one Windows diagnostics executable. Both processes used the same copied save, warmed cache, DLSS Performance (960×540 to 1920×1080), 2x DLSS frame generation, and the 15 rendered FPS cap. VICTORY_AB was clear. Only VICTORY_WATCH_UNLOCKED_PROTECT changed.
Foreground was polled for the duration. The enabled attempt lost focus after 15.46 seconds, so I compared an interior 14-second interval before that loss to the same world time in the disabled run. The initial screenshots matched the same porch pose. Both windows contain 210 rendered-frame intervals, with median draws 5,787 and 5,750. A later complete enabled window advanced to a much heavier scene and is excluded.
The enabled p95 is 68.3–70.9 ms using either endpoint for the CSV clock alignment. The shown rate uses complete plugin reporting intervals, not individual display-frame timings. This supports lower guard contention in a second profile. The short matched window shows modest improvement at the cap and leaves steadiness under higher load unverified.
Protection protocol mode
The diagnostics toggle currently allows VICTORY_AB to switch which protection implementation and which publication path writes_with chooses. The legacy and unlocked implementations use the same protection bookkeeping, and the legacy path does not honor PROTECTING during an unlocked protection change. A live flip can therefore mix protocols across workers, or within one call if its two flag reads differ. The performance cases above explicitly clear VICTORY_AB and set the mode before each process.
I isolated the setting at first use in a follow-up commit. Default-on and exact =0 behavior stay the same. The regression launches fresh child processes with VICTORY_AB targeting this switch and checks unset, =0, and =1. The old selector failed the extracted regression. The integrated Windows regression and all 70 watch tests passed in both fresh switch modes after correction.
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by ihyajb on 2026-11-30T11:27:40Z.
Whole-process stalls of 2.2–2.7 s with this PR (busy-wait in
wait_protecting)Tested this PR merged with ten other open PRs (#3733, #3850, #3832, #3848, #3750, #3753, #3705, #3694, #3762, #3726) on
41adb551, diagnostics build, Series S profile, DLSS + FG, 5-minute standing runs from one save.VICTORY_WATCH_UNLOCKED_PROTECTon (default): a single frame of 2.2–2.7 s every 2–4 minutes, in all 4 runs.VICTORY_WATCH_UNLOCKED_PROTECT=0: none (worst frame 163 ms).41adb551(3 runs): none (worst 499 ms).A sampling profiler with per-round timestamps took 3–7 samples during each long frame instead of ~250, so its own thread was stalled too: the whole process stops, not one waiting thread.
Likely cause:
wait_protecting(called from the write-fault handler on the title's threads) is a purespin_loop(). When several title threads fault on a block inPROTECTING, they can occupy every core while the helper whoseVirtualProtectclears the bit doesn't get scheduled, until Windows' starvation boost runs it. I didn't catch a stack inside a stall (the profiler couldn't sample), so this is inferred. But changing only this loop to spin briefly, thenyield_now(), thensleep(200µs)removed the stalls in 2 runs (worst 153 / 142 ms), with no change in frame rate:cargo test -p victory-gpu --lib watch::: 66 passed. One or two runs per configuration, so the numbers are indicative rather than statistical.Found with Claude Code.
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by ScymicX on 2026-11-30T13:43:39Z.
Thank you @Yoruiopz and @ihyajb for catching those issues — all three fixes are now pushed in
8bdc117:open_unlockedOPENINGownership (@Yoruiopz): SplitOPENING.swap_on(block)fromPROTECTING.any(block, block + 1)so a competing fault returnsfalsewithout clearing another opener'sOPENINGbit; only a caller that claimedOPENINGitself clears it onPROTECTINGfallback.wait_protectingbackoff (@ihyajb): Replaced the purespin_loop()with bounded spin (< 256) ->thread::yield_now()(< 320) ->thread::sleep(200µs)to avoid thread-starvation stalls when multiple title threads fault on aPROTECTINGblock.OnceLock(@Yoruiopz):unlocked_protect()now cachesVICTORY_WATCH_UNLOCKED_PROTECTviaOnceLockat first read instead ofcrate::toggled!, soVICTORY_ABcannot mix legacy and unlocked protocols mid-run.watch::tests::open_unlocked_preserves_existing_opening_claimcovering both the competing-claim preservation and thePROTECTINGfallback clear.Verified locally on
8bdc117:cargo test --locked -p victory-gpu --lib watch:: -- --test-threads=1: 66 passed, 0 failed (default ON) and 66 passed, 0 failed (VICTORY_WATCH_UNLOCKED_PROTECT=0).cargo test --locked -p victory-gpu --lib watch::many_askers_tests: 10 passed, 0 failed + 20 consecutive runs ofno_write_to_resting_views_is_lost_between_askers(runs=20 fails=0).cargo clippy -p victory-gpu --no-deps --all-targets --locked(+--all-features): 0 warnings in touched/new code;cargo xtask policy --staged: passed.Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by mstrmoos on 2026-11-30T19:22:35Z.
Picked onto our branch with #3753, #3756, #3760, #3881, #3832, #3858 and four that have since merged (#3818, #3850, #3874, #3871). #3760 needed a hand merge on top of the others.
All of victory-gpu's and victory-shader's tests passed. On the RTX 5080 16 GB, Ryzen 7 9800X3D, Windows 11, Series X profile, same save and 90 s bench route each run, the frame median went from 40.4 to 39.1 ms for the whole set. I didn't measure the PRs one by one, so this is evidence of no regression rather than this PR's own gain. Screenshots looked clean.
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by paales on 2026-11-30T23:09:48Z.
Written by 🤖:
In-game numbers for this PR. PC: RTX 5070 Ti 16 GB, Ryzen 9 5900X, 32 GB, Windows 11. Series X, 1440p, DLSS Performance, frame generation off, 30 fps cap. Scene: a story save that loads into a mission cutscene in the city, the interview skipped at 35 s into a montage of quick cuts; 82 s from the first scene frame.
I applied only this PR's
watch.rschange (8bdc117band2789218aagainstmain) onto my build (main84bd61e2with #3918, #1727, #3553, #3043, #4206, #4138, #720 and the write-watch part of #2647). One conflict, inwrites_with: the allocation-freekernel_written_intoof #2647 kept, andguard_with_puborguardchosen byunlocked_protect()as in this PR.A profile of the submitting thread in the montage without this PR (a sampler that stops the thread only to copy its stack, about 3 % of the time) had 13 % of it waiting in
watch::waitedunderwatch::guards(fromguardandpublish_range). With the PR, one run each:Within the spread of single runs on this PC, except the first 35 s, which were slower. I did not take it into my build.
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by upipibi on 2026-12-01T00:35:36Z.
Edited 2026-12-01 01:43Z: the cause below is now traced and a fix tested. The window I first suggested (the
OPENING/PROTECTINGorder) was wrong: changing that order didn't help (7 of 14 runs still died). I've replaced that part.Race review of #3760 at
c3470bdb(with8bdc117): withVICTORY_WATCH_UNLOCKED_PROTECTon (the default), a title write to view memory can crash the process with 0xc0000005. This happens in release builds too. It never happened with the switch off or onmain. A 4-line change to the fault handler stops it (below).Test. One 16 MiB view of a section is used, set up as the many-askers tests do. Four threads guard all of it with
writes(at, end, true)in a loop, as refreshes do. 48 threads write random pages of it for 20 s, faulting on guarded blocks. One more thread callswriting()before a store. All of this is CPU-only: no GPU, no game files.the test (in
many_askers_tests,#[ignore], run withREVIEW_WRITERS=48)Results. This PR was merged onto
main7d93ee07(clean merge). Ryzen 9 5950X (16 cores, 32 threads), Windows 11. Faults take no lock in all runs (VICTORY_FAULT_UNLOCKEDdefault).main7d93ee07, same test, debug=0, debug=1(default), debug=1, release=1, 8 writer threads, debug=1, release=1, debugWith the change,
watch::still passes: 70 passed, 0 failed, three runs with=1and one with=0. In the runs that finished, the worst single wait for a title write was lower with=1(18–37 ms) than with=0or onmain(36–117 ms). So the gain this PR is after does show up here.The cause (traced). I added a temporary lock-free ring of per-block events (marked, made read-only, opened, settled, clean, fault, give-up) and dumped the failing block's history when the handler gave up.
At the give-up, the books say the block is open while the page is
PAGE_READONLY:The give-up falls inside another thread's guard of the same block: after it marked the block (
g.protected,PROTECTING) and itsVirtualProtect(PAGE_READONLY)outsideGUARDShad landed, and before it marked the block clean.The faulting thread's last look has two steps that aren't one moment. First it finds nothing to open under the lock, because the books still had the block open (another fault opened it and was settled). Then it asks
writable(at)after letting go of the lock, for example incame_back(watch.rs:4824,open(&mut guards(), at, at + 1) != 0 || writable(at)). A guard that marks the block and protects it between those two steps leaves both answers "no", so the handler returnsEXCEPTION_CONTINUE_SEARCH.mainhas the same two steps (came_back, watch.rs:4145 there). There, though, the guard's whole change of protection happens inside the lock and is short. With this PR, four guards make their protection changes concurrently, outside the lock, and the window is hit easily.A change that holds here. Count the guards taken outside the lock. A write fault that is about to give up makes the write again if a guard began since it faulted; the next fault then finds the block guarded and opens it:
That's 0 of 28 runs against 10 of 22 without it. It only adds a retry on a path that otherwise ends the process. If a page were read-only for some other reason, the write would be retried only while guards keep beginning, then give up as before. The author may prefer to close the gap in
came_backand the tries themselves, for example by looking at the page while holding the lock and with no guard in flight.Not tested: the game, and aliased views (the test uses one view).
Update (2026-12-01): the fix is now a pull request into this branch, ScymicX/VIctory-NVIDIA#1. It adds the stress test (ignored by default) and the retry, bounded by the existing
again(at, 8), so a page that is read-only for another reason still faults out after eight tries. Merged ontomain5fabb46e, release: 4 of 8 runs crashed without it, 0 of 14 with it.Tested with the help of Claude Code (Claude Opus 5.5).
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by Lyrnc on 2026-12-01T15:24:14Z.
Tested on our bench. It cuts the submitting thread's refreshes by about 2.5 ms a frame at the same scene load, and the frame time follows by up to about 1 ms in most of the walk.
Setup
main5fabb46e, andmain+ this PR (headc3470bdbmerged locally; clean merge,watch.rsonly). Same shader cache for both.mainand with #4876 (tested in the same rounds, comment there). Medians of the per-second lines over world+30..330 s.Medians per run
At matched load (both runs of each build, medians of the 5-second windows in each band of draws a frame)
What it shows
main, so that's about the most a submitting-thread cut can give back here. With this PR the wait is 1.6-2.1 ms.main, same walk, the refreshes in front of a submission took 10.3 ms of the submitting thread's time a frame. That was about 1,040 changed spans a frame, 46 ms of thread time over the 7 refreshing threads, and all threads waited about 36 ms a frame for the guards' lock (69 ms on a camera turn).main's too. We didn't check the picture closely: release builds, no captures.mainrun.Checks
cargo test --locked --release -p victory-gpu --lib -- watch::onmain+ this PR: 70 passed, 0 failed.publish_pairs. After the mergec3470bdb, the head callsmain'spublish_range, andpublish_pairsis not in the tree.Not tested: a camera turn (queued, results to follow only if they differ), ray tracing on, frame generation on, Series S, other scenes, other CPUs.
AI use: Claude Code (our agent) ran the builds, the bench and the tests, and wrote this; the numbers are from those runs.
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by trustno1-coder on 2026-12-01T18:48:54Z.
Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.
Pull request closed