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

Merged
Maticcm merged 1 commit from upstream-pr/831 into main 2026-11-24 20:30:37 +00:00
Maticcm commented 2026-11-24 14:20:05 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Maticcm on 2026-11-24T14:20:05Z.


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)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5473923411 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831). Originally posted by [Maticcm](https://github.com/Maticcm) on 2026-11-24T14:20:05Z. --- 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 commented 2026-11-24 14:23:21 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by abnalstlll-byte on 2026-11-24T14:23:21Z.

Review: 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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6040949587 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#pullrequestreview-6040949587). Originally posted by [abnalstlll-byte](https://github.com/abnalstlll-byte) on 2026-11-24T14:23:21Z. **Review:** 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 commented 2026-11-24 14:25:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by abnalstlll-byte on 2026-11-24T14:25:06Z.

Review: APPROVED


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6040984577 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#pullrequestreview-6040984577). Originally posted by [abnalstlll-byte](https://github.com/abnalstlll-byte) on 2026-11-24T14:25:06Z. **Review:** APPROVED --- 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 commented 2026-11-24 14:38:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T14:38:06Z.

Code review location: runtime/test/crt_timed_wait_test.cpp; line 11

@@ -2,6 +2,14 @@
 // statically linked timed wait kept the mutex for the whole timeout, so a thread setting the predicate waited until
 // the wait timed out. Also checks the other definitions that file takes over: std::shared_mutex and
 // this_thread::sleep_for. No game files, no GPU.
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>

This test now unconditionally includes <windows.h>, which will break compilation on non-Windows builders if this test is part of a cross-platform test suite. Consider wrapping the include (and the Windows-only GetLastError/SetLastError test sections) with #if defined(_WIN32) so the file remains portable, or split the Windows-specific portions into a Windows-only test file/target.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4681608521 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608521). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T14:38:06Z. **Code review location:** `runtime/test/crt_timed_wait_test.cpp`; line 11 ~~~~diff @@ -2,6 +2,14 @@ // statically linked timed wait kept the mutex for the whole timeout, so a thread setting the predicate waited until // the wait timed out. Also checks the other definitions that file takes over: std::shared_mutex and // this_thread::sleep_for. No game files, no GPU. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> ~~~~ --- This test now unconditionally includes `<windows.h>`, which will break compilation on non-Windows builders if this test is part of a cross-platform test suite. Consider wrapping the include (and the Windows-only `GetLastError`/`SetLastError` test sections) with `#if defined(_WIN32)` so the file remains portable, or split the Windows-specific portions into a Windows-only test file/target.
Copilot commented 2026-11-24 14:38:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T14:38:06Z.

Code review location: runtime/test/crt_timed_wait_test.cpp; line 135

@@ -112,6 +120,55 @@ int main() {
         check(ms_since(start) >= 90, "this_thread::sleep_for sleeps");
     }
 
+    {
+        // Repeated short unnotified waits must never return cv_status::no_timeout due to an early OS timer wake.
+        bool all_timed_out = true;
+        bool all_reached_target = true;
+        std::unique_lock<std::mutex> lock(mutex);
+        for (int i = 0; i < 25; ++i) {
+            const auto target = Clock::now() + std::chrono::milliseconds(10);
+            const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(10));
+            const auto finished = Clock::now();
+            if (status != std::cv_status::timeout) all_timed_out = false;
+            if (finished < target) all_reached_target = false;
+        }
+        check(all_timed_out, "25 short unnotified wait_for calls all return timeout");

These assertions assume wait_for without a predicate will always return cv_status::timeout when unnotified. However, std::condition_variable is permitted to exhibit spurious wakeups, which can legitimately produce cv_status::no_timeout even without notification; that makes the test potentially flaky. To make the regression robust while still catching the early-OS-timeout issue, consider focusing the assertions on the timing guarantee (e.g., finished >= target) and treating a no_timeout result as a failure only when it returns before the target, or retrying until the deadline expires (while still verifying LastError preservation after the overall wait).

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4681608642 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608642). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T14:38:06Z. **Code review location:** `runtime/test/crt_timed_wait_test.cpp`; line 135 ~~~~diff @@ -112,6 +120,55 @@ int main() { check(ms_since(start) >= 90, "this_thread::sleep_for sleeps"); } + { + // Repeated short unnotified waits must never return cv_status::no_timeout due to an early OS timer wake. + bool all_timed_out = true; + bool all_reached_target = true; + std::unique_lock<std::mutex> lock(mutex); + for (int i = 0; i < 25; ++i) { + const auto target = Clock::now() + std::chrono::milliseconds(10); + const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(10)); + const auto finished = Clock::now(); + if (status != std::cv_status::timeout) all_timed_out = false; + if (finished < target) all_reached_target = false; + } + check(all_timed_out, "25 short unnotified wait_for calls all return timeout"); ~~~~ --- These assertions assume `wait_for` without a predicate will always return `cv_status::timeout` when unnotified. However, `std::condition_variable` is permitted to exhibit spurious wakeups, which can legitimately produce `cv_status::no_timeout` even without notification; that makes the test potentially flaky. To make the regression robust while still catching the early-OS-timeout issue, consider focusing the assertions on the *timing guarantee* (e.g., `finished >= target`) and treating a `no_timeout` result as a failure only when it returns before the target, or retrying until the deadline expires (while still verifying `LastError` preservation after the overall wait).
Copilot commented 2026-11-24 14:38:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-24T14:38:06Z.

Code review location: runtime/test/crt_timed_wait_test.cpp; line 170

@@ -112,6 +120,55 @@ int main() {
         check(ms_since(start) >= 90, "this_thread::sleep_for sleeps");
     }
 
+    {
+        // Repeated short unnotified waits must never return cv_status::no_timeout due to an early OS timer wake.
+        bool all_timed_out = true;
+        bool all_reached_target = true;
+        std::unique_lock<std::mutex> lock(mutex);
+        for (int i = 0; i < 25; ++i) {
+            const auto target = Clock::now() + std::chrono::milliseconds(10);
+            const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(10));
+            const auto finished = Clock::now();
+            if (status != std::cv_status::timeout) all_timed_out = false;
+            if (finished < target) all_reached_target = false;
+        }
+        check(all_timed_out, "25 short unnotified wait_for calls all return timeout");
+        check(all_reached_target, "25 short unnotified wait_for calls reach steady_clock target");
+    }
+
+    {
+        // A pre-existing ERROR_TIMEOUT must not misclassify a real notification as a timeout and must be preserved.
+        bool flag = false;
+        std::thread setter([&] {
+            std::this_thread::sleep_for(std::chrono::milliseconds(20));
+            { std::lock_guard<std::mutex> lock(mutex); flag = true; }
+            cv.notify_one();
+        });
+        SetLastError(ERROR_TIMEOUT);
+        std::cv_status status = std::cv_status::timeout;
+        {
+            std::unique_lock<std::mutex> lock(mutex);
+            while (!flag) {
+                status = cv.wait_for(lock, std::chrono::seconds(5));
+                if (status == std::cv_status::timeout) break;
+            }
+        }
+        const DWORD last_error = GetLastError();
+        setter.join();
+        check(flag && status == std::cv_status::no_timeout, "pre-existing ERROR_TIMEOUT does not mask notification");
+        check(last_error == ERROR_TIMEOUT, "pre-existing ERROR_TIMEOUT is preserved across wait_for");
+    }
+
+    {
+        // Caller LastError is preserved across a timed-out wait_for.
+        SetLastError(ERROR_INVALID_DATA);
+        std::unique_lock<std::mutex> lock(mutex);
+        const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(15));
+        const DWORD last_error = GetLastError();
+        check(status == std::cv_status::timeout, "unnotified wait_for with preset LastError times out");
+        check(last_error == ERROR_INVALID_DATA, "caller LastError is preserved across timed-out wait_for");
+    }

