GPU: two frame waits that wake together take two ticks #357

Closed
JordanFableFur wants to merge 2 commits from upstream-pr/357 into main
JordanFableFur commented 2026-11-24 23:50:32 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by JordanFableFur on 2026-11-24T23:50:32Z.


What

Two waits for one event kind could both end on the same tick: each computed the next tick, slept, and raised last with fetch_max without looking at what it returned, so both reported S_OK on one tick — an event happening once per tick handed two waiters the same one.

A wait now claims its tick through fetch_max's previous value. One that lost the race waits again on the next tick, with what it has already slept taken off its time-out, so the caller's deadline does not stretch and the retry does not extend it.

Fixes #244.

Testing

A regression starts two flip waits together and asserts both return S_OK and that the next tick after the run is the one after both (each took its own tick). The existing single-waiter test is unchanged and passes.

Validated on Windows CI (fork-run of the repository workflow): clippy both builds and the full test suite pass: https://github.com/JordanFableFur/victory-fork/actions/runs/45513129011

AI use: written with Codex and Claude Code (GPT-5.2 Codex); reviewed and posted with my approval. No game files were used.

<!-- greyfinch-sync:fxceless/victory-fork:issue:6593813258 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357). Originally posted by [JordanFableFur](https://github.com/JordanFableFur) on 2026-11-24T23:50:32Z. --- ## What Two waits for one event kind could both end on the same tick: each computed the next tick, slept, and raised `last` with `fetch_max` without looking at what it returned, so both reported `S_OK` on one tick — an event happening once per tick handed two waiters the same one. A wait now claims its tick through `fetch_max`'s previous value. One that lost the race waits again on the next tick, with what it has already slept taken off its time-out, so the caller's deadline does not stretch and the retry does not extend it. Fixes #244. ## Testing A regression starts two flip waits together and asserts both return `S_OK` and that the next tick after the run is the one after both (each took its own tick). The existing single-waiter test is unchanged and passes. Validated on Windows CI (fork-run of the repository workflow): clippy both builds and the full test suite pass: https://github.com/JordanFableFur/victory-fork/actions/runs/45513129011 **AI use:** written with Codex and Claude Code (GPT-5.2 Codex); reviewed and posted with my approval. No game files were used.
chatgpt-codex-connector[bot commented 2026-11-25 00:09:58 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:55:36Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 267a784b0e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:fxceless/victory-fork:review:6049370292 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#pullrequestreview-6049370292). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:55:36Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `267a784b0e` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
chatgpt-codex-connector[bot commented 2026-11-25 00:10:12 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:50:45Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T23:55:39.336990Z 267a784 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:fxceless/victory-fork:comment:7147859190 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#issuecomment-7147859190). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:50:45Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"267a784b0e15a92104b62f40b1cac87faaa37b4d","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-24T23:55:39.336990Z">2026-11-24T23:55:39.336990Z</relative-time> | `267a784` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
chatgpt-codex-connector[bot commented 2026-11-25 00:10:14 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:55:36Z.

Code review location: crates/victory-gpu/src/frame.rs; line 165

@@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait(
         TIMEOUT
     } else {
         std::thread::sleep(wait);
-        last(kind).fetch_max(tick, Ordering::Relaxed);
-        S_OK
+        // The tick is this waiter's only when it advanced `last`: two waits
+        // that wake together otherwise both end on it. A loser waits again,
+        // on the next tick, against its original time-out.
+        let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick;
+        if claimed {
+            S_OK
+        } else if limit > wait {
+            let left = limit - wait;
+            let (tick, wait) = next_tick(kind);
+            if wait > left {
+                std::thread::sleep(left);
+                TIMEOUT
+            } else {
+                std::thread::sleep(wait);
+                last(kind).fetch_max(tick, Ordering::Relaxed);
+                S_OK

P2 Badge Recheck tick ownership after every retry

With three waits for the same kind targeting tick N, the two initial losers both retry tick N+1. This second fetch_max ignores its previous value, so both retries return S_OK even though only one claims that tick; a synchronized three-waiter probe produced three successes while LAST advanced by only two ticks. This can also occur with two threads if the first winner starts another wait. Keep the ownership check in a retry loop until a tick is actually claimed or the deadline expires.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4688247850 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#discussion_r4688247850). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:55:36Z. **Code review location:** `crates/victory-gpu/src/frame.rs`; line 165 ~~~~diff @@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait( TIMEOUT } else { std::thread::sleep(wait); - last(kind).fetch_max(tick, Ordering::Relaxed); - S_OK + // The tick is this waiter's only when it advanced `last`: two waits + // that wake together otherwise both end on it. A loser waits again, + // on the next tick, against its original time-out. + let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick; + if claimed { + S_OK + } else if limit > wait { + let left = limit - wait; + let (tick, wait) = next_tick(kind); + if wait > left { + std::thread::sleep(left); + TIMEOUT + } else { + std::thread::sleep(wait); + last(kind).fetch_max(tick, Ordering::Relaxed); + S_OK ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Recheck tick ownership after every retry** With three waits for the same kind targeting tick N, the two initial losers both retry tick N+1. This second `fetch_max` ignores its previous value, so both retries return `S_OK` even though only one claims that tick; a synchronized three-waiter probe produced three successes while `LAST` advanced by only two ticks. This can also occur with two threads if the first winner starts another wait. Keep the ownership check in a retry loop until a tick is actually claimed or the deadline expires. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-25 00:10:14 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:55:36Z.

Code review location: crates/victory-gpu/src/frame.rs; line 157

@@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait(
         TIMEOUT
     } else {
         std::thread::sleep(wait);
-        last(kind).fetch_max(tick, Ordering::Relaxed);
-        S_OK
+        // The tick is this waiter's only when it advanced `last`: two waits
+        // that wake together otherwise both end on it. A loser waits again,
+        // on the next tick, against its original time-out.
+        let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick;
+        if claimed {
+            S_OK
+        } else if limit > wait {
+            let left = limit - wait;

P2 Badge Calculate the retry budget from elapsed time

When the initial sleep wakes late, subtracting its requested duration leaves more retry time than the caller actually has. For example, with a 30 ms timeout, a requested 20 ms sleep that wakes at 25 ms leaves only 5 ms, but this calculation allows another 10 ms sleep and returns TIMEOUT at 35 ms. A controlled timing probe reproduces that overrun without any oversleep on the retry itself. Use an absolute deadline and recompute the remaining duration from elapsed time before sleeping again.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4688247856 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#discussion_r4688247856). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:55:36Z. **Code review location:** `crates/victory-gpu/src/frame.rs`; line 157 ~~~~diff @@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait( TIMEOUT } else { std::thread::sleep(wait); - last(kind).fetch_max(tick, Ordering::Relaxed); - S_OK + // The tick is this waiter's only when it advanced `last`: two waits + // that wake together otherwise both end on it. A loser waits again, + // on the next tick, against its original time-out. + let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick; + if claimed { + S_OK + } else if limit > wait { + let left = limit - wait; ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Calculate the retry budget from elapsed time** When the initial sleep wakes late, subtracting its requested duration leaves more retry time than the caller actually has. For example, with a 30 ms timeout, a requested 20 ms sleep that wakes at 25 ms leaves only 5 ms, but this calculation allows another 10 ms sleep and returns `TIMEOUT` at 35 ms. A controlled timing probe reproduces that overrun without any oversleep on the retry itself. Use an absolute deadline and recompute the remaining duration from elapsed time before sleeping again. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-25 00:10:14 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:55:36Z.

Code review location: crates/victory-gpu/src/frame.rs; line 163

@@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait(
         TIMEOUT
     } else {
         std::thread::sleep(wait);
-        last(kind).fetch_max(tick, Ordering::Relaxed);
-        S_OK
+        // The tick is this waiter's only when it advanced `last`: two waits
+        // that wake together otherwise both end on it. A loser waits again,
+        // on the next tick, against its original time-out.
+        let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick;
+        if claimed {
+            S_OK
+        } else if limit > wait {
+            let left = limit - wait;
+            let (tick, wait) = next_tick(kind);
+            if wait > left {
+                std::thread::sleep(left);
+                TIMEOUT
+            } else {
+                std::thread::sleep(wait);

P2 Badge Account for retry sleeps in pacing diagnostics

In the Windows diagnostics path, a losing waiter executes this additional sleep, but the later C::PaceUs update still uses only the outer wait.min(limit). Consequently, two simultaneous waits that sleep for approximately three intervals are reported as sleeping for only two in copystat's per-frame summary, hiding the added pacing cost from performance measurements. Accumulate the retry sleep, including the retry-timeout branch, in the reported total.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4688247866 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#discussion_r4688247866). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:55:36Z. **Code review location:** `crates/victory-gpu/src/frame.rs`; line 163 ~~~~diff @@ -147,8 +147,26 @@ pub(crate) extern "system" fn wait( TIMEOUT } else { std::thread::sleep(wait); - last(kind).fetch_max(tick, Ordering::Relaxed); - S_OK + // The tick is this waiter's only when it advanced `last`: two waits + // that wake together otherwise both end on it. A loser waits again, + // on the next tick, against its original time-out. + let claimed = last(kind).fetch_max(tick, Ordering::Relaxed) < tick; + if claimed { + S_OK + } else if limit > wait { + let left = limit - wait; + let (tick, wait) = next_tick(kind); + if wait > left { + std::thread::sleep(left); + TIMEOUT + } else { + std::thread::sleep(wait); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Account for retry sleeps in pacing diagnostics** In the Windows `diagnostics` path, a losing waiter executes this additional sleep, but the later `C::PaceUs` update still uses only the outer `wait.min(limit)`. Consequently, two simultaneous waits that sleep for approximately three intervals are reported as sleeping for only two in `copystat`'s per-frame summary, hiding the added pacing cost from performance measurements. Accumulate the retry sleep, including the retry-timeout branch, in the reported total. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-25 00:10:14 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T23:55:36Z.

Code review location: crates/victory-gpu/src/frame.rs; line 285

@@ -242,5 +260,28 @@ mod tests {
         // Even when a flip wait begins on the tick another just ended on.
         let (tick, _) = next_tick(FLIP);
         assert!(tick > flips[3]);
+
+        // Two waits that wake together take two ticks: one does not end on
+        // the tick another has claimed, both succeed.
+        assert_eq!(set_interval(null, null, 10_000, 2, 0), S_OK);
+        let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
+        let results: Vec<HRESULT> = std::thread::scope(|s| {
+            // `wait` does not dereference `this`; each thread builds its own
+            // null (a raw pointer does not cross a closure capture's Send).
+            let joins: Vec<_> = (0..2)
+                .map(|_| {
+                    s.spawn(|| {
+                        let this: This = std::ptr::null();
+                        let mut token = 0;
+                        wait(this, FLIP, u32::MAX, std::ptr::null(), 0, &mut token)
+                    })
+                })
+                .collect();
+            joins.into_iter().map(|j| j.join().unwrap()).collect()
+        });
+        assert_eq!(results, [S_OK; 2]);
+        let end = LAST[2].load(Ordering::Relaxed);
+        let (next, _) = next_tick(FLIP);
+        assert_eq!(next, end + 1, "both waits took their own tick");

P2 Badge Assert that the concurrent waits actually consume two ticks

When both waits incorrectly finish on a single tick, end is simply that tick, and next_tick(FLIP) can still return end + 1 because it schedules after LAST[2]. This assertion therefore does not establish that the waits claimed distinct ticks; running the added test block against the pre-change wait implementation still passes. Synchronize the starts and observe the claimed ticks or their progression so the regression test rejects the original race.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:fxceless/victory-fork:review-comment:4688247873 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#discussion_r4688247873). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T23:55:36Z. **Code review location:** `crates/victory-gpu/src/frame.rs`; line 285 ~~~~diff @@ -242,5 +260,28 @@ mod tests { // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); assert!(tick > flips[3]); + + // Two waits that wake together take two ticks: one does not end on + // the tick another has claimed, both succeed. + assert_eq!(set_interval(null, null, 10_000, 2, 0), S_OK); + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + let results: Vec<HRESULT> = std::thread::scope(|s| { + // `wait` does not dereference `this`; each thread builds its own + // null (a raw pointer does not cross a closure capture's Send). + let joins: Vec<_> = (0..2) + .map(|_| { + s.spawn(|| { + let this: This = std::ptr::null(); + let mut token = 0; + wait(this, FLIP, u32::MAX, std::ptr::null(), 0, &mut token) + }) + }) + .collect(); + joins.into_iter().map(|j| j.join().unwrap()).collect() + }); + assert_eq!(results, [S_OK; 2]); + let end = LAST[2].load(Ordering::Relaxed); + let (next, _) = next_tick(FLIP); + assert_eq!(next, end + 1, "both waits took their own tick"); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Assert that the concurrent waits actually consume two ticks** When both waits incorrectly finish on a single tick, `end` is simply that tick, and `next_tick(FLIP)` can still return `end + 1` because it schedules after `LAST[2]`. This assertion therefore does not establish that the waits claimed distinct ticks; running the added test block against the pre-change `wait` implementation still passes. Synchronize the starts and observe the claimed ticks or their progression so the regression test rejects the original race. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
JordanFableFur commented 2026-11-25 01:12:01 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by JordanFableFur on 2026-11-25T00:32:57Z.


All four findings addressed in f005ddd:

  • The claim is in a loop: a loser recomputes the next tick and claims again, checking fetch_max's previous value each time, so three synchronized waiters take three ticks.
  • The deadline is measured from the call (limit.saturating_sub(slept) per attempt), so a late wake does not stretch the caller's time-out.
  • The retry sleeps count into C::PaceUs (slept.min(limit)).
  • The regression asserts LAST moved exactly two on across two barrier-synchronized waits, which the pre-change code fails.
<!-- greyfinch-sync:fxceless/victory-fork:comment:7148622946 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#issuecomment-7148622946). Originally posted by [JordanFableFur](https://github.com/JordanFableFur) on 2026-11-25T00:32:57Z. --- All four findings addressed in f005ddd: - The claim is in a loop: a loser recomputes the next tick and claims again, checking `fetch_max`'s previous value each time, so three synchronized waiters take three ticks. - The deadline is measured from the call (`limit.saturating_sub(slept)` per attempt), so a late wake does not stretch the caller's time-out. - The retry sleeps count into `C::PaceUs` (`slept.min(limit)`). - The regression asserts `LAST` moved exactly two on across two barrier-synchronized waits, which the pre-change code fails.
upstream-sync closed this pull request 2026-11-25 02:09:27 +00:00
kaayzouee commented 2026-11-25 02:10:06 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by kaayzouee on 2026-11-25T01:17:54Z.


Duplicate of #281?

<!-- greyfinch-sync:fxceless/victory-fork:comment:7149404574 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#issuecomment-7149404574). Originally posted by [kaayzouee](https://github.com/kaayzouee) on 2026-11-25T01:17:54Z. --- Duplicate of #281?
JordanFableFur commented 2026-11-25 02:10:11 +00:00 (Migrated from github.com)

Imported from fxceless/victory-fork. Originally posted by JordanFableFur on 2026-11-25T01:46:18Z.


Closing — #281 fixes the same issue (#244) and was opened first, with the same claim-and-retry shape. Thanks for flagging.

<!-- greyfinch-sync:fxceless/victory-fork:comment:7149937107 --> Imported from [fxceless/victory-fork](https://github.com/fxceless/victory-fork/pull/357#issuecomment-7149937107). Originally posted by [JordanFableFur](https://github.com/JordanFableFur) on 2026-11-25T01:46:18Z. --- Closing — #281 fixes the same issue (#244) and was opened first, with the same claim-and-retry shape. Thanks for flagging.

Pull request closed

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
fxceless/victory-fork!357
No description provided.