Files
prometeu-studio/discussion/lessons/DSC-0082-pbs-runtime-random-integration/LSN-0086-explicit-random-handles-and-source-conformance.md
T

9.0 KiB

id, ticket, title, created, tags
id ticket title created tags
LSN-0086 pbs-runtime-random-integration Explicit Random handles and source-to-runtime conformance 2026-10-17
runtime-integration

Original problem and ownership

Owner: compiler/pbs; supporting integration: compiler/general. This lesson consolidates AGD-0084, accepted DEC-0070 and completed PLN-0149 of DSC-0082. The user accepted the direction and authorized plan generation and implementation. The workflow scaffolding is removed by housekeeping; the normative PBS contract is Runtime Random Integration.

The common catalog already contained all four Random entries, with a synthetic IR test of mutation and aliasing. That did not establish a usable PBS SDK or prove source evaluation, typed storage, imports and captures. A deterministic operation can still mutate state: the same seed is not permission to fold or eliminate a call.

Consolidated decision

Expose an explicit opaque Random handle and random.new/next/nextf/range. Use the runtime's exact signatures, single-slot BuiltinId 0x0016 and catalog metadata. All operations mutate guest state; only new allocates. Do not add an implicit global generator, duplicate algorithm or compiler-side billing engine.

Copies alias the same generator. Two allocations with the same seed begin with equal sequences and evolve independently. Source order, named-argument effects and discarded calls must survive lowering and optimization. Handle identity must survive locals, globals, fields, arrays, parameters, results, captures and private Dynamic storage. The runtime remains authoritative for faults, transactional mutation, resources and cycles. No game seed policy or replay serialization API is introduced.

Final implementation

Game SDK 1 publishes Random and random from @sdk:random, with normal import aliases and reserved metadata bindings. PBS registers Random as the existing runtime builtin. The parser accepts new in callable/member positions so the published spelling is random.new(seed). It still distinguishes source allocation expressions, and rejects new Random().

Fieldless builtins are treated as opaque by the semantic model. Exact contextual types prevent returning a Random reference as an unrelated Struct or contract; explicit contract adaptation is rejected too. Existing member checks reject payload access. The discovered return-path gap is now a frontend diagnostic, not a later backend stack/Registry error.

Existing array, optional, struct and closure lowering already preserves reference identity, so no second storage representation or common backend algorithm was needed. Common catalog tests and runtime execution verify the inherited effects and costs. The reference model remains language-neutral.

import { Random, random } from @sdk:random;

fn sample() -> long {
    let generator: Random = random.new(42 as long);
    let alias = generator;
    random.next(generator); // discarded result still advances shared state
    return random.range(alias, 0 as long, 100 as long);
}

The four operations use long/Float carriers exactly. nextf returns [0,1); range returns [min,max) and requires min < max. Intrinsic costs are 32, 8, 12 and 4 + 8*N respectively. Range accepts at most 64 attempted words: attempt 64 can succeed, while rejecting all 64 faults and rolls state back without refunding 516 charged cycles. Explicit source conversions and ordinary bytecode instructions have separate costs.

Source evidence and provider evidence

PbsRuntimeRandomTest compiles the packaged SDK and project declarations through production linking, common lowering, optimization and PBX emission. A dedicated fixture uses the real workspace builder, import aliases and lifecycle assembler. The focused callable driver explicitly calls file initialization before Probe.main; it does not replace or introduce a lifecycle feature.

The 48 provider oracle rows cover six seeds and eight draws. Projecting both integer and Float outputs, with optimization off/on, produces 192 fixtures. Another 30 source fixtures cover aliases, independent objects, mixed/discarded operations, named/positional effects, storage/captures, limits, faults and GC. Four controlled provider fixtures cover null and typed-null carriers. Together with real imports this is 223 source fixtures plus four controlled provider fixtures. The DEC-0073 follow-up requalified this revised corpus in the dev profile; the original debug/release evidence below describes the earlier source corpus. Each of the 226 callable fixtures executes with single-step budgets and twice with full budgets to compare exact bits/faults, call charges and total cycles. The runner checks oracle byte equality against the selected runtime.

The GC fixture reuses the established test-only FRAME_SYNC marker mechanism. All allocations and accesses are PBS source. After at least 1,100 discarded Random objects are reclaimed, array, field and closure roots still draw the expected shared sequence. The source corpus also exercises a genuine rejected PCG word followed by acceptance, charging range 20 cycles.

PBS has no public null or Dynamic type. Following the explicit DEC-0073 clarification, every completing constructor path initializes every field. Null coverage uses a controlled provider fixture: compile a fully initialized Random field, then suppress its unique field store in test bytecode to exercise the provider reference default. Storing it in a typed array preserves a present Dynamic tag and exact TypeId; extracting it then drawing traps NULL_REFERENCE. This must not be confused with an empty array slot. Existing global-initializer restrictions are unchanged.

Provider evidence is separate: 13 guest contract tests and 11 private Random engine/VM tests passed in both debug and release. Those prove synthetic 64th-attempt success, capped rejection rollback, malformed carriers, fault precedence, resource refusal, exact Dynamic types, stale handles, reset and native provenance. They are not described as PBS-produced rare-path execution.

Validation and limits

The evidence record pins source/catalog/oracle/lockfile hashes, commands, toolchains, profiles and suite counts. Executed on macOS arm64 with runtime f7d7c167531bb662a1af9d73fc326bb476bf8aa7.

  • Java: frontend 249 passed; architecture 63 passed; common pipeline 175 passed with 12 existing skips; installed knowledge 2 passed. Total: 489 passed.
  • Full production-loader conformance harness passed in debug and release, including all 227 Random fixtures and existing math/input/Registry/collection and closure suites.
  • Runtime provider Random suites: 13 contract + 11 private tests per profile.
  • Catalog copies and provider exporter matched; workflow and diff validation passed.

Qualification covers the local target only. Other platforms and the reference game's corpus are not claimed. The full harness retains the pre-existing, explicitly reported runtime fault-schema gaps for LifecycleRole and NonFiniteValue; this work neither changes nor hides them. Installed knowledge validates packaged SDK/spec/example delivery, not execution through an installed runtime process.

Pitfalls and maintenance

  1. Do not confuse deterministic with pure. Eliminating a discarded draw changes every subsequent result; eliminating discarded new also changes allocation.
  2. Do not duplicate the RNG in Java to prove Java output. Keep independent provider vectors and execute generated PBX on the VM.
  3. Do not use interface-module validation for arbitrary project code. The tests compile SDK metadata separately and link trusted declarations into project source.
  4. Do not use a runtime carrier's physical HeapRef shape as permission for a Struct/contract adaptation. Exact source and Registry identities matter.
  5. Distinguish present typed null from absent Dynamic. Check the tag before unpacking.
  6. Keep new fixture families separate from older enumerated corpora; the old eight-type input suite must not accidentally count Random fixtures.
  7. Record fingerprints and distinguish provider rare-path proofs from source tests. A passing synthetic common-IR test is not a source integration claim.

References