Implement GC-managed random generators, next/nextf intrinsics, bounded ranges and deterministic conformance coverage. Publish the runtime contract and producer guidance. Give coverage domains at least five percentage points of measured headroom while preserving sufficient floors. Record local qualification: make ci-domains passes with 939 tests and all domain gates green.
8.8 KiB
VM-owned random core
Identity and memory
Random version 1 is BuiltinId 0x0016, an opaque nullable reference builtin.
It occupies one execution slot: present values use Value::HeapRef; the default
is Value::Null. Typed storage uses index:u32 and generation:u32, eight bytes
aligned to eight, with GuestReference ownership. Registry categories remain
Builtin, Struct, Array, Trait and Fn. PBX v1 encoding is unchanged.
ObjectKind::Random has tag 9; DynamicBox remains 8 and tag 6 remains reserved.
Its private logical payload is State:u128 and Inc:u128, 32 bytes with no child
references. Payload, header, handle tables and auxiliary storage are charged
to existing session quotas. Only random.new constructs Random; NEW and
Struct/array access cannot construct or expose its payload.
Random is valid in locals, globals, fields, arrays, captures and function parameters/results. Copying a handle aliases the same state. Separate objects with equal seeds have equal initial streams and evolve independently. Dynamic retains the exact TypeId and direct single-slot HeapRef without copying state or allocating a multislot box. Extraction requires that exact type, including typed null. There is no implicit Struct or Trait adaptation.
Existing reference maps and roots retain reachable objects. Random is a GC leaf; collection occurs only at existing safepoints. There are no guest finalizers, callbacks or reentrant collection. Pause/resume preserves state; reset/unload releases the session and prior handles cease to authorize access. Existing native-boundary provenance rules apply: copying raw reference bits between sessions is not an import operation.
Exact algorithm
Use PCG-XSL-RR 128/64 setseq, with unsigned wrapping modulo 2^128:
M = 0x2360ED051FC65DA44385DF649FCCF645
= 47026247687942121848144207491837523525
seq = 54
Inc = (seq << 1) | 1 = 109
B = zero_extend_128(bits_u64(seed))
State = ((B + 109) * M + 109) mod 2^128
each draw:
State = (State * M + 109) mod 2^128
X = low_u64(State) XOR high_u64(State)
R = State >> 122
W = rotate_right_64(X, R)
Int64 seed bits are reinterpreted as u64 and zero-extended, never sign-extended or expanded. Zero, negative and extreme seeds are valid. Advance before output; rotation zero preserves X. Inc is always 109 and State zero is valid. There is no additional warm-up, discard, buffer, implicit global RNG or host entropy. Explicit wrapping produces identical debug/release bits. Equivalent limb arithmetic must match; operational host bigint/FFI or platform-selected variants are forbidden. PCG32, PCG64DXSM and NumPy SeedSequence compatibility is not promised.
Seed=42, seq=54 reference vectors; the Float column maps the same W:
| Draw | W hex | nextf binary64 bits |
|---|---|---|
| 1 | 86B1DA1D72062B68 | 3FE0D63B43AE40C5 |
| 2 | 1304AA46C9853D39 | 3FB304AA46C98538 |
| 3 | A3670E9E0DD50358 | 3FE46CE1D3C1BAA0 |
| 4 | F9090E529A7DAE00 | 3FEF2121CA534FB5 |
| 5 | C85B9FD837996F2C | 3FE90B73FB06F32D |
| 6 | 606121F8E3919196 | 3FD818487E38E464 |
Intrinsics and metadata
| ID | Version 1 name | Ordered signature | Virtual cycles |
|---|---|---|---|
| 0x4000 | random.new | (seed:Int64)->Random | 32 |
| 0x4001 | random.next | (rng:Random)->Int64 | 8 |
| 0x4002 | random.nextf | (rng:Random)->Float | 12 |
| 0x4003 | random.range | (rng:Random,min:Int64,max:Int64)->Int64 | 4+8*N |
There are no hidden receivers, defaults, Int32 coercions or alternative names. Random is the type and random the namespace, not a singleton. Version 1 has no PickRandom, collection/string/Bool helpers, destroy, reseed, clone, split, exposed stream selector or serialization/replay API. It is not cryptographic.
All four descriptors publish deterministic=true and mutates_guest_state=true; only new publishes may_allocate=true. Deterministic means reproducible with the same state and ordered inputs, not pure. Compilers must preserve calls, source evaluation order and state consumption, including named arguments. They must not execute the generator at compile time, fold, eliminate or reorder calls based on literals or deterministic metadata.
The shared catalog publishes cost_model. Fixed entries use fixed, complete
cost_cycles and zero attempt_cost_cycles/max_attempts. range uses
random_rejection_v1, cost_cycles=4 (base), attempt_cost_cycles=8 and
max_attempts=64. Four is not range's total cost. Existing identities and costs
are preserved. Execution is VM-owned through the same catalog/resolver/verifier,
without a HostContext RNG, host syscall or public host heap-access API.
Outputs and bounded intervals
next consumes one W and reinterprets its bits as Int64, including negatives. nextf consumes one W, computes k=W>>11 and returns k/2^53 through the VM's software binary64 semantics. Values are exact points on [0,1); +0 is valid and 1 is excluded. Float32, rounded W/2^64, host libm and frontend floating arithmetic are forbidden. Calls share the same stream; no per-output buffers.
range requires exact Int64 min<max and returns [min,max). Compute n=max-min in wide arithmetic, then as u64 (1 through 2^64-1). Compute threshold=2^64 mod n using wrapping_neg(n)%n. For each word, reject W<threshold; otherwise return min+(W%n) in wide arithmetic with exact Int64 conversion. No abs, signed modulus, Float, swapped or clamped limits. A unit span consumes one word.
At most 64 words are attempted; acceptance on attempt 64 succeeds. Rejecting
all 64 raises TRAP_RANDOM_REJECTION_LIMIT 0x00000015, without fallback.
The mapping removes additional modulo bias for uniform input words; it does
not promise statistical independence between deterministic words or streams.
Validation and atomicity
Order checks as follows: instruction structure/height; all argument carriers in parameter order; complete receiver reference; limits; resource reservations; draws. Wrong carriers use TYPE, null receiver NULL_REFERENCE, invalid index, generation or liveness INVALID_HANDLE, live wrong object/type TYPE, min>=max NUMERIC_DOMAIN, and quota/recoverable allocation refusals RESOURCE_LIMIT. Keep PC, opcode, source span and available resource details. No operational panic, guest catchable exception or host-status substitute is introduced.
Retain operands and roots, validate, and reserve result/resources before mutation. Stage candidate state and result, then publish and consume operands atomically with no fallible work afterward. Every fault preserves operands, generator state and prior owners, releases provisional resources and publishes no partial handle. range draws on private candidate state and rolls it back on any fault, including the rejection limit. Executed cycles are not refunded.
Loader/verifier recognize Random and all signatures without changing PBX v1. Unknown intrinsic IDs, including unreachable ones, use LOAD_INVALID_CODE/NativeId; runtime INVALID_INTRINSIC is invariant defense. Invalid Registry IDs/signatures retain existing categories. Unknown type analysis requires full runtime checks. An old VM may reject the new identities; no alternate-algorithm fallback exists.
Budget and evidence
Charge fixed cost or range base before checks/reservations and 8 before every draw, rejected or accepted. N counts words actually drawn: refusal before draws costs 4, a unit interval 12, 64 attempts 516. Do not charge generic INTRINSIC +1 or public math/next costs for private steps. Argument-producing instructions retain their own costs.
Zero budget starts/charges no instruction. Positive budget admits the whole instruction with existing overshoot between instructions. Fault retains cycles and takes precedence over BudgetExhausted; failed calls are not successful steps. There is no mid-attempt pause, continuation, added GC, tick or frame sync.
Qualification requires independently sourced words/Int64/Float bits, consumption, faults and cycles in debug/release, seeds 0/1/42/-1/MIN/MAX, interleaving, aliasing, storage/capture/Dynamic roots, GC/stale/provenance cases, extreme spans, threshold boundaries, 64th acceptance, cap rollback and resource refusals. Test-only synthetic words exercise rare paths without changing production RNG. Record executed target/toolchain/profile and catalog fingerprints; do not claim unexecuted host comparisons. CPU benchmarks do not set virtual costs.
Frontend and reference-game integration consume the published contract through separate handoffs. Local core completion does not require those implementations or acquisition of hardware. See numeric semantics, Registry/PBX, memory and cycles.
Producer examples and integration acceptance tests are published in the random handoff. Executed evidence is recorded in random qualification.