gdk rt: fix XTaskQueue handle duplication, pool dispatch, monitors, close, and manual terminate wakeup (6 conformance scenarios) #307

Closed
github-bot wants to merge 2 commits from gh-pr/307/head into gh-pr/307/base
Owner

@⁠Bexx1107 on GitHub · 2026-11-23 17:30 UTC · original
Bexx1107:fix/xtq-port-dispatch-handles → main · +309 −131 · 2 files · 2 commits · closed without merging

Library / area: compat-common, GDK runtime task queues (crates/compat/compat-common/src/gdk/rt.rs), conformance table (crates/compat/compat-common/tests/gdk_xtaskqueue_conformance.rs)

Exports changed (exports.txt rows): none

Source of the behaviour: existing conformance scenarios in crates/compat/compat-common/tests/support/xtq.rs (verified against local PC xgameruntime.dll via gdk_xtaskqueue_conformance_real) and the Win32 Thread Pool API (TrySubmitThreadpoolCallback / CallbackMayRunLong). Rewritten cleanly in Rust; no game/console files or binaries included.

Scoped to avoid overlapping open PRs #210, #270, and #271 (does not alter AState/XAsync wait/completion state, XTaskQueueRegisterWaiter/UnregisterWaiter, or two-phase termination, and does not edit docs/BLOCKERS.md).

Changes (src/gdk/rt.rs)

  • Distinct duplicated queue handles (verify_duplicate_queue_handle): track open handles in a global handle table keyed by unique heap-allocated handle tokens (alloc_handle / close_handle) referencing Arc<Queue>. XTaskQueueDuplicateHandle returns a distinct handle per call, XTaskQueueGetCurrentProcessTaskQueue / XTaskQueueSetCurrentProcessTaskQueue manage distinct handle tokens cleanly, and invalid pointers fail validation without raw dereferencing.
  • Shared-port queue monitors (verify_queue_monitor_has_correct_ports): store monitors keyed by Queue::id() with (target_port_ptr, handle, Weak<Queue>) and include the submitted port in submit_tagged / submit_marker. Port::notify invokes all registered monitors attached to that Port, passing each queue its own live handle and registered port.
  • Thread-pool concurrency & pool-port dispatch (verify_thread_pool_callbacks_can_block, verify_dispatch_on_pool_port): replace the fixed 2–8 worker Pool with Win32 TrySubmitThreadpoolCallback + CallbackMayRunLong (falling back to std::thread::spawn if Win32 submission fails) draining Port::items via Port::drain_one, and allow q_dispatch to pop from all non-IMMEDIATE ports (MANUAL, THREAD_POOL, SERIALIZED).
  • Manual INFINITE dispatch wakeup on terminate (verify_multithread_manual_dispatch): add Port::terminate() (called only when qq.owns) and break out of Port::dispatch when items is empty and self.terminated is set, while composite termination leaves the underlying shared port running.
  • Close keeps queued callbacks (verify_close_keeps_queued_callbacks): stop calling cancel_all() inside Port::release() so closing the last handle lets already-queued and delayed callbacks complete non-canceled before idle serialized workers exit. Updated port_tests::serialized_worker_exits_after_last_user_releases_the_port and added port_tests::released_serialized_port_runs_queued_callbacks_then_exits.

Rows removed from DIFFERS (6, 13 remain)

  • verify_close_keeps_queued_callbacks
  • verify_dispatch_on_pool_port
  • verify_duplicate_queue_handle
  • verify_multithread_manual_dispatch
  • verify_queue_monitor_has_correct_ports
  • verify_thread_pool_callbacks_can_block

