runtime: retain presented readback ownership until fence completion #2968

Manually merged
github merged 2 commits from github-bot/gh-2968 into gh-pr/2968/base 2026-11-27 04:51:33 +00:00 AGit
Owner

@⁠chadhyatt on GitHub · 2026-11-27 00:10 UTC · original
chadhyatt:backport/present-readback-completion → main · +344 −16 · 8 files · 2 commits · merged 2026-11-27 04:46 UTC

AI-assisted backport patch from x2w-microlift.

The presented-surface diagnostic resets its allocator on the next sample even if the previous queue copy timed out, and trusts an event without checking the fence value. Check Close, Signal, event registration, wait completion and Map; retain the submitted surface and queue across incomplete waits. A failed signal or removal disables reuse rather than publishing or resetting storage. Share the existing draw-dump removal classification.

Documented API: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12fence-getcompletedvalue

Verification on Apple Silicon, commit 31759f429e:

  • clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/startup_present_readback_check.cpp -o out/present_readback_check && out/present_readback_check passed pending, stale-event, completion, failed-signal and device-removal boundaries.
  • python3 -B tests/docs_links_check.py passed; PR preset includes the new portable check.
  • Windows build and actual D3D12/GPU execution not run on this host. No forced device loss or title inputs. Windows CI/reviewer verification welcome.
**@⁠chadhyatt** on GitHub · 2026-11-27 00:10 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968) `chadhyatt:backport/present-readback-completion` → `main` · +344 −16 · 8 files · 2 commits · merged 2026-11-27 04:46 UTC AI-assisted backport patch from x2w-microlift. The presented-surface diagnostic resets its allocator on the next sample even if the previous queue copy timed out, and trusts an event without checking the fence value. Check Close, Signal, event registration, wait completion and Map; retain the submitted surface and queue across incomplete waits. A failed signal or removal disables reuse rather than publishing or resetting storage. Share the existing draw-dump removal classification. Documented API: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12fence-getcompletedvalue Verification on Apple Silicon, commit 31759f429ed6: - `clang++ -std=c++17 -Wall -Wextra -Werror -Isrc tests/startup_present_readback_check.cpp -o out/present_readback_check && out/present_readback_check` passed pending, stale-event, completion, failed-signal and device-removal boundaries. - `python3 -B tests/docs_links_check.py` passed; PR preset includes the new portable check. - Windows build and actual D3D12/GPU execution not run on this host. No forced device loss or title inputs. Windows CI/reviewer verification welcome.
Check recording, signalling, completion notification and mapping results; retain the submitted surface and queue until the private fence confirms completion. Never interpret device removal as a successful readback.
Add a portable completion-policy fixture to the Windows PR preset.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 01:31:13 +00:00
Author
Owner

@⁠Jess-Doit on GitHub · 2026-11-27 01:25 UTC · original

The fence-state control passed. Please drain a successfully queued readback when its fence completes even if there is no later diagnostic sample. The current path can keep the final timed-out sample's surface and queue alive for the rest of the module lifetime. Ready for more review

**@⁠Jess-Doit** on GitHub · 2026-11-27 01:25 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#issuecomment-7207277850) The fence-state control passed. Please drain a successfully queued readback when its fence completes even if there is no later diagnostic sample. The current path can keep the final timed-out sample's surface and queue alive for the rest of the module lifetime. Ready for more review
Retire only confirmed matching submissions through a module-pinned threadpool wait, preserving fail-closed removal and signal handling.
AI-assisted backport patch from x2w-microlift.
Author
Owner

@⁠chadhyatt on GitHub · 2026-11-27 01:27 UTC · original

Thanks for the review and passing fence-state control. I am preparing a focused follow-up to reap successfully queued readbacks independently of future diagnostic sampling, while retaining failed-signal or incomplete work. I will update this PR with the exact new verification.

**@⁠chadhyatt** on GitHub · 2026-11-27 01:27 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#issuecomment-7207307292) Thanks for the review and passing fence-state control. I am preparing a focused follow-up to reap successfully queued readbacks independently of future diagnostic sampling, while retaining failed-signal or incomplete work. I will update this PR with the exact new verification.
Author
Owner

