gpu: wait for every queue before settling the in-flight retire stage #3459

Manually merged
github merged 1 commit from github-bot/gh-3457 into main 2026-11-29 14:19:38 +00:00 AGit
Owner

@⁠Not-Saii on GitHub · 2026-11-29 13:57 UTC · original
Not-Saii:tests/retire-in-flight-sync → main · +3 −0 · 1 files · 1 commits · merged 2026-11-29 14:17 UTC

Change

startup_resource_retire failed once in the /O2 job of main at 6747721c on WARP (Microsoft Basic Render Driver), at the in flight passed stage, with 2 textures (131072 bytes) still retained. This fixes that failure in the test. Refs #3428.

The runtime frees a released texture of the retire class only after two things: every queue has passed its release-time fence, and every submission that names the texture has completed (retire_fences_reached and the flight list in src/startup_stubs/d3d12_xs_device.cpp). Neither the runtime nor the test's drain waits for the GPU.

in_flight() releases R and D while one queue is gated and the other three are idle, so each release signals a release-time fence on all four queues. The stage then waited only for the gated queue (c.sync(queue)) before settle(), which retries the drain up to 200 times in a row without sleeping. When WARP had not passed another queue's release-time fence within those 200 drains, both textures were still retained.

The test now syncs all four queues before settle(), as every other stage that settles after a release already does. The expectation is unchanged: both textures must be freed, and stays("in flight") still checks that nothing goes early while the submission is held. The runtime is unchanged.

Verification

Base 212d4b5f; fix 5530c7a3. The branch is rebased onto e3f9a64f without conflicts (80ab69e8); the loops below were measured before the rebase, and main has since changed the retire hold path in d3d12_xs_device.cpp. Windows 11 build 26300; WARP (Microsoft Basic Render Driver); NVIDIA GeForce RTX 4090, driver 32.0.16.1088; Windows SDK 10.0.26100; debug layer off (debug0). Builds: dev (Debug) and release (/O2) presets.

Locally, startup_resource_retire_hardware_debug0 picks the RTX 4090. The CI run that failed picked the Basic Render Driver, so startup_resource_retire_warp_debug0, which runs the same steps on WARP, stands in for it.

Each loop runs ctest --preset <dev|release> --no-tests=error -R '^<test>$' a fixed number of times and counts failures (script below). "load 24" adds 24 busy-loop processes on a 24-thread CPU. "2 cores" pins ctest, the test and 4 busy-loop processes to affinity mask 0x3.

startup_resource_retire_warp_debug0, failures out of 1000:

Build Condition Before (212d4b5f) After
Debug idle 0 not run
Debug load 24 167 0
Debug 2 cores 134 0
/O2 idle 0 not run
/O2 load 24 630 0
/O2 2 cores 224 0

Every failure before the fix is the CI line, at the gated-queue step (17 textures live) or the copy-queue step (15 live):

FAIL: resources kept after their submission passed
  stage 'in flight passed' texture live=5242880/17 expected=5242880/17 retained=131072/2 expected=0/0

Revert control. With settle_limit set to 1 (a single drain), Debug, load 24, 200 runs: the test before the fix fails 183/200, all at in flight passed. With the fix it fails 0/200. With all four queues synced, one drain is enough, so the stage no longer depends on how fast WARP finishes. (Idle, one drain: 0/200 before and 0/200 after; an idle WARP passes those fences in time.)

startup_resource_retire_hardware_debug0 on the RTX 4090: before the fix 0/1000 idle and 0/1000 under load 24, in each build. After: 0/1000 idle in Debug and 0/1000 idle in /O2 (not repeated under load, which took 1.5 h per configuration before the fix).

One run of each startup_resource_retire_* test passed with the fix on both adapters: warp_debug0, warp_debug1, off_warp, hardware_debug0, hardware_debug1 and off_hardware. The passing warp_debug1 run prints D3D12 debug-layer lines (ExecuteCommandLists: ... the command queue fence has not advanced past previous executions of the command list). This change doesn't touch submission, and I did not check whether those lines also appear before it.

Loop script (loop.py)
"""Counted ctest loop: loop.py <preset> <test> <runs> [--load N] [--cores MASK] [--out DIR]

Runs ctest N times (not until-fail) so the result is a rate. --load starts N busy-loop processes;
--cores restricts this process (and so ctest, the test and the load) to an affinity mask."""
import argparse, ctypes, multiprocessing, os, subprocess, sys, time


def burn():
    while True:
        pass


