HLE: report queue termination after running callbacks #544

Open
github-bot wants to merge 2 commits from github-bot/gh-544 into main AGit
Owner

@⁠Quat3rnion on GitHub · 2026-11-24 04:42 UTC · original
Quat3rnion:victory-queue-terminate → main · +357 −13 · 1 files · 2 commits · open

What

XTaskQueueTerminate called its completion callback immediately even when a
dispatcher had already taken a callback off the queue and was still running
it. The title could then free state the callback still used. The queue now
counts in-flight callbacks: wait=true blocks until they finish, and
wait=false returns immediately with the completion callback deferred to a
thread that waits. Pending callbacks drained during termination go through
the same count, so completion is reported exactly once and only after work
has stopped.

An AI tool wrote part of this change.

Tested

  • Linux: cargo test --workspace: 165 passed, 0 failed, 3 ignored, stable over three runs. A new regression blocks a dispatched callback on a flag, calls Terminate(false), checks the termination callback has not run, releases the worker and checks it is reported once afterwards.
  • Windows cross-build: cargo check --target x86_64-pc-windows-gnu --workspace --tests passes. No Windows host here.
  • cargo xtask policy passes (150 files ok). No game files or data from them were added.

Checklist

  • Workspace tests and Windows cross-check pass.
  • cargo xtask policy passes. No game files or data from them were added.
  • AI authorship is disclosed above.
**@⁠Quat3rnion** on GitHub · 2026-11-24 04:42 UTC · [original](https://github.com/Marvisak/VIctory/pull/544) `Quat3rnion:victory-queue-terminate` → `main` · +357 −13 · 1 files · 2 commits · open ## What `XTaskQueueTerminate` called its completion callback immediately even when a dispatcher had already taken a callback off the queue and was still running it. The title could then free state the callback still used. The queue now counts in-flight callbacks: `wait=true` blocks until they finish, and `wait=false` returns immediately with the completion callback deferred to a thread that waits. Pending callbacks drained during termination go through the same count, so completion is reported exactly once and only after work has stopped. An AI tool wrote part of this change. ## Tested - Linux: `cargo test --workspace`: 165 passed, 0 failed, 3 ignored, stable over three runs. A new regression blocks a dispatched callback on a flag, calls `Terminate(false)`, checks the termination callback has not run, releases the worker and checks it is reported once afterwards. - Windows cross-build: `cargo check --target x86_64-pc-windows-gnu --workspace --tests` passes. No Windows host here. - `cargo xtask policy` passes (150 files ok). No game files or data from them were added. ## Checklist - [x] Workspace tests and Windows cross-check pass. - [x] `cargo xtask policy` passes. No game files or data from them were added. - [x] AI authorship is disclosed above.
XTaskQueueTerminate called its completion callback immediately even when a dispatcher had already taken a callback off the queue and was still running it, letting the title free state too early. Count in-flight callbacks per queue; with wait, block until idle, otherwise defer the termination callback to a thread that waits. Pending callbacks are run through the same count. Add a regression that blocks a dispatched callback and checks termination is reported once, after it finishes.
A shared tracker counts callbacks submitted to manual, thread-pool, serialized and immediate ports. Tasks are counted under the port lock before a dispatcher can observe them gone, and wait=true waits even without a termination callback. Termination from inside a callback no longer waits for itself.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:07:49 +00:00
Author
Owner

@⁠geiyiliyabumo on GitHub · 2026-11-24 11:45 UTC · original

Independent verification & code review on Windows 11 Pro (build 26100, Rust 1.98.1), cleanly merged onto main (ffe310e):

  • cargo xtask policy: PASS (154 files ok)
  • cargo clippy -p victory-hle --all-targets --locked -- -D warnings: PASS
  • cargo clippy -p victory-hle --all-targets --features diagnostics --locked -- -D warnings: PASS
  • cargo test -p victory-hle --locked: 95 passed + 1 integration test (no_dll_planting), 0 failed (including new termination_waits_for_a_running_callback)

Concurrency findings (crates/victory-hle/src/modules/xasync.rs)

  1. wait == true is ignored when callback is None: if wait { queue.wait_idle(); ... } is placed inside if let Some(callback) = callback. Calling XTaskQueueTerminate(q, true, null, None) (a common synchronous drain pattern) returns immediately without waiting for in-flight callbacks. Moving if wait { queue.wait_idle(); } ahead of if let Some(callback) = callback fixes this.
  2. Only Mode::Manual callbacks are tracked in queue.running: Mode::ThreadPool (POOL.work), Mode::Serialized (its own worker loop), and Mode::Immediate all call task.run(false) directly without going through queue.run(), so XTaskQueueTerminate can still report completion while non-manual callbacks are running.
  3. TOCTOU window between port.take() and queue.run(): In XTaskQueueDispatch, port.take() releases port.tasks before queue.run() increments queue.running. If XTaskQueueTerminate runs in that gap, it drains an empty port.tasks, observes running == 0, and fires the termination callback before the popped task even starts. Incrementing running before releasing port.tasks (or tracking in-flight count on Port) closes that window.

AI-assisted; synthetic tests only, no game files.

**@⁠geiyiliyabumo** on GitHub · 2026-11-24 11:45 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7130511802) Independent verification & code review on Windows 11 Pro (build 26100, Rust `1.98.1`), cleanly merged onto `main` (`ffe310e`): - `cargo xtask policy`: PASS (`154 files ok`) - `cargo clippy -p victory-hle --all-targets --locked -- -D warnings`: PASS - `cargo clippy -p victory-hle --all-targets --features diagnostics --locked -- -D warnings`: PASS - `cargo test -p victory-hle --locked`: **95 passed + 1 integration test (`no_dll_planting`), 0 failed** (including new `termination_waits_for_a_running_callback`) ### Concurrency findings (`crates/victory-hle/src/modules/xasync.rs`) 1. **`wait == true` is ignored when `callback` is `None`**: `if wait { queue.wait_idle(); ... }` is placed inside `if let Some(callback) = callback`. Calling `XTaskQueueTerminate(q, true, null, None)` (a common synchronous drain pattern) returns immediately without waiting for in-flight callbacks. Moving `if wait { queue.wait_idle(); }` ahead of `if let Some(callback) = callback` fixes this. 2. **Only `Mode::Manual` callbacks are tracked in `queue.running`**: `Mode::ThreadPool` (`POOL.work`), `Mode::Serialized` (its own worker loop), and `Mode::Immediate` all call `task.run(false)` directly without going through `queue.run()`, so `XTaskQueueTerminate` can still report completion while non-manual callbacks are running. 3. **TOCTOU window between `port.take()` and `queue.run()`**: In `XTaskQueueDispatch`, `port.take()` releases `port.tasks` before `queue.run()` increments `queue.running`. If `XTaskQueueTerminate` runs in that gap, it drains an empty `port.tasks`, observes `running == 0`, and fires the termination callback before the popped task even starts. Incrementing `running` before releasing `port.tasks` (or tracking in-flight count on `Port`) closes that window. *AI-assisted; synthetic tests only, no game files.*
Author
Owner

