fix(vcores): defer a core move while a guest mutex is held #2417

Open
DuckNintendo wants to merge 3 commits from DuckNintendo/Longshot:pr/06-lock-held into main
Contributor

Summary

A thread owning an nn::os::Mutex can be moved or preempted at a virtual-core checkpoint: a mask change, a better waiter, or YieldThread releases its core, so the rest of the critical section runs on another core (or, if no allowed core frees, with no core at all). The guest’s per-core data and GetCurrentCoreNumber assume the owner stays on one core for the critical section.

This counts the distinct nn::os::Mutex objects a thread owns and keeps a pending scheduler move until the outermost unlock. A block still gives the core up; the count covers nn::os::Mutex only, not svcArbitrateLock or reader/writer locks. The deferred take rewrites the TLS core cell as before.

The follow-up keeps an explicit non-strict yield that was suppressed by a held mutex: it is recorded in vc_yield_pending and retried at the outermost unlock even when no vc_kick asked for the core. The fixture's H3b case queues an equal-priority waiter with no kick, yields while the mutex is held, and requires the unlock to hand the core over. The follow-up also pins the fixture's own HOS_* switches, asserts that the owed condition-variable case reserves the mutex, and releases the contended-mutex test promptly instead of polling a worker that cannot finish until the mutex is released.

Follow-up to the mask-0/core-cache work merged in #327 and #2368.

Testing

Tested: rebased onto current main (694ae582). The host fixture tests/test_vcore_mutex.py cuts the real scheduler block and the real mutex/condition-variable paths, with real SRW locks and std::thread; it covers a remask, waiter pressure, explicit yield/checkpoint (H3 and the new H3b), two mutexes and recursion, condition-variable wait/direct/owed/timed, the non-owner release guard, the TLS cell, a block, TryLock, and an owed relock. It prints ok in 0.7 s.

The follow-up's evidence, all reproducible:

  • L1/H3b: with the old retry (only vc_kick), the new H3b case fails: FAIL: H3b: the waiter never got the deferred yield's core. With the production change it passes, and the equal-priority waiter never got a vc_kick.
  • L2: the fixture now starts from an environment with every inherited HOS_* switch removed before setting HOS_VCORE_ESCAPE_US, HOS_VCORE_ESCAPE_EQ_US and HOS_VCORE_SLICE_US. Running it with HOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1 still prints ok (0.7 s). The owed case now asserts mo.reserved == 1 while the woken waiter is asleep on the mutex.
  • L3: the old contended-mutex case waited for done for 21.8 s before releasing the mutex the worker needed; the new case waits for mwait, checks the waiter's depth, releases, and finishes in 0.7 s.
  • Focused vcore checks: 11 passed, including tests/test_vcore_mutex.py, test_vcore_mask0.py, test_vcore_escape.py, test_cv_signal_race.py, test_cv_handoff_threads.py, test_cv_signal_early.py, test_thread_wake_cleanup.py and test_svc_core_mask.py.
  • Full game-free suite: 765 passed, 17 failed, 110 skipped; untouched main (694ae582) is 764 passed, the same 17 failures, 110 skipped. The 17 are tests/test_bug_report.py, test_cloth_kernels.py, test_control_picture.py, test_crash_record.py, test_dev_update.py, test_framegen_hdr.py, test_guest_holes.py, test_input_background.py, test_lifter.py, test_log_levels.py, test_oot_cloth.py, test_perf_send.py, test_pipeline_tour.py, test_screensaver.py, test_switch_table.py, test_windows_on_linux.py and test_xinput_thread.py. The extra pass is the new fixture.

A fresh base was built with the new longshot-builder from current main (694ae582), and the pack and runtime from f3494c4e. On that rebased head, an integrated Radeon GPU ran a 30 s title/new-game movie smoke: 1012 frames, 33.7 fps mean, 29.4 ms median, 42.7 ms p99, no crash. A 30 s Hyrule Field smoke from the fixed save played 310 frames at 10.33 fps mean, 7.23 fps 1% low, 94.7 ms median, 130.8 ms p99, GPU 39 ms a frame, 0 escapes and no crash. The earlier 4C/8T proxy below remains labelled as the earlier head; it was not rerun on this base.

Still to test:

  • Native Windows: play with a masked and a never-masked thread active, expecting no move or preemption at a checkpoint while nn::os::Mutex is held, and no frame-time regression (by hand).
  • A real Steam Deck or low-core machine: the same, expecting no regression; a better waiter can wait until the holder unlocks (by hand). The 4C/8T taskset proxy is not that hardware.
  • A longer instrumented game route counting deferred kicks, moves at unlock, explicit yields, and escapes with depth > 0 (@Beanstalk or by hand).

Measurements

Verdict: the new H3b check fails against the old retry and passes here; the full suite is unchanged except for the new check. This is a correctness fix, not a performance change.

Setup: Linux host-only; the fixture compiles the production scheduler and mutex/condition-variable blocks with real SRW locks and std::thread; the suite runs each tests/test_*.py in its own process. No GPU path is involved.

