Skip to content

Engine-wide: SpinWait-based waiting gives a 2.7 µs spin budget then a 4.4 ms yield — locks have no wake path #803

Open

Description

@nockawa

Every wait path in the engine funnels into .NET's SpinWait.SpinOnce(). Measured, that primitive gives a 2.7 µs spin budget and then falls off a cliff: on a saturated runqueue the first Thread.Yield() costs 4 434 µs, and Thread.Sleep(1) costs 15 000 µs. For a critical section measured in microseconds — which is most of Typhon's — that is a ~1 600× penalty for missing the lock by 3 µs.

Found while root-causing #802, where it turns a sub-microsecond critical section into 6.8 ms/tick of stall. But #802 is one caller; this is the shared primitive underneath 43 call sites across 16 files.

Measured

Scratch POC, 32 logical CPUs, Stopwatch.Frequency = 10 MHz. One SpinWait run to completion, timing each SpinOnce() individually — first on an idle machine, then with every core busy:

iteration idle machine all cores busy
0–9 (pure spin phase) 2.7 µs total 2.7 µs total
10 — first yield 4.0 µs 4 434 µs
12 0.3 µs 2 898 µs
14 0.2 µs 859 µs
20 — first Sleep(1) 7 185 µs 13 897 µs
21+ ~15 000 µs each 10 000–40 000 µs each

Three findings:

  1. The entire pure-spin budget is 2.7 µs. Ten iterations of Thread.SpinWait with a doubling count, and that is the whole thing.

  2. On a saturated machine the first Thread.Yield() costs 4.4 ms — not the Sleep(1), the yield. When the runqueue is full, yielding hands the core to another runnable thread and it is not returned until a full scheduler quantum later. Typhon runs ProcessorCount - 2 workers by default, so the saturated case is the normal case.

  3. Thread.Sleep(1) measures 15 ms, not 1 ms — the global Windows timer resolution sits at its 15.6 ms default. Whatever HighResolutionTimerServiceBase raises, it is not the process-wide timer as seen by Sleep. The BCL's "real CPU relief" step is a 15 ms stall.

Scope

SpinOnce() is reached from 43 call sites in 16 files:

AccessControlSmall, AccessControl.LockData, ResourceAccessControl, AdaptiveWaiter, PagedMMF, PagedMMF.PageInfo, BTree (+.Insert, .Remove), WalCommitBuffer, SpatialRTree, TransientStore, ConcurrentArray, ConcurrentBitmapL3Any, ViewDeltaRingBuffer, DatabaseEngine.ClusterMigration.

AdaptiveWaiter is not a different policy. Its own doc comment says the progression is "delegated to SpinWait.SpinOnce()". It adds a telemetry emit on the spin→yield transition and nothing else. The engine has no bounded-spin primitive at all — the name suggests a tuned waiter and there is none behind it.

The structural flaw: poll-only waiting

AccessControlSmall.ExitExclusiveAccess is a bare atomic store. Nothing notifies a waiter. So a waiter's only options are to burn CPU or to sleep on a timer — and the timer has 15.6 ms granularity. There is no path by which a releaser can wake a waiter promptly.

That is why the backoff schedule matters so much here and why no amount of tuning fully fixes it: the wake latency is bounded below by the polling interval, not by the release.

Why "just spin longer" is not sufficient on its own

Tempting, and it is the right direction, but the required budget is not a property of the critical section — it is a property of the convoy. In #802, 45 chunks converge on one latch with a ~1 µs hold, so a waiter may need to outlast 45 × hold ≈ 45 µs, and that scales with worker count. Sizing the spin to survive that means picking a number that grows with core count.

Spinning is also nearly free in #802's case (every worker is in the same phase barrier, so there is no other work to steal the core) and decidedly not free at the PagedMMF / BTree call sites, where a spinning waiter starves a thread that has real work. One global constant cannot be right for both.

Suggested direction

Not a design — a starting point for one:

  1. Never call Thread.Sleep(1). At 15.6 ms granularity it is pathological for every call site in the list.
  2. Two-phase waiting: bounded spin (calibrated, and larger than 2.7 µs), then park on a real OS wait released by the unlocker. That converts the 15 ms poll into a 5–50 µs wake and removes the yield cliff entirely. Requires giving AccessControlSmall / AccessControl a wake path, which they do not have today.
  3. Make the spin budget a property of the call site, not one global constant — a page latch, a B-tree node latch and a fence-phase epilogue have different hold-time distributions and different opportunity costs for burning a core.
  4. Whatever lands, it should be measured under saturation, not on an idle box. Every one of the pathological numbers above is invisible when cores are free.

Relationship to #802

Independent. #802 should be fixed by removing the lock from that path (a barrier drain), regardless of what happens here — a lock on a path every worker traverses every dispatch is wrong even with a perfect waiter. This issue is the floor-raiser underneath it, and it is what turns any short-critical-section contention anywhere in the engine into millisecond stalls.

Reproduction

POC measuring the progression, dotnet run spin.cs:

var sw = new SpinWait();
for (int i = 0; i < 30; i++)
{
    long t0 = Stopwatch.GetTimestamp();
    sw.SpinOnce();
    Console.WriteLine($"{i} {(Stopwatch.GetTimestamp() - t0) * 1e6 / Stopwatch.Frequency:F2} us");
}