Tests (after final edit)

  • cargo test -p compat-common --lib gdk::rt::port_tests: 5 passed, 0 failed

  • cargo test -p compat-common --test gdk_xtaskqueue_conformance: 5 consecutive debug runs passed (61 passed, 0 failed each) + release run passed (61 passed, 0 failed). (Note: an earlier pre-rerun batch hit the pre-existing verify_simple_async_call XAsyncGetStatus(wait) race once on run 2; verify_simple_async_call passed 20/20 standalone — that wait-vs-callback ordering is addressed separately in open PR #210.)

  • cargo test -p compat-common --test gdk_xtaskqueue_conformance_real: 61 passed, 0 failed (debug and release)

  • cargo test -p compat-common --lib: 148 passed, 0 failed, 1 ignored

  • python .github/scripts/pr_gate.py --base main --head HEAD: 2 file(s) checked, 0 problem(s)

  • cargo test -p compat-common passes for the targets listed above

  • No game or console files and no binaries included

  • No fake success; anything not possible is left missing with a note

**@⁠Bexx1107** on GitHub · 2026-11-23 17:30 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307) `Bexx1107:fix/xtq-port-dispatch-handles` → `main` · +309 −131 · 2 files · 2 commits · closed without merging **Library / area:** `compat-common`, GDK runtime task queues (`crates/compat/compat-common/src/gdk/rt.rs`), conformance table (`crates/compat/compat-common/tests/gdk_xtaskqueue_conformance.rs`) **Exports changed (exports.txt rows):** none **Source of the behaviour:** existing conformance scenarios in `crates/compat/compat-common/tests/support/xtq.rs` (verified against local PC `xgameruntime.dll` via `gdk_xtaskqueue_conformance_real`) and the Win32 Thread Pool API (`TrySubmitThreadpoolCallback` / `CallbackMayRunLong`). Rewritten cleanly in Rust; no game/console files or binaries included. Scoped to avoid overlapping open PRs `#210`, `#270`, and `#271` (does not alter `AState`/`XAsync` wait/completion state, `XTaskQueueRegisterWaiter`/`UnregisterWaiter`, or two-phase termination, and does not edit `docs/BLOCKERS.md`). ### Changes (`src/gdk/rt.rs`) - **Distinct duplicated queue handles (`verify_duplicate_queue_handle`):** track open handles in a global handle table keyed by unique heap-allocated handle tokens (`alloc_handle` / `close_handle`) referencing `Arc<Queue>`. `XTaskQueueDuplicateHandle` returns a distinct handle per call, `XTaskQueueGetCurrentProcessTaskQueue` / `XTaskQueueSetCurrentProcessTaskQueue` manage distinct handle tokens cleanly, and invalid pointers fail validation without raw dereferencing. - **Shared-port queue monitors (`verify_queue_monitor_has_correct_ports`):** store monitors keyed by `Queue::id()` with `(target_port_ptr, handle, Weak<Queue>)` and include the submitted port in `submit_tagged` / `submit_marker`. `Port::notify` invokes all registered monitors attached to that `Port`, passing each queue its own live handle and registered port. - **Thread-pool concurrency & pool-port dispatch (`verify_thread_pool_callbacks_can_block`, `verify_dispatch_on_pool_port`):** replace the fixed 2–8 worker `Pool` with Win32 `TrySubmitThreadpoolCallback` + `CallbackMayRunLong` (falling back to `std::thread::spawn` if Win32 submission fails) draining `Port::items` via `Port::drain_one`, and allow `q_dispatch` to pop from all non-`IMMEDIATE` ports (`MANUAL`, `THREAD_POOL`, `SERIALIZED`). - **Manual `INFINITE` dispatch wakeup on terminate (`verify_multithread_manual_dispatch`):** add `Port::terminate()` (called only when `qq.owns`) and break out of `Port::dispatch` when `items` is empty and `self.terminated` is set, while composite termination leaves the underlying shared port running. - **Close keeps queued callbacks (`verify_close_keeps_queued_callbacks`):** stop calling `cancel_all()` inside `Port::release()` so closing the last handle lets already-queued and delayed callbacks complete non-canceled before idle serialized workers exit. Updated `port_tests::serialized_worker_exits_after_last_user_releases_the_port` and added `port_tests::released_serialized_port_runs_queued_callbacks_then_exits`. ### Rows removed from `DIFFERS` (6, 13 remain) - `verify_close_keeps_queued_callbacks` - `verify_dispatch_on_pool_port` - `verify_duplicate_queue_handle` - `verify_multithread_manual_dispatch` - `verify_queue_monitor_has_correct_ports` - `verify_thread_pool_callbacks_can_block` ### Tests (after final edit) - `cargo test -p compat-common --lib gdk::rt::port_tests`: 5 passed, 0 failed - `cargo test -p compat-common --test gdk_xtaskqueue_conformance`: 5 consecutive debug runs passed (61 passed, 0 failed each) + release run passed (61 passed, 0 failed). *(Note: an earlier pre-rerun batch hit the pre-existing `verify_simple_async_call` `XAsyncGetStatus(wait)` race once on run 2; `verify_simple_async_call` passed 20/20 standalone — that wait-vs-callback ordering is addressed separately in open PR `#210`.)* - `cargo test -p compat-common --test gdk_xtaskqueue_conformance_real`: 61 passed, 0 failed (debug and release) - `cargo test -p compat-common --lib`: 148 passed, 0 failed, 1 ignored - `python .github/scripts/pr_gate.py --base main --head HEAD`: `2 file(s) checked, 0 problem(s)` - [x] `cargo test -p compat-common` passes for the targets listed above - [x] No game or console files and no binaries included - [x] No fake success; anything not possible is left `missing` with a note
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 06:18:03 +00:00
github-bot closed this pull request 2026-11-26 06:18:03 +00:00
Author
Owner