def main():
    p = argparse.ArgumentParser()
    p.add_argument("preset"); p.add_argument("test"); p.add_argument("runs", type=int)
    p.add_argument("--load", type=int, default=0); p.add_argument("--cores", type=lambda s: int(s, 0), default=0)
    p.add_argument("--out", default="out/loops"); p.add_argument("--env", action="append", default=[])
    a = p.parse_args()
    if a.cores:
        from ctypes import wintypes
        k = ctypes.WinDLL("kernel32", use_last_error=True)
        k.GetCurrentProcess.restype = wintypes.HANDLE
        k.SetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.c_size_t]
        if not k.SetProcessAffinityMask(k.GetCurrentProcess(), a.cores):
            sys.exit(f"SetProcessAffinityMask failed: {ctypes.get_last_error()}")
    for e in a.env:
        key, _, val = e.partition("=")
        os.environ[key] = val
    workers = [multiprocessing.Process(target=burn, daemon=True) for _ in range(a.load)]
    for w in workers: w.start()
    tag = f"{a.test}.{a.preset}.load{a.load}.cores{a.cores:x}"
    os.makedirs(a.out, exist_ok=True)
    fails, t0 = 0, time.time()
    try:
        for i in range(a.runs):
            r = subprocess.run(["ctest", "--preset", a.preset, "--no-tests=error", "-R", f"^{a.test}$",
                                "--output-on-failure"], capture_output=True, text=True, errors="replace")
            if r.returncode:
                fails += 1
                with open(os.path.join(a.out, f"{tag}.fail{fails}.txt"), "w") as f:
                    f.write(f"run {i + 1}\n{r.stdout}\n{r.stderr}")
    finally:
        for w in workers: w.terminate()
    line = f"{tag}: {fails}/{a.runs} failed, {time.time() - t0:.0f} s"
    print(line)
    with open(os.path.join(a.out, "summary.txt"), "a") as f: f.write(line + "\n")


if __name__ == "__main__":
    main()

Evidence and follow-up

The test is unchanged apart from the extra syncs, and no new fixture is added. The other two failures in #3428 are separate.

AI-assisted.

🤖 Generated with Claude Code