Run it once as-is, then again with Environment.ProcessorCount background threads busy-spinning to reproduce the saturated column.

Activity

  1. added
    performance
    on Aug 14, 2026
  2. self-assigned this
    on Aug 14, 2026
  3. added theissue type on Aug 14, 2026
  4. updated Product Engine, Priority P0-Critical and Area Concurrency on Aug 14, 2026
  5. moved this to Todo in Typhonon Aug 14, 2026
  6. nockawa commented on Aug 14, 2026

    @nockawa
    CollaboratorAuthor

    Tier 1 landed (f286b40) — no measurable effect, and it removes the only backpressure on pathological waits

    AccessControl and AccessControlSmall now pass SpinOnce(-1), which disables the BCL's Thread.Sleep(1) escalation. Three call sites, two files. The loop bounds make the old worst case concrete: WaitForSharedCanStart runs to 100 iterations and the BCL escalates at 20, so up to 80 could land on the 15.625 ms timer (~1.2 s); WaitForIdleState runs to 1000, so up to 980 (~15 s) on one wait pass.

    This was already the convention elsewhere in the engine — BTree's three OLC restart loops, ConcurrentHashMap, ConcurrentHashMapKV, PagedHashMapBase all pass -1. The two primary lock primitives were simply missed, their SpinWait being two abstraction layers below every call site.

    Measured impact: none

    Baseline Tier 1
    SwgFixtureStressTests ×3 6044 / 5861 / 6002 ms 5814 / 5871 / 5742 ms
    Full suite 1 m 26 s 1 m 24 s

    Inside noise. Expected: reaching iteration 20 takes ~20 consecutive failed acquisitions, and the suite does not sustain that on a 32-thread box. Full suite 5299 passed / 0 failed; ChaosStressTests failure set is a subset of the unmodified baseline's.

    The risk this introduces, which argues for Tier 2

    With Sleep(1) gone the BCL alternates Yield() and Sleep(0) forever. No livelock (Yield() genuinely relinquishes, so the holder can always be scheduled) and no arm64 concern (the flag selects a BCL branch; no ordering added or removed). But:

    • TimeoutOptions defaults are 5 s (page cache, B-tree, revision chain) and 10 s (transaction chain, segment allocation). A waiter that previously spent that deadline asleep now polls hot for all of it.
    • 22 acquisition sites wait with no deadline at all (ref WaitContext.Null / ref nullCtx), including every _finalizeLock acquisition. For those, Sleep(1) was the only thing stopping a pathological wait from pegging a core.

    Arguably a diagnostic improvement — a pegged core is visible where a sleeping thread is not — but it means Tier 1 should not be the end state. A bounded, call-site-tuned spin budget (Tier 2) is what stops a 5-second hot poll, and WaitContext is already threaded by-ref into every Enter* call, so it is the natural carrier.

    On the numbers in this issue

    The 4.4 ms first-yield and 15 ms Sleep(1) figures are real for the primitive in isolation, but the engine-level impact from the same session should be re-checked: that dotTrace run measures ~1,190 ms/tick against an unprofiled 8.6 ms/tick. See #802 (comment).

    Suggested split

    Retitle this as the Epic (two-phase waiting with a real wake path, scoped to the page-cache latches where a lock genuinely must exist), and track Tier 2 — spin budget as a WaitContext field — as its own Task. AdaptiveWaiter is worth noting in the Epic: it is used in exactly one non-profiler file (WalCommitBuffer), so the engine's real waiting is raw SpinWait at 43 sites, and the named "adaptive waiter" is barely wired in.

  7. added a commit that references this issue on Aug 15, 2026
  8. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Split, so this issue tracks only what is actually left.

    • Tier 1 → AccessControl / AccessControlSmall must never escalate to Thread.Sleep(1) (Tier 1 of #803) #809, shipped and closed. AccessControl / AccessControlSmall never escalate to Thread.Sleep(1). f286b40 on PR #792 #803 #696 #802 Four bug-bash fixes, and three performance issues that measured flat #808.
    • This issue now stands for the real ask in its title: locks have no wake path. Bounded spin then a park released by the unlocker, which is what turns a 15 ms poll into a 5–50 µs wake. Suggest scoping it to the page-cache latches (PageExclusiveLatch, StateSyncRoot) — the one place a lock genuinely must exist, convoys form, and the hold can be long enough to justify parking.
    • Tier 2 is not filed yet, and is the piece I would do next: the spin budget as a WaitContext field. WaitContext is already passed by-ref into every Enter* call and there is already a per-site policy convention (TimeoutOptions.Current.*LockTimeout), so it needs no new plumbing. It is what stops the 5-second hot poll that Tier 1 leaves behind.

    One correction to this issue's framing, from reading the call sites: AdaptiveWaiter is used in exactly one non-profiler file (WalCommitBuffer). So it is not merely "not a different policy" — it is barely wired in. The engine's real waiting is raw SpinWait at 43 sites across 19 files, and the type whose name promises a tuned waiter is almost unused. Worth stating in the Epic, because "fix AdaptiveWaiter" would touch nearly nothing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performance

Type

Fields

Priority

P0-Critical

Estimate

None yet

Area

Concurrency

Start date

None yet

Target date

None yet

Bug status

None yet

Product

Engine

Projects

  • Status
    Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions