Files
sakurac/docs/random.md
T

469 lines
25 KiB
Markdown
Raw Normal View History

2026-10-26 10:14:11 -05:00
# Plan: random numbers
Written 2026-10-08, and brought up to date 2026-10-20 for what std has gained since:
ranges as values, `real` and `std::math`, threads and atomics, Windows, and checked runs
in place of the collector. This is a proposal. std is yours, so the decisions at the end
are yours to make. Nothing is built yet.
**Comes after the ffi plan, now built:** `std::sys` is `system`, and `@foreign` and
`@link` are `extern` sections.
**Built in the rebuild alone** ([roadmap.md](roadmap.md), decision 1). Where this plan
says both compilers, C's half is left out. What was measured in C stays as measured.
**What it is:** generators of random numbers, numbers drawn from them in a range,
shuffling and picking, and the system's randomness for keys and seeds.
**Its users:**
- games and simulations: dice, procedural worlds, and replays, which need the same
numbers from the same seed;
- tests whose inputs are made from a seed, so a failure can be repeated. std's own tests
of memory, vectors, words and threads each write a generator by hand today;
- programs with secrets: keys, tokens, and names nobody can guess;
- the algorithms plan ([algorithms.md](algorithms.md)), whose sorts are tested on random
orders, and which counts this plan's `shuffle` among the users of its `swap`;
- the grammars plan ([grammars.md](grammars.md)), whose tests make sentences and bytes
at random.
**Probed:** on 2026-10-08, and again on 2026-10-20 against today's std, in the
scratchpad (`plans/random/`). Each part ran:
- with each compiler, in its machine and as executables at `-O0` and `-O2`;
- with the rebuild's `run --checks`;
- while compiling.
The results agreed everywhere, except where noted. It covered:
- **The generator:** xoshiro256++ seeded through SplitMix64. Its first numbers for seed
42, and those after a jump, matched a Python reference, including in a constant. A
generator was a constant too.
- **Numbers in a range** by Lemire's method, generic over every integer type through
`u64`. `i8` from −100 to 100 and the whole of `u64` matched the reference. 600,000
draws from 0 to 5 each came within 0.3% of 100,000.
- **Ranges as values:** draws from `1..=6`, `-5..5` and a `range<u8>`.
- **Reals from 0 up to 1,** with `f32` ones made from their own 24 bits, the largest
being 0.99999994. Both compilers inferred the type from the declaration, and asked for
`fraction::<...>` where nothing gave it.
- **Shuffling** a vector of strings by swapping bytes, under `run --checks`.
- **The system's randomness:** 16 bytes from `getrandom`. Both compilers also built a
Windows executable calling `ProcessPrng`, which wasn't run.
- **Forking:** a page marked `MADV_WIPEONFORK`, where a forked child read 0 and its
parent read 12345.
- **Threads:** four threads, each handed a copy of one generator jumped between them,
summed the same in both compilers' machines and executables.
- **Speed in an `-O2` executable,** measured 2026-10-20 on a P-core, with bounds checked
as [How it fits the rules](#how-it-fits-the-rules) says. On 2026-10-08 the rebuild's
were 5.3, 11 and 5.4 ns.
| A draw | Rebuild | C |
|---|---|---|
| 64 bits | 2.5 ns | 5.8 ns |
| A number below a bound | 6.8 ns | 12 ns |
| A real | 4.0 ns | 9.2 ns |
In the machines, each draw took 76 to 250 ns.
**Still so: a parameter taken by value draws from a copy.** Parameters belong to the
function, which may change them (README, "Functions"). So `def roll(g: generator)` can
call `g.next()`, and the caller's generator gives the same numbers again. Decision 5
settles it for generators.
**Found: `contract::expects` costs about 22 ns where it holds,** in either compiler's
`-O2` executables. A draw below a bound took 28.5 ns checked by it in the rebuild,
against 6.8 ns checked by a plain test and `sys::abort()`, and 33 to 36 ns against 12 ns
in C. Its default arguments, a `string` among them, are made at every call.
**Found: C doesn't take a range's type from where the result goes.** `val b: u8 =
g.within(0..200)` draws a `u8` in the rebuild, while C makes `0..200` a `range<i64>` and
refuses it. Both take `g.within::<u8>(0..200)`, a `range<u8>` variable, and
`val b: u8 = g.below(200)`.
## What's there now
- **`hash` and `mix`** (`std/traits/hashable.sakura`), which scramble words but take no
seed.
- **No generator.** std's tests write their own: an xorshift in `test/std/mem.sakura`,
`simd.sakura` and `swar.sakura` and in the corpus's `simd_lanes_agree_everywhere_1`,
and a multiplying one in `test/std/threads.sakura`.
- **No system randomness, no shuffling, and no generic swap.** `sort` and `heap` move
elements' bytes themselves, and the algorithms plan proposes `swap`.
- **`std::sys`** has `syscall` and `fork` on Linux, but neither `getrandom` nor a way to
map memory; the runtime, `runtime`, maps its own. On Windows it calls the system's DLLs through
`@link`, and `fork` gives `unsupported`.
- **`real` and `integer`** (`std/traits`), which draws are bounded by. `std::math` has
`rotate_left` and the other integer operations, but no wide product.
- **Ranges are values:** `a..b` and `a..=b` make a `range<T>` of integers
(`std/iterators/range.sakura`).
- **Threads and atomics:** `std::thread`, with `spawn_with`, `mutex<T>` and `once`, and
`atomic<T>` (`std/atomic.sakura`). Nothing gives a thread storage of its own.
- **Clocks:** `std::time`'s `instant::now()` and `timestamp::now()` read nanoseconds. Two
runs can read the same, and a clock is no secret, so seeds come from the system.
- **Constants** run any function, unless it reads a global variable, calls C, or turns
an address into a number (README, "Constants"). The rebuild runs a constant and stops
where it can't go on. C decides from the call graph, so it refuses anything that could
reach `contract::report` ([inconsistencies.md](inconsistencies.md), "Contracts in a
constant").
## What it needs
1. **A fast generator** that gives the same numbers from the same seed, wherever it
runs, and in every version (decision 3).
2. **Integers in a range,** with no bias, of any integer type, given as a range (decision
4).
3. **Reals** from 0 up to 1 and in a range, as `f32` and `f64`.
4. **Chances, shuffling and picking.**
5. **The system's randomness,** for secrets and seeds, on Linux and Windows.
6. **A generator ready to use with no setup,** seeded differently on each run, which
threads draw from at once (decision 6), and which a forked child doesn't share with
its parent (decision 7).
7. **Seeded generators in constants,** worked out while compiling, in both compilers.
8. **Portable above `std::sys`.**
## How it fits the rules
- **A generator is plain data (decision 5).** It's four words, so it copies freely,
compares through `equatable`, and can be a constant. Drawing takes `&mut this`, so
functions that draw take `&mut generator`.
- **The same numbers in the machine, in executables, and while compiling,** by
construction:
- the generator, and everything drawn from it, is integer arithmetic;
- reals are made from integers by conversions that are exact, so no rounding can
differ.
It was probed in both compilers' machines and executables, under `run --checks`, and
in constants.
- **Nothing fails:**
- A bound of 0, or an empty range, stops the program, as indexing past an end does.
It's a plain test and `sys::abort()`, which reports where the program was, not
`contract::expects`. Through `contract`, C refuses every constant drawing in a range,
and such a draw takes three to four times as long (found above).
- The system's randomness doesn't fail on Linux 3.17 or later, nor on Windows, where
`ProcessPrng` never fails. Where it can't be had at all, the program stops, as Go
1.24's `crypto/rand` does: no program should go on with keys it believes are
random.
- **Nothing allocates.** Shuffling swaps elements where they are.
- **Threads:** a generator belongs to whoever holds it, as any value does. Each thread is
handed its own, as `spawn_with` gives a value, and `jump` keeps their numbers apart.
The shared generator is drawn from by every thread at once (decision 6).
- **It isn't for secrets.** xoshiro256++'s state can be worked out from four of its
numbers, so keys and tokens come from `system_bytes`, as its documentation will say.
- **A build stays the same every time.** A seeded generator runs while compiling, in
both compilers. The system's randomness makes a system call, or calls C on Windows,
and the shared generator reads a global, so both compilers refuse a constant drawing
from either. Probed.
## Layers
### `std::sys` gains
| Operation | Does |
|---|---|
| `getrandom(into: *mut u8, length: u64): i64` | Bytes from the system's generator, or the negated error number. Probed |
| `map_wiped(length: u64): *mut u8` | Zeroed memory of its own, which a forked child sees as zeros again, or null where the system can't. Probed. Decision 7 |
- **On Linux:**
- `getrandom` (318 on x86-64);
- `mmap` (9), then `madvise` (28) with `MADV_WIPEONFORK` (18), from Linux 4.14.
- **On Windows:** `getrandom` is `ProcessPrng`, from `bcryptprimitives.dll`, as Go and
Rust use, linked as `std::sys` links `kernel32.dll`. Both compilers built an
executable calling it. There are no forks to guard against, so `map_wiped` is plain
zeroed memory.
- Both join the operations `std/system/system.sakura` lists for each system.
### `std::random` (decision 1)
```sakura
module std::random;
#! A generator of random numbers, xoshiro256++ (decision 2), in four words. One made
#! from a seed gives the same numbers every time (decision 3).
pub struct generator : equatable { var _s: u64[4]; }
pub def generator::seeded(seed: u64): generator; # SplitMix64 spreads the seed
pub def generator::from_system(): generator; # 32 bytes from the system
pub def generator::next(&mut this): u64; # 64 bits
pub def generator::equals(&this, other: &generator): bool;
#! From 0 up to a bound, not including it.
pub def generator::below<T>(&mut this, bound: T): T where T: integer;
#! From a range: `a..b` leaves its end out, and `a..=b` takes it in (decision 4).
pub def generator::within<T>(&mut this, among: range<T>): T where T: integer;
#! From 0 up to 1, not including 1.
pub def generator::fraction<T>(&mut this): T where T: real;
#! From low up to high, not including high.
pub def generator::between<T>(&mut this, low: T, high: T): T where T: real;
pub def generator::chance(&mut this, probability: f64): bool;
pub def generator::fill(&mut this, into: slice<u8>): void;
pub def generator::shuffle<T>(&mut this, items: slice<T>): void;
pub def generator::pick<T>(&mut this, items: span<T>): maybe<&T>; # none where empty
pub def generator::jump(&mut this): void; # 2^128 numbers ahead
# The shared generator, seeded from the system when first drawn from, which every
# thread may draw from at once (decision 6).
pub def below<T>(bound: T): T where T: integer;
pub def within<T>(among: range<T>): T where T: integer;
pub def fraction<T>(): T where T: real;
pub def between<T>(low: T, high: T): T where T: real;
pub def chance(probability: f64): bool;
pub def shuffle<T>(items: slice<T>): void;
pub def pick<T>(items: span<T>): maybe<&T>;
# The system's randomness, for keys, tokens and seeds.
pub def system_bytes(into: slice<u8>): void;
pub def system_word(): u64;
```
```sakura
import std;
import std::random;
import std::thread;
val roll := random::within(1..=6); # the shared generator
random::shuffle(deck.slice());
# The same level from the same seed, every time.
var world := random::generator::seeded(level.seed);
for _ in 0..level.trees {
val x := world.below(level.width);
val y := world.below(level.height);
val height: f32 = world.between(2.0, 9.0);
plant(x, y, height);
}
# A generator for each thread, from one seed, whose numbers never overlap.
var source := random::generator::seeded(run.seed);
var workers := vector::<thread::handle<void>>::new();
for _ in 0..thread::cpu_count() {
var started := thread::spawn_with(simulate, source) else (e) { return; };
workers.append(move(started));
source.jump();
}
var key: u8[32];
random::system_bytes(key[:]); # a secret
```
## How each part works
- **The generator (decision 2):** xoshiro256++, by Blackman and Vigna.
- Its four words change by adding, shifting, rotating and xor, with no
multiplication, so it's quick in the machine too. It writes its rotations as two
shifts, since `math::rotate_left` takes any width, and so a remainder and a branch.
- Its period is 2^256 − 1, and it passes BigCrush and PractRand.
- Its reference code is public domain. It's Julia's default generator, and Rust's
`SmallRng` on 64-bit processors.
- **Seeding:**
- `seeded` fills the four words from SplitMix64 run from the seed, as the authors
advise. Nearby seeds then give unrelated numbers.
- The state is never all zeros, xoshiro's one forbidden state, since at most one of
SplitMix64's four words can be zero.
- `from_system` takes 32 bytes from the system, and takes them again if all were
zero.
- **Integers in a range:** Lemire's method (2019).
- A 64-bit number is multiplied by the count of numbers in the range, and the high
word of the 128-bit product is the result.
- A number is drawn again only when the low word falls below 2^64 mod the count.
That happens with a chance below the count divided by 2^64, and the division that
works it out happens only then.
- **Every integer type goes through `u64`.** `end as u64 - start as u64` wraps to the
right count for signed types too, so nothing asks whether a type is signed. A range
covering all of `u64` or `i64` takes a number as it is. Probed.
- **A range** counts `end − start` numbers, and one more where it takes its end in, as
`a..=b` does. Probed with both.
- **The 128-bit product** is made of four 32-bit products today. A 64-bit `mul` gives
both halves in one instruction, but `std::math` gave no wide product among its
integer operations, and there are no 128-bit integers ([later.md](later.md),
"128-bit integers"). An intrinsic for its high word would cut most of the 4 ns a
draw in a range adds to `next`, and give the same bits.
- **Reals:**
- An `f64` is the top 53 bits times 2^−53, and an `f32` is the top 24 bits times
2^−24. The values are evenly spaced and never reach 1.
- Each width has its own because `fraction::<f64>() as f32` can round up to 1.0.
`if const size_of::<T>() == 4` chooses between them in both compilers, where C
refuses `T is f32` ([inconsistencies.md](inconsistencies.md), "Testing a type
against another type").
- **The type comes from where the result goes,** as `val x: f32 = g.fraction();`.
With nothing to say, both compilers ask for `fraction::<...>()`. Probed.
- **The bound is `real`,** which std has had since 2026-10-14.
- **`between`** gives low + (high − low) × a fraction. In the rare case where rounding
reaches high, it draws again. It takes two ends, since a `range<T>` holds integers.
- **`chance(p)`** is a fraction below `p`: never at 0, always at 1, and exactly the top
bit at 0.5.
- **`shuffle`** is Fisher–Yates from the end, swapping elements' bytes. An element is
moved, never copied, so strings and other owning values shuffle safely. Probed under
`run --checks`. It uses the algorithms plan's `swap` if that's built first, and
otherwise swaps bytes itself, as `heap` does.
- **`pick`** takes the element at `below(length)`, or none where there are none. A
`maybe<&T>` is one word.
- **`fill`** writes each number's 8 bytes from the lowest, so a seed gives the same bytes
on every processor.
- **`jump`** is the authors' jump, 2^128 numbers ahead. A generator jumped once for each
thread, and handed to it by `spawn_with`, gives every thread numbers from one seed that
never overlap. Probed.
- **The shared generator (decision 6):**
- Its state is kept in memory from `sys::map_wiped`, mapped and seeded from the
system the first time it's drawn from. A program that never draws from it pays
nothing. Threads that race to map it agree through `compare_exchange`, and the one
that loses gives its page back.
- **Threads draw from it at once.** Under 6(a) it's SplitMix64 over one `atomic<u64>`
counter: each draw is one `fetch_add` and a mix. No thread waits, and since the mix
gives each count its own number, no two draws are the same. Alone, a draw took
14 ns in the rebuild's executables and 18 ns in C's. With four threads drawing at
once in the rebuild's, 40 million draws took 27 ns each by the clock, where
xoshiro256++ behind a lock took 370 to 400 ns.
- **The draws are written once,** generic over where their words come from, so
`random::within` and `world.within` count a range alike.
- **A forked child** finds it zeroed and seeds its own (decision 7), whatever forked:
`sys::fork`, `process::command`'s child before it runs the new program, or C code a
program calls.
- **The system's randomness:**
- `getrandom` with no flags waits only at boot, until the kernel's pool is first
ready.
- A read of up to 256 bytes is never cut short, longer ones are read in a loop, and an
interrupted call is made again.
- Before Linux 3.17, the call is missing, so `/dev/urandom` is read instead. Where
neither works, the program stops.
- On Windows, `ProcessPrng` fills any length in one call.
## Testing
- **`test/std/random.sakura`, written with `std::testing`,** in both repositories,
covers:
- **known answers:** xoshiro256++, its jump, and SplitMix64, checked against the
authors' C code, which is run once in the scratchpad;
- **ranges at each width's edges:** all of `i8` and of `u64`, `a..b` and `a..=b`, and
the bounds 1 and 2^63 + 1, which is the worst for drawing again. A bound of 0, or an
empty range, stops a forked copy, on Linux;
- **evenness:**
- chi-squared over a small bound and a large one;
- the mean of reals;
- never 1, for `f32` and `f64`.
Every check uses a fixed seed, so none can fail by chance;
- **shuffling:** every order of 4 elements appearing about equally, strings, and
runs of none and one;
- **`pick`** of nothing giving none;
- **the system:** two reads differing, and, on Linux, a forked child's shared numbers
differing from its parent's;
- **threads:** four drawing from the shared generator at once, with no number given
twice under 6(a);
- **while compiling:**
- a constant from a seeded generator, drawing in a range and shuffling, equalling
what running gives, in both compilers;
- a constant from the system or the shared generator being refused, in both
compilers' tests.
- **Where they run:** in each compiler's machine, as executables at `-O0` and `-O2`, and
with `run --checks`. They're also built for `windows-x86_64`. The C compiler must
still accept std, since it builds the rebuild.
## Phases
About 50 lines of `std::sys`, for Linux and Windows, 600 of `std::random`, and 400 of
tests, with no change to either compiler.
1. **`sys::getrandom`, and the generator:**
- `seeded`, `from_system` and `next`;
- `below`, `within`, `fraction`, `chance` and `fill`;
- also `system_bytes` and `system_word`.
2. **`between`, `shuffle`, `pick` and `jump`.**
3. **`sys::map_wiped`,** with the shared generator and its functions.
4. **The README:** a `std::random` row in its table of modules, and a paragraph with an
example under "The standard library", as `std::time` and `std::math` have.
5. **std's tests moved onto it:** `mem`, `simd`, `swar` and `threads` drop the
generators they write by hand. The corpus's `simd_lanes_agree_everywhere_1` keeps
its own, since its expected output is made of its numbers.
6. **Distributions,** if decision 8 is (a):
- normal, by the ziggurat method, with its tables made while compiling. A table of
`math::exp` and `math::log` in a constant agreed in both compilers;
- exponential, Poisson and binomial;
- picks by weight, by the alias method.
## Later, where wanted
- **Samples:** k different elements out of n.
- **An iterator of draws,** as `world.draws(1..=6).take(10).to_vector()`, for the
adapters and consumers every iterator has.
- **A wide product,** as an intrinsic among `std::math`'s integer operations, or
128-bit integers, for Lemire's method and for hashing.
- **A generator per thread behind the free functions,** in place of the atomic counter,
once threads have storage of their own ([later.md](later.md), "Thread-local
variables"). A draw would then cost what `next` does, with nothing shared.
- **Text:** tokens, and version 4 UUIDs.
- **Seeding `dict`'s hashes on each run,** against inputs crafted to collide. Its
entries keep their places as it grows, so the order it gives them in wouldn't change.
- **A strong generator in the program,** such as ChaCha, for a program that draws secrets
too often for a system call each. `std::simd`'s `u32x4` and `u32x8` would work four or
eight of its blocks at once in the rebuild's executables.
- **macOS,** once `std::sys` has it.
## Decisions for you
1. **Where it lives:**
- **(a) `std::random`, in `std/random/` (recommended),** as `std::time`,
`std::math` and `std::thread` are modules of their own.
- **(b) In module `std`.** Names such as `generator`, `below` and `shuffle` would
then be taken in every program that imports `std`.
2. **The generator:**
- **(a) xoshiro256++ (recommended).**
- It's 32 bytes and 2.5 ns here (5.8 ns in C's executables), with no
multiplication, so it's also quick in the machine.
- `jump` gives each thread its own numbers.
- It isn't for secrets, which is why the system's randomness is separate.
- **(b) PCG64 DXSM,** a variant of NumPy's default, PCG64. Each step multiplies
128-bit numbers. Without 128-bit integers, that takes several of the four-multiply
products, so it's slower here and much slower in the machine.
- **(c) ChaCha8,** Go 1.22's default. Its numbers can't be predicted, so a program
that wrongly makes tokens from it is still safe. But it keeps 64 bytes of state and
a buffer, and it's many times slower per number in the machines, which work vector
lanes one at a time. `std::simd` would speed it only in the rebuild's executables.
3. **Numbers from a seed:**
- **(a) The same in every version of std (recommended).** This covers the generator
and every method drawing from it, for replays, saved worlds, and tests with seeds.
The methods' algorithms then belong to the contract: Lemire's, 53 bits, and
Fisher–Yates from the end. A faster way later needs a new name.
- **(b) Only `next` stays the same.** Ranges, reals and shuffling may change between
versions, as Rust's `rand` allows for `StdRng`.
4. **How a range is given:**
- **(a) As a `range<T>` (recommended),** as `within(1..=6)` and `within(0..n)`. `..`
and `..=` say whether the end is in, as they do in `for`, so one name serves both.
`below(n)` stays, for indexes. C needs a range of a narrow type written as one, as
`within::<u8>(0..200)`, until it takes the type from the declaration (found
above).
- **(b) Two ends, both included,** as `within(1, 6)`, as this plan first had it. It
reads the same in both compilers, but a range leaving its end out is
`within(0, n - 1)`.
5. **Copying a generator:**
- **(a) Plain data, copying freely (recommended).**
- A copy is a saved state to replay from.
- It can be a constant, and it can be held in structs and arrays without making
them close.
- But `roll(g)` draws from a copy, as noted above, so the documentation says to
take `&mut generator`.
- **(b) `owning`, with a `close` that does nothing, and `copyable`,** as `atomic<T>`
is `owning` so that it isn't copied by accident.
- `roll(g)` is refused in both compilers, and copies are named, as `copy(&g)`,
which asks for `copy_of`.
- A constant still works through `copy(&kept)`. All three were probed again.
- But everything holding a generator then closes.
6. **The shared generator:**
- **(a) Yes, behind the free functions, as SplitMix64 over one atomic counter
(recommended).** `random::within(1..=6)` needs no setup, which is what most
programs want. It's seeded only when first drawn from. Threads draw from it at once
without waiting: 14 ns a draw alone, and 27 ns by the clock with four drawing at
once. Its numbers aren't xoshiro's, but nobody can seed it, so nothing can depend
on them.
- **(b) Yes, as xoshiro256++ behind a lock.** It's one generator throughout, and
14 ns a draw alone, but 370 to 400 ns by the clock with four threads drawing at
once.
- **(c) Only generators a program makes.** There's no state in std, but every program
makes and passes its own.
7. **Forked children,** under 6(a) or 6(b):
- **(a) Its state in memory a forked child sees as zeros (recommended).** This
catches every fork, including C's, for one 4 KiB page, from Linux 4.14. `std::sys`
gains `map_wiped`. Windows can't fork, so there it's plain memory.
- **(b) A count of forks that `sys::fork` keeps, checked at each draw.** There's no
page, but forks made by C code are missed.
- **(c) Nothing.** A child repeats its parent's numbers, as the documentation would
say.
8. **Distributions:**
- **(a) The uniform ones first, and normal, exponential and the rest in phase 6
(recommended).** `std::math`'s `exp` and `log`, which they waited on, are built.
- **(b) The uniform ones only.** Programs write their own.