Skip to content

XGameRuntime: a task queue's termination callback runs on its completion port - #1154

Merged
Prime1997 merged 1 commit into
xcl-dev:mainfrom
emirduran707:taskqueue-terminate-port
Nov 30, 2026
Merged

Prime1997 merged 1 commit into
xcl-dev:mainfrom
emirduran707:taskqueue-terminate-port

Conversation

@emirduran707

@emirduran707 emirduran707 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

XTaskQueueTerminate with wait = false ran the title's termination callback on XCL's own worker thread, as soon as the queue's work had finished. Microsoft's documentation of XTaskQueueTerminate says the callback is invoked from the completion thread at the end of termination. Its example for a manual completion port relies on that: the callback is queued to the completion port, so it already runs on the title's UI thread. A title that dispatches its completion port by hand could get the callback on a thread it does not expect, while that thread may still be touching the queue.

Now, with wait = false, the callback is submitted to the queue's completion port once the pending work and completions are done. The port's monitors are notified, so on a manual port the callback runs from the title's own XTaskQueueDispatch. While an async termination callback is still pending submission, a completion-port XTaskQueueDispatch with a timeout (including INFINITE) waits for it instead of returning false early. With wait = true the callback still runs on the calling thread before Terminate returns: queuing it there could hang a caller whose manual port nobody dispatches while it waits.

What is in it

  • crates/xcl/src/hle/xgameruntime/taskqueue.rs:
    • submit_now goes through a private submit that can let the termination entry past the terminated check.
    • QueueState::termination_cb_pending keeps a manual completion-port dispatch waiting until the async termination entry has been queued.
    • run_terminated runs the queued callback.
    • Tests termination_callback_runs_from_a_manual_completion_port_dispatch and infinite_completion_pump_receives_termination_callback.

Tested

  • AMD Radeon RX 9060 XT (driver 32.0.31044.16), Ryzen 5 5600, Windows 11 Pro 26300, Rust 1.100.0; tests debug, smoke release
  • cargo test --workspace -- --test-threads=4 on cc8fbcd: 743 passed, 0 failed, 41 ignored; no SKIPPED GPU tests
  • cargo test -p xcl --lib taskqueue -- --test-threads=4: 12 passed, 0 failed
  • infinite_completion_pump_receives_termination_callback failed before the pending-termination wait (pump exited before termination callback in 49 of 50 runs); passes 50/50 after

Regression run

main:

xcl-smoke v1
commit: 47efa2ecea0a12934719ae69b81930cf02a4b1c3
gpu: AMD Radeon RX 9060 XT
title: retail-title
seconds: 60
exit: 0x0
frames shown: 1541 (PresentX 1541)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 19650 MB

this PR:

xcl-smoke v1
commit: cc8fbcd64d5aaa3efe11dd937a623082801e7c95
gpu: AMD Radeon RX 9060 XT
title: retail-title
seconds: 60
exit: 0x0
frames shown: 1593 (PresentX 1593)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14785 MB