Before: main @ 694ae582 After: this PR @ f3494c4e
remask while locked (H1) holder moves at the next checkpoint keeps core and cell; moves at unlock
waiter pressure while locked (H2) holder yields at a checkpoint waiter gets the core at the unlock
explicit yield/checkpoint, kick (H3) holder moves no move; request stays pending
explicit yield, equal-priority waiter, no kick (H3b) waiter never gets the core (old retry fails) waiter gets it at the unlock
recursive/two mutexes (H4) no depth, moves depth counts objects; moves at last unlock
condition-variable wait (H5/H13) no depth; retry under cv->lk would block depth falls; retry after cv->lk; reservation checked
TLS cell (H6) cell follows the moved core early old cell through the deferral, new at the take
contended-mutex fixture 21.8 s (waits for a worker that needs the mutex) 0.7 s (waits for mwait, then releases)
full game-free suite 764 passed / 17 failed / 110 skipped 765 passed / 17 failed / 110 skipped

The mutation controls are reproducible: removing the vc_yield depth guard makes H1–H4/H6 fail; removing the six hos_thread_lock_enter() calls makes H1–H6/H8/H12/H13 fail; removing only the sleeping-lock enter fails the contended case; dropping the owned half of mutex_release_all’s guard fails the non-owner case. Restoring the source returns ok. The H3b case is the new control for a suppressed explicit yield with no kick.

Earlier-head low-core proxies

Setup: the same integrated-GPU PC, the game restricted to CPUs 0-3 and 8-11 (4 cores/8 threads) with taskset, the game's default 6 vcores. These runs are from the earlier head (4d057359), before the L1 follow-up; the scheduling paths are otherwise the same.

Before: main @ 90fae88c After: this PR @ 4d057359
new-game movie · fps mean 31.61 31.66
new-game movie · 1% low fps 21.7 21.1
new-game movie · frame median 31.33 ms 31.18 ms
new-game movie · p99 41.36 ms 42.07 ms
process CPU 156.3 s 160.9 s
Before: main @ 90fae88c After: this PR @ 4d057359
Hyrule Field · fps mean 9.45 9.36
Hyrule Field · 1% low fps 6.48 5.94
Hyrule Field · frame median 105.93 ms 105.66 ms
Hyrule Field · p99 146.06 ms 157.24 ms
process CPU 203.8 s 197.1 s

No crash and 0 escapes on either side. The movie mean is within noise; the gameplay p99 and 1% low were worse in that proxy (about 8% on the p99). At ~9 fps with two runs each, GPU/thermal noise is large enough that this is not separable from the deferral. The fix can delay a waiter until the holder unlocks, so this is the trade-off named in Risks; a real low-core/Deck run is still needed to judge it.

Risks

  • A better waiter can be delayed until the holder unlocks; the existing 1 s starved rule hands it the core at the unlock, and the 2 s escape remains the liveness backstop. A holder that never unlocks can still lead to an escape.
  • A block (hos_vcore_away) still releases the core and can move the holder; only checkpoint moves/yields are deferred.
  • Scope is nn::os::Mutex; svcArbitrateLock, reader/writer write ownership and other guest locks are not counted.
  • A leaked depth (a fiber resumed on another host thread, or guest misuse) conservatively disables moves for that thread rather than underflowing. The non-owner and count-0 wait paths are tested.
  • A pending explicit yield is one relaxed store on a suppressed yield and one exchange at the outermost unlock. It is consumed at that unlock; a block or a later kick still wins.
  • Cost: two uncontended relaxed atomics per mutex acquisition/release and one branch in vc_yield; no new lock is taken.

Checklist

Ready for review

  • One topic, on current main; the title is a Conventional Commit.
  • Tested on my own PC, in the game for a change the game runs, as Testing says.
  • The game-free suite passes (python -I -B tests/run_all.py --jobs 8), with the 17 failures named above.
  • mise run test passes (the same 17 failures named above also fail on main).
  • Measured against main, or Measurements says why there is nothing to measure.
  • No game files, build output or hand-edited generated files; third_party/ untouched; nothing GPL-incompatible.

When it applies

  • A fix: a game-free test that fails on main and passes here.
  • A check under tests/ that reads changed source is updated, not weakened.
  • AI assistance recorded with Assisted-by: / Co-Authored-By: trailers.

Ready to merge

  • Everything in Still to test has run, its results in Tested.
  • Tier 1 hardware it can affect is tested.
  • Approved in review, every comment answered.
  • CI passes on the head.

Generated by opencode with deepseek-v4.1-flash-1017