@⁠QuentinDanblon on GitHub · 2026-11-23 18:08 UTC · original

This overlaps #270 (mine) in rt.rs (q_terminate, submit_marker, flush_timers, resolve), so I checked both against a public reference: microsoft/libHttpClient (MIT) ships a full XTaskQueue/XAsync implementation and its unit tests, at commit c5007fd9. It is not xgameruntime.dll, so where it disagrees with a PC measurement the measurement wins; here they agree.

Where this PR matches the reference:

  • Duplicate returns a distinct handle per call (USE_UNIQUE_HANDLES, test VerifyDuplicateQueueHandle).
  • Closing the last handle does not cancel queued or delayed callbacks: entries hold a reference on the queue (TaskQueue.cpp L479-L544).
  • Monitors are per port context, each queue gets its own handle and port (L276-L294, test VerifyQueueMonitorHasCorrectPorts).

One point to adjust, Dispatch(INFINITE) exiting at termination: the reference exits when the dispatching queue's port context reaches Terminated with its port empty (L836-L923), which happens only after the termination marker has run on that port. If the exit flag is raised when XTaskQueueTerminate is called, a manual queue dispatched by a single thread can leave before the marker runs, and the termination callback never fires (test VerifyManualDispatchAtTermination). A dispatch on a composite handle should also end with the composite, not with the shared port.

On the termination order itself, #270's two-phase model (work port refuses at once with E_ABORT, completion port accepts until the work marker has run, delayed entries and waiters run canceled at the end) is what the reference does (L2254-L2318, L2359-L2410) and what #270 measured on the PC runtime. #270 also confirms from the reference its two points it had left unverified (waiter handle not duplicated; WAIT_ABANDONED ignored and not rearmed, L1902-L1916).

So a merge order that keeps both: #270 first, then this PR rebased so the dispatch exit keys on the port context status that #270 sets, and release() still drops wait registrations (no callback) but nothing else. If it helps, I can do that rebase on top of #270 in a branch you can pull, or adapt #270 to whatever you prefer. In #270, waiters should then be keyed by the queue identity rather than the handle, since handles become distinct per duplicate here.

