Repository navigation
Description
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:
-
The entire pure-spin budget is 2.7 µs. Ten iterations of
Thread.SpinWaitwith a doubling count, and that is the whole thing. -
On a saturated machine the first
Thread.Yield()costs 4.4 ms — not theSleep(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 runsProcessorCount - 2workers by default, so the saturated case is the normal case. -
Thread.Sleep(1)measures 15 ms, not 1 ms — the global Windows timer resolution sits at its 15.6 ms default. WhateverHighResolutionTimerServiceBaseraises, it is not the process-wide timer as seen bySleep. 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:
- Never call
Thread.Sleep(1). At 15.6 ms granularity it is pathological for every call site in the list. - 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/AccessControla wake path, which they do not have today. - 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.
- 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.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Estimate
Area
Start date
Target date
Bug status
Product
Projects
- StatusShow more project fieldsTodo
Activity
nockawa commentedon Aug 14, 2026
Tier 1 landed (f286b40) — no measurable effect, and it removes the only backpressure on pathological waits
AccessControlandAccessControlSmallnow passSpinOnce(-1), which disables the BCL'sThread.Sleep(1)escalation. Three call sites, two files. The loop bounds make the old worst case concrete:WaitForSharedCanStartruns to 100 iterations and the BCL escalates at 20, so up to 80 could land on the 15.625 ms timer (~1.2 s);WaitForIdleStateruns 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,PagedHashMapBaseall pass-1. The two primary lock primitives were simply missed, theirSpinWaitbeing two abstraction layers below every call site.Measured impact: none
SwgFixtureStressTests×3Inside 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;
ChaosStressTestsfailure set is a subset of the unmodified baseline's.The risk this introduces, which argues for Tier 2
With
Sleep(1)gone the BCL alternatesYield()andSleep(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:TimeoutOptionsdefaults 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.ref WaitContext.Null/ref nullCtx), including every_finalizeLockacquisition. 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
WaitContextis already threaded by-ref into everyEnter*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
WaitContextfield — as its own Task.AdaptiveWaiteris worth noting in the Epic: it is used in exactly one non-profiler file (WalCommitBuffer), so the engine's real waiting is rawSpinWaitat 43 sites, and the named "adaptive waiter" is barely wired in.#792 #803 #696 #802 Four bug-bash fixes, and three performance issues…
nockawa commentedon Aug 15, 2026
Split, so this issue tracks only what is actually left.
AccessControl/AccessControlSmallnever escalate toThread.Sleep(1). f286b40 on PR #792 #803 #696 #802 Four bug-bash fixes, and three performance issues that measured flat #808.PageExclusiveLatch,StateSyncRoot) — the one place a lock genuinely must exist, convoys form, and the hold can be long enough to justify parking.WaitContextfield.WaitContextis already passed by-ref into everyEnter*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:
AdaptiveWaiteris 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 rawSpinWaitat 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.