@⁠fromthemoonx on GitHub · 2026-11-24 11:48 UTC · original

One case to add to @⁠geiyiliyabumo's list. Tested 2a55463 merged onto main ffe310e; Windows 11 Pro 26300, Ryzen 7 5700X, Rust 1.98.1 x86_64-pc-windows-msvc.

Terminate(wait = true) from a callback on the same queue never returns. The dispatched callback is counted in running by queue.run, and wait_idle then waits for running to reach 0, which includes itself. A throwaway test (not pushed) submits a callback that calls XTaskQueueTerminate on its own queue and dispatches it from another thread:

callback calls result (3 s limit)
XTaskQueueTerminate(q, true, null, Some(done)) does not return: the dispatcher thread is stuck in wait_idle
XTaskQueueTerminate(q, true, null, None) returns, but only because wait is skipped without a callback (point 1 above)

So once point 1 is fixed, both forms deadlock. On main the call returns, since wait is ignored there. A game may well terminate a queue from one of its own completion callbacks (for example when an async operation finishes and its owner is torn down). One option is to note the dispatching thread's queue in a thread-local inside queue.run, and not wait for that one callback when Terminate is called from it.

The race between port.take() and the running increment that I'd also noticed is point 3 above, so I won't repeat it.

AI-assisted (Claude Code); synthetic test only, no game data.

**@⁠fromthemoonx** on GitHub · 2026-11-24 11:48 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7130570226) One case to add to @⁠geiyiliyabumo's list. Tested `2a55463` merged onto `main` `ffe310e`; Windows 11 Pro 26300, Ryzen 7 5700X, Rust 1.98.1 `x86_64-pc-windows-msvc`. **`Terminate(wait = true)` from a callback on the same queue never returns.** The dispatched callback is counted in `running` by `queue.run`, and `wait_idle` then waits for `running` to reach 0, which includes itself. A throwaway test (not pushed) submits a callback that calls `XTaskQueueTerminate` on its own queue and dispatches it from another thread: | callback calls | result (3 s limit) | |---|---| | `XTaskQueueTerminate(q, true, null, Some(done))` | **does not return**: the dispatcher thread is stuck in `wait_idle` | | `XTaskQueueTerminate(q, true, null, None)` | returns, but only because `wait` is skipped without a callback (point 1 above) | So once point 1 is fixed, both forms deadlock. On `main` the call returns, since `wait` is ignored there. A game may well terminate a queue from one of its own completion callbacks (for example when an async operation finishes and its owner is torn down). One option is to note the dispatching thread's queue in a thread-local inside `queue.run`, and not wait for that one callback when `Terminate` is called from it. The race between `port.take()` and the `running` increment that I'd also noticed is point 3 above, so I won't repeat it. AI-assisted (Claude Code); synthetic test only, no game data.
Author
Owner

