6.9 KiB
PBS Runtime Random Integration
Owner: compiler/pbs. This specification defines the PBS projection of runtime Random v1. The runtime owns the algorithm, heap identity, validation, atomicity, resource accounting and virtual cycles. The common catalog is the binding authority; the frontend does not implement a generator.
Source surface
import { Random, random } from @sdk:random;
fn draw() -> long {
let seed: long = 42;
let generator: Random = random.new(seed);
let alias = generator;
random.next(generator);
return random.range(alias, 0 as long, 100 as long);
}
Game SDK 1 exports the opaque builtin Random and service namespace random from @sdk:random. Both may be imported with aliases. The exact v1 signatures are:
| Operation | PBS signature | Runtime result/cost |
|---|---|---|
random.new |
(seed: long) -> Random |
New independent generator; 32 cycles |
random.next |
(rng: Random) -> long |
Next word reinterpreted as signed Int64; 8 cycles |
random.nextf |
(rng: Random) -> float |
Exact binary64 grid value in [0,1); 12 cycles |
random.range |
(rng: Random, min: long, max: long) -> long |
Integer in [min,max); 4 + 8*N cycles |
new is accepted as a callable declaration/member name; the new Type(...) allocation expression remains distinct. new Random() is invalid. The builtin has no public fields, source constructor, implicit Struct/Trait adaptation, receiver defaults or hidden seed. Only random.new allocates a generator. The API does not expose helpers, clone, reseed, split, snapshot or a global generator. Seeds are Int64 bit patterns: zero, negatives and extrema are valid. An existing int binding requires an explicit conversion to long; contextual long literals remain governed by the numeric specification.
Identity and storage
Random is runtime BuiltinId 0x0016, with one opaque nullable reference slot. Program TypeIds are local identities, not BuiltinIds. The frontend MUST register this exact builtin and MUST NOT model its payload as a source Struct or emit NEW to construct it.
Assignment, parameter passing, returns and capture copy a reference to the same state. Calling random.new twice with the same seed creates equal initial sequences that evolve independently. Copying an existing handle does not fork the sequence. All output operations consume the same stream, including a unit-width range and calls whose results are discarded.
The reference MUST retain identity and ownership in locals, globals, fields, arrays, function parameters/results and captures. Captures use the existing snapshot rules: the copied reference continues to identify the shared generator. Reachable references MUST remain valid across runtime collection.
PBS does not expose a null literal or a public Dynamic type. Runtime reference defaults remain null at the provider boundary. PBS constructors MUST explicitly initialize every field on every completing path, including Random fields; an empty constructor cannot expose that runtime default. Existing global-initializer restrictions remain unchanged; an unsupported arbitrary call in a global initializer does not become legal because it returns Random.
Typed arrays use their existing private Array<Dynamic> representation. Packing Random MUST preserve its exact runtime TypeId and direct reference without cloning state or adding a multi-slot box. A present typed-null Random element MUST remain distinguishable from an empty array position: presence is checked by tag before exact extraction. Consuming that null generator raises the runtime null-reference fault rather than treating the element as absent.
Evaluation, faults and billing
All four operations are deterministic and mutate guest state; only new may allocate. Determinism means reproducibility from the same state and ordered inputs. The compiler MUST NOT execute, fold, eliminate or reorder these calls based on literals, seeds or the deterministic flag. Discarding a result MUST retain the call and its mutation.
Arguments MUST be evaluated in source order. Named application may rearrange already evaluated carriers into signature order but MUST NOT change the order of their effects.
range requires min < max, with exact long arguments and no swapping, clamping, absolute-value or Float conversion. The runtime charges base 4 before checks and 8 for each attempted draw. Acceptance on attempt 64 succeeds; 64 rejections raise the rejection-limit trap at 516 intrinsic cycles. A unit interval consumes a word and costs 12. Argument evaluation, calls, storage and other bytecode instructions have their own costs.
The runtime contract governs fault precedence and atomicity: wrong carriers, null/invalid references, invalid limits and resource refusals retain the applicable identities. Failed operations do not publish partial state or handles, but executed cycles are not refunded. Compiler and SDK MUST preserve these semantics without a second validator, generator or cycle emulator in production.
Conformance
The source corpus MUST run the production PBS → common IR → PBX → runtime path with optimization on and off, and repeat equal ordered inputs to compare exact bits, faults and cycles. Required coverage includes:
- all four signatures, real SDK imports/aliases and incompatible-source diagnostics;
- provider vectors for seeds
0,1,42,-1, Int64 MIN/MAX, integer and Float draws; - aliases, independent equal-seed objects, mixed outputs, discarded draws and positional/named argument effects;
- locals/globals/fields/arrays/parameters/results/captures, private Dynamic and retained roots across collection;
- unit/extreme intervals, excluded upper bound, invalid bounds and real rejection followed by acceptance;
- exact intrinsic charges and replay/optimizer agreement.
Null receivers and present typed-null Array elements MUST be covered by separately identified controlled provider fixtures. Such fixtures may suppress a fully initialized field store after compilation to exercise provider reference defaults; they MUST NOT depend on accepting incomplete source constructors. Rare synthetic rejection paths, cap rollback, malformed carriers and native reference provenance remain separately identified provider evidence. Tests MUST reuse the provider's controlled fixtures without adding injection or alternate algorithms to the public SDK. Record runtime revision, platform, profiles, toolchain, features and source/catalog/oracle/lockfile fingerprints. Local results do not qualify unexecuted platforms or the reference game.