@⁠chadhyatt on GitHub · 2026-11-27 01:56 UTC · original

Updated 005c7d87db: a signalled readback abandoned by the sample now has a matching fence/value threadpool drain independent of later samples. The callback holds an actual shim module reference, releases surface/queue exactly once only after confirmed completion, never publishes pixels, and refuses/retains on registration failure or removal. On Apple Silicon, clang++ -std=c++20 -Wall -Wextra -Werror -I src tests/startup_present_readback_check.cpp and the resulting executable passed. The exact production drain block also passed x86_64-w64-mingw32-g++ -std=c++20 -fsyntax-only -Wall -Wextra -Werror against Windows/D3D12 headers. Independent source review accepted. Full Windows shim build and live GPU callback execution were not run here; CI and existing Windows evidence remain separate.

**@⁠chadhyatt** on GitHub · 2026-11-27 01:56 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#issuecomment-7207699986) Updated 005c7d87db23fb557833c6ea1a151975af157d39: a signalled readback abandoned by the sample now has a matching fence/value threadpool drain independent of later samples. The callback holds an actual shim module reference, releases surface/queue exactly once only after confirmed completion, never publishes pixels, and refuses/retains on registration failure or removal. On Apple Silicon, clang++ -std=c++20 -Wall -Wextra -Werror -I src tests/startup_present_readback_check.cpp and the resulting executable passed. The exact production drain block also passed x86_64-w64-mingw32-g++ -std=c++20 -fsyntax-only -Wall -Wextra -Werror against Windows/D3D12 headers. Independent source review accepted. Full Windows shim build and live GPU callback execution were not run here; CI and existing Windows evidence remain separate.
Author
Owner

@⁠Jess-Doit on GitHub · 2026-11-27 02:04 UTC · original

The independent drain addresses my late-retirement finding. I reran the Windows CPU fixture and it passed the pending, stale callback, exactly-once release, failed-signal, and device-removal controls. This rerun covered the ownership state machine. Ready to merge from our side

**@⁠Jess-Doit** on GitHub · 2026-11-27 02:04 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#issuecomment-7207815033) The independent drain addresses my late-retirement finding. I reran the Windows CPU fixture and it passed the pending, stale callback, exactly-once release, failed-signal, and device-removal controls. This rerun covered the ownership state machine. Ready to merge from our side
Author
Owner

@⁠KelboLive on GitHub · 2026-11-27 04:27 UTC · original · reviewed

PR #2968 fixes a lifetime/ownership bug in the present diagnostic readback. Good find.

What works

  • fence_completion(): clean utility that categorizes fence results into pending/completed/removed.
    Replaces the bare if(value != UINT64_MAX) check with a typed enum, making the device-removal
    path explicit. Used by both the new readback drain and the existing draw-dump tracking.
  • PresentReadbackState: well-structured state machine over the readback lifecycle: submitted -> pending ->
    completed (reuse allowed) or removed/unusable (lifetime disable). retire() correctly guards against
    settling a different submission than the one held (expected target check). stale-event test confirms
    that a late fence observation cannot settle a subsequent submission.
  • PresentedReadback struct: owns surface+queue refs with RAII-style release_readback_ownership(),
    serialized through a mutex between the sampling path and the drain callback.
  • draw_dump_tracking.h: updates GetCompletedValue() path to use fence_completion(), inheriting the
    pending/completed/removed classification. The UINT64_MAX device-removal sentinel now properly
    keeps entries pending rather than removing them.
  • Unit test presents 7 test cases against PresentReadbackState: initial state, pending retention,
    stale-completion rejection, past-target settling, device removal, signal failure, and fence
    boundary values (UINT64_MAX-1 completed, UINT64_MAX removed). All pass on Apple Silicon.
  • Docs startup-runtime.md correctly explains the drain semantics and fence ownership policy.

