runtime: map early OS ERROR_TIMEOUT to _Timedout in _Cnd_timedwait_for_unchecked (RT-CRT-TIMED-WAIT-EARLY-TIMEOUT) #831

Merged
leonida/mandy
Maticcm merged 1 commit from fix/crt-timed-wait-early-timeout into main 2026-11-24 20:30:37 +00:00

Pull request successfully merged and closed

Maticcm commented 2026-11-24 14:20:05 +00:00

Claimed in the coordination issue as: RT-CRT-TIMED-WAIT-EARLY-TIMEOUT

What and why

Fixes intermittent crt_timed_wait failures on Windows where std::condition_variable::wait_for without a predicate returned std::cv_status::no_timeout early (observed at 199–200 ms on a 200 ms wait, failing in baseline -j 8 CTest and in 2/10 standalone runs on Windows 11).

runtime/src/crt_timed_wait.cpp implements _Cnd_timedwait_for_unchecked via msvcp140.dll!_Cnd_timedwait against a TIME_UTC deadline. Inside msvcp140.dll, if SleepConditionVariableSRW times out (ERROR_TIMEOUT) even a fraction of a millisecond before target, _Xtime_diff_to_millis2(target, &now) is still non-zero, so _Cnd_timedwait returns _Thrd_result::_Success. MSVC STL's std::condition_variable::wait_for (<condition_variable>) treats _Success as a notification/spurious wake and returns cv_status::no_timeout instead of checking steady_clock::now() < _Target and waiting out the deadline.

timedwait_for_impl now saves and clears LastError around _Cnd_timedwait (restoring the caller's LastError afterwards) and maps _Thrd_result::_Success with wait_error == ERROR_TIMEOUT back to _Thrd_result::_Timedout for _Cnd_timedwait_for_unchecked, while preserving checked semantics for _Cnd_timedwait_for. Added regression tests in runtime/test/crt_timed_wait_test.cpp covering 25 consecutive 10 ms unnotified wait_for calls, pre-existing ERROR_TIMEOUT across a notified wait, and LastError preservation on timeout.

Tested

  • scripts\build_runtime.ps1 (MSVC 19.50.35729.0, Windows SDK 10.0.26100.0, RelWithDebInfo): [260/260] incremental targets built cleanly (0 errors, 0 warnings).
  • runtime\build\crt_timed_wait_test.exe x 25 consecutive runs: 25/25 passed (RESULT: PASS, exit 0).
  • ctest --test-dir runtime/build -R "crt_timed_wait|vk_fence|d3d12_fence|d3d12_queue_wait|frame_pacer|xtaskqueue" --output-on-failure: 10/10 passed (100%).
  • python -I scripts/check_no_game_data.py runtime/src/crt_timed_wait.cpp runtime/test/crt_timed_wait_test.cpp: ok (2 file(s)).
  • python -m compileall -q make_game.py tools tests: exit 0.

GPUs tested: NVIDIA GeForce RTX 3080, driver 630.20, Windows 11 (CPU/CRT runtime change)

AI-assisted: yes

Known limitations: Tested on native Windows 11; preserves the msvcp140.dll!_Cnd_timedwait path for Wine 9 compatibility without touching _Mtx_t, not yet re-run under Wine 9 locally.

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — no translator changes)
Claimed in the coordination issue as: RT-CRT-TIMED-WAIT-EARLY-TIMEOUT ### What and why Fixes intermittent `crt_timed_wait` failures on Windows where `std::condition_variable::wait_for` without a predicate returned `std::cv_status::no_timeout` early (observed at 199–200 ms on a 200 ms wait, failing in baseline `-j 8` CTest and in 2/10 standalone runs on Windows 11). `runtime/src/crt_timed_wait.cpp` implements `_Cnd_timedwait_for_unchecked` via `msvcp140.dll!_Cnd_timedwait` against a `TIME_UTC` deadline. Inside `msvcp140.dll`, if `SleepConditionVariableSRW` times out (`ERROR_TIMEOUT`) even a fraction of a millisecond before `target`, `_Xtime_diff_to_millis2(target, &now)` is still non-zero, so `_Cnd_timedwait` returns `_Thrd_result::_Success`. MSVC STL's `std::condition_variable::wait_for` (`<condition_variable>`) treats `_Success` as a notification/spurious wake and returns `cv_status::no_timeout` instead of checking `steady_clock::now() < _Target` and waiting out the deadline. `timedwait_for_impl` now saves and clears `LastError` around `_Cnd_timedwait` (restoring the caller's `LastError` afterwards) and maps `_Thrd_result::_Success` with `wait_error == ERROR_TIMEOUT` back to `_Thrd_result::_Timedout` for `_Cnd_timedwait_for_unchecked`, while preserving checked semantics for `_Cnd_timedwait_for`. Added regression tests in `runtime/test/crt_timed_wait_test.cpp` covering 25 consecutive 10 ms unnotified `wait_for` calls, pre-existing `ERROR_TIMEOUT` across a notified wait, and `LastError` preservation on timeout. ### Tested - `scripts\build_runtime.ps1` (MSVC 19.50.35729.0, Windows SDK 10.0.26100.0, RelWithDebInfo): `[260/260]` incremental targets built cleanly (0 errors, 0 warnings). - `runtime\build\crt_timed_wait_test.exe` x 25 consecutive runs: `25/25` passed (`RESULT: PASS`, exit 0). - `ctest --test-dir runtime/build -R "crt_timed_wait|vk_fence|d3d12_fence|d3d12_queue_wait|frame_pacer|xtaskqueue" --output-on-failure`: `10/10` passed (`100%`). - `python -I scripts/check_no_game_data.py runtime/src/crt_timed_wait.cpp runtime/test/crt_timed_wait_test.cpp`: `ok (2 file(s))`. - `python -m compileall -q make_game.py tools tests`: exit 0. GPUs tested: NVIDIA GeForce RTX 3080, driver 630.20, Windows 11 (CPU/CRT runtime change) AI-assisted: yes Known limitations: Tested on native Windows 11; preserves the `msvcp140.dll!_Cnd_timedwait` path for Wine 9 compatibility without touching `_Mtx_t`, not yet re-run under Wine 9 locally. ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a — no translator changes)
abnalstlll-byte approved these changes 2026-11-24 14:23:21 +00:00
abnalstlll-byte left a comment