**@⁠Not-Saii** on GitHub · 2026-11-29 13:57 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/3457) `Not-Saii:tests/retire-in-flight-sync` → `main` · +3 −0 · 1 files · 1 commits · merged 2026-11-29 14:17 UTC ## Change `startup_resource_retire` failed once in the /O2 job of main at `6747721c` on WARP (Microsoft Basic Render Driver), at the `in flight passed` stage, with 2 textures (131072 bytes) still retained. This fixes that failure in the test. Refs #3428. The runtime frees a released texture of the retire class only after two things: every queue has passed its release-time fence, and every submission that names the texture has completed (`retire_fences_reached` and the flight list in `src/startup_stubs/d3d12_xs_device.cpp`). Neither the runtime nor the test's drain waits for the GPU. `in_flight()` releases R and D while one queue is gated and the other three are idle, so each release signals a release-time fence on all four queues. The stage then waited only for the gated queue (`c.sync(queue)`) before `settle()`, which retries the drain up to 200 times in a row without sleeping. When WARP had not passed another queue's release-time fence within those 200 drains, both textures were still retained. The test now syncs all four queues before `settle()`, as every other stage that settles after a release already does. The expectation is unchanged: both textures must be freed, and `stays("in flight")` still checks that nothing goes early while the submission is held. The runtime is unchanged. ## Verification Base `212d4b5f`; fix `5530c7a3`. The branch is rebased onto `e3f9a64f` without conflicts (`80ab69e8`); the loops below were measured before the rebase, and main has since changed the retire hold path in `d3d12_xs_device.cpp`. Windows 11 build 26300; WARP (Microsoft Basic Render Driver); NVIDIA GeForce RTX 4090, driver 32.0.16.1088; Windows SDK 10.0.26100; debug layer off (`debug0`). Builds: `dev` (Debug) and `release` (/O2) presets. Locally, `startup_resource_retire_hardware_debug0` picks the RTX 4090. The CI run that failed picked the Basic Render Driver, so `startup_resource_retire_warp_debug0`, which runs the same steps on WARP, stands in for it. Each loop runs `ctest --preset <dev|release> --no-tests=error -R '^<test>$'` a fixed number of times and counts failures (script below). "load 24" adds 24 busy-loop processes on a 24-thread CPU. "2 cores" pins ctest, the test and 4 busy-loop processes to affinity mask `0x3`. `startup_resource_retire_warp_debug0`, failures out of 1000: | Build | Condition | Before (`212d4b5f`) | After | |---|---|---|---| | Debug | idle | 0 | not run | | Debug | load 24 | 167 | 0 | | Debug | 2 cores | 134 | 0 | | /O2 | idle | 0 | not run | | /O2 | load 24 | 630 | 0 | | /O2 | 2 cores | 224 | 0 | Every failure before the fix is the CI line, at the gated-queue step (17 textures live) or the copy-queue step (15 live): ``` FAIL: resources kept after their submission passed stage 'in flight passed' texture live=5242880/17 expected=5242880/17 retained=131072/2 expected=0/0 ``` **Revert control.** With `settle_limit` set to 1 (a single drain), Debug, load 24, 200 runs: the test before the fix fails 183/200, all at `in flight passed`. With the fix it fails 0/200. With all four queues synced, one drain is enough, so the stage no longer depends on how fast WARP finishes. (Idle, one drain: 0/200 before and 0/200 after; an idle WARP passes those fences in time.) `startup_resource_retire_hardware_debug0` on the RTX 4090: before the fix 0/1000 idle and 0/1000 under load 24, in each build. After: 0/1000 idle in Debug and 0/1000 idle in /O2 (not repeated under load, which took 1.5 h per configuration before the fix). One run of each `startup_resource_retire_*` test passed with the fix on both adapters: `warp_debug0`, `warp_debug1`, `off_warp`, `hardware_debug0`, `hardware_debug1` and `off_hardware`. The passing `warp_debug1` run prints D3D12 debug-layer lines (`ExecuteCommandLists: ... the command queue fence has not advanced past previous executions of the command list`). This change doesn't touch submission, and I did not check whether those lines also appear before it. <details><summary>Loop script (loop.py)</summary> ```python """Counted ctest loop: loop.py <preset> <test> <runs> [--load N] [--cores MASK] [--out DIR] Runs ctest N times (not until-fail) so the result is a rate. --load starts N busy-loop processes; --cores restricts this process (and so ctest, the test and the load) to an affinity mask.""" import argparse, ctypes, multiprocessing, os, subprocess, sys, time def burn(): while True: pass def main(): p = argparse.ArgumentParser() p.add_argument("preset"); p.add_argument("test"); p.add_argument("runs", type=int) p.add_argument("--load", type=int, default=0); p.add_argument("--cores", type=lambda s: int(s, 0), default=0) p.add_argument("--out", default="out/loops"); p.add_argument("--env", action="append", default=[]) a = p.parse_args() if a.cores: from ctypes import wintypes k = ctypes.WinDLL("kernel32", use_last_error=True) k.GetCurrentProcess.restype = wintypes.HANDLE k.SetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.c_size_t] if not k.SetProcessAffinityMask(k.GetCurrentProcess(), a.cores): sys.exit(f"SetProcessAffinityMask failed: {ctypes.get_last_error()}") for e in a.env: key, _, val = e.partition("=") os.environ[key] = val workers = [multiprocessing.Process(target=burn, daemon=True) for _ in range(a.load)] for w in workers: w.start() tag = f"{a.test}.{a.preset}.load{a.load}.cores{a.cores:x}" os.makedirs(a.out, exist_ok=True) fails, t0 = 0, time.time() try: for i in range(a.runs): r = subprocess.run(["ctest", "--preset", a.preset, "--no-tests=error", "-R", f"^{a.test}$", "--output-on-failure"], capture_output=True, text=True, errors="replace") if r.returncode: fails += 1 with open(os.path.join(a.out, f"{tag}.fail{fails}.txt"), "w") as f: f.write(f"run {i + 1}\n{r.stdout}\n{r.stderr}") finally: for w in workers: w.terminate() line = f"{tag}: {fails}/{a.runs} failed, {time.time() - t0:.0f} s" print(line) with open(os.path.join(a.out, "summary.txt"), "a") as f: f.write(line + "\n") if __name__ == "__main__": main() ``` </details> ## Evidence and follow-up The test is unchanged apart from the extra syncs, and no new fixture is added. The other two failures in #3428 are separate. AI-assisted. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
in_flight() released R and D while every queue was idle except the
gated one, so each release signalled a release-time fence on all four
queues. The stage then synced only the gated queue before settle(),
whose 200 drains never wait for the GPU. When WARP had not yet passed
another queue's release-time fence within those drains, the textures
were still retained and the stage failed with
"resources kept after their submission passed" (seen in CI on the
Microsoft Basic Render Driver at /O2).

Sync all four queues before settle(), as every other stage does. The
check itself is unchanged: both textures must still be freed.

Refs #3426

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-29 14:02:19 +00:00
github manually merged commit c252ff0481 into main 2026-11-29 14:19:38 +00:00
Author
Owner

@⁠JohnConnorNPC on GitHub · 2026-11-29 14:16 UTC · original

Review of head 80ab69e8 (one commit on main e3f9a64f). git merge-tree --write-tree origin/main 80ab69e8 against main 0ed385dc exits 0. The diff is three lines in tests/startup_resource_retire.cpp. The runtime is unchanged.