@⁠Quat3rnion on GitHub · 2026-11-24 14:26 UTC · original

@⁠geiyiliyabumo @⁠fromthemoonx Thanks for the detailed concurrency review. New head f8b3cfa9 fixes all four points:

  1. wait=true now waits before the callback check, so it also drains when callback is None.
  2. A Tracker shared by every Task counts callbacks from all modes (manual, thread pool, serialized and immediate), not just manual dispatch.
  3. Task::begin() runs while the port lock is held (in Port::take and while draining on terminate), closing the take-to-run window.
  4. wait_idle() ignores callbacks running on the calling thread via a thread-local scope, so Terminate(wait=true) from inside a queue callback returns instead of deadlocking; a scope guard also ends the slot on unwind.

Added regressions for wait-without-callback, termination from an own callback, and thread-pool callback tracking. cargo test --workspace --no-fail-fast: 222 passed, 0 failed (11 xasync tests). Would appreciate a re-check.

**@⁠Quat3rnion** on GitHub · 2026-11-24 14:26 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7134371102) @⁠geiyiliyabumo @⁠fromthemoonx Thanks for the detailed concurrency review. New head `f8b3cfa9` fixes all four points: 1. `wait=true` now waits before the `callback` check, so it also drains when `callback` is `None`. 2. A `Tracker` shared by every `Task` counts callbacks from all modes (manual, thread pool, serialized and immediate), not just manual dispatch. 3. `Task::begin()` runs while the port lock is held (in `Port::take` and while draining on terminate), closing the take-to-run window. 4. `wait_idle()` ignores callbacks running on the calling thread via a thread-local scope, so `Terminate(wait=true)` from inside a queue callback returns instead of deadlocking; a scope guard also ends the slot on unwind. Added regressions for wait-without-callback, termination from an own callback, and thread-pool callback tracking. `cargo test --workspace --no-fail-fast`: 222 passed, 0 failed (11 xasync tests). Would appreciate a re-check.
Author
Owner

@⁠Quat3rnion on GitHub · 2026-11-24 14:27 UTC · original

One more edge case covered in the same head: nested callbacks on one thread. wait_idle() now leaves a slot for each callback running on the calling thread (not just one), with a regression terminate_from_nested_callbacks_does_not_wait_on_itself. 12 xasync tests pass.

**@⁠Quat3rnion** on GitHub · 2026-11-24 14:27 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7134400285) One more edge case covered in the same head: nested callbacks on one thread. `wait_idle()` now leaves a slot for each callback running on the calling thread (not just one), with a regression `terminate_from_nested_callbacks_does_not_wait_on_itself`. 12 xasync tests pass.
Author
Owner

@⁠geiyiliyabumo on GitHub · 2026-11-24 14:33 UTC · original

Re-verified new head f861613 merged onto main ffe310e on Windows 11 x64 MSVC:

Checks Run

  • cargo xtask policy: PASS (154 files ok)
  • cargo test -p victory-hle --locked -- xasync: PASS (12/12 tests)
  • cargo clippy -p victory-hle --all-targets --locked -- -D warnings: FAIL (3 errors)

Findings to Fix Before Merge

1. Three clippy -D warnings CI blockers

  • crates/victory-hle/src/modules/xasync.rs:104: clippy::ptr_eq — replace **p == self as *const Tracker with std::ptr::eq(**p, self) (and same in CallbackScope::drop).
  • crates/victory-hle/src/modules/xasync.rs:1550 and :1657: clippy::undocumented_unsafe_blocks — add // SAFETY: comments above both unsafe { (*context).0.load(Ordering::SeqCst) } loops in the new tests.

2. Two remaining subtle deadlock cases in Tracker / CallbackScope