Clean-Room Peer Review for PR #831 (runtime: map early OS ERROR_TIMEOUT to _Timedout in _Cnd_timedwait_for_unchecked)

Crucial timing synchronization fix for MSVC CRT condition variable waits:

  • Root Cause & Behavior Analysis:
    • msvcp140's _Cnd_timedwait evaluates _Xtime_diff_to_millis2(target, &now) == 0 when SleepConditionVariableSRW returns ERROR_TIMEOUT. Sub-millisecond timer resolution jitter causes early OS timer wakes to report _Thrd_result::_Success.
    • In std::condition_variable::wait_for/wait_until, reporting _Success causes premature cv_status::no_timeout returns instead of properly waiting out the deadline.
  • Defensive Error & LastError Preservation:
    • Correctly captures caller's GetLastError() before calling _Cnd_timedwait and restores saved_error afterwards.
    • Maps unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT to _Thrd_result::_Timedout, allowing the caller to re-evaluate steady_clock.
  • Rigorous Test Suite Verification:

untime/test/crt_timed_wait_test.cpp:
1. 25 consecutive short unnotified waits verify zero false
o_timeout returns.
2. Pre-existing ERROR_TIMEOUT correctly preserved without masking legitimate notifications.
3. Caller LastError (ERROR_INVALID_DATA) strictly preserved across waits.

  • Clean-room verification: Pure C++20 standard library runtime fix, no game assets, builds cleanly under MSVC.

LGTM! Outstanding investigation and fix. Approved.

