You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Unsynchronized lazy statics in sys/random (data race on first concurrent call) #985
Low-severity race, benign in practice (audit finding SYS-001).
Source chain
lib/std/sys.w:20-37 lazily initializes five var globals behind a plain bool flag; lib/std/random.w:9-27 mutates global rng_state non-atomically. First-concurrent-call from two OS threads races. Writes are idempotent (same values recomputed), so benign in practice — but a race under 'exactly as safe as Rust'. std already has panic-resetting Once; rng_state additionally has a latent checked-overflow panic path (0 - v on INT32_MIN at 2^-32 per call — wrapping arithmetic is the one-line fix).
Repair boundary
Gate init on Once; atomics or a lock for rng_state; wrapping negation.
Verdict. Established on current main. std.sys lazily initialises five bare var globals behind a plain bool, and std.random mutates the bare global rng_state on every call; both are reachable from two OS threads at once with no synchronisation. The compiler's own global-race rule (E0921) rejects the same pattern in user code but explicitly exempts stdlib and runtime modules, so nothing catches it. The secondary claim also holds: range_i32 and chance compute 0 - v with checked arithmetic, and next_i32 can return i32 minimum, so that path is a (rare) panic rather than a wrap. The report's "benign in practice" assessment is fair for sys.w (idempotent writes); for rng_state two threads interleaving read-modify-write can repeat or skip outputs, which is a correctness issue for anyone relying on the stream, though still not memory-unsafe.
Tested revision and compiler
item
value
source
main @ 5809ac1 (2026-09-14); lib/std/sys.w and lib/std/random.w unchanged since the reported 450733e
compiler
with build of 5809ac1 in a detached worktree, self-reports with v0.15.2.1
platform
macOS Darwin 25.6.0, arm64
Probes
program
with check
with run
user global var counter written from a spawn_os closure and from main
E0921: read of global `counter` may race
n/a
spawn_os worker and main both calling next_i32() 1000 times and cpu_count() (mutates rng_state, _cached, _cpu_count, ...)
ok
main=549 thread=545 cores=18, rc 0
let v: i32 = -2147483647 - 1; if v < 0: 0 - v (the exact expression in range_i32)
ok
panic: integer overflow: i32 subtraction out of range, rc 134
Source
lib/std/sys.w:20-37: _cached, _cpu_count, _total_memory, _page_size, _bandwidth are bare var globals; _ensure_init tests _cached then writes all five and sets _cached = true last, with no Once, atomic, or lock. _measure_bandwidth runs inside the window, so two first-callers both measure.
lib/std/random.w:9-27: rng_state is a bare var i64; xorshift64 reads it, computes, and stores it back non-atomically; ensure_seeded has the same check-then-write shape.
lib/std/random.w:41-59: next_i32 returns (v >> 16) as i32, so every i32 value including the minimum is reachable; range_i32 and chance then do 0 - v, which is checked.
Checker exemption: src/SemaCheck.w:1657 skips global-race bookkeeping when sema_path_is_std_implementation or sema_path_is_runtime_implementation holds. That is a reasonable design (the stdlib is trusted to synchronise its own globals) but it means the stdlib must actually do so, and here it does not.
Spec
§ "Safety rule (data races)" (spec lines 3562-3590): "Bare mutation is safe iff the program is provably single-threaded ... the program ... never calls thread.spawn_os ... When the proof fails, each such access requires an unsafe context." Rule 2 names Atomic[T], Mutex[T], and "types whose mutation flows through their own thread-safe APIs" as the idiom. std.sys and std.random mutate bare globals from a program that has gained concurrency and carry no unsafe and no synchronisation, so they are non-conforming under the rule that user code is held to. std.sync.Once exists in the same tree (lib/std/sync.w:351 has its Drop).
Related PRs
None since 450733e touch either file. No open PR does.
Would I champion a fix? Yes, small and low-risk.
Acceptance criteria:
_ensure_init runs under Once (or the five values move into a single Once-guarded struct), so concurrent first callers observe one initialisation.
rng_state becomes Atomic[i64] with a compare-exchange step loop (or the RNG is made per-thread); seed/seed_now store through the same atomic.
range_i32 and chance use wrapping negation or mask (v & 0x7fffffff), with a test that feeds i32 minimum through the same helper.
A --debug-alloc-style thread test (two spawn_os workers calling next_i32 in a loop) runs under the sanitizer-equivalent lane if one exists, otherwise a behaviour test that at least exercises the concurrent path.
Separately worth recording in docs/decisions.md: the stdlib exemption from E0921 and the obligation it creates.
Untested
The race itself was not made observable (no TSAN lane, and the interleaving window is microseconds); the verdict rests on the source, the spec rule, and the checker's demonstrated exemption. Linux and Windows not executed.
Triage 2026-10-25, with v0.15.3.0 (main a261b65): reproduced in source; a benign race cannot be shown by a run. lib/std/sys.w still guards its lazy globals with a plain var _cached: bool, and lib/std/random.w still updates the global rng_state without synchronization.
post-release: the writes are idempotent, so no user sees a wrong result today; the fix is Once and an atomic state.
Activity
ehartford commentedon Sep 16, 2026
Review: reproduced
Verdict. Established on current
main.std.syslazily initialises five barevarglobals behind a plain bool, andstd.randommutates the bare globalrng_stateon every call; both are reachable from two OS threads at once with no synchronisation. The compiler's own global-race rule (E0921) rejects the same pattern in user code but explicitly exempts stdlib and runtime modules, so nothing catches it. The secondary claim also holds:range_i32andchancecompute0 - vwith checked arithmetic, andnext_i32can returni32minimum, so that path is a (rare) panic rather than a wrap. The report's "benign in practice" assessment is fair forsys.w(idempotent writes); forrng_statetwo threads interleaving read-modify-write can repeat or skip outputs, which is a correctness issue for anyone relying on the stream, though still not memory-unsafe.Tested revision and compiler
main@ 5809ac1 (2026-09-14);lib/std/sys.wandlib/std/random.wunchanged since the reported 450733ewith buildof 5809ac1 in a detached worktree, self-reportswith v0.15.2.1Probes
with checkwith runvar counterwritten from aspawn_osclosure and from mainspawn_osworker and main both callingnext_i32()1000 times andcpu_count()(mutatesrng_state,_cached,_cpu_count, ...)main=549 thread=545 cores=18, rc 0let v: i32 = -2147483647 - 1; if v < 0: 0 - v(the exact expression inrange_i32)panic: integer overflow: i32 subtraction out of range, rc 134Source
lib/std/sys.w:20-37:_cached,_cpu_count,_total_memory,_page_size,_bandwidthare barevarglobals;_ensure_inittests_cachedthen writes all five and sets_cached = truelast, with noOnce, atomic, or lock._measure_bandwidthruns inside the window, so two first-callers both measure.lib/std/random.w:9-27:rng_stateis a barevar i64;xorshift64reads it, computes, and stores it back non-atomically;ensure_seededhas the same check-then-write shape.lib/std/random.w:41-59:next_i32returns(v >> 16) as i32, so everyi32value including the minimum is reachable;range_i32andchancethen do0 - v, which is checked.src/SemaCheck.w:1657skips global-race bookkeeping whensema_path_is_std_implementationorsema_path_is_runtime_implementationholds. That is a reasonable design (the stdlib is trusted to synchronise its own globals) but it means the stdlib must actually do so, and here it does not.Spec
§ "Safety rule (data races)" (spec lines 3562-3590): "Bare mutation is safe iff the program is provably single-threaded ... the program ... never calls
thread.spawn_os... When the proof fails, each such access requires anunsafecontext." Rule 2 namesAtomic[T],Mutex[T], and "types whose mutation flows through their own thread-safe APIs" as the idiom.std.sysandstd.randommutate bare globals from a program that has gained concurrency and carry nounsafeand no synchronisation, so they are non-conforming under the rule that user code is held to.std.sync.Onceexists in the same tree (lib/std/sync.w:351has itsDrop).Related PRs
None since 450733e touch either file. No open PR does.
Would I champion a fix? Yes, small and low-risk.
Acceptance criteria:
_ensure_initruns underOnce(or the five values move into a singleOnce-guarded struct), so concurrent first callers observe one initialisation.rng_statebecomesAtomic[i64]with a compare-exchange step loop (or the RNG is made per-thread);seed/seed_nowstore through the same atomic.range_i32andchanceuse wrapping negation or mask (v & 0x7fffffff), with a test that feedsi32minimum through the same helper.--debug-alloc-style thread test (twospawn_osworkers callingnext_i32in a loop) runs under the sanitizer-equivalent lane if one exists, otherwise a behaviour test that at least exercises the concurrent path.docs/decisions.md: the stdlib exemption from E0921 and the obligation it creates.Untested
The race itself was not made observable (no TSAN lane, and the interleaving window is microseconds); the verdict rests on the source, the spec rule, and the checker's demonstrated exemption. Linux and Windows not executed.
ehartford commentedon Oct 25, 2026
Triage 2026-10-25,
with v0.15.3.0(main a261b65): reproduced in source; a benign race cannot be shown by a run.lib/std/sys.wstill guards its lazy globals with a plainvar _cached: bool, andlib/std/random.wstill updates the globalrng_statewithout synchronization.post-release: the writes are idempotent, so no user sees a wrong result today; the fix is
Onceand an atomic state.Pre-release fixes: std len casts, no host sample, AEAD (#1054), races (…
emitc 983 (#2812)