## Summary A thread owning an `nn::os::Mutex` can be moved or preempted at a virtual-core checkpoint: a mask change, a better waiter, or `YieldThread` releases its core, so the rest of the critical section runs on another core (or, if no allowed core frees, with no core at all). The guest’s per-core data and `GetCurrentCoreNumber` assume the owner stays on one core for the critical section. This counts the distinct `nn::os::Mutex` objects a thread owns and keeps a pending scheduler move until the outermost unlock. A **block** still gives the core up; the count covers `nn::os::Mutex` only, not `svcArbitrateLock` or reader/writer locks. The deferred take rewrites the TLS core cell as before. The follow-up keeps an explicit non-strict yield that was suppressed by a held mutex: it is recorded in `vc_yield_pending` and retried at the outermost unlock even when no `vc_kick` asked for the core. The fixture's H3b case queues an equal-priority waiter with no kick, yields while the mutex is held, and requires the unlock to hand the core over. The follow-up also pins the fixture's own `HOS_*` switches, asserts that the owed condition-variable case reserves the mutex, and releases the contended-mutex test promptly instead of polling a worker that cannot finish until the mutex is released. Follow-up to the mask-0/core-cache work merged in #327 and #2368. ## Testing **Tested:** rebased onto current `main` (`694ae582`). The host fixture `tests/test_vcore_mutex.py` cuts the real scheduler block and the real mutex/condition-variable paths, with real SRW locks and `std::thread`; it covers a remask, waiter pressure, explicit yield/checkpoint (H3 and the new H3b), two mutexes and recursion, condition-variable wait/direct/owed/timed, the non-owner release guard, the TLS cell, a block, TryLock, and an owed relock. It prints `ok` in 0.7 s. The follow-up's evidence, all reproducible: - **L1/H3b:** with the old retry (only `vc_kick`), the new H3b case fails: `FAIL: H3b: the waiter never got the deferred yield's core`. With the production change it passes, and the equal-priority waiter never got a `vc_kick`. - **L2:** the fixture now starts from an environment with every inherited `HOS_*` switch removed before setting `HOS_VCORE_ESCAPE_US`, `HOS_VCORE_ESCAPE_EQ_US` and `HOS_VCORE_SLICE_US`. Running it with `HOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1` still prints `ok` (0.7 s). The owed case now asserts `mo.reserved == 1` while the woken waiter is asleep on the mutex. - **L3:** the old contended-mutex case waited for `done` for 21.8 s before releasing the mutex the worker needed; the new case waits for `mwait`, checks the waiter's depth, releases, and finishes in 0.7 s. - Focused vcore checks: 11 passed, including `tests/test_vcore_mutex.py`, `test_vcore_mask0.py`, `test_vcore_escape.py`, `test_cv_signal_race.py`, `test_cv_handoff_threads.py`, `test_cv_signal_early.py`, `test_thread_wake_cleanup.py` and `test_svc_core_mask.py`. - Full game-free suite: **765 passed, 17 failed, 110 skipped**; untouched `main` (`694ae582`) is **764 passed, the same 17 failures, 110 skipped**. The 17 are `tests/test_bug_report.py`, `test_cloth_kernels.py`, `test_control_picture.py`, `test_crash_record.py`, `test_dev_update.py`, `test_framegen_hdr.py`, `test_guest_holes.py`, `test_input_background.py`, `test_lifter.py`, `test_log_levels.py`, `test_oot_cloth.py`, `test_perf_send.py`, `test_pipeline_tour.py`, `test_screensaver.py`, `test_switch_table.py`, `test_windows_on_linux.py` and `test_xinput_thread.py`. The extra pass is the new fixture. A fresh base was built with the new `longshot-builder` from current `main` (`694ae582`), and the pack and runtime from `f3494c4e`. On that rebased head, an integrated Radeon GPU ran a 30 s title/new-game movie smoke: 1012 frames, 33.7 fps mean, 29.4 ms median, 42.7 ms p99, no crash. A 30 s Hyrule Field smoke from the fixed save played 310 frames at 10.33 fps mean, 7.23 fps 1% low, 94.7 ms median, 130.8 ms p99, GPU 39 ms a frame, 0 escapes and no crash. The earlier 4C/8T proxy below remains labelled as the earlier head; it was not rerun on this base. **Still to test:** - Native Windows: play with a masked and a never-masked thread active, expecting no move or preemption at a checkpoint while `nn::os::Mutex` is held, and no frame-time regression (by hand). - A real Steam Deck or low-core machine: the same, expecting no regression; a better waiter can wait until the holder unlocks (by hand). The 4C/8T `taskset` proxy is not that hardware. - A longer instrumented game route counting deferred kicks, moves at unlock, explicit yields, and escapes with depth > 0 (@Beanstalk or by hand). ## Measurements **Verdict:** the new H3b check fails against the old retry and passes here; the full suite is unchanged except for the new check. This is a correctness fix, not a performance change. Setup: Linux host-only; the fixture compiles the production scheduler and mutex/condition-variable blocks with real SRW locks and `std::thread`; the suite runs each `tests/test_*.py` in its own process. No GPU path is involved. | | Before: main @ 694ae582 | After: this PR @ f3494c4e | |---|---|---| | remask while locked (H1) | holder moves at the next checkpoint | keeps core and cell; moves at unlock | | waiter pressure while locked (H2) | holder yields at a checkpoint | waiter gets the core at the unlock | | explicit yield/checkpoint, kick (H3) | holder moves | no move; request stays pending | | explicit yield, equal-priority waiter, no kick (H3b) | waiter never gets the core (`old retry` fails) | waiter gets it at the unlock | | recursive/two mutexes (H4) | no depth, moves | depth counts objects; moves at last unlock | | condition-variable wait (H5/H13) | no depth; retry under `cv->lk` would block | depth falls; retry after `cv->lk`; reservation checked | | TLS cell (H6) | cell follows the moved core early | old cell through the deferral, new at the take | | contended-mutex fixture | 21.8 s (waits for a worker that needs the mutex) | 0.7 s (waits for `mwait`, then releases) | | full game-free suite | 764 passed / 17 failed / 110 skipped | 765 passed / 17 failed / 110 skipped | The mutation controls are reproducible: removing the `vc_yield` depth guard makes H1–H4/H6 fail; removing the six `hos_thread_lock_enter()` calls makes H1–H6/H8/H12/H13 fail; removing only the sleeping-lock enter fails the contended case; dropping the `owned` half of `mutex_release_all`’s guard fails the non-owner case. Restoring the source returns `ok`. The H3b case is the new control for a suppressed explicit yield with no kick. ### Earlier-head low-core proxies Setup: the same integrated-GPU PC, the game restricted to CPUs 0-3 and 8-11 (4 cores/8 threads) with `taskset`, the game's default 6 vcores. These runs are from the earlier head (`4d057359`), before the L1 follow-up; the scheduling paths are otherwise the same. | | Before: main @ 90fae88c | After: this PR @ 4d057359 | |---|---|---| | new-game movie · fps mean | 31.61 | 31.66 | | new-game movie · 1% low fps | 21.7 | 21.1 | | new-game movie · frame median | 31.33 ms | 31.18 ms | | new-game movie · p99 | 41.36 ms | 42.07 ms | | process CPU | 156.3 s | 160.9 s | | | Before: main @ 90fae88c | After: this PR @ 4d057359 | |---|---|---| | Hyrule Field · fps mean | 9.45 | 9.36 | | Hyrule Field · 1% low fps | 6.48 | 5.94 | | Hyrule Field · frame median | 105.93 ms | 105.66 ms | | Hyrule Field · p99 | 146.06 ms | 157.24 ms | | process CPU | 203.8 s | 197.1 s | No crash and 0 escapes on either side. The movie mean is within noise; the gameplay p99 and 1% low were worse in that proxy (about 8% on the p99). At ~9 fps with two runs each, GPU/thermal noise is large enough that this is not separable from the deferral. The fix can delay a waiter until the holder unlocks, so this is the trade-off named in Risks; a real low-core/Deck run is still needed to judge it. ## Risks - A better waiter can be delayed until the holder unlocks; the existing 1 s starved rule hands it the core at the unlock, and the 2 s escape remains the liveness backstop. A holder that never unlocks can still lead to an escape. - A block (`hos_vcore_away`) still releases the core and can move the holder; only checkpoint moves/yields are deferred. - Scope is `nn::os::Mutex`; `svcArbitrateLock`, reader/writer write ownership and other guest locks are not counted. - A leaked depth (a fiber resumed on another host thread, or guest misuse) conservatively disables moves for that thread rather than underflowing. The non-owner and count-0 wait paths are tested. - A pending explicit yield is one relaxed store on a suppressed yield and one exchange at the outermost unlock. It is consumed at that unlock; a block or a later kick still wins. - Cost: two uncontended relaxed atomics per mutex acquisition/release and one branch in `vc_yield`; no new lock is taken. ## Checklist ### Ready for review - [x] One topic, on current `main`; the title is a Conventional Commit. - [x] Tested on my own PC, in the game for a change the game runs, as Testing says. - [x] The game-free suite passes (`python -I -B tests/run_all.py --jobs 8`), with the 17 failures named above. - [x] `mise run test` passes (the same 17 failures named above also fail on `main`). - [x] Measured against `main`, or Measurements says why there is nothing to measure. - [x] No game files, build output or hand-edited generated files; `third_party/` untouched; nothing GPL-incompatible. ### When it applies - [x] A fix: a game-free test that fails on `main` and passes here. - [x] A check under `tests/` that reads changed source is updated, not weakened. - [x] AI assistance recorded with `Assisted-by:` / `Co-Authored-By:` trailers. ### Ready to merge - [ ] Everything in Still to test has run, its results in Tested. - [ ] Tier 1 hardware it can affect is tested. - [ ] Approved in review, every comment answered. - [ ] CI passes on the head. Generated by opencode with deepseek-v4.1-flash-1017
fix(vcores): defer a core move while a guest mutex is held
Some checks failed
Guide screenshots / Guide images and local UI source review (pull_request) Blocked by required conditions
Third-party parts / As their notes say (pull_request) Blocked by required conditions
Third-party parts / The same as upstream (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request_target) Has been skipped
PR description / Description follows the template (pull_request_target) Successful in 6s
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
4d0573595a
A thread owning an nn::os::Mutex could be moved or preempted at a vcore
checkpoint (a mask change, a better waiter, or an explicit yield), so the rest
of its critical section ran on another core. Count the distinct mutex objects
a thread owns and keep a pending scheduler move until the outermost unlock;
a block still gives the core up, and the retry runs only with no host lock
held. The TLS cell follows the actual take.