Not tested

  • A title that terminates a queue with a manual completion port and wait = false (the smoke title's run is a regression check only).
  • If the title never dispatches that manual port again, the small record holding the callback is not freed.
  • NVIDIA and Intel GPUs.

AI use

  • Claude Code with Claude Opus 5.5: original change, test and description.
  • Antigravity with Gemini 4 Neon: addressed the infinite-dispatch race from review, added the regression test, ran the updated test suite and smoke run, and updated this description.

@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows 11 build 26300 check, Ryzen 7 9800X3D, Rust 1.99.1 MSVC, debug. I queued a completion on a parent, then terminated a child asynchronously while both shared that manual completion port.

  • On 47efa2e, the child’s termination callback ran before any dispatch. Dispatching the parent then ran only its own completion.
  • On ea68eaa, neither callback ran before dispatch. The parent handle dispatched its own uncanceled completion first, then the child’s termination callback. Both ran on the dispatching thread. This passed in the 12-test taskqueue::tests run and in three separate runs of scratch_child_termination_obeys_shared_manual_port_order.

Both revisions used cargo test --offline --locked -p xcl --lib <filter> -- --nocapture --test-threads=1. Synthetic queue callbacks only.

AI-assisted. Codex (GPT-6, exact variant unavailable) wrote and ran the scratch fixture and drafted this report.

@DavidM1911

Copy link
Copy Markdown
Contributor

Independent verification on current main 384f7f7 (branch already contains it — clean).

Machine: Windows 11, Ryzen 9 7900X; Rust stable MSVC, debug.

  • cargo test -p xcl --lib taskqueue: 11 passed, 0 failed — includes the new termination_callback_runs_from_a_manual_completion_port_dispatch.

AI use: test runs by Devin (Cognition, SWE-2); no code changes.

@fromthemoonx

fromthemoonx commented Nov 24, 2026 •

Copy link
Copy Markdown

Rerun on the new head cc8fbcd (the INFINITE completion-pump fix): still passes on the RTX 3060, and the new pump test catches the case it was added for.

result
cargo test --workspace --no-fail-fast -- --test-threads=4, cc8fbcd merged onto main b49be18 (clean) 1437 passed, 0 failed, 47 ignored; 25 SKIPPED lines
termination_callback_runs_from_a_manual_completion_port_dispatch, infinite_completion_pump_receives_termination_callback, composite_queue_termination_preserves_shared_parent_port_work, alone, 40 runs each 40 of 40 each
hle::xgameruntime::taskqueue:: (12 tests), --test-threads=8, 30 runs 30 of 30
scratch: the dispatch wait loop without || (port == PORT_COMPLETION && state.termination_cb_pending > 0) infinite_completion_pump_receives_termination_callback fails at taskqueue.rs:951; the other 11 pass

Same machine, debug. The report below is for ea68eaa.


NVIDIA run with the whole suite, since Not tested lists NVIDIA.

Tested

  • NVIDIA GeForce RTX 3060 12 GB (32-lane waves), driver 32.0.16.1088; AMD Ryzen 7 5700X; native Windows 11 Pro 26H2 (build 26300.9974), Graphics Tools installed; rustc 1.100.0 stable-x86_64-pc-windows-msvc; DXC 1.9.2602.17; debug
  • Exact head ea68eaab214f941b0f12b4274b156b165c588cfa, which is on current main 47efa2e (so also the merged result): cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4: 742 passed, 0 failed, 41 ignored. The new taskqueue::tests::termination_callback_runs_from_a_manual_completion_port_dispatch passed.
  • Fails without the change: with taskqueue.rs as on main plus only the new test, it fails with the termination callback ran before the completion port was dispatched, left: Some(ThreadId(4)), right: None.
  • hle::xgameruntime::taskqueue tests, 10 runs: 10 of 10 passed (11 each)
  • e2e, 3 runs: 3 of 3 passed. The test title uses XGameRuntime task queues through the GDK thunks.
  • SKIPPED (no wave64 on this adapter): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware

Not tested

  • A retail title closing a task queue with a manual completion port; release build.

AI use

  • Claude Code (Claude Opus 5.5) ran the build and tests on the machine above, including the check without the change, and wrote this report from the output.

@kacper-serewis

Copy link
Copy Markdown

On ea68eaa, a title that pumps its manual completion port with XTaskQueueDispatch(h, Completion, INFINITE) in a loop does not get the termination callback.

Tested: Windows 11, debug, CPU only. Idle queue (ThreadPool / Manual), a pump thread blocked in dispatch, then XTaskQueueTerminate(wait = false). The pump is joined, then 50 ms pass:

callback not run
base 47efa2e 0 of 200
ea68eaa 200 of 200

From the code: Terminate wakes the dispatcher, which returns false because the queue is terminated and empty, so the pump ends before the callback is queued. The PR's test waits for the entry and then dispatches once with a zero timeout. Suggested (not tested): an infinite dispatch must not return false on a terminated queue until its termination entry has run.

Test (append to taskqueue.rs)
#[cfg(test)]
mod pump_probe {
    use super::*;
    #[test]
    fn infinite_completion_pump_gets_the_termination_callback() {
        unsafe extern "system" fn terminated(ctx: *mut c_void) {
            (*(ctx as *const std::sync::atomic::AtomicBool)).store(true, std::sync::atomic::Ordering::SeqCst);
        }
        let mut missed = 0;
        for _ in 0..200 {
            unsafe {
                let mut h = std::ptr::null_mut();
                assert_eq!(XTaskQueueCreate(MODE_THREAD_POOL, MODE_MANUAL, &mut h), S_OK);
                let ran = std::sync::atomic::AtomicBool::new(false);
                let hp = h as usize;
                let pump = std::thread::spawn(move || while XTaskQueueDispatch(hp as *mut c_void, PORT_COMPLETION, u32::MAX) {});
                std::thread::sleep(Duration::from_millis(5));
                assert_eq!(XTaskQueueTerminate(h, false, &ran as *const _ as *mut c_void, terminated as usize), S_OK);
                pump.join().unwrap();
                std::thread::sleep(Duration::from_millis(50));
                if !ran.load(std::sync::atomic::Ordering::SeqCst) { missed += 1; }
                // drain so that `ran` outlives the callback
                let t = Instant::now() + Duration::from_secs(2);
                while !ran.load(std::sync::atomic::Ordering::SeqCst) && Instant::now() < t { XTaskQueueDispatch(h, PORT_COMPLETION, 1); }
                XTaskQueueCloseHandle(h);
            }
        }
        assert_eq!(missed, 0, "missed {missed} of 200");
    }
}

AI use: Claude Code (Claude Opus 5.5) ran the tests and wrote this comment. I checked the points before posting.

…ion port

XTaskQueueTerminate(wait = false) had a worker of the shared pool call the
title's termination callback directly. The GDK docs say the callback "will be
invoked from the completion thread at the end of termination", and their
example terminates a queue with a manual completion port from WM_CLOSE and
calls DestroyWindow in the callback, relying on it running from the UI
thread's own XTaskQueueDispatch. libHttpClient likewise queues a termination
entry on the completion port and notifies the queue's monitors.

Once in-flight work and completions have drained, the callback is now
submitted to the completion port through the same path as other completion
callbacks (which notifies monitors), allowed past the terminated check. On a
manual port it runs from the title's XTaskQueueDispatch, on a thread-pool
port on the pool. QueueState tracks pending async termination callbacks so
a completion-port XTaskQueueDispatch with a timeout (such as INFINITE) waits
for the termination entry before returning false. With wait = true the
callback still runs on the calling thread before Terminate returns: on a
manual port nobody may dispatch while the caller waits, which the docs warn
may deadlock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Antigravity (Gemini 4 Neon)
@emirduran707
emirduran707 force-pushed the taskqueue-terminate-port branch from ea68eaa to cc8fbcd Compare November 24, 2026 21:21
@emirduran707

Copy link
Copy Markdown
Contributor Author

Fixed in cc8fbcd (squashed and force-pushed).

QueueState now tracks pending async termination callbacks (termination_cb_pending): set in XTaskQueueTerminate when !wait && cb != 0, and decremented inside the p.items + q.state locks in submit as the termination entry is pushed onto PORT_COMPLETION (waking waiting dispatchers with notify_all). dispatch keeps waiting on PORT_COMPLETION while termination_cb_pending > 0, and returns false once the queue is empty and terminated with no pending termination entry.

Reproduced the failure with infinite_completion_pump_receives_termination_callback (missed 49 of 50 runs on ea68eaa); on cc8fbcd it passes 50/50, cargo test -p xcl --lib taskqueue passes 12/12, and the full workspace suite passes (743 passed, 0 failed, 41 ignored).

AI use: Antigravity with Gemini 4 Neon wrote the fix, test, and this reply.

@DavidM1911

Copy link
Copy Markdown
Contributor

Re-verification on RTX 3060 Ti (Windows 11), new head merged with current main:

  • cargo test -p xcl --lib: all passed, 0 failed, 27 ignored. The earlier merge conflict is resolved.

Thanks!

— Devin

rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
…cl-dev#1154, verbatim Windows + Linux twin)

Upstream xcl-dev#1154 (live pr1154head=cc8fbcd6, still OPEN, merge-base false):
docs say the Terminate callback is invoked from the completion thread,
but XCL ran it on a pool worker. Windows hle/xgameruntime/taskqueue.rs
is the upstream diff applied verbatim (git apply clean, +114/-10):
termination_cb_pending field, submit/submit_now terminating split
(lets the callback through once terminated, notify_all on manual
ports), completion-port Dispatch waits while pending > 0, Terminate
wait=false queues run_terminated to PORT_COMPLETION (wait=true still
runs inline on the caller). Two upstream tests verbatim.

Linux live twin hle/xtaskqueue_linux.rs mirrors the production hunks
(win64 ABI; no pc() legs exist on the twin): same field, wrapper +
submit(terminating), dispatch pending-wait, Terminate-via-port +
run_terminated (extern win64). One Linux-shaped twin test (manual
completion port, wait=false, callback must not run before Dispatch and
must run on the dispatch thread).

Failing-first: new twin test FAILED pre-fix (callback ran on pool
worker ThreadId(4) before any Dispatch), green post-fix.

Gates: cargo check -p xcl --tests + cargo check --workspace 0 errors;
lib 651/0/1 t=4 (+1); twin 6/6; diff --check clean; lock audit clean
(named guards; dispatch wait binds state in a block dropping before the
body; test lock is a poll-only temporary in the while condition).
Title fresh-root: done failures 12, all D3D12.X GPU-only, 0 non-GPU,
ExitProcess(0xc). Retail fresh-root: SIGSEGV
game_scarlett_master.exe+0x2237320 fault 0x0 exit 139, stubs 20, xgr
exactly XAsync/XNetworking/XUser - HOLDS, M1-RE TERMINAL.
rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
, verbatim Windows + Linux twin)