These assertions assume wait_for without a predicate will always return cv_status::timeout when unnotified. However, std::condition_variable is permitted to exhibit spurious wakeups, which can legitimately produce cv_status::no_timeout even without notification; that makes the test potentially flaky. To make the regression robust while still catching the early-OS-timeout issue, consider focusing the assertions on the timing guarantee (e.g., finished >= target) and treating a no_timeout result as a failure only when it returns before the target, or retrying until the deadline expires (while still verifying LastError preservation after the overall wait).

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4681608736 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#discussion_r4681608736). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T14:38:06Z. **Code review location:** `runtime/test/crt_timed_wait_test.cpp`; line 170 ~~~~diff @@ -112,6 +120,55 @@ int main() { check(ms_since(start) >= 90, "this_thread::sleep_for sleeps"); } + { + // Repeated short unnotified waits must never return cv_status::no_timeout due to an early OS timer wake. + bool all_timed_out = true; + bool all_reached_target = true; + std::unique_lock<std::mutex> lock(mutex); + for (int i = 0; i < 25; ++i) { + const auto target = Clock::now() + std::chrono::milliseconds(10); + const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(10)); + const auto finished = Clock::now(); + if (status != std::cv_status::timeout) all_timed_out = false; + if (finished < target) all_reached_target = false; + } + check(all_timed_out, "25 short unnotified wait_for calls all return timeout"); + check(all_reached_target, "25 short unnotified wait_for calls reach steady_clock target"); + } + + { + // A pre-existing ERROR_TIMEOUT must not misclassify a real notification as a timeout and must be preserved. + bool flag = false; + std::thread setter([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + { std::lock_guard<std::mutex> lock(mutex); flag = true; } + cv.notify_one(); + }); + SetLastError(ERROR_TIMEOUT); + std::cv_status status = std::cv_status::timeout; + { + std::unique_lock<std::mutex> lock(mutex); + while (!flag) { + status = cv.wait_for(lock, std::chrono::seconds(5)); + if (status == std::cv_status::timeout) break; + } + } + const DWORD last_error = GetLastError(); + setter.join(); + check(flag && status == std::cv_status::no_timeout, "pre-existing ERROR_TIMEOUT does not mask notification"); + check(last_error == ERROR_TIMEOUT, "pre-existing ERROR_TIMEOUT is preserved across wait_for"); + } + + { + // Caller LastError is preserved across a timed-out wait_for. + SetLastError(ERROR_INVALID_DATA); + std::unique_lock<std::mutex> lock(mutex); + const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(15)); + const DWORD last_error = GetLastError(); + check(status == std::cv_status::timeout, "unnotified wait_for with preset LastError times out"); + check(last_error == ERROR_INVALID_DATA, "caller LastError is preserved across timed-out wait_for"); + } ~~~~ --- These assertions assume `wait_for` without a predicate will always return `cv_status::timeout` when unnotified. However, `std::condition_variable` is permitted to exhibit spurious wakeups, which can legitimately produce `cv_status::no_timeout` even without notification; that makes the test potentially flaky. To make the regression robust while still catching the early-OS-timeout issue, consider focusing the assertions on the *timing guarantee* (e.g., `finished >= target`) and treating a `no_timeout` result as a failure only when it returns before the target, or retrying until the deadline expires (while still verifying `LastError` preservation after the overall wait).
copilot-pull-request-reviewer[bot] commented 2026-11-24 14:38:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-24T14:38:07Z.

Review: COMMENTED


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 for more details.

Copilot review overview

3 open issues
What changed in this PR

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.

Review effort: Lite

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6041247995 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#pullrequestreview-6041247995). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-24T14:38:07Z. **Review:** COMMENTED --- > [!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 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Maticcm on 2026-11-24T14:48:21Z.


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.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7134976214 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#issuecomment-7134976214). Originally posted by [Maticcm](https://github.com/Maticcm) on 2026-11-24T14:48:21Z. --- 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 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by aslan2142 on 2026-11-24T20:30:39Z.


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).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7143656486 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/831#issuecomment-7143656486). Originally posted by [aslan2142](https://github.com/aslan2142) on 2026-11-24T20:30:39Z. --- 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 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
ProjectLeonida/mandy!831
No description provided.