The host fixture cuts the real scheduler block and the real mutex/condition
variable paths and checks a remask, waiter pressure, yield/checkpoint, two
mutexes and recursion, a condition-variable wait and its non-owner guard, the
TLS cell, a block, TryLock, and an owed relock. Removing the yield guard or
the enter hooks makes it fail.

Assisted-by: opencode (deepseek-v4.1-flash)
Member

Possibly related, for context:

  • PR #1957 WIP: perf(os): LockMutex's wait out of line, and LockMutex/UnlockMutex take the calling thread and the core checkpoint's test from their context — Open mutex/core-checkpoint work touches the same lock and scheduler paths; check for overlap/conflicts.
  • PR #594 fix(vcores): a thread starved of its core gets it after 1 s, not an escape after 2 s (#262) — Merged virtual-core starvation behavior is relevant to the unlock handoff/liveness assumptions.
Possibly related, for context: - PR #1957 WIP: perf(os): LockMutex's wait out of line, and LockMutex/UnlockMutex take the calling thread and the core checkpoint's test from their context — Open mutex/core-checkpoint work touches the same lock and scheduler paths; check for overlap/conflicts. - PR #594 fix(vcores): a thread starved of its core gets it after 1 s, not an escape after 2 s (#262) — Merged virtual-core starvation behavior is relevant to the unlock handoff/liveness assumptions.
Owner
@review
BeanBot left a comment