Issues

  1. PresentReadback struct in d3d12_xs_device.cpp is a global non-pointer (not wrapped in ComPtr or
    unique_ptr). The individual fields (submitted_surface, submitted_queue) use Release() instead of
    ComPtr reset. This is consistent with the existing stub codebase style (which uses raw pointers +
    Release()), but the struct has no destructor. If an exception is thrown between submission and
    drain release, surface/queue refs leak. Consider wrapping the release_readback_ownership() call
    in a RAII guard in the drain entry point.
  2. PendingDrain struct includes HMODULE module field but the CA callback body (cut off at API limit)
    does not call FreeLibrary on it. The module-hold pattern suggests it loads the shim module to
    keep it resident during the async drain. If FreeLibrary is omitted, the module leaks for the
    process lifetime, which is harmless but worth noting.
  3. fence_completion(observed >= target ? completed : pending) uses >= not == for completion check.
    This is intentional (once a fence passes the value, it stays passed) but the comment only mentions
    UINT64_MAX. Add a comment noting that >= is used intentionally so late observations still resolve.
  4. PresentReadbackState::submitted() overwrites target_ without checking if a previous submission is
    still pending. The drain should catch this via the stale-event test. However, if a new present
    races the drain callback, submitted() could overwrite a pending target before retire() settles it.
    The retire(expected=...) overload helps, but the caller must pass the correct expected value.

Recommendations

  • Wrap PresentReadback in a class with a destructor that releases any held surface/queue refs as a
    safety net (RAII), even if the drain path is always called.
  • Document the >= semantics in fence_completion() comment.
  • Verify PendingDrain module is freed in the CA callback body after release_readback_ownership().
  • Consider checking that PresentReadbackState::submitted() does not overwrite a still-pending target
    without first draining it, or add an assert/warning in dev builds.

Overall: a solid fix for a real bug. The state machine is well designed and the portable unit tests
cover all the edge cases without needing GPU hardware to verify.

**@⁠KelboLive** on GitHub · 2026-11-27 04:27 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#pullrequestreview-6083488012) · **reviewed** PR #2968 fixes a lifetime/ownership bug in the present diagnostic readback. Good find. ## What works - fence_completion(): clean utility that categorizes fence results into pending/completed/removed. Replaces the bare if(value != UINT64_MAX) check with a typed enum, making the device-removal path explicit. Used by both the new readback drain and the existing draw-dump tracking. - PresentReadbackState: well-structured state machine over the readback lifecycle: submitted -> pending -> completed (reuse allowed) or removed/unusable (lifetime disable). retire() correctly guards against settling a different submission than the one held (expected target check). stale-event test confirms that a late fence observation cannot settle a subsequent submission. - PresentedReadback struct: owns surface+queue refs with RAII-style release_readback_ownership(), serialized through a mutex between the sampling path and the drain callback. - draw_dump_tracking.h: updates GetCompletedValue() path to use fence_completion(), inheriting the pending/completed/removed classification. The UINT64_MAX device-removal sentinel now properly keeps entries pending rather than removing them. - Unit test presents 7 test cases against PresentReadbackState: initial state, pending retention, stale-completion rejection, past-target settling, device removal, signal failure, and fence boundary values (UINT64_MAX-1 completed, UINT64_MAX removed). All pass on Apple Silicon. - Docs startup-runtime.md correctly explains the drain semantics and fence ownership policy. ## Issues 1. PresentReadback struct in d3d12_xs_device.cpp is a global non-pointer (not wrapped in ComPtr or unique_ptr). The individual fields (submitted_surface, submitted_queue) use Release() instead of ComPtr reset. This is consistent with the existing stub codebase style (which uses raw pointers + Release()), but the struct has no destructor. If an exception is thrown between submission and drain release, surface/queue refs leak. Consider wrapping the release_readback_ownership() call in a RAII guard in the drain entry point. 2. PendingDrain struct includes HMODULE module field but the CA callback body (cut off at API limit) does not call FreeLibrary on it. The module-hold pattern suggests it loads the shim module to keep it resident during the async drain. If FreeLibrary is omitted, the module leaks for the process lifetime, which is harmless but worth noting. 3. fence_completion(observed >= target ? completed : pending) uses >= not == for completion check. This is intentional (once a fence passes the value, it stays passed) but the comment only mentions UINT64_MAX. Add a comment noting that >= is used intentionally so late observations still resolve. 4. PresentReadbackState::submitted() overwrites target_ without checking if a previous submission is still pending. The drain should catch this via the stale-event test. However, if a new present races the drain callback, submitted() could overwrite a pending target before retire() settles it. The retire(expected=...) overload helps, but the caller must pass the correct expected value. ## Recommendations - Wrap PresentReadback in a class with a destructor that releases any held surface/queue refs as a safety net (RAII), even if the drain path is always called. - Document the >= semantics in fence_completion() comment. - Verify PendingDrain module is freed in the CA callback body after release_readback_ownership(). - Consider checking that PresentReadbackState::submitted() does not overwrite a still-pending target without first draining it, or add an assert/warning in dev builds. Overall: a solid fix for a real bug. The state machine is well designed and the portable unit tests cover all the edge cases without needing GPU hardware to verify.
Author
Owner