**@⁠QuentinDanblon** on GitHub · 2026-11-23 18:08 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307#issuecomment-7109705409) This overlaps #270 (mine) in `rt.rs` (`q_terminate`, `submit_marker`, `flush_timers`, `resolve`), so I checked both against a public reference: microsoft/libHttpClient (MIT) ships a full XTaskQueue/XAsync implementation and its unit tests, at commit [c5007fd9](https://github.com/microsoft/libHttpClient/tree/c5007fd9cbdc785518ea6dccc5751b125d451cc1/Source/Task). It is not `xgameruntime.dll`, so where it disagrees with a PC measurement the measurement wins; here they agree. Where this PR matches the reference: - Duplicate returns a distinct handle per call (`USE_UNIQUE_HANDLES`, test `VerifyDuplicateQueueHandle`). - Closing the last handle does not cancel queued or delayed callbacks: entries hold a reference on the queue ([TaskQueue.cpp L479-L544](https://github.com/microsoft/libHttpClient/blob/c5007fd9cbdc785518ea6dccc5751b125d451cc1/Source/Task/TaskQueue.cpp#L479-L544)). - Monitors are per port context, each queue gets its own handle and port ([L276-L294](https://github.com/microsoft/libHttpClient/blob/c5007fd9cbdc785518ea6dccc5751b125d451cc1/Source/Task/TaskQueue.cpp#L276-L294), test `VerifyQueueMonitorHasCorrectPorts`). One point to adjust, `Dispatch(INFINITE)` exiting at termination: the reference exits when the *dispatching queue's port context* reaches `Terminated` with its port empty ([L836-L923](https://github.com/microsoft/libHttpClient/blob/c5007fd9cbdc785518ea6dccc5751b125d451cc1/Source/Task/TaskQueue.cpp#L836-L923)), which happens only after the termination marker has run on that port. If the exit flag is raised when `XTaskQueueTerminate` is called, a manual queue dispatched by a single thread can leave before the marker runs, and the termination callback never fires (test `VerifyManualDispatchAtTermination`). A dispatch on a composite handle should also end with the composite, not with the shared port. On the termination order itself, #270's two-phase model (work port refuses at once with `E_ABORT`, completion port accepts until the work marker has run, delayed entries and waiters run canceled at the end) is what the reference does ([L2254-L2318, L2359-L2410](https://github.com/microsoft/libHttpClient/blob/c5007fd9cbdc785518ea6dccc5751b125d451cc1/Source/Task/TaskQueue.cpp#L2254-L2410)) and what #270 measured on the PC runtime. #270 also confirms from the reference its two points it had left unverified (waiter handle not duplicated; `WAIT_ABANDONED` ignored and not rearmed, L1902-L1916). So a merge order that keeps both: #270 first, then this PR rebased so the dispatch exit keys on the port context status that #270 sets, and `release()` still drops wait registrations (no callback) but nothing else. If it helps, I can do that rebase on top of #270 in a branch you can pull, or adapt #270 to whatever you prefer. In #270, waiters should then be keyed by the queue identity rather than the handle, since handles become distinct per duplicate here.
Author
Owner

@⁠Bexx1107 on GitHub · 2026-11-23 18:23 UTC · original

Thanks @⁠QuentinDanblon for checking this against libHttpClient and catching that Dispatch(INFINITE) edge case!

Pushed follow-up commit 558b6ff to fix it before the rebase:

  • Queue now holds per-queue per-port exit flags (port_done: [Arc<AtomicBool>; 2]), flipped only when each port's termination marker runs (forward on the work port, deliver / done on the completion port) and wakes waiting dispatchers via Port::wake(), while Port::terminated remains for submit rejection and canceled execution.
  • q_dispatch passes &qq.port_done[port as usize] so a manual queue's completion dispatcher waits until the completion marker runs, and terminating a composite ends Dispatch(INFINITE) on that composite without affecting dispatchers on the shared base port.
  • Added two regression tests in port_tests: manual_completion_infinite_dispatch_waits_for_termination_marker and composite_infinite_dispatch_exits_when_composite_terminates_without_stopping_base.

Checked on 558b6ff:

  • cargo test -p compat-common --lib gdk::rt::port_tests: 7 passed, 0 failed
  • cargo test -p compat-common --test gdk_xtaskqueue_conformance: 5 debug runs + 1 release run, 61 passed, 0 failed each
  • cargo test -p compat-common --test gdk_xtaskqueue_conformance_real: 61 passed, 0 failed
  • cargo test -p compat-common --lib: 150 passed, 0 failed, 1 ignored
  • python .github/scripts/pr_gate.py --base main --head HEAD: 2 file(s) checked, 0 problem(s)