Recommendation: Approve. The fixture demonstrates the intended checkpoint deferral, but its cost on a real low-core machine and its behavior on Windows remain untested. The recorded low-core proxy also shows worse tail frame times, so the scheduling trade-off needs a representative run before merge. Nothing blocking is left: what remains is for the author before merging (below). Recommend approval; not approved on the forge.

This keeps checkpoint-driven virtual-core moves pending while a thread owns guest mutexes and retries them after the last unlock. It addresses the tested critical-section move at the cost of delaying other runnable threads and adding work to mutex operations.

Should fix (3): not blocking, but worth doing before merging.

  • L1 host/hos_thread.c:2175: An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick. (more on the line) Do: Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick.
  • L2 tests/test_vcore_mutex.py:704: The fixture inherits scheduler and handoff switches from the invoking environment. (more on the line) Do: Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex.
  • L3 tests/test_vcore_mutex.py:617: The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs. (more on the line) Do: Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly.

Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)

  • L4 host/hos_thread.c:2175: The scheduling change needs representative platform and contention runs before its cost and behavior are settled. (more on the line) Do: Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows.

@fix can do L1, L2 and L3.

Checks: Still running: 9 checks.

More: does it help, other systems, switches, what was read

Does it help: Yes for the deterministic checkpoint cases: the author reports the fixture failing without the production guards and passing with them. The rare game failure was not reproduced; in the 4-core/8-thread gameplay proxy, p99 rose from 146.06 to 157.24 ms and 1% low fell from 6.48 to 5.94 fps across two runs per side, so the gameplay cost remains unproven.

Other systems: The scheduler and mutex paths run on Windows and Linux regardless of GPU. The author reports a Linux 780M smoke run and a CPU-restricted proxy; native Windows, a real Steam Deck or low-core machine, and a longer instrumented route remain untested. Blocking operations can still move a mutex holder, as the description states.

Switches: None added, changed, or removed.

Reviewed: 4d0573595a against 90fae88c13: Read the repository rules, standards, pull request template, commit and diff; inspected the changed scheduler and synchronization paths, their callers and the new fixture. Skimmed the existing modified fixtures and recorded runs. Tooling's adjacent AGENTS.md and docs/review-checklist.md were absent. The large host files were not read in full.; nothing run (a code review).

Checked and fine:

  • The commit includes an AI-assistance trailer.
  • The diff changes no generated files, renderer API, shaders, switch table, or third-party files.
  • The condition-variable retry is placed after releasing the host condition-variable lock.

Testing: Read-only review; no code, builds, or tests were run. The pull request reports its own fixture, suite and Linux game runs; CI is still running.

Overlaps and merge order: Not checked; the network is closed.


Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.

