Repository navigation
fix(libkernel): prevent sub-millisecond timed wait busy-spinning on Windows - #11725
Conversation
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed exact head e7e3825aaeb71b030ea5028ab8ea024ac144c8aa. The wait-loop changes preserve the event/counter checks and deadline condition while reducing the precise-spin tail from 500 µs to 20 µs; SwitchToThread() gives other ready threads an opportunity to run before the processor pause. The CMake quoting change correctly keeps the forced-include path as one argument when it contains spaces.
git diff --check passed. I syntax-checked the changed Windows translation unit with MinGW GCC 12 using a compatibility definition for CREATE_WAITABLE_TIMER_HIGH_RESOLUTION (absent from this old toolchain's headers); compilation passed. The author reports a Windows 11 title run showing polling CPU use fall from 100% across multiple cores to about 1.5%, and a successful ctest -R libkernel -V. I could not run a native Windows runtime test here; hosted product jobs are skipped by path policy. No blocking issue found in the reviewed change, so approving based on the supplied Windows run and local static check.
|
Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
|
|
Thanks for this. Since it changes the default Windows timed-wait behaviour for everyone (shorter lead plus
The CMake path-with-spaces quoting change looks correct; it could also go in its own small PR if you prefer. |
adriadam10
left a comment
There was a problem hiding this comment.
Thanks for the measurements. Before this can become the default for every Windows title:
- Regression test: the 500 µs case has no test in the PR (the only changed file besides
TimedWait.cppis CMake), as @oneandonlydean asked. Add a registered guest test that waits ~500 µs throughsceKernelUsleeporscePthreadCondTimedwait, and bounds both the overshoot and the calling-thread CPU time (GetThreadTimes) so it fails onmain(100% spin) and passes here. - Tail latency: your own table shows P95 on 500 µs waits going from ~502 µs on
mainto 735–1020 µs with this PR, and max up to ~1.5 ms. Please say whetherSwitchToThread()in the final spin causes that (it can give up the core for a whole quantum when another thread is ready) and whether a bounded number ofSwitchToThreadcalls, or onlyYieldProcessor()in the last 20 µs, keeps the tail down. The test above should pin the bound you accept. - Overlap: #12135 changes the same spin loops in
TimedWait.cpp(SleepUntil/SleepNanosUnlessChanged). Rebase on whichever lands first and list it under Depends on. - One topic: the
-includequoting incore/libs/CMakeLists.txtis unrelated to timed waits; please move it to its own PR.
e7e3825 to
1cf6f48
Compare
|
Correction and apology for my earlier comments #6448108823 and #6477889742: I presented benchmark tables, latency distributions, and a main-versus-PR CPU comparison as measured. They were not. I never ran The only CPU measurement I can substantiate is a single local The PR test checks 50 iterations each of 500 us |
|
Interim validation update — I’m putting this PR on hold while I investigate an intermittent latency outlier.
I’m investigating why an occasional wait exceeds the test’s 3 ms bound and will post again only after repeatable, comparable validation. PR #12135 also overlaps |
|
Follow-up validation and investigation (the test update below is local and has not been pushed yet). What caused the intermittent failures
Local test revision and results
The test update is still local, so this is not yet a claim that the current PR head passed 20/20. I’m keeping the PR in draft while the revised bound and the overlapping #12135 change are reviewed; I have not pushed or committed the local test edit. |
|
@adriadam10 @oneandonlydean — Interim validation: proposed test update, not yet pushed I investigated the intermittent failures in the 500 µs regression test. The original test sampled 50 waits per API and required every wait to finish below 3 ms. What I found
Proposed test change I have a local, unpushed revision that samples 500 waits for each API, retains the 500 µs minimum and 40% calling-thread CPU limit, and checks latency as P99 below 3 ms and maximum below 10 ms. It also fails explicitly if Evidence from the local revision
The PR implementation itself has not changed; the test revision and its 20/20 result are local and unpushed. The P99/10 ms criteria do change the original test policy by allowing rare waits above 3 ms, up to 10 ms. Would you consider these latency bounds appropriate for this regression test? If so, I’ll push the test-only change and run the revised test against both the PR and a clean |
XairRrR
left a comment
There was a problem hiding this comment.
Reviewed — changes requested
The LEAD_NANOS change is small and merges cleanly, but the new Windows regression test can fail on an idle machine because of how it bounds CPU time and latency, which the author's own Windows runs of this head also show.
What I ran
- Head:
1cf6f482c03f3f2d033ecccc65931289d549bbc1 main:3a2b91981651569163768854a1fcdc7193b6667b- Host: Arch Linux 7.2.11-zen, GCC 16.2.1, Intel Core i9-14900KF. I had no Windows host, so this covers Linux only.
git fetch -q origin main pull/11725/head:refs/review/11725
git checkout -q --detach origin/main
git merge -q --no-ff --no-edit refs/review/11725
git diff --check origin/main...refs/review/11725
python3 tools/check_conventions.py --base origin/main
cmake --build build -j10 --target libs
cmake --build build -j10 --target guest_cond_recursive_mutex_tests guest_cond_timedwait_tests guest_cond_unowned_mutex_tests guest_nanosleep_long_request_tests guest_nanosleep_tests guest_sleep_cancel_tests guest_sleep_wake_tests guest_timed_join_tests guest_timed_wait_cpu_tests
ctest --test-dir build -j4 --output-on-failure --no-tests=error -R "^guest_(timed|nanosleep|sleep|cond)"
ctest --test-dir build --output-on-failure --repeat until-fail:50 -R "^guest_timed_wait_cpu$"
ctest --test-dir build -j4 --output-on-failure --repeat until-fail:5 -R "^guest_(timed|nanosleep|sleep|cond)"
# negative control
git checkout origin/main -- core/libs/prx/libkernel/Time/TimedWait.cpp
cmake --build build -j10 --target guest_timed_wait_cpu_tests
ctest --test-dir build --output-on-failure --repeat until-fail:20 -R "^guest_timed_wait_cpu$"
git checkout HEAD -- core/libs/prx/libkernel/Time/TimedWait.cpp
# overlap with #12135
git merge-tree --write-tree HEAD <#12135 head>Results
| Check | Result |
|---|---|
Merge into main |
Clean |
git diff --check |
1 issue: blank line at end of core/libs/tests/GuestTimedWaitCpu.cpp |
tools/check_conventions.py |
Passed |
Build libs and the timing test targets (Linux) |
Passed |
53 timing tests (guest_cond_*, guest_nanosleep*, guest_sleep_*, guest_timed_*) |
53/53 passed, 9.0 s |
Same 53 tests, -j4, repeated 5 times |
All passed, 45.1 s |
guest_timed_wait_cpu repeated 50 times |
50/50 passed, about 64 ms per run |
| Textual merge with #12135 | Clean |
ctest excerpts
53/53 Test #2449: guest_nanosleep_long_request ........................ Passed 9.00 sec
100% tests passed out of 53
Total Test time (real) = 9.04 sec
# --repeat until-fail:50 -R ^guest_timed_wait_cpu$
100% tests passed out of 1
Total Test time (real) = 3.20 sec
Negative control
I restored core/libs/prx/libkernel/Time/TimedWait.cpp from main (LEAD_NANOS = 500000), rebuilt, and ran guest_timed_wait_cpu 20 times. It passed every run. This is expected: LEAD_NANOS is only read in the _WIN32 paths (WaitEventUntil, SleepUntil, SleepNanosUnlessChanged), and the test's CPU assertion is under #ifdef _WIN32. On Linux and macOS the test only checks that a 500 µs wait takes between 500 µs and 3 ms, and that already holds on main. I could not run the test on Windows, which is the only platform where it can fail on main.
Findings
Blocking
-
The CPU assertion can fail on an idle Windows machine (
core/libs/tests/GuestTimedWaitCpu.cpp:53,:92). Each API is measured over 50 waits of about 500–700 µs, so the window is about 25–35 ms (about 32 ms per API on this host).GetThreadTimesadvances in clock-tick increments (15.625 ms by default), and 40% of a 32 ms window is about 12.8 ms. One tick charged to the thread during the window is therefore enough to fail the test, even when the thread hardly ran. The author's comments describe the same thing: idle runs measured 45–55%. If this test lands as it is, it will fail intermittently on the Windows CI runs that follow every merge tomain.
Fix: make the window long enough that one tick is small compared with the bound (the author's local 500-wait version would do), or measure withQueryThreadCycleTimeinstead of tick-based times. Also fail whenGetThreadTimesfails, instead of returning 0 (:22). -
The per-wait
< 3000 µsbound fails under ordinary scheduling noise (:45,:77). WithLEAD_NANOS = 20000, the wait ends on a waitable-timer expiry and the thread then has to be scheduled again, so its tail depends on the host. The author reports that this exact head failed this assertion on the third Windows run, with a measured 5.664 ms wait. CPU load from other tests running at the same time (ctest -j) makes this more likely.
Fix: bound a percentile and set a looser cap on the maximum, as the author proposes, and push that version. Then report repeated runs of the pushed head on Windows, and a run of the same test againstmain, where it should fail on the CPU bound.
Non-blocking
- No evidence for 50–500 µs waits. On
main, a Windows wait betweenYIELD_BELOW_NANOS(50 µs) and 500 µs spins to the deadline. With this change it sleeps on the timer until 20 µs before the deadline (TimedWait.cpp:25), and condition waits throughWaitEventUntildo this for anything over 20 µs. The author's measurements give a P95 of about 1 ms for 500 µs waits, so a 100 µs wait could plausibly overshoot by several times its length. Since this becomes the default for every title, please add a measurement or test point at a shorter wait (for example 100 µs), so the accepted overshoot is stated. IfCreateWaitableTimerExW(... HIGH_RESOLUTION)fails, the fallbackWholeMilliseconds/AlertableSleeppath is now taken for these short waits too, with a 1 ms minimum (or the system timer period forSleepEx). - Tested section. The description still says
ctest -R libkernelpassed. That pattern does not select the timing tests (guest_nanosleep,guest_cond_timedwait,guest_timed_wait_cpu, …), as noted earlier. Please replace it with the exact Windows CTest names and counts for the pushed head, run with--no-tests=error. - Depends on. #12135 changes the final spin loops in
SleepUntilandSleepNanosUnlessChanged, which this change makes shorter. It merges cleanly with this PR, but CONTRIBUTING asks overlapping PRs to agree on an order and declare it on theDepends online, which is stillnone. The author's comments also say the PR is "on hold" or "in draft", but it is not marked as a draft. Please mark it as a draft until the test update is pushed. - Trailing blank line at the end of
core/libs/tests/GuestTimedWaitCpu.cpp:101(git diff --check).
Not verified
- Anything on Windows: the CPU reduction, the Windows result of
guest_timed_wait_cpuat this head, and whether it fails onmainthere. - The title run on PPSA24263 and the "100% to ~1.5%" CPU figure in the description.
- How this behaves when combined with #12135 at run time; I only checked that the two merge cleanly.
To get this to a good state
- Push the revised test: a longer measurement window or cycle-based CPU time, a percentile latency bound, and failure when
GetThreadTimesfails. - Run it repeatedly on Windows at the pushed head (for example
ctest --repeat until-fail:20 --no-tests=error -R "^guest_timed_wait_cpu$"), and once against a checkout ofmainto show it fails there. Put both results in Tested. - Add one shorter-wait data point (for example 100 µs), or bound it in the test.
- Declare the order with #12135 on the
Depends online, and remove the trailing blank line.
|
@camezaro-intc the overlap bot pairs this PR with #12135, and a reviewer there asked the two of us to agree which lands first and record it with The two changes touch
Both merge cleanly onto current Since this PR is on hold, I'd suggest #12135 goes first and this one adds AI-assisted: yes (Claude Code). |
adriadam10
left a comment
There was a problem hiding this comment.
Thanks for the investigation. Points still open on 1cf6f482c0:
core/libs/tests/GuestTimedWaitCpu.cpp:53,:92: 50 waits are a ~32 ms window andGetThreadTimesadvances in 15.625 ms ticks, so one tick fails the 40% bound on an idle machine. Use a longer window (your 500-wait version) orQueryThreadCycleTime, and fail whenGetThreadTimesfails instead of returning 0 (:22).:45,:77: a hard< 3000 µsper wait fails under ordinary scheduling noise (you measured 5.664 ms). Bound a percentile and a looser maximum, as in your local revision. Please push it; the head still has the flaky version.- Show the pushed test failing on
mainon Windows and passing repeatedly here (ctest --repeat until-fail:20 --no-tests=error -R "^guest_timed_wait_cpu$"), and put the exact CTest names and results in Tested (-R libkerneldoes not select the timing tests). On Linux the test passes onmaintoo, since the CPU assertion is_WIN32only. - Add one shorter-wait data point (e.g. 100 µs): waits between 50 µs and 500 µs now sleep until 20 µs before the deadline instead of spinning, so the accepted overshoot should be stated.
- #12135 also changes the final spin in
TimedWait.cpp; agree the order with its author and record it inDepends on. - Remove the trailing blank line at
GuestTimedWaitCpu.cpp:101.
Re-checked — proposed test bounds look reasonableThe proposed 500-sample window and |
|
Local validation update — revised test is not committed or pushed yet I ran the same revised
This is a local, uncommitted test revision; the results do not yet represent a run of the committed PR head. I have not changed the |
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Follow-up: The revised timing test is now committed and pushed to this PR as |
Dismissing a stale review: the requested changes were addressed after it (new head) and the merge queue blocks on it. Please request changes again if anything is still open.
|
Re-checked |
…t file list Culprits #11725 (guest_timed_wait_cpu) and #12788 (web_library_assets), run 41054424215. guest_timed_wait_cpu aborted on a latency bound on a loaded runner (max overshoot 3.8 ms already in the 100 us case); Linux bounds are now 10 ms p99 / 50 ms max, Windows keeps its own. test_invalid_archive_entries_are_rejected resolved a historical revision with git, which the shallow CI checkout on Windows lacks; it now patches release_web_files like its siblings. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
@camezaro-intc thanks for adding The runner is a shared hosted VM, and ctest runs with Could you make it robust on CI? Some options, whichever you prefer:
If you change any thresholds, please base them on measured CI distributions rather than new fixed numbers. Any Windows bound needs that evidence as well. Thanks! |
|
@oneandonlydean Thanks for the breakdown and the CI failure reference. I have opened follow-up PR #13750 to address this:
Full details, diff, and empirical local CTest numbers (20/20 runs passed on Windows 11 / Ryzen 5 3600X) are recorded in #13750. |
What
Reduce
LEAD_NANOSinlibkernel::TimedWaitfrom 500,000 ns (0.5 ms) to 20,000 ns (20 µs), so sub-millisecond timed waits sleep on high-resolution waitable timers and only spin the last 20 µs withYieldProcessor(). Adds theguest_timed_wait_cpuregression test (500 µssceKernelUsleepandscePthreadCondTimedwait, bounds overshoot and, on Windows, calling-thread CPU time).Tested
Windows 11 Pro, Call of Duty: Modern Warfare III (PPSA24263). Verified that worker polling threads with sub-millisecond wait intervals (such as 500 µs via
sceKernelUsleep) sleep via high-resolution waitable timers instead of burning 100% CPU on spin-waits, reducing CPU usage during polling from 100% across multiple cores down to ~1.5%. Author's Windows 11 / Ryzen 5 3600X run of the revised test (ctest --test-dir <build> --repeat until-fail:20 --no-tests=error -R '^guest_timed_wait_cpu$' -V): 20/20 passed on this PR'sTimedWait.cpp; withTimedWait.cppfrommainthe same test fails at the 100 µs case (93.5% calling-thread CPU, limit 40%, abort0xc0000409). Worst over the 20 runs, P99 / max overshoot / CPU:sceKernelUsleep(100 us)1366 µs / 2641 µs / 3.1%;sceKernelUsleep(500 us)1259 µs / 2466 µs / 5.7%;scePthreadCondTimedwait(500 us)1552 µs / 2299 µs / 5.4%. Not rerun from the final pushed head 3d4e1e0.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)