Your merge plan makes total sense — let's land #270 first, and I'm happy to rebase #307 onto #270 once it's in (keying dispatch exit on #270's port-context status and keeping #270's wait-registration cleanup in release()). Keying #270's waiters by Queue::id() instead of the handle pointer aligns both cleanly.

**@⁠Bexx1107** on GitHub · 2026-11-23 18:23 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307#issuecomment-7110094069) Thanks @⁠QuentinDanblon for checking this against `libHttpClient` and catching that `Dispatch(INFINITE)` edge case! Pushed follow-up commit `558b6ff` to fix it before the rebase: - `Queue` now holds per-queue per-port exit flags (`port_done: [Arc<AtomicBool>; 2]`), flipped only when each port's termination marker runs (`forward` on the work port, `deliver` / `done` on the completion port) and wakes waiting dispatchers via `Port::wake()`, while `Port::terminated` remains for submit rejection and canceled execution. - `q_dispatch` passes `&qq.port_done[port as usize]` so a manual queue's completion dispatcher waits until the completion marker runs, and terminating a composite ends `Dispatch(INFINITE)` on that composite without affecting dispatchers on the shared base port. - Added two regression tests in `port_tests`: `manual_completion_infinite_dispatch_waits_for_termination_marker` and `composite_infinite_dispatch_exits_when_composite_terminates_without_stopping_base`. Checked on `558b6ff`: - `cargo test -p compat-common --lib gdk::rt::port_tests`: 7 passed, 0 failed - `cargo test -p compat-common --test gdk_xtaskqueue_conformance`: 5 debug runs + 1 release run, 61 passed, 0 failed each - `cargo test -p compat-common --test gdk_xtaskqueue_conformance_real`: 61 passed, 0 failed - `cargo test -p compat-common --lib`: 150 passed, 0 failed, 1 ignored - `python .github/scripts/pr_gate.py --base main --head HEAD`: 2 file(s) checked, 0 problem(s) Your merge plan makes total sense — let's land `#270` first, and I'm happy to rebase `#307` onto `#270` once it's in (keying dispatch exit on `#270`'s port-context status and keeping `#270`'s wait-registration cleanup in `release()`). Keying `#270`'s waiters by `Queue::id()` instead of the handle pointer aligns both cleanly.
Author
Owner

@⁠QuentinDanblon on GitHub · 2026-11-23 18:33 UTC · original

Thanks, 558b6ff matches the reference on that point. Agreed on the order. On main a duplicated handle is the same pointer as the queue, so #270's waiters keyed by handle are correct there; Queue::id() only exists once this PR lands, so the re-key fits best in your rebase onto #270. If you would rather I do it in #270 first with a stand-in identity, say so and I will push it.

**@⁠QuentinDanblon** on GitHub · 2026-11-23 18:33 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307#issuecomment-7110321944) Thanks, `558b6ff` matches the reference on that point. Agreed on the order. On main a duplicated handle is the same pointer as the queue, so #270's waiters keyed by handle are correct there; `Queue::id()` only exists once this PR lands, so the re-key fits best in your rebase onto #270. If you would rather I do it in #270 first with a stand-in identity, say so and I will push it.
Author
Owner

@⁠Bexx1107 on GitHub · 2026-11-23 18:52 UTC · original

Sounds good — leave #270 as-is and I'll handle the waiter re-key to Queue::id() when rebasing #307 onto #270 once it lands.

**@⁠Bexx1107** on GitHub · 2026-11-23 18:52 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307#issuecomment-7110770289) Sounds good — leave #270 as-is and I'll handle the waiter re-key to Queue::id() when rebasing #307 onto #270 once it lands.
Author
Owner

@⁠omonkeyz on GitHub · 2026-11-25 13:49 UTC · original

Applied on main in ba8e0e5 (cherry-picked onto the current history with your authorship kept; comment lines stripped per CONTRIBUTING). Thank you.

**@⁠omonkeyz** on GitHub · 2026-11-25 13:49 UTC · [original](https://github.com/omonkeyz/xbox-emulator/pull/307#issuecomment-7164334915) Applied on main in ba8e0e5 (cherry-picked onto the current history with your authorship kept; comment lines stripped per CONTRIBUTING). Thank you.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.