**Recommendation: Approve.** The fixture demonstrates the intended checkpoint deferral, but its cost on a real low-core machine and its behavior on Windows remain untested. The recorded low-core proxy also shows worse tail frame times, so the scheduling trade-off needs a representative run before merge. Nothing blocking is left: what remains is for the author before merging (below). Recommend approval; not approved on the forge. This keeps checkpoint-driven virtual-core moves pending while a thread owns guest mutexes and retries them after the last unlock. It addresses the tested critical-section move at the cost of delaying other runnable threads and adding work to mutex operations. **Should fix (3)**: not blocking, but worth doing before merging. - **L1** `host/hos_thread.c:2175`: An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick. (more on the line) **Do:** Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick. - **L2** `tests/test_vcore_mutex.py:704`: The fixture inherits scheduler and handoff switches from the invoking environment. (more on the line) **Do:** Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex. - **L3** `tests/test_vcore_mutex.py:617`: The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs. (more on the line) **Do:** Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly. **Testing before merging (1)** (runs on the systems it can change; it doesn't hold the recommendation) - **L4** `host/hos_thread.c:2175`: The scheduling change needs representative platform and contention runs before its cost and behavior are settled. (more on the line) **Do:** Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows. `@fix` can do L1, L2 and L3. **Checks:** Still running: 9 checks. <details> <summary>More: does it help, other systems, switches, what was read</summary> **Does it help:** Yes for the deterministic checkpoint cases: the author reports the fixture failing without the production guards and passing with them. The rare game failure was not reproduced; in the 4-core/8-thread gameplay proxy, p99 rose from 146.06 to 157.24 ms and 1% low fell from 6.48 to 5.94 fps across two runs per side, so the gameplay cost remains unproven. **Other systems:** The scheduler and mutex paths run on Windows and Linux regardless of GPU. The author reports a Linux 780M smoke run and a CPU-restricted proxy; native Windows, a real Steam Deck or low-core machine, and a longer instrumented route remain untested. Blocking operations can still move a mutex holder, as the description states. **Switches:** None added, changed, or removed. **Reviewed:** 4d0573595a5b against 90fae88c1396: Read the repository rules, standards, pull request template, commit and diff; inspected the changed scheduler and synchronization paths, their callers and the new fixture. Skimmed the existing modified fixtures and recorded runs. Tooling's adjacent AGENTS.md and docs/review-checklist.md were absent. The large host files were not read in full.; nothing run (a code review). **Checked and fine:** - The commit includes an AI-assistance trailer. - The diff changes no generated files, renderer API, shaders, switch table, or third-party files. - The condition-variable retry is placed after releasing the host condition-variable lock. **Testing:** Read-only review; no code, builds, or tests were run. The pull request reports its own fixture, suite and Linux game runs; CI is still running. **Overlaps and merge order:** Not checked; the network is closed. </details> --- <sub>Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.</sub>
@ -2167,0 +2172,4 @@
/* A guest mutex held: a move now would run the rest of the critical section on another core, which the guest's
per-core data (and the core it reports) does not allow. The request stays pending (vc_kick is not cleared) and
the outermost unlock's retry takes it (hos_thread_lock_retry). Blocks still give the core up (hos_vcore_away). */
if (__atomic_load_n(&t->vc_lock_depth, __ATOMIC_RELAXED) > 0) return;
Member

L1 (should fix): An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick.

When: An equal-priority thread is queued for the holder's core but has not yet waited the 2 ms slice needed to set a kick. If the mutex holder calls YieldThread, this guard returns; an immediate unlock sees no kick and does not yield, delaying that waiter until a later scheduler request.

Do: Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick.

**L1** (should fix): An explicit yield can be discarded instead of deferred because this return does not record it, and the unlock retry only acts on vc_kick. *When:* An equal-priority thread is queued for the holder's core but has not yet waited the 2 ms slice needed to set a kick. If the mutex holder calls YieldThread, this guard returns; an immediate unlock sees no kick and does not yield, delaying that waiter until a later scheduler request. **Do:** Record a pending non-strict explicit yield when it is suppressed and retry it at the outermost unlock, with a fixture case where a waiter is queued without a kick.
Member

L4 (should fix): The scheduling change needs representative platform and contention runs before its cost and behavior are settled.

When: A higher-priority waiter now remains blocked until the holder unlocks; the low-core proxy reports an approximately 8% worse p99, but its two runs cannot distinguish the change from noise.

Do: Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows.

**L4** (should fix): The scheduling change needs representative platform and contention runs before its cost and behavior are settled. *When:* A higher-priority waiter now remains blocked until the holder unlocks; the low-core proxy reports an approximately 8% worse p99, but its two runs cannot distinguish the change from noise. **Do:** Run the described native Windows and real Steam Deck or low-core checks, plus the longer instrumented route, comparing the same gameplay and settings against the base and reporting deferred kicks, escapes, frame times and 1% lows.
@ -0,0 +614,4 @@
done.store(1);
});
while (!started.load()) std::this_thread::yield();
for (int i = 0; i < 20000 && !done.load(); i++) std::this_thread::sleep_for(std::chrono::milliseconds(1));
Member

L3 (should fix): The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs.

When: On every successful run, done cannot become true while the main thread still owns mo, so the loop consumes its entire 20,000-iteration timeout before the test can proceed.

Do: Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly.

**L3** (should fix): The contended mutex case waits for its worker to finish before releasing the mutex that the worker needs. *When:* On every successful run, done cannot become true while the main thread still owns mo, so the loop consumes its entire 20,000-iteration timeout before the test can proceed. **Do:** Wait for an explicit signal that the worker has entered the contended wait, then check its depth and release the mutex promptly.
@ -0,0 +701,4 @@
flags.append("-pthread")
subprocess.run([compiler, *flags, "-include", str(ENV_ON_H), str(folder / "fixture.cpp"), "-o", str(exe)],
check=True, timeout=120)
env = {k: v for k, v in os.environ.items() if k != "HOS_VCORES"} # (the virtual cores on)
Member

L2 (should fix): The fixture inherits scheduler and handoff switches from the invoking environment.

When: With HOS_NO_HANDOFF=1, cv_reserve does not reserve the mutex, so the cases labelled as testing the owed relock take the ordinary mutex path and can pass without exercising the owed hooks.

Do: Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex.

**L2** (should fix): The fixture inherits scheduler and handoff switches from the invoking environment. *When:* With HOS_NO_HANDOFF=1, cv_reserve does not reserve the mutex, so the cases labelled as testing the owed relock take the ordinary mutex path and can pass without exercising the owed hooks. **Do:** Remove inherited HOS_ switches from the fixture environment before setting the values required by the test, and assert that the owed cases actually reserve the mutex.
Owner
@fix
Member