### Clean-Room Peer Review for PR #831 (runtime: map early OS ERROR_TIMEOUT to _Timedout in _Cnd_timedwait_for_unchecked) Crucial timing synchronization fix for MSVC CRT condition variable waits: - **Root Cause & Behavior Analysis**: - msvcp140's _Cnd_timedwait evaluates _Xtime_diff_to_millis2(target, &now) == 0 when SleepConditionVariableSRW returns ERROR_TIMEOUT. Sub-millisecond timer resolution jitter causes early OS timer wakes to report _Thrd_result::_Success. - In std::condition_variable::wait_for/wait_until, reporting _Success causes premature cv_status::no_timeout returns instead of properly waiting out the deadline. - **Defensive Error & LastError Preservation**: - Correctly captures caller's GetLastError() before calling _Cnd_timedwait and restores saved_error afterwards. - Maps unchecked && res == _Thrd_result::_Success && wait_error == ERROR_TIMEOUT to _Thrd_result::_Timedout, allowing the caller to re-evaluate steady_clock. - **Rigorous Test Suite Verification**: - untime/test/crt_timed_wait_test.cpp: 1. 25 consecutive short unnotified waits verify zero false o_timeout returns. 2. Pre-existing ERROR_TIMEOUT correctly preserved without masking legitimate notifications. 3. Caller LastError (ERROR_INVALID_DATA) strictly preserved across waits. - **Clean-room verification**: Pure C++20 standard library runtime fix, no game assets, builds cleanly under MSVC. LGTM! Outstanding investigation and fix. Approved.
abnalstlll-byte approved these changes 2026-11-24 14:25:06 +00:00
abnalstlll-byte left a comment

Clean-room verified (zero game data). Excellent Windows CRT concurrency fix: maps OS ERROR_TIMEOUT on early sub-millisecond timer tick to _Thrd_result::_Timedout in _Cnd_timedwait_for_unchecked, preserving caller LastError and preventing premature wait_for loop exit in std::condition_variable. Comprehensive test cases in crt_timed_wait_test.cpp.