Semantics (checked against src/startup_stubs/d3d12_xs_device.cpp on main)

  • retire_resource signals the release-time fence on every registered queue (q.queue->Signal(q.fence, q.signaled + 1)). retire_fences_reached compares each fence->GetCompletedValue() with its target. drain_retired_resources starts with TryAcquireSRWLockExclusive and never waits. The body describes this correctly.
  • Context::sync signals the test's own fence on the same queue, after those markers, and waits for it. A queue completes its signals in order, so after sync on all four queues every release-time target has passed. Then one drain is enough, which matches your settle_limit = 1 control.
  • In every other stage that settles after a release, the release-time fences have already passed on all four queues: closed_lists, discards, destination_released, texture_region, resolve_destination, open_list and classes sync all four. release_time_fence syncs three and then the gated one. second_submission settles R, which was released and synced in stage 1. in_flight was the only stage that settled before the release-time fences of the idle queues had passed.
  • The added syncs come after stays("in flight") has already passed. So the early-release check still runs while the submission is held. The stage still requires both textures to be freed, so a runtime that kept them would still fail at in flight passed.

Default path: none. X2W_D3D12_RELEASE_RETIRED=1 is in the base env of tools/startup/run_presets.json, so the retire path is used in real runs, but this PR does not touch it. The drain never blocks. The flake was a race in the test's timing, not a wait or a stall in the runtime.

MUST: none.

NIT

  1. The subject gpu: wait for every queue … reads like a runtime change that adds a GPU wait. The change is test-only. Someone bisecting a present or queue stall could pick it up as a suspect. tests: would match how this repo labels test-only commits (e.g. c68ffa88 tests: compute stand-in source lines instead of pinning them). Optional.

CI note: CI on 80ab69e8 is green. But the Windows job runs the 82-test pr preset, and its log has no startup_resource_retire_(warp|hardware|off) line (grep -c gives 0). The only retire test in that job is startup_resource_retire_title_inline_warp_debug0. So CI did not run this change. Your 1000-run loops are the only Windows evidence, and main's full job will run it after merge. There are no WARP reports on the PR yet. I could not run D3D12 WARP here (Linux).

No reviews or change requests. No binary files, no title-specific inputs.

Merging.

AI-assisted.

**@⁠JohnConnorNPC** on GitHub · 2026-11-29 14:16 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/3457#issuecomment-7257173053) Review of head `80ab69e8` (one commit on `main` `e3f9a64f`). `git merge-tree --write-tree origin/main 80ab69e8` against `main` `0ed385dc` exits 0. The diff is three lines in `tests/startup_resource_retire.cpp`. The runtime is unchanged. **Semantics (checked against `src/startup_stubs/d3d12_xs_device.cpp` on `main`)** - `retire_resource` signals the release-time fence on every registered queue (`q.queue->Signal(q.fence, q.signaled + 1)`). `retire_fences_reached` compares each `fence->GetCompletedValue()` with its target. `drain_retired_resources` starts with `TryAcquireSRWLockExclusive` and never waits. The body describes this correctly. - `Context::sync` signals the test's own fence on the same queue, after those markers, and waits for it. A queue completes its signals in order, so after `sync` on all four queues every release-time target has passed. Then one drain is enough, which matches your `settle_limit = 1` control. - In every other stage that settles after a release, the release-time fences have already passed on all four queues: `closed_lists`, `discards`, `destination_released`, `texture_region`, `resolve_destination`, `open_list` and `classes` sync all four. `release_time_fence` syncs three and then the gated one. `second_submission` settles `R`, which was released and synced in stage 1. `in_flight` was the only stage that settled before the release-time fences of the idle queues had passed. - The added syncs come after `stays("in flight")` has already passed. So the early-release check still runs while the submission is held. The stage still requires both textures to be freed, so a runtime that kept them would still fail at `in flight passed`. **Default path:** none. `X2W_D3D12_RELEASE_RETIRED=1` is in the `base` env of `tools/startup/run_presets.json`, so the retire path is used in real runs, but this PR does not touch it. The drain never blocks. The flake was a race in the test's timing, not a wait or a stall in the runtime. **MUST:** none. **NIT** 1. The subject `gpu: wait for every queue …` reads like a runtime change that adds a GPU wait. The change is test-only. Someone bisecting a present or queue stall could pick it up as a suspect. `tests:` would match how this repo labels test-only commits (e.g. `c68ffa88 tests: compute stand-in source lines instead of pinning them`). Optional. **CI note:** CI on `80ab69e8` is green. But the Windows job runs the 82-test `pr` preset, and its log has no `startup_resource_retire_(warp|hardware|off)` line (`grep -c` gives 0). The only retire test in that job is `startup_resource_retire_title_inline_warp_debug0`. So CI did not run this change. Your 1000-run loops are the only Windows evidence, and main's full job will run it after merge. There are no WARP reports on the PR yet. I could not run D3D12 WARP here (Linux). No reviews or change requests. No binary files, no title-specific inputs. Merging. AI-assisted.
This discussion has been locked. Commenting is limited to contributors.
No description provided.