I didn't fix this pull request: it doesn't allow edits from maintainers (the author can turn on Allow edits from maintainers).


Automated fix by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.

I didn't fix this pull request: it doesn't allow edits from maintainers (the author can turn on *Allow edits from maintainers*). --- <sub>Automated fix by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.</sub>
DuckNintendo force-pushed pr/06-lock-held from 4d0573595a
Some checks failed
Guide screenshots / Guide images and local UI source review (pull_request) Blocked by required conditions
Third-party parts / As their notes say (pull_request) Blocked by required conditions
Third-party parts / The same as upstream (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request_target) Has been skipped
PR description / Description follows the template (pull_request_target) Successful in 6s
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
to f3494c4ebc
Some checks are pending
CI / What the change needs (pull_request) Blocked by required conditions
CI / Lint (pre-commit, ShellCheck, actionlint) (pull_request) Blocked by required conditions
CI / Third-party parts and guide screenshots (pull_request) Blocked by required conditions
CI / Rust (rustfmt, clippy, cargo test, end to end) (pull_request) Blocked by required conditions
CI / Host C for Windows (llvm-mingw, compile only) (pull_request) Blocked by required conditions
CI / Renderer build check (Windows, compile --only renderer, without and with FSR 4) (pull_request) Blocked by required conditions
CI / Renderer build check (Linux, compile --only renderer, without and with FSR 4) (pull_request) Blocked by required conditions
CI / Game-free checks (run_all.py, part 1/2) (pull_request) Blocked by required conditions
CI / Game-free checks (run_all.py, part 2/2) (pull_request) Blocked by required conditions
CI / Website build and checks (pull_request) Blocked by required conditions
PR description / Title and description (pull_request_target) Successful in 6s
2026-11-28 23:28:48 +00:00
Compare
Author
Contributor

