vkback: decouple deferred remap releases from vkback-submit callback queue #199

Open
github-bot wants to merge 1 commit from github-bot/gh-199 into main AGit
Owner

@⁠Mhyster on GitHub · 2026-12-02 07:34 UTC · original
Mhyster:opt/vkback-remap-release-decouple → main · +175 −5 · 3 files · 1 commits · open

What

Decouples deferred page-mapping remap releases (maporder::release) from vkback-submit's blocking Job::Call / present queue (greenfield/vkback/src/submit.rs, live.rs, lib.rs):

  • Previously, Live::remap_front called self.be.queue_call(Box::new(move || crate::maporder::release(seq))), which enqueued a Job::Call behind any in-flight vkQueuePresent / blit callbacks and forced an immediate vkQueueSubmit boundary even when all submissions prior to the remap had already been handed to the GPU queue.
  • Now Submitter shares a lightweight RemapGate (submitted: AtomicU64, pending: Mutex<RemapPending>) with vkback-submit:
    • VulkanBackend::release_remap(seq) flushes any held command buffers and checks submitted >= self.serial. If every prior submission has already gone through dev::submit_on (which publishes umem::Memory::reader_submitted), it calls maporder::release(seq) immediately on the renderer thread without touching vkback-submit or waiting behind presents.
    • Otherwise it registers (self.serial, seq) in RemapGate (re-checking submitted under the lock so no wakeup can be lost), and vkback-submit calls gate.advance(serial, maporder::release) immediately after dev::submit_on returns — before Job::Call presents or subsequent batches' tape::resolve.
    • Direct renderer submissions (submit_now) also advance RemapGate, and gate.close drains any remaining entries when vkback-submit exits so teardown cannot hang.

Addresses the remap-wait tail latency noted in docs/TASKS.md (present waits for the remapper) while preserving the exact console queue-order invariant: maporder::release still runs only after dev::submit_on has published reader_submitted for every prior submission.

The reference

  • vkd3d-proton libs/vkd3d/command.c (d3d12_command_queue_enqueue_callback / VKD3D_SUBMISSION_QUEUE_USING_CALLBACK): queue_call exists for Vulkan queue operations such as swapchain present that must run on the queue worker; maporder::release only signals a CPU condvar once reader_submitted is published, so gating it on the submitted timeline serial avoids serializing it behind swapchain presents.

Evidence

  • Unit tests added in greenfield/vkback/src/submit.rs:
    • remap_gate_releases_immediately_when_already_submitted
    • remap_gate_defers_until_serial_advances_and_preserves_order (including close drain)
    • remap_gate_concurrent_release_and_advance_drops_nothing (2,000-serial multi-threaded race stress test)
  • Local CI checks passed (Linux x86_64):
    • cargo test -p victory-shader -p victory-formats -p victory-core -p xtask --locked
    • (cd greenfield && cargo test -p umem -p frame -p vkback --lib --locked && cargo test -p vkback --test policy --locked) (171 passed, 3 ignored; 6/6 policy tests including file_size)
    • cargo clippy --all-targets --locked -- -D warnings on root native crates, greenfield, greenfield/wine, and greenfield/vkback/translate.
  • Not run: live game / AMD GPU A/B frame timing (frames.py) and Vulkan validation run (house scene) could not be run in this session (no live game run performed); cargo xwin clippy runs in GitHub Actions CI.