Live pr805head=e88ee4d1 still OPEN (merge-base false); Windows
hle/xgameruntime/taskqueue.rs hunks hand-applied byte-identical
(cherry-pick -n conflicted at the shared test-site tail: steps-49/50
tests moved the append anchor; production + test hunks verified
identical to the head by direct diff, only line numbers drift).
Fidelity: git diff pr805head shows only steps-49/50 drift
(xcl-dev#1276/xcl-dev#1681 timer, xcl-dev#1154 terminate); pool block + mpsc test import +
new test byte-identical.

Production: fixed clamp(2,8) mpsc pool -> Pool{Mutex<PoolState>,Condvar,
base} + MAX_WORKERS=256 + IDLE_EXIT 30s + worker loop + spawn
wake-idle-else-grow with rollback + notify on spawn failure.
Linux live twin hle/xtaskqueue_linux.rs mirrors the production hunks
(ABI-neutral pool; win64 ABI untouched) + 1 Linux-shaped twin test
(16 blockers + releaser through wait=true Terminate, extern win64).

Failing-first: twin test FAILED pre-fix (7 vs 16, releaser starved on
the fixed 8-worker pool), green post-fix. Gates: both cargo checks 0
errors; lib 652/0/1 t=4 (+1); diff --check clean; lock audit clean
(named g/ng guards, explicit drop before job). Title fresh-root 12
unique FAILs all D3D12.X GPU-only 0 non-GPU (harness FAILs by design,
M2 baseline). Retail fresh-root SIGSEGV game_scarlett_master.exe
+0x2237320 fault 0x0 unmapped exit 139 stubs 20 xgr exactly
XAsync/XNetworking/XUser unimplemented [] - HOLDS, M1-RE TERMINAL.
@futurepro62

Copy link
Copy Markdown

NVIDIA and AMD full-suite run, to go with the reports above by fromthemoonx, since none of them covers AMD. Tested exact head cc8fbcd6 (on its base 47efa2e).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, DXC + dxil.dll 1.9.2602.17 (Windows SDK 10.0.26100), debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4 --skip heap_window_out_of_memory_falls_back_to_the_switch_form --skip gpu::recomp::lower_dxil::tests::f16_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::integer_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::f64_programs_on_the_gpu --skip gpu::recomp::lower_dxil::tests::const_and_null_mask_operands_agree_with_hlsl_on_the_gpu --skip gpu::recomp::lower_dxil::tests::mask_ff0_and_flbit_agree_with_hlsl_on_the_gpu --skip gpu::dxil::fuzz_tests: 743 passed, 0 failed, 41 ignored. SKIPPED (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware.
  • The new tests ran and passed: termination_callback_runs_from_a_manual_completion_port_dispatch, infinite_completion_pump_receives_termination_callback.
  • Same head on the AMD Radeon integrated GPU (iGPU) of the Ryzen 7 9800X3D (RDNA2, XCL_ADAPTER=radeon), cargo test --workspace -- --test-threads=4 --skip gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_1: 743 passed, 0 failed, 41 ignored, no skips.
  • --skip leaves out tests that fail on main b49be183 too, not because of this PR. On NVIDIA: heap_window_out_of_memory_falls_back_to_the_switch_form (Tests: heap_window_out_of_memory_falls_back_to_the_switch_form fails under XCL_REQUIRE_GPU=mesh (opt-in skip counted as missing coverage) #1651), the four gpu::recomp::lower_dxil::tests::*_programs_on_the_gpu tests, const_and_null_mask_operands_agree_with_hlsl_on_the_gpu and mask_ff0_and_flbit_agree_with_hlsl_on_the_gpu (follow-up on #1651) fail because runner::skip_test turns their skips into failures under XCL_REQUIRE_GPU=mesh, and gpu::dxil::fuzz_tests seeds 70, 545, 1019 and 1507 fail CreateComputePipelineState with E_OUTOFMEMORY on this card (drivers 616.64 and 621.40). On AMD: fuzz_validate_and_gpu_1 fails on seed 540 (res[833] 0x7 vs CPU 0x6). The AMD run does not set XCL_REQUIRE_GPU.

Not tested

  • a release build, a game (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: cc8fbcd

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: e429936
head: cc8fbcd
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2128 passed, 9 failed, 48 ignored (26 SKIPPED lines). The 9 failures are main's own at e429936 on this GPU (reported on #3041: they arrive with the merge of #2959); base alone: 2126 passed, 9 failed, 48 ignored.
review: no blocking finding. Lock order is consistent (items, then state; Terminate takes state alone; nothing takes the timer lock while holding either), the pending-callback counter stays balanced, and the private state struct's two constructors are updated. Behaviour to know: with wait=false on a manually pumped completion port the callback now runs only if the title keeps dispatching through a live handle (said to match the reference implementation; not verified here). It applies together with #1681 in either order.
performance: none; not on the frame path.
verdict: safe to merge
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).

@jsalzy

jsalzy commented Nov 30, 2026

Copy link
Copy Markdown

merge-check claim
head: cc8fbcd

@github-actions github-actions Bot added area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) labels Nov 30, 2026
@jsalzy

jsalzy commented Nov 30, 2026

Copy link
Copy Markdown

merge-check
base: 53e85fb
head: cc8fbcd
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2794 passed, 1 failed, 49 ignored; SKIPPED: 28 (22 no wave64 on this GPU; 3 per-lane form refused: V_CVT_F16_F32, V_MUL_F16, V_PK_MUL_F16 (#1426 semantics); 2 no heap windows (opt-in XCL_HEAP_WINDOWS=1); 1 driver cache cannot be disabled without Windows Developer Mode); failing: hle::d3d12x::standin::tests::concurrent_shell_miss_reuses_winner_and_releases_loser_pipeline (standin.rs:459, left (0, 1, 1), right (0, 0, 1)), fails on base too: main alone at 53e85fb gives 2792 passed, 1 failed (same test, same assertion), 49 ignored. The PR's two new tests (termination_callback_runs_from_a_manual_completion_port_dispatch, infinite_completion_pump_receives_termination_callback) pass.
review: no blocking finding; whole diff read (one file). With wait = false the termination callback is now queued to the queue's completion port once its work and completions have drained, instead of running on XCL's worker thread; with wait = true it still runs inline, so a manual port cannot deadlock there. Lock order stays items -> state (dispatch's new wait condition takes the state lock under the port's items lock, as submit does). termination_cb_pending goes up once per async callback in XTaskQueueTerminate and down once when the entry is pushed, and all four port modes take the new path; on immediate and thread-pool completion ports the callback still runs on an XCL thread, as before. Behaviour to know: on a manual completion port the callback now runs only if the title dispatches that port again; if it stops dispatching (or closes its last handle) first, the callback never runs, as with any completion left on an undispatched manual port. The new tests cover only the manual completion port; wait = false on immediate and thread-pool completion ports has no test. Duplicates: none among the open and merged task-queue PRs.
performance: none measurable: one counter under the existing state lock; dispatch takes the state lock once per wake-up while it waits on an empty port.
verdict: safe to merge
hardware / tool and model: RTX 4070 SUPER 12 GB (621.24 / 32.0.16.2124), Ryzen 7 7800X3D, 32 GB, Windows 11 Pro 25H2 26200.9974, Rust 1.100.0, debug / Claude app (Claude Opus 5.5): merge, build and suite run on this PC with git and cargo only; diff review by Claude Opus 5.5.

@github-actions github-actions Bot added ready-to-merge Has 2 independent safe merge-checks on current head (#3041) and removed needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) labels Nov 30, 2026
@Prime1997
Prime1997 merged commit 7f77c44 into xcl-dev:main Nov 30, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH ready-to-merge Has 2 independent safe merge-checks on current head (#3041)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants