GPU: a marked page goes back at its first access (VICTORY_LAZY_COPY_BACK) #3118
No reviewers
Labels
No labels
accessibility
area: build
area: formats
area: gpu
area: loader
area: runtime
area: shader
bug
documentation
duplicate
enhancement
good first issue
gpu: amd
gpu: intel
gpu: nvidia
help wanted
host: wine
invalid
out of scope
question
request
run report
triage: confirmed
triage: has patch
triage: merge candidate
triage: needs info
triage: needs rebase
triage: needs work
triage: proposed close
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/Marvisak--VIctory!3118
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-3118"
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?
@borosf on GitHub · 2026-11-26 08:44 UTC · original
borosf:vibe/lazy-copy-back-842ca5→main· +466 −12 · 6 files · 7 commits · closed without mergingSummary
Shadow::copy_back_markedbrings every page its shaders marked as written back into title memory — on the card that is 60–127 ms a frame, 95 % of it waiting (FIND-33: the snapshot's pages fetched, and the waits around them; the host-side merge is 2.4–2.9 ms, the write 0.4–0.5 ms). The world marks ~2,250 pages a frame; most are never read by title code before a later pass overwrites them.VICTORY_LAZY_COPY_BACK=1(opt-in, off by default — behavior is unchanged without it), a marked page leaves the submission sealed no-access. The first read faults that one page back; the first write faults it back and then lands as the title's own over it (the merge happens underneath, as eager copy-back would have); a page nothing touched is written by the next submission's copy-back and never holds the critical path.watch): sealed pages holding their copy alive, and the vectored handler — which today services write faults — also taking read faults on those pages, servicing exactly one page each time. Arming is oneVirtualProtectper run of pages.Shadow::update,copy_back,copy_back_page), writes the guards do not see drain before they mark (watch::writing— kernel reads, DirectStorage), and remaps, retakes and new aliases drop the wait and unseal (title_memory_remapped,retake,title_memory_aliased). In-process reads of a sealed page fault into the handler and service transparently.Verification
-D warnings,cargo test --workspace --locked); with the switch off the suite is unchanged.marked_pages_leave_the_submission_and_go_back_at_their_first_accessdrives the real fault handler on the Intel Arc B580: the submission leaves pages sealed (asserted viaVirtualQuery, arming counters(3, 0, 0)— sealed, none refused), aread_volatilefaults the GPU's byte back and the page is guarded again, awrite_volatilemerges underneath and lands on top, an untouched page is written by the next copy-back, and the ledger ends empty.cargo clippy -p victory-gpu --all-targets --locked -- -D warningsclean;cargo test -p victory-gpu --lib --lockedgreen except the two known Intel heap-cap failures (#1744) pristine main also fails.claiming: FIND-33 — lazy copy-back on read (marked pages go back at their first access), the 95 %-wait copy-back stall (#1633 comment, per the ledger)
@Dukestar69 on GitHub · 2026-11-26 08:48 UTC · original · approved these changes
Verified on RTX 5090 & WARP against
origin/main(63bcca4):cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 11/11 passed on RTX 5090 and WARP (includingmarked_pages_leave_the_submission_and_go_back_at_their_first_access).cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 15/15 passed.cargo test -p victory-gpu --lib draw:: -- --test-threads=1: 20/20 passed on RTX 5090.cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.cargo xtask policy: 191 files ok.Clean opt-in
VICTORY_LAZY_COPY_BACKmechanism deferring marked-page copy-backs until first CPU access.Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
@fuzeofficlal on GitHub · 2026-11-26 09:05 UTC · original · requested changes
The single-threaded synthetic test passes on Windows 11 (
shadow::+watch::26/26 on RTX 5090;VICTORY_LAZY_COPY_BACK=115/15 on RTX 5090 and WARP; Clippy andcargo xtask policyclean), and deferring unneeded copy-backs is an interesting direction for FIND-33. However, deep review ofwatch.rsandshadow.rsfound several serious correctness and performance issues that make this unsafe even under opt-in use and regress the default-off fast path:1. Multithreaded / drain crash (
EXCEPTION_CONTINUE_SEARCH) and stale-read window (watch.rs:367-398, 425-440, 1068-1075,shadow.rs:91-111)lazy_page,take_lazy, andtake_all_lazyall remove pages fromg.lazyand releaseGUARDSbefore unsealingPAGE_NOACCESS. If any other thread accesses a page while it is being serviced (especially duringtake_all_lazy, which removes every sealed page up front before looping over them one by one), it faults onPAGE_NOACCESS, callslazy_pagewhich now returnsNone, hitsif r.ExceptionInformation[0] == READ { return EXCEPTION_CONTINUE_SEARCH; }, and crashes the process with an unhandled access violation.copy_back_onecallsrepaged(page / PAGE)(PAGE_NOACCESS->PAGE_READONLY) beforecopy.copy_back_marked(page)writes the GPU's bytes into title memory. Between those two calls, any concurrent reader succeeds without faulting and observes stale pre-GPU bytes.PAGE_READONLY— or write through an alias / side view before flipping protection).2.
ReadProcessMemory(host::copy_mapped) andVirtualQuery(texture::committed) silently zero/skipPAGE_NOACCESSpages without firing VEH (host.rs:2499-2510,texture.rs:752-777)host::copy_mapped(Step::Copy/Step::Fill) readssrcusingReadProcessMemory(GetCurrentProcess(), ...). BecauseReadProcessMemoryis a kernel syscall, hitting aPAGE_NOACCESSpage returnsERROR_PARTIAL_COPY(false) without delivering a VEH exception, andcopy_mapped's fallback fills the destination with zeros.copy_mappedonly callswatch::writingondst(whentitle_dstis true) and never drainssrc.texture::committed(texture.rs:765-768) explicitly rejectsPAGE_NOACCESS(info.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0), soStaging::refresh_nowsilently skips uploading any texture overlapping a sealed page rather than faulting it back.3.
title_memory_aliasedcallsforget_lazyinstead of draining pending GPU writes (watch.rs:1024-1035)forget_lazydrops the ledger entry and flips protection back toPAGE_READONLYwithout callingservice_lazy. Unliketitle_memory_remappedorretake, mapping a second alias view of a live physical page does not invalidate the GPU writes waiting ing.lazy— callingforget_lazysilently discards those writes permanently for both views. Those pages must be drained (service_lazy) before installing the alias.4. Default-off performance regression:
lazy_armed()locksGUARDSon everyShadow::update(watch.rs:362-364,shadow.rs:555,watch.rs:816)lazy_armed()currently acquires the globalGUARDSmutex (guards().lazy.iter().next().is_some()), and is called at the top ofShadow::updatebeforeif self.clean() { return 0; }(as well as incopy_back_page,copy_back_or_not, andwatch::writing). That defeats the lock-free fast path even whenVICTORY_LAZY_COPY_BACKis off (the default). Tracking the armed count in anAtomicUsize(checked before lockingGUARDS) keeps the default-off / empty path lock-free.5. VEH allocation / re-entrancy &
README.mdtable placementon_writeallocates a heapVec(vec![(copy, at / PAGE)]) inside the Vectored Exception Handler; switching to a single-page helper (service_lazy_one(©, at / PAGE)) avoids unnecessary heap allocation in the fault path (and note the general re-entrancy risk of acquiringShadow::beforeinside VEH if any path ever reads title memory while holdingself.before).README.md:220addsVICTORY_LAZY_COPY_BACK=1inside the--features victory-gpu/diagnosticstable, even thoughlazy_on()is active in all builds.@Marvisak on GitHub · 2026-11-26 09:20 UTC · original
Automated triage for the maintainers.
Needs work. This adds
VICTORY_LAZY_COPY_BACK. Marked pages are sealedPAGE_NOACCESSinwatch::arm_lazyand copied back from the vectored handler at their first access, with drains inShadow::update,copy_back_page,copy_back_or_notandwatch::writing. Three things block it:WriteFilefrom a title buffer, for example). These fail with an access error instead of faulting into the handler.watch::writingdrains only for writes into title memory.on_writenow callslazy_page, which takes theGUARDSlock, on every read access violation, even with the switch off.watch::writingalso takes an extra lock throughlazy_armed(). Please gate both on a cheap atomic that is set only when the switch is on.copy_back_marks_withdrains every armed page at the start of the next submission, so the copy-back seems to move rather than go away. Please show world frame timings with the switch on and off.Also, the README row is a paragraph of rationale. Please cut it to one line saying what the switch does.
CI:
checkpassing.Generated by Claude Code
@borosf on GitHub · 2026-11-26 12:08 UTC · original
All five points are addressed at the new head
8ad0123(=0bfafb0plus deduplicating an accidental double definition oflazy_arms).Concurrent servicing / stale window: arming now keeps a claim ledger.
Guards.lazy: BTreeMap<page, Arc<Shadow>>+servicing: BTreeSet<page>; the fault handler claims a page before copying it back, and concurrent faults on the same page spin onyield_nowuntil the first service finishes — so only one thread ever opens the seal, and there is no window where a second writer lands on a still-sealed or torn page.title_memory_aliasednow drains (take_lazy+service_lazy) before re-linking instead of forgetting, andtitle_memory_remapped/retakedecrement the counter throughforget_lazy.Kernel reads of sealed pages: copies that will be read without faulting are drained up front.
will_read(re-exported asvictory_gpu::kernel_will_read) is applied tocopy_mapped's source and tonet.rs'ssendto+WSASendTo(walking the WSABUF descriptors).WSASendMsgis the one remaining unwrapped pass-through I found — noted here rather than guessed at; it can be wrapped the same way if reviewers agree it's needed.Default-path lock regression: the whole protocol is gated by
static LAZY_PAGES: AtomicUsize. With the switch off it is zero, andShadow::update/writing/the fault handler read it relaxed once and skip every lock and map lookup — no mutex is touched on the default path.lazy_armed()perShadow::update: same gate — the relaxed atomic load is the only cost with lazy off.Handler allocations / README: the handler no longer allocates on the lazy path, and the README row is one line.
Hardware verify (Arc B580, Windows 11):
marked_pages_leave_the_submission_and_go_back_at_their_first_accesspasses on hardware through the real vectored exception handler (a read fault unseals and copies back one page; the guard re-engages; the final state has no lazy pages armed). Fullcargo test -p victory-gpu --lib --lockedis 230 passed / 2 failed — the two being the known #1744 Intel heap-cap failures that pristine main also fails on this card.cargo clippy -p victory-gpu --all-targets --locked -- -D warningsclean;cargo xtask policyok.On the measurement criterion: if/when a card that sustains a world run measures the diagnostics frame-time medians with the switch on vs off at matching draw counts, the mechanism should show most marked pages skipping copy-back entirely (a page never CPU-read gets one
VirtualProtectinstead of a page copy per submission). If that measurement can't be produced, closing this as a null result on the measurement criterion alone is also fine — with the switch off the change is a provable no-op (the atomic gate), so default behavior and default perf are untouched either way.@borosf on GitHub · 2026-11-26 12:29 UTC · original
Measurement at
8ad0123(Arc B580, Windows 11, release build). Synthetic pools only — no game data used.cargo test --release -p victory-gpu --lib --locked -- --test-threads=1 --ignored --nocapture frame_copy_back_cost_eager_against_lazy(a temporary ignored test, reverted after the run; the tree is back to8ad0123): 2,250 marked pages a frame — the world's per-frame mark count — 12 frames a case, a 141 MiB write-watched pool holding one copy, marks and a shader byte per page set each frame, then a share of the pages read by title code.(Two runs each, same process, the eager cases first so that no sealed page is ever read by an eager copy.)
The arming is fully engaged, not falling back: 2,250 pages sealed a frame, 0 refused by the guard state, 0 by the host. And the pages still go back — 2,062 serviced a frame at 0 % reads, 2,344 at 50 % — because
copy_back_marks_withdrains every still-armed page at the next submission (take_all_lazy→service_lazy). So the copy-back is paid a frame later rather than removed, and each page adds two protection changes (the seal inarm_lazy,open_lazyat service) plus a fault and a 64 KiB service for every page title code reads. Net 1.7–2.0× the eager frame cost on this card.One correction to the description while I am here:
arm_lazycallsVirtualProtectonce per page, not "oneVirtualProtectper run of pages".So this fails the measurement criterion, as I noted in my last comment it might: closing as a null result on measurement alone. Default behaviour is untouched either way — with the switch off
LAZY_PAGESis zero and the path is a no-op. For the idea to pay, the next submission would have to drop armed pages it is about to overwrite instead of servicing all of them, which is a different design rather than a tweak to this one.Pull request closed