The L1–L3 items are fixed on f3494c4e, rebased onto current main (694ae582):

  • L1: vc_yield now records a non-strict yield that a held mutex suppressed in vc_yield_pending; hos_thread_lock_retry consumes it at the outermost unlock after checking vc_kick. The new H3b case (an equal-priority waiter queued with no kick) fails with the old retry (FAIL: H3b: the waiter never got the deferred yield's core) and passes here.
  • L2: the fixture removes every inherited HOS_* switch before setting its own. It passes with HOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1, and the owed condition-variable case now asserts reserved == 1 while the woken waiter sleeps on the mutex.
  • L3: the contended case waits for mwait, checks the waiter's depth, and releases promptly: the old fixture took 21.8 s, the new one 0.7 s.

Evidence: 11 focused vcore checks passed; the full game-free suite is 765 passed / 17 failed / 110 skipped against 764 / the same 17 / 110 on untouched main (the same local toolchain failures named in the description). The description check passes. Maintainer edits are enabled.

Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route. The earlier 4C/8T proxy is in the description, labelled as the earlier head; the rebuilt-head smoke is in the next comment.

Generated by opencode with deepseek-v4.1-flash-1017

The L1–L3 items are fixed on `f3494c4e`, rebased onto current `main` (`694ae582`): - **L1:** `vc_yield` now records a non-strict yield that a held mutex suppressed in `vc_yield_pending`; `hos_thread_lock_retry` consumes it at the outermost unlock after checking `vc_kick`. The new H3b case (an equal-priority waiter queued with no kick) fails with the old retry (`FAIL: H3b: the waiter never got the deferred yield's core`) and passes here. - **L2:** the fixture removes every inherited `HOS_*` switch before setting its own. It passes with `HOS_NO_HANDOFF=1 HOS_VCORES=0 HOS_VCORE_SLICE_US=1 HOS_VCORE_ESCAPE_US=1 HOS_VCORE_ESCAPE_EQ_US=1`, and the owed condition-variable case now asserts `reserved == 1` while the woken waiter sleeps on the mutex. - **L3:** the contended case waits for `mwait`, checks the waiter's depth, and releases promptly: the old fixture took 21.8 s, the new one 0.7 s. Evidence: 11 focused vcore checks passed; the full game-free suite is **765 passed / 17 failed / 110 skipped** against **764 / the same 17 / 110** on untouched `main` (the same local toolchain failures named in the description). The description check passes. Maintainer edits are enabled. Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route. The earlier 4C/8T proxy is in the description, labelled as the earlier head; the rebuilt-head smoke is in the next comment. Generated by opencode with deepseek-v4.1-flash-1017
Author
Contributor

The pack base is now rebuilt with the new longshot-builder from 694ae582; the pack and runtime are from f3494c4e (the same head). On that base:

  • Title/new-game movie, 30 s: 1012 frames, 33.7 fps mean, 29.4 ms median, 42.7 ms p99, no crash.
  • Hyrule Field from the fixed save, 30 s: 310 frames, 10.33 fps mean, 7.23 fps 1% low, 94.7 ms median, 130.8 ms p99, GPU 39 ms a frame, 0 escapes, no crash.

No profiler and no memfd were used. The code is unchanged since f3494c4e; the fresh base is bench-base-694 locally. Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route.

Generated by opencode with deepseek-v4.1-flash-1017

The pack base is now rebuilt with the new `longshot-builder` from `694ae582`; the pack and runtime are from `f3494c4e` (the same head). On that base: - Title/new-game movie, 30 s: **1012 frames, 33.7 fps mean**, 29.4 ms median, 42.7 ms p99, no crash. - Hyrule Field from the fixed save, 30 s: **310 frames, 10.33 fps mean, 7.23 fps 1% low**, 94.7 ms median, 130.8 ms p99, GPU 39 ms a frame, 0 escapes, no crash. No profiler and no memfd were used. The code is unchanged since `f3494c4e`; the fresh base is `bench-base-694` locally. Still to test: native Windows, a real Steam Deck or low-core machine, and the longer instrumented route. Generated by opencode with deepseek-v4.1-flash-1017
futondestroyer left a comment

Recommendation: Request changes. The new fixture verifies the deferred yield with no kick. The same explicit yield can still be dropped when a strict kick is present at unlock.

hos_thread_lock_retry clears vc_yield_pending before handling the kick. When that kick is strict, the checkpoint only yields to a higher-priority eligible waiter. If the waiter that requested the kick no longer needs the core and an equal-priority waiter is still eligible, the strict check has no effect and the explicit yield is lost. Let the recorded yield retain its non-strict semantics when both requests are present. Extend the existing fixture to cover a strict kick and a pending explicit yield together.

The author's exact-head Linux run reports 11 focused passes and 765 passed, 17 failed, 110 skipped in the full suite, with the same failures on its base. The earlier 4-core proxy showed Hyrule Field p99 of 146.06 to 157.24 ms with two runs per side. Repeat on real Deck or comparable hardware and cover Windows before merge. Exact-head CI remains blocked. Reviewed f3494c4ebc1bf5e59b9ddbc944eac4dccd459d51 against actual base 694ae582, with Forge target 01d6878b. CI

**Recommendation: Request changes.** The new fixture verifies the deferred yield with no kick. The same explicit yield can still be dropped when a strict kick is present at unlock. `hos_thread_lock_retry` clears `vc_yield_pending` before handling the kick. When that kick is strict, the checkpoint only yields to a higher-priority eligible waiter. If the waiter that requested the kick no longer needs the core and an equal-priority waiter is still eligible, the strict check has no effect and the explicit yield is lost. Let the recorded yield retain its non-strict semantics when both requests are present. Extend the existing fixture to cover a strict kick and a pending explicit yield together. The author's exact-head Linux run reports 11 focused passes and 765 passed, 17 failed, 110 skipped in the full suite, with the same failures on its base. The earlier 4-core proxy showed Hyrule Field p99 of 146.06 to 157.24 ms with two runs per side. Repeat on real Deck or comparable hardware and cover Windows before merge. Exact-head CI remains blocked. Reviewed `f3494c4ebc1bf5e59b9ddbc944eac4dccd459d51` against actual base `694ae582`, with Forge target `01d6878b`. [CI](https://git.magicbean.dev/MagicBeanDev/Longshot/actions/runs/57223)
@ -2286,0 +2316,4 @@
HosThread *t = cur;
if (!t || __atomic_load_n(&t->vc_lock_depth, __ATOMIC_RELAXED) != 0) return;
const int kick = __atomic_load_n(&t->vc_kick, __ATOMIC_RELAXED);
const int pending = __atomic_exchange_n(&t->vc_yield_pending, 0, __ATOMIC_RELAXED);
Member

[P2] Preserve a recorded non-strict yield when there is also a strict kick. The exchange clears it before the checkpoint can reject an equal-priority waiter. Cover both requests together when the higher-priority waiter no longer needs the core.

[P2] Preserve a recorded non-strict yield when there is also a strict kick. The exchange clears it before the checkpoint can reject an equal-priority waiter. Cover both requests together when the higher-priority waiter no longer needs the core.
Some checks are pending
CI / What the change needs (pull_request) Blocked by required conditions
CI / Lint (pre-commit, ShellCheck, actionlint) (pull_request) Blocked by required conditions
CI / Third-party parts and guide screenshots (pull_request) Blocked by required conditions
CI / Rust (rustfmt, clippy, cargo test, end to end) (pull_request) Blocked by required conditions
CI / Host C for Windows (llvm-mingw, compile only) (pull_request) Blocked by required conditions
CI / Renderer build check (Windows, compile --only renderer, without and with FSR 4) (pull_request) Blocked by required conditions
CI / Renderer build check (Linux, compile --only renderer, without and with FSR 4) (pull_request) Blocked by required conditions
CI / Game-free checks (run_all.py, part 1/2) (pull_request) Blocked by required conditions
CI / Game-free checks (run_all.py, part 2/2) (pull_request) Blocked by required conditions
CI / Website build and checks (pull_request) Blocked by required conditions
PR description / Title and description (pull_request_target) Successful in 6s
This pull request doesn't have enough approvals yet. 0 of 1 approvals granted.
Some workflows are waiting to be reviewed.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'pr/06-lock-held:DuckNintendo-pr/06-lock-held'
git switch 'DuckNintendo-pr/06-lock-held'
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
4 participants
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
MagicBeanDev/Longshot!2417
No description provided.