Checklist (docs/AGENTS.md)

  • One topic (rule 31); docs/TASKS.md not edited, the fixed item named above (rule 29)
  • "Allow edits by maintainers" on; after review, no force-push and no close-and-reopen (it drops the maintainers' commits)
  • No fallback or second path for a case that can't happen, in title data or in our own setup (rule 33); unexpected input fails loudly (rule 9)
  • Constants come from the console, the hardware or the title's data, not tuned by eye or ear (rule 9b)
  • Every switch is listed, read in one place, and a bad value stops the start (rule 2)
  • Queues and other externally synchronized Vulkan objects are used under their lock (rule 35)
  • Every unsafe block has a // SAFETY: comment; no raw pointer around the borrow checker (rule 36)
  • Clippy clean; tests call the production code; TRANSLATOR_VERSION bumped if the translator's output changes (rule 27)
  • Comments say what is true now and name functions, not line numbers (rule 3)
  • Nothing from the title, and no pointers to where non-free data can be found (hard constraints)
**@⁠Mhyster** on GitHub · 2026-12-02 07:34 UTC · [original](https://github.com/vktory6/VKtory/pull/199) `Mhyster:opt/vkback-remap-release-decouple` → `main` · +175 −5 · 3 files · 1 commits · open ## What Decouples deferred page-mapping remap releases (`maporder::release`) from `vkback-submit`'s blocking `Job::Call` / present queue (`greenfield/vkback/src/submit.rs`, `live.rs`, `lib.rs`): - Previously, `Live::remap_front` called `self.be.queue_call(Box::new(move || crate::maporder::release(seq)))`, which enqueued a `Job::Call` behind any in-flight `vkQueuePresent` / blit callbacks and forced an immediate `vkQueueSubmit` boundary even when all submissions prior to the remap had already been handed to the GPU queue. - Now `Submitter` shares a lightweight `RemapGate` (`submitted: AtomicU64`, `pending: Mutex<RemapPending>`) with `vkback-submit`: - `VulkanBackend::release_remap(seq)` flushes any held command buffers and checks `submitted >= self.serial`. If every prior submission has already gone through `dev::submit_on` (which publishes `umem::Memory::reader_submitted`), it calls `maporder::release(seq)` immediately on the renderer thread without touching `vkback-submit` or waiting behind presents. - Otherwise it registers `(self.serial, seq)` in `RemapGate` (re-checking `submitted` under the lock so no wakeup can be lost), and `vkback-submit` calls `gate.advance(serial, maporder::release)` immediately after `dev::submit_on` returns — before `Job::Call` presents or subsequent batches' `tape::resolve`. - Direct renderer submissions (`submit_now`) also advance `RemapGate`, and `gate.close` drains any remaining entries when `vkback-submit` exits so teardown cannot hang. Addresses the remap-wait tail latency noted in `docs/TASKS.md` (present waits for the remapper) while preserving the exact console queue-order invariant: `maporder::release` still runs only after `dev::submit_on` has published `reader_submitted` for every prior submission. ## The reference - `vkd3d-proton` `libs/vkd3d/command.c` (`d3d12_command_queue_enqueue_callback` / `VKD3D_SUBMISSION_QUEUE_USING_CALLBACK`): `queue_call` exists for Vulkan queue operations such as swapchain present that must run on the queue worker; `maporder::release` only signals a CPU condvar once `reader_submitted` is published, so gating it on the submitted timeline serial avoids serializing it behind swapchain presents. ## Evidence - Unit tests added in `greenfield/vkback/src/submit.rs`: - `remap_gate_releases_immediately_when_already_submitted` - `remap_gate_defers_until_serial_advances_and_preserves_order` (including `close` drain) - `remap_gate_concurrent_release_and_advance_drops_nothing` (2,000-serial multi-threaded race stress test) - Local CI checks passed (Linux x86_64): - `cargo test -p victory-shader -p victory-formats -p victory-core -p xtask --locked` - `(cd greenfield && cargo test -p umem -p frame -p vkback --lib --locked && cargo test -p vkback --test policy --locked)` (171 passed, 3 ignored; 6/6 policy tests including `file_size`) - `cargo clippy --all-targets --locked -- -D warnings` on root native crates, `greenfield`, `greenfield/wine`, and `greenfield/vkback/translate`. - **Not run**: live game / AMD GPU A/B frame timing (`frames.py`) and Vulkan validation run (house scene) could not be run in this session (no live game run performed); `cargo xwin clippy` runs in GitHub Actions CI. ## Checklist (docs/AGENTS.md) - [x] One topic (rule 31); `docs/TASKS.md` not edited, the fixed item named above (rule 29) - [x] "Allow edits by maintainers" on; after review, no force-push and no close-and-reopen (it drops the maintainers' commits) - [x] No fallback or second path for a case that can't happen, in title data or in our own setup (rule 33); unexpected input fails loudly (rule 9) - [x] Constants come from the console, the hardware or the title's data, not tuned by eye or ear (rule 9b) - [x] Every switch is listed, read in one place, and a bad value stops the start (rule 2) - [x] Queues and other externally synchronized Vulkan objects are used under their lock (rule 35) - [x] Every `unsafe` block has a `// SAFETY:` comment; no raw pointer around the borrow checker (rule 36) - [x] Clippy clean; tests call the production code; `TRANSLATOR_VERSION` bumped if the translator's output changes (rule 27) - [x] Comments say what is true now and name functions, not line numbers (rule 3) - [x] Nothing from the title, and no pointers to where non-free data can be found (hard constraints)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-02 07:34:59 +00:00
Author
Owner

@⁠firefloc on GitHub · 2026-12-02 10:04 UTC · original

I reproduced an ordering race in RemapGate at 91bd8ca with a unit test that holds the first release callback open.

  1. Defer remap 10 with after_serial = 1.
  2. On the submit thread, call advance(1) and pause inside the callback before it publishes remap 10.
  3. On the renderer thread, register remap 11 with the same after_serial. The fast path sees serial 1 and publishes 11. Resume the first callback.

The test records [11, 10] with the PR as written. The remapper acknowledges a single high-water mark, so maporder::is_done(10) can return true after 11 is acknowledged while 10 is still pending.

A local candidate uses one mutex for the submitted serial, the FIFO of pending remaps, and publication to maporder::release. It drains the ready prefix in registration order and advances the gate after a successful submission. With the candidate, the same test returns [10, 11]. The vkback suite on RADV passed 207 tests (4 ignored), and neither candidate run showed a premature acknowledgement.

In a warm-cache prison-cell A/B/B/A on RX 7900 XTX, the candidate reduced renderer-to-release p99 from 37.5–41.3 ms to 36.4–36.8 ms. Mean FPS moved in opposite directions between the two pairs. The longer stage here was still remapper take-to-ack, so the performance regression in #171 remains open.

**@⁠firefloc** on GitHub · 2026-12-02 10:04 UTC · [original](https://github.com/vktory6/VKtory/pull/199#issuecomment-7341932325) I reproduced an ordering race in `RemapGate` at `91bd8ca` with a unit test that holds the first release callback open. 1. Defer remap 10 with `after_serial = 1`. 2. On the submit thread, call `advance(1)` and pause inside the callback before it publishes remap 10. 3. On the renderer thread, register remap 11 with the same `after_serial`. The fast path sees serial 1 and publishes 11. Resume the first callback. The test records `[11, 10]` with the PR as written. The remapper acknowledges a single high-water mark, so `maporder::is_done(10)` can return true after 11 is acknowledged while 10 is still pending. A local candidate uses one mutex for the submitted serial, the FIFO of pending remaps, and publication to `maporder::release`. It drains the ready prefix in registration order and advances the gate after a successful submission. With the candidate, the same test returns `[10, 11]`. The vkback suite on RADV passed 207 tests (4 ignored), and neither candidate run showed a premature acknowledgement. In a warm-cache prison-cell A/B/B/A on RX 7900 XTX, the candidate reduced renderer-to-release p99 from 37.5–41.3 ms to 36.4–36.8 ms. Mean FPS moved in opposite directions between the two pairs. The longer stage here was still remapper take-to-ack, so the performance regression in #171 remains open.
Author
Owner

@⁠TheRifai on GitHub · 2026-12-02 15:23 UTC · original

Current-main numbers for the TASKS "Remap release behind the submission thread" row, in case they help the race fix in this PR. Seen on main 963df8e (same code as d59b4f8 apart from docs), RX 9070 XT / RADV 26.3.1, GE-Proton11-16, Series X 3840x2160, house rt3, 85 s warm-store run with VKB_FREC_ARM=30,34 (gpuprof frames serialised, so treat the GPU-adjacent numbers as upper bounds):

From the final page mappings: stats line: deferred remaps released 1,493 (release→done 11,236.8 ms total, 7.53 ms each, longest 398.8 ms, 25 over 50 ms); renderer blocked on one at a present 1,635.1 ms cumulative, longest 178.1 ms, given up 0; reads while a remap was under way 3,508, all on the fill path. registered not reached 0, reached but never registered 0 — the gate itself did not lose a remap in this run.

So on the reference card about 1.6 s of a short house run is presents waiting on deferred remaps, with a 178 ms longest single wait; the PR's FIFO/serial fix is aimed at exactly this. I have not reproduced the ordering race you found, and no code change from me.

**@⁠TheRifai** on GitHub · 2026-12-02 15:23 UTC · [original](https://github.com/vktory6/VKtory/pull/199#issuecomment-7350229791) Current-main numbers for the TASKS "Remap release behind the submission thread" row, in case they help the race fix in this PR. Seen on main `963df8e` (same code as `d59b4f8` apart from docs), RX 9070 XT / RADV 26.3.1, GE-Proton11-16, Series X 3840x2160, house `rt3`, 85 s warm-store run with `VKB_FREC_ARM=30,34` (gpuprof frames serialised, so treat the GPU-adjacent numbers as upper bounds): From the final `page mappings:` stats line: deferred remaps released **1,493** (release→done 11,236.8 ms total, **7.53 ms each**, longest **398.8 ms**, 25 over 50 ms); renderer blocked on one at a present **1,635.1 ms** cumulative, longest **178.1 ms**, given up 0; reads while a remap was under way 3,508, all on the `fill` path. `registered not reached 0`, `reached but never registered 0` — the gate itself did not lose a remap in this run. So on the reference card about 1.6 s of a short house run is presents waiting on deferred remaps, with a 178 ms longest single wait; the PR's FIFO/serial fix is aimed at exactly this. I have not reproduced the ordering race you found, and no code change from me.
Author
Owner

@⁠vktory6 on GitHub · 2026-12-02 15:28 UTC · original

Thanks, and thanks to firefloc for the race test. That race is real: the PR's own test asserts out-of-order release [101, 100], but maporder acknowledges by high-water mark, so a later release can acknowledge an earlier one that hasn't run. Two fixes:

  • One mutex over the submitted serial and a FIFO, releasing in registration order.
  • Advance the gate only after a successful submit. submit_now currently advances it even when the submit failed.

firefloc's A B B A shows p99 −1 to −4 ms, so it is worth finishing. Note that #218 touches the same code in live.rs.

**@⁠vktory6** on GitHub · 2026-12-02 15:28 UTC · [original](https://github.com/vktory6/VKtory/pull/199#issuecomment-7350392331) Thanks, and thanks to firefloc for the race test. That race is real: the PR's own test asserts out-of-order release `[101, 100]`, but `maporder` acknowledges by high-water mark, so a later release can acknowledge an earlier one that hasn't run. Two fixes: - One mutex over the submitted serial and a FIFO, releasing in registration order. - Advance the gate only after a successful submit. `submit_now` currently advances it even when the submit failed. firefloc's A B B A shows p99 −1 to −4 ms, so it is worth finishing. Note that #218 touches the same code in live.rs.
Author
Owner

@⁠firefloc on GitHub · 2026-12-02 17:30 UTC · original

I rechecked 91bd8ca and reproduced two ordering failures in a standalone test of the extracted gate. Pausing the release of sequence 10 lets 11 publish first. A later FIFO entry with a lower serial can also pass an earlier entry that is still ineligible. The stress test in the PR sorts the result, so it cannot detect either inversion before the high-water-mark acknowledgement.

The submit-success check applies to both submit_now and the worker closure. The worker can proceed to another batch after a failed submit, so a later successful serial must also be prevented from crossing a failed predecessor. At present, maporder::{is_done, wait_done} can report success when the renderer stops. Shutdown after submission failure should wake waiters with an explicit failure instead of publishing or acknowledging entries that depended on that submission.

A standalone candidate with one mutex over the FIFO and publication and a separate failed state passed six deterministic Rust tests, including a failed submission followed by a higher-serial success and shutdown. This tests the ordering algorithm in isolation. Real call sites, error propagation, and lock order still need integration coverage. #218 also changes the signature of maporder::release, so preserve the queue attribution when reconciling the branches.

**@⁠firefloc** on GitHub · 2026-12-02 17:30 UTC · [original](https://github.com/vktory6/VKtory/pull/199#issuecomment-7353374583) I rechecked `91bd8ca` and reproduced two ordering failures in a standalone test of the extracted gate. Pausing the release of sequence 10 lets 11 publish first. A later FIFO entry with a lower serial can also pass an earlier entry that is still ineligible. The stress test in the PR sorts the result, so it cannot detect either inversion before the high-water-mark acknowledgement. The submit-success check applies to both `submit_now` and the worker closure. The worker can proceed to another batch after a failed submit, so a later successful serial must also be prevented from crossing a failed predecessor. At present, `maporder::{is_done, wait_done}` can report success when the renderer stops. Shutdown after submission failure should wake waiters with an explicit failure instead of publishing or acknowledging entries that depended on that submission. A standalone candidate with one mutex over the FIFO and publication and a separate failed state passed six deterministic Rust tests, including a failed submission followed by a higher-serial success and shutdown. This tests the ordering algorithm in isolation. Real call sites, error propagation, and lock order still need integration coverage. #218 also changes the signature of `maporder::release`, so preserve the queue attribution when reconciling the branches.
Author
Owner

@⁠firefloc on GitHub · 2026-12-02 18:50 UTC · original

I integrated the candidate in an isolated copy of 91bd8ca. The submission gate protects the serial, deferred FIFO, and release publication together. The shared helper is used by both the direct and worker submission paths. A failed submit prevents a later successful serial and shutdown from releasing work that was never submitted. An error is reported to waiters on the failure path.

The integration also covers a second edge case: a higher remap sequence may already be acknowledged when an older deferred sequence is first handed to the remapper. maporder keeps the protocol's numeric high-water mark, but applies it only to sequences that have actually been handed over, including when a later acknowledgement repeats the same high-water mark.

The local suite passed 178 vkback tests with 3 ignored. Clippy and the Unix/Windows compile checks passed. The submission failure was injected into the shared helper; this did not exercise a live driver failure. Lock-order review, reconciliation with #218, and validation in the title are still open.

**@⁠firefloc** on GitHub · 2026-12-02 18:50 UTC · [original](https://github.com/vktory6/VKtory/pull/199#issuecomment-7355242715) I integrated the candidate in an isolated copy of `91bd8ca`. The submission gate protects the serial, deferred FIFO, and release publication together. The shared helper is used by both the direct and worker submission paths. A failed submit prevents a later successful serial and shutdown from releasing work that was never submitted. An error is reported to waiters on the failure path. The integration also covers a second edge case: a higher remap sequence may already be acknowledged when an older deferred sequence is first handed to the remapper. `maporder` keeps the protocol's numeric high-water mark, but applies it only to sequences that have actually been handed over, including when a later acknowledgement repeats the same high-water mark. The local suite passed 178 vkback tests with 3 ignored. Clippy and the Unix/Windows compile checks passed. The submission failure was injected into the shared helper; this did not exercise a live driver failure. Lock-order review, reconciliation with #218, and validation in the title are still open.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/199/head:github-bot/gh-199'
git switch 'github-bot/gh-199'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-199'
git switch 'github-bot/gh-199'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-199'
git switch 'github-bot/gh-199'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-199'
git switch 'main'
git merge --squash 'github-bot/gh-199'
git switch 'main'
git merge --ff-only 'github-bot/gh-199'
git switch 'main'
git merge 'github-bot/gh-199'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.