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

Merged
Not-Saii merged 1 commit from upstream-pr/3457 into main 2026-11-29 14:17:09 +00:00
Not-Saii commented 2026-11-29 13:57:11 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Not-Saii on 2026-11-29T13:57:11Z.


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 #3426.

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 #3426 are separate.

AI-assisted.

🤖 Generated with Claude Code

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:5551411781 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/3457). Originally posted by [Not-Saii](https://github.com/Not-Saii) on 2026-11-29T13:57:11Z. --- ## 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 #3426. 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 #3426 are separate. AI-assisted. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
JohnConnorNPC commented 2026-11-29 14:16:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by JohnConnorNPC on 2026-11-29T14:16:16Z.


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.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7257173053 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/3457#issuecomment-7257173053). Originally posted by [JohnConnorNPC](https://github.com/JohnConnorNPC) on 2026-11-29T14:16:16Z. --- 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.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!3457
No description provided.