feat(pbs): integrate explicit runtime Random handles

This commit is contained in:
2026-10-17 13:51:12 +01:00
parent d1e9259085
commit b62db87245
22 changed files with 895 additions and 8 deletions
@@ -74,3 +74,5 @@ Function creation and calls remain subject to existing resource checks and runti
`declare callback`, callback barrel exports and `bind(context, function)` are retired source forms and must be rejected. Existing programs and examples must use structural Fn and explicit lambdas. Historical provenance and negative tests may mention the removed forms.
Conformance must compile actual PBS through production PBX and execute it in the production VM. Required cases include signature errors, explicit capture enforcement, snapshots, escaped closures, shared and isolated objects, collection transport, nested closures and function captures, receiver/contract integration, and reachable/unreachable closure behavior across the existing frame lifecycle and GC. Installed knowledge must package this specification and a compilable example.
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
@@ -0,0 +1,71 @@
# 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
```pbs
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, including an uninitialized Random field in an explicitly invoked ordinary struct constructor. 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, typed null and retained roots across collection;
- unit/extreme intervals, excluded upper bound, invalid bounds, null receiver and real rejection followed by acceptance;
- exact intrinsic charges and replay/optimizer agreement.
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.
## References
- [Typed arrays and optional execution](typed-arrays-and-optional-execution.md).
- [First-class functions and captures](first-class-functions-and-captures.md).
- [Runtime math and exact numeric carriers](service-constants-and-runtime-math.md).
- [Runtime Random v1](../../../../../runtime/docs/specs/runtime/02e-vm-owned-random-core.md).
- [Provider handoff](../../../../../runtime/docs/vm-arch/random-producer-handoff.md).
@@ -74,3 +74,5 @@ Conformance must compile real PBS through typed IR and production PBX into the p
- [Existing type runtime alignment](input-and-existing-type-runtime-alignment.md)
List/Set/Map, growth, iteration, equality and hashing policies belong to the separate SDK collections discussion. A future list capacity does not create logical elements; fixed array length does.
See [Runtime Random integration](runtime-random-integration.md) for opaque generator aliases in typed storage and captures.
+5 -1
View File
@@ -54,7 +54,7 @@ for exact rules rather than inferring compatibility with another language.
`pbs:sdk:game:1:sdk/gfx/main.pbs` exposes the actual installed Gfx source,
including documentation comments and signatures. Its `mod.barrel` reference
defines exports. Equivalent references exist for `sdk/asset`, `sdk/composer`,
`sdk/input`, `sdk/log`, and `core/color`. Read those interfaces before calling
`sdk/input`, `sdk/log`, `sdk/math`, `sdk/mathf`, `sdk/random`, and `core/color`. Read those interfaces before calling
them. Game SDK 1 does not currently ship `audio` or `core/math` modules.
Ordinary game source uses public services such as `Gfx`; it must not manufacture
@@ -135,3 +135,7 @@ That means:
- PBS semantic highlight resources belong to PBS rather than to Studio or LSP,
- PBS publishes that contract through `FrontendSpec`,
- and Studio/LSP consume that contract without becoming owners of PBS semantic presentation assets.
The `@sdk:random` module exports `Random` and `random`. Use an explicit long seed;
copying a generator shares its state. Read `pbs:spec:runtime-random-integration.md`
and `pbs:example:game:1:src/random.pbs` for the exact contract and a small example.