Skip to content

Unsynchronized lazy statics in sys/random (data race on first concurrent call) #985

Closed

Description

@eas4ai

Classification

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.

Activity

  1. ehartford commented on Sep 16, 2026

    @ehartford
    Contributor

    Review: reproduced

    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:

    1. _ensure_init runs under Once (or the five values move into a single Once-guarded struct), so concurrent first callers observe one initialisation.
    2. 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.
    3. range_i32 and chance use wrapping negation or mask (v & 0x7fffffff), with a test that feeds i32 minimum through the same helper.
    4. 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.
    5. 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.

  2. ehartford commented on Oct 25, 2026

    @ehartford
    Contributor

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions