fix(vk): the capture's copy is queued to the copy helpers at the submit, the take waits for it #2244
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
6 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2244
Loading…
Reference in a new issue
No description provided.
Delete branch "shitpost/Longshot:perf/capture-async-copy"
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?
Summary
Jumping stuttered. The replay's capture of the game's GPU memory — the copy of the pages the game's
CPU had just written into the replay's mirror — ran on the game's own thread at each submit, and on
jump frames (which write several times more pages) that copy took up to 3.34 ms, dropping the frame.
This queues the copy to the copy helpers at the submit: the submitting (game) thread does none of it
and is not blocked on it, and the capture's take waits for the copy to finish. With the render thread
off the take is on the submitting thread, so the copy stays synchronous, as before. New switch
RX_VK_CAPTURE_ASYNC(on by default;=0for the old synchronous copy). The process's exit stopsand joins the helpers (their queue drained, each pending count let go) before the static destruction
frees the captures the copies read. Read
gpu/vk/vk_memory.cpp:capture_make(the newdefer),capture_copy_wait, thecopy_split_asynccall, andcopy_helpers_stop_and_join. See #2073.Testing
Tested: On this PC (Linux, RX 7900 XTX, Mesa 26.2.5, Vulkan 1.4.354), in the game: a fresh run to
the plains and the castle, jumping repeatedly — the large frame drops on jumps are gone (confirmed by
playing). The per-submit capture on the submitting thread is now 0.02–0.23 ms (was up to 3.34 ms on
jump frames); the stutter stacks show the game's thread no longer in the copy (
memcpy/copy_part) —it is on the copy-helper thread. The process's-exit path (the exit hook that drains and joins the
helpers) is exercised by a headless test-profile run through the control bridge (a memory tour: the
kokiri-start save, one teleport, a clean quit): the four helper threads are joined at the exit with no
hang and no error, and the per-submit capture stays deferred (0.02–0.30 ms, the copy on the helpers).
The game-free test
tests/test_capture_async_copy.pyfails onmainfor the bug's reason ("the submitran the capture's copy to completion on the submitting thread") and passes here, on both compilers
(clang++ 22.1.8, g++ 16.2.1); the broken variant fails as it must. The helpers' fixture
(
tests/test_capture_copy_helpers.py) ends with the exit: it queues parts, starts a take stillwaiting for its copy, and runs the stop and join — the queue is drained (each part's count let go, so
the take finishes) and the helpers are joined, so its plain return's destructors are safe. Whole suite
(
tests/run_all.py, this PC, clang++ 22.1.8, vulkan headers from the project's cpm cache): 947passed, 14 failed, 18 skipped; on a base worktree of current
main(@6bf8cf34) in the sameenvironment, 939 passed, 20 failed, 19 skipped. Every one of the branch's 14 failing files fails
on the base alike (the suite was run on the base worktree, and the branch's failing set is a subset of
the base's); the 6 base-only failures are the fresh worktree's environment (its
lz4module, andtiming-sensitive tests under two suites at once on this PC), and the one test the base worktree
skipped (unicorn not found there) passes on the branch. None is caused by this change. Named
below (14 files):
The 14 files that also fail on
main@6bf8cf34tests/test_amd_subgroup_profiles.py, tests/test_appimage_package_retry.py, tests/test_audio_source.py, tests/test_dev_packs.py, tests/test_dev_update.py, tests/test_flat_map.py, tests/test_guest_holes.py, tests/test_nonuniform_image_arrays.py, tests/test_rdna2_mesh_only.py, tests/test_readback_timeout_source.py, tests/test_shader_profile_caps.py, tests/test_target_image_reuse.py, tests/test_vram_compact.py, tests/test_wb_spans.py
Observed, not this change: A 4K run (3840×2160,
vsync=0) to the castle, with the in-game FPScounter on, showed a brief end-of-run present-rate dip to ~4–6 fps for about a second (the counter's
0.5 s window read 12–15). It is not this change: across that window the capture waits are ~0
(
readback_wait0.0 ms,late_wait6.7 ms total) and the copy is on themkw_vk_capture_helper. Thestall is the guest's own swapchain
AcquireTexturewaiting on the presenter's frame fence (a 4Kpresent-path back-pressure,
main_blockedup to 326 ms) — pre-existing and out of scope here.Still to test:
the large frame drops on jumps are gone and the capture still records (the async copy's helper count
varies with the CPU's threads, and
RX_VK_LOW_SPECkeeps it synchronous). The farm declined thisonce "as asked"; it needs a re-request. (The fork's CI also needs the
ci: approvedlabel.)Measurements
Verdict: the submitting thread's per-submit capture cost dropped from up to 3.34 ms (jump frames)
to 0.23 ms — the copy is now on the copy helpers.
Setup: this PC (Linux, RX 7900 XTX, Mesa 26.2.5, Vulkan 1.4.354), a run to the plains and the castle
with jumps, HOS_PROFILE on; the per-submit capture cost from the "vk: capture: a submit X ms" log
lines (the submitting thread's CPU cost of the capture submit; resolution-independent).
Baseline: the before side is the pre-fix synchronous copy, measured on the stable v3.0.0 build (the
closest available pre-fix reference) at 1080p internal; the after side is this PR at 1440p native. The
per-submit capture cost is the submitting thread's CPU cost of the capture submit, so it is comparable
across the two resolutions. The before numbers still hold on current
main: since9dd41326, main'sonly change to
vk_memory.cppis the culling-table reads (682a6640), which does not touch thecapture's copy, and the pre-fix synchronous copy —
capture_make'scopy_pageson the submittingthread — is unchanged. The after numbers were taken on this branch before the review's fix-up commits;
those commits change the process's exit (the stop and join) and the tests only, not the steady-state
per-submit cost, and a run on the rebased tree confirms the order (submits at 0.02–0.30 ms, the copy
on the helpers).
6bf8cf34c84ffb90Does the replay wait offset the submit-time saving or worsen frame pacing? (a same-tree A/B): this
PR's commits on
main@79d192c6, RX 9070 XT, RADV Mesa 26.3.1, headless, 60 fps cap, Link walking backand forth across one line in Hyrule Field (issue #2285: the neighbouring map's preload writes a burst of
pages) for 180 s a run, interleaved: fewer frames over 100 ms per crossing with the async copy (12 in 22
against 20 in 22), but most crossings still stall — the game's thread is in the copy only 3 % of the
stall (43 % on
main) and 29 % innvn_wait, waiting for its GPU work, which waits for the replay'stake of the capture. For that case the copy's time moves rather than goes: the submit-time saving holds
in the copy itself, and the take's wait offsets part of it; the rest of the stall is the GPU's own work
reading the capture (a separate cost, out of scope here).
Risks
The async copy reads the game's memory after the submit, while the game keeps writing: a word written
in the gap between the submit and the helper's read can land in the copy. This is the same class as
the documented late pages' second copy (a page written after its capture is copied again at the take);
accepted and documented at the deferral's site in
capture_make, and checked per byte intests/test_capture_async_copy.py(a page rewritten in the gap holds the submit's or the write'sbytes, never a third value). The window is the helper pool's: the take waits for the copy, so the
pages are read within a frame. To turn it off:
RX_VK_CAPTURE_ASYNC=0(the old synchronous copy). Arevert is enough. A player notices nothing after updating: the capture is a replay/tool cost, not a
game feature; no change to saves or
longshot_options.ini(the switch is an environment switch, not amenu row).
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.gpu/vk/switches.def.tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.Tested in game: Linux, RX 7900 XTX, Mesa 26.2.5, Vulkan 1.4.354: plains+castle with repeated jumps at 1080p and 4K — the large frame drops on jumps are gone; per-submit capture on the game thread now 0.02–0.23 ms (was up to 3.34 ms)
Possibly related, for context:
4956bb26ef294eb290bdWIP: fix(vk): the capture's copy is queued to the copy helpers at the submit, the take waits for itto fix(vk): the capture's copy is queued to the copy helpers at the submit, the take waits for it@Beanstalk on a different GPU/OS (e.g. Windows, or a non-AMD GPU): go to the future, then in front of Ganondorf's castle right in front of the cliff, jump repeatedly — confirm the large frame drops on jumps are gone and the capture still records.
@shitpost only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.Beanstalk test farm
Commit
0451d31· approved by nobody yet · dashboardA member of
BigBeanscan review this commit and comment@Beanstalkto test it.I will run the tests for this soon myself
@review
@Beanstalk
Recommendation: Request changes. The deferred copy can capture a later frame’s data instead of the submitted frame’s data, and its worker lifetime is not protected during shutdown.
The change moves large capture copies from the submitting thread to helper threads and waits for them on the replay thread. This can reduce time spent in submit, but it loses the submit-time snapshot and introduces shutdown and test-portability problems.
Blocking (3): must change before merging.
gpu/vk/vk_memory.cpp:2540: Deferring the guest-memory read loses the submit-time snapshot that replay relies on. (more on the line) Do: Preserve the submitted bytes before the game can overwrite them, for example with a protected or copy-on-write snapshot, and add a test that changes guest memory after submit while the copy is held.gpu/vk/vk_memory.cpp:2278: The shutdown check does not keep queued captures or the helper pool alive until workers stop using them. (more on the line) Do: Stop and join the helpers during shutdown, draining or cancelling their work while the captures and synchronization objects remain alive.tests/test_capture_async_copy.py:255: On Windows the generated C++ source is named fixture.cpp.exe, so the compiler does not recognize it as C++ source. (more on the line) Do: Keep the source filenames ending in .cpp on every platform and add .exe only to executable filenames.Should fix (1): not blocking, but worth doing before merging.
tests/test_capture_async_copy.py:245: The fixture inherits its own FIX_RENDER_THREAD and FIX_PAGES controls from the caller’s environment. (more on the line) Do: Remove the fixture’s FIX_ variables from base_env before setting each run’s explicit values.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
gpu/vk/vk_memory.cpp:2540: The changed capture and helper path has only been played on one Linux AMD system. (more on the line) Do: Run the corrected change through the jump scene and verify capture and frame pacing on Windows and the other affected Tier 1 systems, including Steam Deck. (@fixdoes its part first: Keep the synchronous path as the safe default until the corrected asynchronous path is validated on the affected systems.)@fixcan do L1, L2, L3, L4 and L5.Questions (1) (not confirmed from the code; they don't hold the recommendation)
gpu/vk/vk_memory.cpp:2540: Do comparable base and PR runs show that the replay wait offsets the submit-time saving or worsens frame pacing?Checks: Still running: 10 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The PR reports a maximum submit cost of 3.34 ms before and 0.23 ms after, but compares different builds and resolutions, without several interleaved runs or frame-time and 1% low results. The author reports that jump drops disappeared in play on Linux with an RX 7900 XTX.
Other systems: The capture feeds mirror synchronization, texture shadows and event-signal captures on both Windows and Linux; its contents can affect rendering beyond the jump scene. Helper counts vary by CPU, while RX_VK_LOW_SPEC and a disabled render thread retain synchronous copying. No other GPU or OS run is reported.
Switches: RX_VK_CAPTURE_ASYNC is added, defaults on, and has a switches.def row. Its default is unsafe while deferred reads can observe later guest writes; the measurements also do not establish its performance across supported systems.
Reviewed:
294eb290bdagainsta2dc538590: Read AGENTS.md, CONTRIBUTING.md, the PR template, relevant standards and replay architecture rules, the full diff, commit messages, the new test and changed test hunks, and the capture, copy-helper, take and submit paths. Skimmed the remaining portions of the large vk_memory.cpp and vk_replay.cpp files rather than reading them in full. docs/review-checklist.md and ../Tooling/AGENTS.md were absent.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no build, test or project script was run. The author reports an in-game Linux AMD run and a game-free fixture pass; CI is still running.
Overlaps and merge order: Not checked; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -2260,6 +2275,11 @@ void copy_helper_main() {w = copy_helpers.parts.front();copy_helpers.parts.pop_front();}if (cap_shutting_down.load(std::memory_order_acquire)) { // (at exit: the capture's pages and ok flags go with theL2 (blocking): The shutdown check does not keep queued captures or the helper pool alive until workers stop using them.
When: On Linux, exit can begin with a deferred capture still queued or a helper already copying. The exit hook does not join or drain these detached helpers; static destruction can free the capture’s pages and counter, or destroy the helper synchronization objects, while a helper copies or decrements the counter.
Do: Stop and join the helpers during shutdown, draining or cancelling their work while the captures and synchronization objects remain alive.
@ -2467,0 +2537,4 @@w.stage = c->sidx.empty() ? nullptr : c->stage.get();w.sidx = c->sidx.empty() ? nullptr : c->sidx.data();if (defer && capture_async_on() && replay_render_thread_on()) { // (the take, on the render thread, waits for it)c->copy_left = std::make_unique<int>(0);L1 (blocking): Deferring the guest-memory read loses the submit-time snapshot that replay relies on.
When: When a submit captures at least 128 pages, the game thread can return from submit and overwrite a captured page for the next frame before a helper reads it. The helper then puts the newer words, or a mixture of both frames, in the earlier submission’s capture; the replay can use those words for its mirror sync and render the wrong frame.
Do: Preserve the submitted bytes before the game can overwrite them, for example with a protected or copy-on-write snapshot, and add a test that changes guest memory after submit while the copy is held.
L5 (should fix): The changed capture and helper path has only been played on one Linux AMD system.
When: Windows uses a different guarded-copy path, and different CPU thread counts change the number of helpers and when the replay waits; their capture correctness and frame pacing remain untested.
Do: Run the corrected change through the jump scene and verify capture and frame pacing on Windows and the other affected Tier 1 systems, including Steam Deck.
@ -0,0 +242,4 @@raise SystemExit("the fixture still has unfilled slots: " + ", ".join(sorted(set(leftover))))# (a hermetic env: no HOS_/RX_VK_ name from the test's own environment, the helpers' number said per run)base_env = {k: v for k, v in os.environ.items() if not k.startswith(("HOS_", "RX_VK_"))}runs = [L4 (should fix): The fixture inherits its own FIX_RENDER_THREAD and FIX_PAGES controls from the caller’s environment.
When: For example, FIX_RENDER_THREAD=0 makes the nominal default run synchronous, allowing it to pass without exercising deferred copying; FIX_PAGES can likewise change the tested page count.
Do: Remove the fixture’s FIX_ variables from base_env before setting each run’s explicit values.
@ -0,0 +252,4 @@failures = []with tempfile.TemporaryDirectory(prefix="capture-async-copy-") as tmp:suffix = ".exe" if os.name == "nt" else ""cpp = Path(tmp) / ("fixture.cpp" + suffix)L3 (blocking): On Windows the generated C++ source is named fixture.cpp.exe, so the compiler does not recognize it as C++ source.
When: With os.name equal to nt, both fixture source paths end in .exe; the compiler treats them as linker inputs instead of compiling the fixture, so this new check fails on Windows.
Do: Keep the source filenames ending in .cpp on every platform and add .exe only to executable filenames.
Tested on one PC only (RX 9070 XT, RADV Mesa 26.3.1, Ryzen 5 5600X, Fedora 45): other GPUs, drivers, CPUs and Windows are untested, so the numbers below may differ there.
A data point from issue #2285 (stutter crossing one line in Hyrule Field, likely the neighbouring map's preload writing a burst of pages): this PR's commits put onto
main@79d192c6(head294eb290unchanged), RX 9070 XT, RADV Mesa 26.3.1, Linux, headless, 60 fps cap, Link walking back and forth across that line for 180 s a run, interleaved:RX_VK_CAPTURE_ASYNC=0RX_VK_CAPTURE_ASYNC=0Fewer long frames per crossing (12 in 22 against 20 in 22), but most crossings still stall. Sampled with the async copy, the game's thread is in the copy only 3 % of the stall (43 % on
main), and 29 % innvn_waitwaiting for its GPU work, which waits for the replay's take of the capture. For this case the copy's time moves rather than goes. Nothing here bears on the review's L1 (the deferred read's snapshot); these runs only measured frame times.294eb290bdc84ffb906cAddressed the review: the async copy's gap is documented at the deferral's site and checked per byte in the fixture (L1); the process's exit now stops and joins the copy helpers, with an exit-drain scenario in the helpers' fixture (L2); the fixture's source keeps its .cpp name on every platform and its runs no longer inherit the caller's FIX_ variables (L3, L4). Rebased on current main. Suite re-run against a base worktree of current main (the failing set is a subset of the base's, none is this change's); the new exit path was run in the game (a clean quit, the helpers joined, no hang). After:
c84ffb90.All findings addressed (inline), rebased on current
main(6bf8cf34); after:c84ffb90.The question — does the replay wait offset the submit-time saving or worsen frame pacing?
No: the wait is, in practice, free. The per-submit capture on the submitting thread is now 0.02–0.20 ms,
so the helpers finish the copy inside the submit-to-take gap and the take's wait finds it already done —
a 17,722-frame profile window shows the take-side waits at ~0 (
late_wait60 ms total, i.e. one framewaiting once;
readback_wait0.5 ms), and the wait for this copy works out to ≈ 0.003 ms/frame. Thesubmit-time saving holds: per-submit capture cost on the submitting thread, largest 3.34 → 0.23 ms, p90
1.09 → 0.05, median 0.09 → 0.02. One honest caveat: there was never a direct same-tree A/B — the before
numbers are the pre-fix synchronous copy measured on the stable v3.0.0 build at 1080p, the after on this
branch at 1440p (the per-submit figure is the submitting thread's CPU cost, comparable across
resolutions). What playing shows: the large frame drops on jumps are gone.
The findings: L1 accepted and documented at the deferral's site (inline; the mix is the late
pages' class, the window is the helper pool's, and there is no cheaper true snapshot — see the
inline for why); L2 fixed — the process's exit now stops and joins the helpers before the static
destruction frees what they read (inline); L3 and L4 fixed in the fixture (inline on the test file).
L5 (the jump scene on Windows and the Steam Deck) is still outstanding: the farm declined it once "as
asked", so it needs a BigBean's re-request; the fork's CI also needs the
ci: approvedlabel.Verified: whole suite on this PC against a base worktree of current
main(branch 947 passed / 14failed / 18 skipped, base 939 / 20 / 19 — the branch's failures are a strict subset of the base's; the
6 base-only ones are the fresh worktree's environment: its missing
lz4module and timing-sensitivetests under two suites at once). The new exit path was run in the game (a headless test-profile run to
kokiri-start and a clean quit: the four helpers joined at the exit, no hang, submits at 0.02–0.30 ms on
the helpers). L2 is a thread/ownership change, so a second cold review pass would be welcome.
@ -1492,2 +1503,4 @@cap_shutting_down = true;cap_workers_done.wait(lk, [] { return cap_prewarm_busy == 0; });lk.unlock();copy_helpers_stop_and_join(); // (the capture's copies the helpers were working: drained and the helpers joined,Fixed. The process's exit now stops and joins the helpers while the captures and the synchronization are still alive:
cap_exit_hook_register()registers this atexit hook once (called fromcap_prewarm_classand from the helpers' start block, so it is in before the first helper exists), and at the exit — after the prewarm workers are done — the pool'sstopis set under its mutex and the helpers are woken: they drain their queue, each part's count let go (so a take still waiting for its copy can finish it), the copies skipped, and they stop;cap_exit_notejoins them here. Windows stays flag-only (ExitProcess has already ended the helpers, and the process ends without its static destruction), and~CopyHelpersdoes the same where the hook never ran (it is constructed after the captures' globals, so it is destroyed before them). The helpers are no longer detached: the start blocks keep them incopy_helpers.workers.tests/test_capture_copy_helpers.pyends with exactly this: it queues parts, starts a take still waiting for its copy, runs the stop and join, checks the take finished, and returns through its destructors. Since this is a thread/ownership change, a second cold review is welcome.@ -2553,0 +2659,4 @@CopyPart w{c->pages.data(), 0, n, (uint8_t*)c->map, c->ok.data()};w.stage = c->sidx.empty() ? nullptr : c->stage.get();w.sidx = c->sidx.empty() ? nullptr : c->sidx.data();// (longshot) the gap the deferral opens, documented: a page the game rewrites between the submit and theAccepted, and documented here. Why there is no cheaper true snapshot: a page's generation is re-baselined at the take (all its pages stamped with the take's generation), so a game write in the gap is masked, and in-gap writes are not stampable per write — the write marks are consumed at the next collection, not at the write. The only exact snapshot would be a protected or copy-on-write page, which faults every such rewrite into the game's thread — the cost class this deferral removes — and the staged texture pages already hold the submit's bytes (guest → staging → out) before the gap. The mix is the late pages' class: their second copy at the take takes the CPU's words of later frames too, and the console has no order between the game's write and the GPU's read of a page either. The window is bounded by the helper pool: the take waits for the copy, so the pages are read within a frame.
tests/test_capture_async_copy.pyrewrites a scatter of pages in the gap and checks every captured byte: the submit's or the write's value, never a third one.RX_VK_CAPTURE_ASYNC=0gives the exact submit-time snapshot.@ -0,0 +268,4 @@raise SystemExit("the fixture still has unfilled slots: " + ", ".join(sorted(set(leftover))))# (a hermetic env: no HOS_/RX_VK_/FIX_ name from the test's own environment - a FIX_RENDER_THREAD=0 or a FIX_PAGES in# it would steer a run's config, its explicit values set per run only - the helpers' number said per run)base_env = {k: v for k, v in os.environ.items() if not k.startswith(("HOS_", "RX_VK_", "FIX_"))}Fixed:
FIX_names are now filtered out of the inherited environment withHOS_andRX_VK_, so aFIX_RENDER_THREAD=0orFIX_PAGESin the caller's environment can no longer steer a run — each run sets its own values explicitly.@ -0,0 +278,4 @@]failures = []with tempfile.TemporaryDirectory(prefix="capture-async-copy-") as tmp:cpp = Path(tmp) / "fixture.cpp" # (the source's name ends in .cpp on every platform: a .exe would be a linkerFixed: the generated source keeps its
.cppname on every platform, and.exeis the executable's name only.Added to Measurements the same-tree A/B GrimVisage measured for issue #2285 (this PR on main @
79d192c6, RX 9070 XT): fewer frames over 100 ms per crossing (12 in 22 vs 20 in 22), the game's thread in the copy 3 % of the stall against 43 % on main; for that case the copy's time moves rather than goes, the rest of the stall waiting on the GPU's work that reads the capture. It answers the reviewer's question with the direct base-vs-PR comparison it asked for.This is the same-tree A/B the review's question asked for, and it is now in Measurements (with the numbers and the #2285 setup). Thank you. It sharpens the answer: on jumps the submit-time saving holds almost free (the take's wait rides inside the submit-to-take gap, ~0.003 ms a frame), and on the cross-map preload the saving still holds in the copy itself (3 % of the stall against 43 % on main) while the take's wait offsets part of it there - the stall moves onto the GPU's work reading the capture. The 'moves rather than goes' reading is right for that case, and it is the honest one.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.