@⁠chadhyatt on GitHub · 2026-11-27 04:31 UTC · original

Thanks for reviewing. Rechecked the four actual retirement sites at this head. sample_presented_surface guards prior pending ownership before submitting again, and both sampling and callback retirement run under the same mutex. The callback checks the fence identity and the expected submission value before release. The callback holds its own fence reference and releases its module reference with FreeLibraryWhenCallbackReturns; registration failures release their allocated resources. These cover the noted races/module-lifetime concern without replacing the existing module-lifetime recording state with a destructor that could release an in-flight surface. Late fence completion is covered by the past-target control. No additional behavior change proposed here.

**@⁠chadhyatt** on GitHub · 2026-11-27 04:31 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#issuecomment-7209866826) Thanks for reviewing. Rechecked the four actual retirement sites at this head. `sample_presented_surface` guards prior pending ownership before submitting again, and both sampling and callback retirement run under the same mutex. The callback checks the fence identity and the expected submission value before release. The callback holds its own fence reference and releases its module reference with `FreeLibraryWhenCallbackReturns`; registration failures release their allocated resources. These cover the noted races/module-lifetime concern without replacing the existing module-lifetime recording state with a destructor that could release an in-flight surface. Late fence completion is covered by the past-target control. No additional behavior change proposed here.
github-bot changed target branch from main to gh-pr/2968/base 2026-11-27 04:51:31 +00:00
github manually merged commit 005c7d87db into gh-pr/2968/base 2026-11-27 04:51:33 +00:00
Author
Owner

@⁠R0Y00 on GitHub · 2026-11-27 04:46 UTC · original · approved these changes

Reviewed 005c7d87db23fb557833c6ea1a151975af157d39. Checked the callback's fence identity, expected fence value and synchronized ownership release, including FreeLibraryWhenCallbackReturns. The Release DLL built in a clean merge trial and ctest --preset release --no-tests=error -R '^startup_present_readback$' passed. I also compiled this head's async drain implementation unchanged in an isolated /O2 test DLL on Windows 11 build 26200.9974. A real Microsoft WARP queue (10.0.26100.9818) waited on a gate before signaling the readback fence. Both references remained held while the fence was pending, and the callback released both once fence 7 completed, without another sample. That supplemental harness verifies the drain after registration; it does not exercise the full Present timeout entry point. Required Windows CI passed.

**@⁠R0Y00** on GitHub · 2026-11-27 04:46 UTC · [original](https://github.com/R0Y00/Xbox2Windows/pull/2968#pullrequestreview-6083597751) · **approved these changes** Reviewed `005c7d87db23fb557833c6ea1a151975af157d39`. Checked the callback's fence identity, expected fence value and synchronized ownership release, including `FreeLibraryWhenCallbackReturns`. The Release DLL built in a clean merge trial and `ctest --preset release --no-tests=error -R '^startup_present_readback$'` passed. I also compiled this head's async drain implementation unchanged in an isolated `/O2` test DLL on Windows 11 build 26200.9974. A real Microsoft WARP queue (10.0.26100.9818) waited on a gate before signaling the readback fence. Both references remained held while the fence was pending, and the callback released both once fence 7 completed, without another sample. That supplemental harness verifies the drain after registration; it does not exercise the full Present timeout entry point. Required Windows CI passed.
This discussion has been locked. Commenting is limited to contributors.
No description provided.