The overall Tracker + Task::begin() under port lock + thread-local IN_CALLBACK design is much cleaner and fixes all 4 previous issues, but two edge cases in the new tracking code can still hang:

  1. Tracker::end() only notifies when *running == 0 (xasync.rs:90-96):
    • Suppose Thread A is inside a callback on queue Q (own = 1), Thread B is simultaneously running another callback on Q (running = 2), and Thread A calls XTaskQueueTerminate(Q, true, ...).
    • Thread A sleeps in wait_idle() waiting for *n <= own (1). When Thread B finishes, *running drops 2 -> 1, which skips if *running == 0 { self.idle.notify_all(); }, leaving Thread A parked forever.
    • Fix: Call self.idle.notify_all() whenever *running is decremented (not only at 0).
  2. CallbackScope::drop removes all matching entries via retain (xasync.rs:127-131):
    • In nested callbacks on the same queue (IN_CALLBACK = [T, T]), when the inner callback returns, v.borrow_mut().retain(|p| *p != ptr) strips both entries. If the outer callback subsequently calls XTaskQueueTerminate(Q, true, ...), own evaluates to 0 while running == 1, deadlocking on itself.
    • Fix: Remove only a single matching entry (e.g., if let Some(i) = v.iter().rposition(|p| std::ptr::eq(*p, ptr)) { v.remove(i); }).

AI-assisted; synthetic tests only, no game files.

**@⁠geiyiliyabumo** on GitHub · 2026-11-24 14:33 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7134582419) Re-verified new head `f861613` merged onto `main` `ffe310e` on Windows 11 x64 MSVC: ### Checks Run - `cargo xtask policy`: **PASS** (`154 files ok`) - `cargo test -p victory-hle --locked -- xasync`: **PASS** (`12/12` tests) - `cargo clippy -p victory-hle --all-targets --locked -- -D warnings`: **FAIL** (3 errors) ### Findings to Fix Before Merge #### 1. Three `clippy -D warnings` CI blockers - `crates/victory-hle/src/modules/xasync.rs:104`: `clippy::ptr_eq` — replace `**p == self as *const Tracker` with `std::ptr::eq(**p, self)` (and same in `CallbackScope::drop`). - `crates/victory-hle/src/modules/xasync.rs:1550` and `:1657`: `clippy::undocumented_unsafe_blocks` — add `// SAFETY:` comments above both `unsafe { (*context).0.load(Ordering::SeqCst) }` loops in the new tests. #### 2. Two remaining subtle deadlock cases in `Tracker` / `CallbackScope` The overall `Tracker` + `Task::begin()` under port lock + thread-local `IN_CALLBACK` design is much cleaner and fixes all 4 previous issues, but two edge cases in the new tracking code can still hang: 1. **`Tracker::end()` only notifies when `*running == 0` (`xasync.rs:90-96`)**: - Suppose Thread A is inside a callback on queue `Q` (`own = 1`), Thread B is simultaneously running another callback on `Q` (`running = 2`), and Thread A calls `XTaskQueueTerminate(Q, true, ...)`. - Thread A sleeps in `wait_idle()` waiting for `*n <= own` (`1`). When Thread B finishes, `*running` drops `2 -> 1`, which skips `if *running == 0 { self.idle.notify_all(); }`, leaving Thread A parked forever. - **Fix**: Call `self.idle.notify_all()` whenever `*running` is decremented (not only at `0`). 2. **`CallbackScope::drop` removes all matching entries via `retain` (`xasync.rs:127-131`)**: - In nested callbacks on the same queue (`IN_CALLBACK = [T, T]`), when the inner callback returns, `v.borrow_mut().retain(|p| *p != ptr)` strips **both** entries. If the outer callback subsequently calls `XTaskQueueTerminate(Q, true, ...)`, `own` evaluates to `0` while `running == 1`, deadlocking on itself. - **Fix**: Remove only a single matching entry (e.g., `if let Some(i) = v.iter().rposition(|p| std::ptr::eq(*p, ptr)) { v.remove(i); }`). *AI-assisted; synthetic tests only, no game files.*
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 00:24 UTC · original

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: crates/victory-hle/src/modules/xasync.rs.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 00:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/544#issuecomment-7148483089) <!-- victory-triage v1 head=f861613328da95ffb4d004384d589e80ca61c6af verdict=needs-rebase at=2026-11-25T00:13:20Z --> Automated triage for the maintainers. **Needs rebase.** This PR does not merge cleanly into current `main` (ac2525d). Conflicting files: `crates/victory-hle/src/modules/xasync.rs`. The content has not been reviewed yet; it will be once the branch is rebased onto `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
This pull request has changes conflicting with the target branch.
  • crates/victory-hle/src/modules/xasync.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/544/head:github-bot/gh-544'
git switch 'github-bot/gh-544'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-544'
git switch 'github-bot/gh-544'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-544'
git switch 'github-bot/gh-544'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-544'
git switch 'main'
git merge --squash 'github-bot/gh-544'
git switch 'main'
git merge --ff-only 'github-bot/gh-544'
git switch 'main'
git merge 'github-bot/gh-544'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!544
No description provided.