Clean-room verified (zero game data). Excellent Windows CRT concurrency fix: maps OS ERROR_TIMEOUT on early sub-millisecond timer tick to _Thrd_result::_Timedout in _Cnd_timedwait_for_unchecked, preserving caller LastError and preventing premature wait_for loop exit in std::condition_variable. Comprehensive test cases in crt_timed_wait_test.cpp.
copilot-pull-request-reviewer[bot] reviewed 2026-11-24 14:38:07 +00:00
copilot-pull-request-reviewer[bot] left a comment
No description provided.
> [!WARNING] > Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a `copilot-code-review.yml` file specifying one with the `runs-on` attribute. See the [docs](https://gh.io/AA11tgch) for more details. <!-- ccr-overview-v2 --> ## Copilot review overview <details open> <summary><strong>3 open issues</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [This test now unconditionally includes `<windows.h>`, which will break compilation on non-Windows…](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608521) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [These assertions assume `wait_for` without a predicate will always return `cv_status::timeout` when…](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608642) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [These assertions assume `wait_for` without a predicate will always return `cv_status::timeout` when…](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608736) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Fixes early/incorrect `std::condition_variable::wait_for` results on Windows by mapping an early OS `ERROR_TIMEOUT` back to `_Thrd_result::_Timedout` in the unchecked timed-wait path, and adds regression tests to prevent reintroducing the issue. **Changes:** - Add `LastError` save/clear/restore around `_Cnd_timedwait` and remap `_Success + ERROR_TIMEOUT` to `_Timedout` for `_Cnd_timedwait_for_unchecked`. - Keep checked semantics for `_Cnd_timedwait_for` by routing it through the shared implementation with `unchecked = false`. - Add Windows-focused regression tests covering repeated short waits, pre-existing `ERROR_TIMEOUT`, and `LastError` preservation. | File | Description | | ---- | ----------- | | runtime/​src/​crt_timed_wait.cpp | Preserves `LastError` while detecting early OS timeout and remaps result for the unchecked condition-variable wait path. | | runtime/​test/​crt_timed_wait_test.cpp | Adds Windows regression tests to catch early-timer wake behavior and validate `LastError` preservation. | </details> <sub>Review effort: Lite</sub>
Maticcm commented 2026-11-24 14:48:21 +00:00

Addressed @Copilot's review feedback (rebased onto main f3e26be7c, commit bc9d0a5f8):

  • Wrapped <windows.h> and the SetLastError/GetLastError regression cases in #ifdef _WIN32.
  • Updated unnotified wait_for assertions in crt_timed_wait_test.cpp to assert finished >= target and flag cv_status::no_timeout only when returned before target, avoiding spurious-wakeup flakes after the deadline while still catching early OS ERROR_TIMEOUT exits.

Re-verified on Windows 11 (MSVC 19.50, RelWithDebInfo, SDL3): crt_timed_wait_test.exe passed 25/25 consecutive runs and ctest -R 'crt_timed_wait|vk_fence|d3d12_fence|d3d12_queue_wait|frame_pacer|xtaskqueue' passed 10/10.

Addressed @Copilot's review feedback (rebased onto main `f3e26be7c`, commit `bc9d0a5f8`): - Wrapped `<windows.h>` and the `SetLastError`/`GetLastError` regression cases in `#ifdef _WIN32`. - Updated unnotified `wait_for` assertions in [crt_timed_wait_test.cpp](runtime/test/crt_timed_wait_test.cpp) to assert `finished >= target` and flag `cv_status::no_timeout` only when returned before `target`, avoiding spurious-wakeup flakes after the deadline while still catching early OS `ERROR_TIMEOUT` exits. Re-verified on Windows 11 (MSVC 19.50, RelWithDebInfo, SDL3): `crt_timed_wait_test.exe` passed `25/25` consecutive runs and `ctest -R 'crt_timed_wait|vk_fence|d3d12_fence|d3d12_queue_wait|frame_pacer|xtaskqueue'` passed `10/10`.
aslan2142 commented 2026-11-24 20:30:39 +00:00

Merged on local results, since CI has been queued for hours. Tested on Linux under Wine (not real Windows): clang-cl 23.1.5 with the xwin SDK 10.0.26100, Wine 11.22, headless, on main 6293c1c4f and main + bc9d0a5f8.

  • crt_timed_wait, 200 runs each: 0 failures on both. Under Wine the 200 ms wait always returned at 201 ms or later, so the 199 ms flake from Windows doesn't reproduce here.
  • Forced early timeout (a local throwaway patch, not for this PR): the underlying wait was made to time out 2 ms early and return what Windows' msvcp140 returns then.
    • main: 21/21 runs fail; wait_for(200 ms) returns no_timeout at 199 ms, and LastError is clobbered.
    • This PR: 21/21 pass; the shim reports _Timedout, wait_until waits out the remainder, and LastError is preserved.
  • Related tests (crt_timed_wait, frame_pacer, vk_fence_dispatcher_sync, acphal*, context_*, wait_registration_*): 29/29 pass on both.
  • The review found the change matches microsoft/STL, and the test only gains checks. The claim is valid.

AI-assisted (Claude Code, Claude Fable 5.2 and Claude Opus 5.5).

Merged on local results, since CI has been queued for hours. Tested on Linux under Wine (not real Windows): clang-cl 23.1.5 with the xwin SDK 10.0.26100, Wine 11.22, headless, on `main` `6293c1c4f` and `main` + `bc9d0a5f8`. - **`crt_timed_wait`, 200 runs each:** 0 failures on both. Under Wine the 200 ms wait always returned at 201 ms or later, so the 199 ms flake from Windows doesn't reproduce here. - **Forced early timeout** (a local throwaway patch, not for this PR): the underlying wait was made to time out 2 ms early and return what Windows' msvcp140 returns then. - `main`: 21/21 runs fail; `wait_for(200 ms)` returns `no_timeout` at 199 ms, and `LastError` is clobbered. - This PR: 21/21 pass; the shim reports `_Timedout`, `wait_until` waits out the remainder, and `LastError` is preserved. - **Related tests** (`crt_timed_wait`, `frame_pacer`, `vk_fence_dispatcher_sync`, `acphal*`, `context_*`, `wait_registration_*`): 29/29 pass on both. - The review found the change matches microsoft/STL, and the test only gains checks. The claim is valid. AI-assisted (Claude Code, Claude Fable 5.2 and Claude Opus 5.5).
Sign in to join this conversation.
No description provided.