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
@@ -0,0 +1,155 @@
---
id: LSN-0086
ticket: pbs-runtime-random-integration
title: Explicit Random handles and source-to-runtime conformance
created: 2026-10-17
tags: [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](../../../docs/compiler/pbs/specs/runtime-random-integration.md).
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.
```pbs
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 34 paired fixtures cover aliases, independent objects, mixed/discarded
operations, named/positional effects, storage/captures, limits, faults and GC.
Together with real imports this is **227 mandatory fixtures per runtime profile**.
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. A source struct constructor that leaves
a Random field at its runtime default provides a null reference for tests.
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](evidence.json) 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
- [PBS Random specification](../../../docs/compiler/pbs/specs/runtime-random-integration.md).
- [Typed arrays and optional execution](../../../docs/compiler/pbs/specs/typed-arrays-and-optional-execution.md).
- [Functions and captures](../../../docs/compiler/pbs/specs/first-class-functions-and-captures.md).
- [Conformance commands and boundaries](../../../tools/pbx-conformance/README.md).
- [Provider Random specification](../../../../runtime/docs/specs/runtime/02e-vm-owned-random-core.md).
- [Provider qualification](../../../../runtime/docs/vm-arch/RANDOM_QUALIFICATION.md).
- Historical accepted DEC-0070 and completed PLN-0149: obligations are preserved
in the normative spec, this lesson and its evidence after workflow cleanup.
@@ -0,0 +1,108 @@
{
"date": "2026-10-17",
"discussion": "DSC-0082",
"decision": "DEC-0070",
"plan": "PLN-0149",
"runtime_revision": "f7d7c167531bb662a1af9d73fc326bb476bf8aa7",
"platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
"rustc": "rustc 1.98.1 (48a229cea 2026-09-01)\nbinary: rustc\ncommit-hash: 48a229ceaefd4985c50990b14116b6d856af0985\ncommit-date: 2026-09-01\nhost: aarch64-apple-darwin\nrelease: 1.98.1\nLLVM version: 22.1.8",
"java": "openjdk version \"25.0.4\" 2026-07-21 LTS\nOpenJDK Runtime Environment Corretto-25.0.4.7.1 (build 25.0.4+7-LTS)\nOpenJDK 64-Bit Server VM Corretto-25.0.4.7.1 (build 25.0.4+7-LTS, mixed mode, sharing)",
"runtime_profiles": [
"dev",
"release"
],
"harness_features": [
"resource-diagnostics"
],
"provider_features": "default",
"source_fingerprints": {
"../runtime/Cargo.lock": "cffad9ed62f38a591538abd81dd39270d6022397342c8189f4ac6c7baaa8e795",
"../runtime/docs/vm-arch/INTRINSICS.csv": "0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa",
"../runtime/docs/vm-arch/BUILTIN_CONSTANTS.csv": "e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039",
"../runtime/crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv": "0bee1cd0366f1716687aee8c7ac39dd495da5fe2908cce37b1443cb04fac542f",
"../runtime/crates/console/prometeu-vm/tests/random_contract.rs": "de961a4c57c4ed7b1f01b002abd8a319c3fed90cb5bce07a5c023ef9239490b1",
"../runtime/crates/console/prometeu-vm/src/random.rs": "48e46d50f0665c85bb899d7324783cb1b5121378cb21f06059f2c2617e6d9e16",
"../runtime/crates/console/prometeu-vm/src/virtual_machine/random.rs": "136cdbe46a687a7b755d559a2842d44f494cf76e8a34427eeb48494820935a42",
"tools/pbx-conformance/main.rs": "76d3d1b90b417c33737fb0ede6ea7af8ffe586bfb2bf4f710684a8d9f72c7466",
"tools/pbx-conformance/run.py": "49b01cfc81d378871ca3cc32dec7b1f830fdb7c86545d5a32e2e3455c4f1588f",
"prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java": "2d474bd65b0ddcfa2b9ad8d7887c2f964cf73336a8747f4f34478e6a2137bf59",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs": "c21c12d99c5a033a1e4026432bbab56393ad09c0fe2d36711504ccca01ce93b5",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/mod.barrel": "7924c022a140b9bc634f3699175c8775f24093d3aa82e650752232971b0380fb",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java": "c973cb5de13a3e1bddaecad140436ea54d4a78ac5f08310511a60b637630889a",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java": "50d494f4e2b79d7147acc25e0ce4cad244ef2a04288ea823aecdd5347feb48c6",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsExprParserContext.java": "7b6de40de18fd676210bcfc6655b0dbbd10d589513d35f1cf0c4b01cbf30e7d5",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowExpressionAnalyzer.java": "4775395a00edba94ff55cd2d93959973fc8ad70cae260cc5e2631087827eee9d",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java": "2c39d3fed360aeef0ac1c6c8f8c1d92989f84f60cbe23dd01ebce8a9d575d128",
"prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java": "ba32cc9521ee4bc4840e0910566b4fad7d50a382dac8288c4f6e1ac3ab2fe4ab"
},
"java_tests": {
"frontend": {
"passed": 249
},
"architecture": {
"passed": 63
},
"common_pipeline": {
"passed": 175,
"existing_skipped": 12
},
"installed_knowledge": {
"passed": 2
}
},
"random_fixtures_per_profile": 227,
"callable_replays_per_fixture": 3,
"provider_tests_per_profile": {
"random_contract": 13,
"private_random": 11
},
"commands": [
"./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-architecture-tests:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-app:installedKnowledgeTest --console=plain",
"CARGO_TARGET_DIR=/tmp/pln149-cargo-target python3 tools/pbx-conformance/run.py",
"CARGO_TARGET_DIR=/tmp/pln149-cargo-target python3 tools/pbx-conformance/run.py --release",
"cargo test --manifest-path ../runtime/Cargo.toml --locked --offline -p prometeu-vm random --target-dir /tmp/pln149-provider-target",
"cargo test --manifest-path ../runtime/Cargo.toml --locked --offline -p prometeu-vm --lib random --release --target-dir /tmp/pln149-provider-target",
"cargo test --manifest-path ../runtime/Cargo.toml --locked --offline -p prometeu-vm --test random_contract --target-dir /tmp/pln149-provider-target",
"cargo test --manifest-path ../runtime/Cargo.toml --locked --offline -p prometeu-vm --test random_contract --release --target-dir /tmp/pln149-provider-target",
"python3 tools/runtime-catalog/verify.py --runtime ../runtime"
],
"logs": {
"regression": {
"sha256": "1379beaf5dbb205c9ff5894775835467dd0772fad3b87f3241b94e03c6609bf8",
"result": "passed"
},
"conformance-dev": {
"sha256": "99e7c3a4b5c3f1a408d22eef8a736b9a6fd061eff5c13e405c1bd019f504ce4d",
"result": "passed"
},
"conformance-release": {
"sha256": "f1df27a348bb98976b4ee0b46a0e121b56d524aab5f43deecc0c705c08e1fd79",
"result": "passed"
},
"provider-dev": {
"sha256": "3b9b0b522d3c5ed305536aa5be621fc34f0b4cce0f6b5705626052a4fb252be2",
"result": "passed"
},
"provider-release": {
"sha256": "8555828137f4e747f079145892c7c11e18ac55f2e9720497affaf9fe828f48b9",
"result": "passed"
},
"provider-contract-dev": {
"sha256": "5c2a31b0f33e75dfe644993e0e79f8cf19bd01bc95db23b41190fc2069d16f8e",
"result": "passed"
},
"provider-contract-release": {
"sha256": "cbf430b84132edbdda2fe0b5ab34cf5fad6e78a048811695efe223eac37a3333",
"result": "passed"
},
"catalog": {
"sha256": "66b7003ff94115aece4b278522b0c080e806497e26ca17dd756163bc7974fa83",
"result": "passed"
}
},
"limitations": [
"macOS arm64 only",
"Reference-game and installed-runtime process qualification excluded",
"Existing explicit provider schema gaps LifecycleRole and NonFiniteValue retained"
]
}
@@ -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.
@@ -0,0 +1,271 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.PbsFrontendCompiler;
import static org.junit.jupiter.api.Assertions.*;
class PbsRuntimeRandomTest {
static String sdk() throws Exception {
try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/sdk/random/main.pbs")) {
assertNotNull(stream);
return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
}
@Test void mixedCallsPreserveAliasing() throws Exception {
for (var suffix : new String[]{"", "-optimized"}) {
PbsRuntimeAlignmentTest.compile("random-mixed"+suffix, sdk()+"""
declare service Probe {
fn main() -> (a: float, b: long, c: long) {
let rng = random.new(42 as long);
let alias = rng;
random.next(rng);
let a = random.nextf(alias);
let b = random.range(rng, -7 as long, -6 as long);
let c = random.next(alias);
return (a: a, b: b, c: c);
}
}
""");
}
}
private static void pair(String name, String source) throws Exception {
for (var suffix : new String[]{"", "-optimized"})
compile("random-"+name+suffix, source);
}
static void compile(String name, String source) throws Exception {
var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
var sdkId = new p.studio.compiler.source.identifiers.FileId(1);
var fileId = new p.studio.compiler.source.identifiers.FileId(0);
var names = new p.studio.compiler.source.tables.NameTable();
var modules = p.studio.utilities.structures.ReadOnlyList.from(
new p.studio.compiler.source.tables.ModuleReference("test",p.studio.utilities.structures.ReadOnlyList.from("client")),
new p.studio.compiler.source.tables.ModuleReference("sdk",p.studio.utilities.structures.ReadOnlyList.from("random")));
var sdkAst = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(sdk(),sdkId,diagnostics), sdkId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
var provider = new PbsFrontendCompiler().compileParsedFile(sdkId,sdkAst,diagnostics,p.studio.compiler.models.SourceKind.SDK_INTERFACE,
new p.studio.compiler.source.identifiers.ModuleId(1),modules,
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),names);
var imported = new java.util.ArrayList<PbsFrontendCompiler.ImportedCallableSurface>();
for (var signature : provider.callableSignatures()) {
var executable = provider.executableFunctions().stream().filter(f -> f.callableName().equals(signature.callableName())).findFirst().orElseThrow();
var method = signature.callableName().substring(signature.callableName().lastIndexOf('.')+1);
String type = switch(method) { case "new" -> "Random"; case "nextf" -> "float"; case "$instance" -> "random"; default -> "long"; };
imported.add(new PbsFrontendCompiler.ImportedCallableSurface(new p.studio.compiler.source.identifiers.ModuleId(1), signature.callableName(), signature.arity(), executable.returnSlots(),
p.studio.compiler.pbs.ast.PbsAst.ReturnKind.PLAIN, p.studio.compiler.pbs.ast.PbsAst.TypeRef.simple(type,sdkAst.span()),signature.typeShape()));
}
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
var file = new PbsFrontendCompiler().compileParsedFile(fileId,ast,diagnostics,p.studio.compiler.models.SourceKind.PROJECT,
new p.studio.compiler.source.identifiers.ModuleId(0),modules,
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),names,
sdkAst.topDecls(),p.studio.utilities.structures.ReadOnlyList.wrap(imported),p.studio.utilities.structures.ReadOnlyList.empty(),provider.reservedMetadata(),java.util.Map.of());
assertFalse(diagnostics.hasErrors(), () -> name+": "+diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList());
var functions = new java.util.ArrayList<>(file.executableFunctions().asList());
var signatures = new java.util.ArrayList<>(file.callableSignatures().asList());
String entry = "Probe.main";
var initializer = functions.stream().filter(f -> f.callableName().startsWith("__pbs.file_init$")).findFirst();
if (initializer.isPresent()) {
var main = functions.stream().filter(f->f.callableName().equals("Probe.main")).findFirst().orElseThrow();
var init = initializer.get();
var id = new p.studio.compiler.source.identifiers.CallableId(signatures.size());
entry = "$test.entry";
int returns = main.returnSlots();
signatures.add(new p.studio.compiler.source.tables.CallableSignatureRef(new p.studio.compiler.source.identifiers.ModuleId(0),entry,0,"test"));
var instructions = p.studio.utilities.structures.ReadOnlyList.from(
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
new p.studio.compiler.source.identifiers.ModuleId(0),init.callableName(),init.callableId(),null,null,0,0,init.span()),
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
new p.studio.compiler.source.identifiers.ModuleId(0),main.callableName(),main.callableId(),null,null,0,returns,main.span()),
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.RET,"",null,null,main.span()));
functions.add(new p.studio.compiler.models.IRBackendExecutableFunction(fileId,new p.studio.compiler.source.identifiers.ModuleId(0),entry,id,0,0,0,0,returns,returns,instructions,main.span(),main.metadata()));
}
var client = new p.studio.compiler.models.IRBackendFile(file.fileId(),file.functions(),file.syntheticFunctions(),file.globals(),
p.studio.utilities.structures.ReadOnlyList.wrap(functions),file.reservedMetadata(),file.modulePool(),
p.studio.utilities.structures.ReadOnlyList.wrap(signatures),file.intrinsicPool(),null,file.registry());
var aggregator = p.studio.compiler.models.IRBackend.aggregator();
aggregator.merge(provider); aggregator.merge(client);
var backend = aggregator.entryPointCallableName(entry).entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).emit();
var program = new LowerToIRVMService().lower(backend);
if(name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program);
var module = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
if (name.startsWith("random-gc")) module = PbsStructuredValuesTest.withTestSafepoint(module);
new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(module);
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-"+name+".pbx"),module.serialize());
}
@Test void providerSeedVectors() throws Exception {
String corpus;
try (var stream = PbsRuntimeRandomTest.class.getResourceAsStream("/random/random-conformance.tsv")) {
assertNotNull(stream);
corpus = new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
var manifest = new StringBuilder();
int index = 0;
for (var row : corpus.lines().skip(1).toList()) {
var parts = row.split("\\s+");
for (var kind : new String[]{"next", "nextf"}) {
String type = kind.equals("next") ? "long" : "float";
int draw = Integer.parseInt(parts[1]);
String name = "vector-"+index++;
pair(name, "declare service Probe { fn main() -> "+type+" { let seed: long = "+parts[0]+"; let rng = random.new(seed); "
+ "random.next(rng);".repeat(draw-1)+"return random."+kind+"(rng); } }");
for (var suffix : new String[]{"", "-optimized"})
manifest.append("pbs-random-").append(name).append(suffix).append(" ")
.append(kind.equals("next") ? "l:"+parts[3] : "f:"+parts[4].toLowerCase())
.append(" ").append(draw).append("\n");
}
}
assertEquals(96, index);
java.nio.file.Files.writeString(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"), "random-vectors.tsv"), manifest);
}
@Test void storageAndIndependentStreams() throws Exception {
pair("storage", """
declare struct Empty(pub value: Random) { ctor create() {} } declare global saved: Random = new Empty.create().value;
declare struct Box(pub value: Random);
fn echo(rng: Random) -> Random { return rng; }
fn capture(rng: Random) -> Fn() -> long { return fn [rng]() -> long { return random.next(rng); }; }
declare service Probe {
fn main() -> (a: long, b: long, c: long, d: long, e: long) {
let rng = random.new(42 as long);
saved = echo(rng);
let box = new Box(saved);
let values: array Random = [box.value];
let draw = capture(rng);
let a = random.next(saved);
let b = random.next(box.value);
if let value = values[0] {
let c = random.next(value);
let d = draw();
let other = random.new(42 as long);
let e = random.next(other);
return (a: a, b: b, c: c, d: d, e: e);
}
return (0 as long, 0 as long, 0 as long, 0 as long, 0 as long);
}
}
""");
pair("named", """
declare global trace: int = 0;
declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value;
declare service Probe {
fn receiver() -> Random { trace = trace * 10 + 1; return rng; }
fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; }
fn high() -> long { trace = trace * 10 + 3; random.next(rng); return -6; }
fn main() -> (trace: int, value: long, next: long) {
rng = random.new(42 as long); trace = 0;
let value = random.range apply (max: Probe.high(), rng: Probe.receiver(), min: Probe.low());
return (trace: trace, value: value, next: random.next(rng));
}
}
""");
pair("positional", """
declare global trace: int = 0;
declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value;
declare service Probe {
fn receiver() -> Random { trace = trace * 10 + 1; return rng; }
fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; }
fn high() -> long { trace = trace * 10 + 3; random.next(rng); return -6; }
fn main() -> (trace: int, value: long, next: long) {
rng = random.new(42 as long); trace = 0;
let value = random.range(Probe.receiver(), Probe.low(), Probe.high());
return (trace: trace, value: value, next: random.next(rng));
}
}
""");
}
@Test void rangeBoundsAndNullDefaults() throws Exception {
String[][] bounds = {{"0","1"},{"-10","-3"},{"-10","10"},{"0","16"},
{"-9223372036854775808","0"},{"-1","9223372036854775807"},{"-9223372036854775808","9223372036854775807"},
{"5","5"},{"6","5"}};
for (int i=0; i<bounds.length; i++)
pair("range-"+i, "declare service Probe { fn main() -> long { let rng = random.new(42 as long); let low: long = "+bounds[i][0]+"; let high: long = "+bounds[i][1]+"; return random.range(rng, low, high); } }");
pair("rejection", """
declare service Probe { fn main() -> (value: long, next: long) {
let rng = random.new(42 as long); random.next(rng);
let low: long = -9223372036854775808; let value = random.range(rng, low, 1 as long);
return (value: value, next: random.next(rng));
} }
""");
pair("null", "declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value; declare service Probe { fn main() -> long { return random.next(empty); } }");
pair("typed-null", """
declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value;
declare service Probe { fn main() -> long {
let values: array Random = [empty];
if let value = values[0] { return random.next(value); }
return 99;
} }
""");
}
@Test void incompatibleSourceCannotConstructOrAdaptRandom() throws Exception {
for (var body : new String[]{"new Random();", "random.new(true);", "let seed: int = 42; random.new(seed);",
"random.next(42);", "random.nextf(1.0);", "let rng = random.new(42 as long); random.range(rng, true, 2 as long);"}) {
var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new p.studio.compiler.source.identifiers.FileId(0),
sdk()+"declare service Probe { fn main() { "+body+" } }", diagnostics, p.studio.compiler.models.SourceKind.SDK_INTERFACE);
assertTrue(diagnostics.hasErrors(), body);
}
}
@Test void installedSdkImportsAndAliases(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
java.nio.file.Files.createDirectories(root.resolve("src"));
java.nio.file.Files.writeString(root.resolve("prometeu.json"), """
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
java.nio.file.Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;");
java.nio.file.Files.writeString(root.resolve("src/main.pbs"), """
import { Random as Generator, random as rng } from @sdk:random;
fn echo(value: Generator) -> Generator { return value; }
[Frame]
fn frame() -> void {
let generator: Generator = rng.new(42 as long);
let expected: long = -8740965581747508376;
if rng.next(echo(generator)) != expected { let fail = 1 / 0; }
if rng.range(generator, -7 as long, -6 as long) != -7 as long { let fail = 1 / 0; }
}
""");
var result = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(
p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),
p.studio.utilities.logs.LogAggregator.stdout());
assertFalse(result.diagnostics().stream().anyMatch(d->d.isError()),result.diagnostics().toString());
assertTrue(result.bytecodeBytes().length>0);
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-random-import.pbx"),result.bytecodeBytes());
}
@Test void referencesSurviveCollection() throws Exception {
pair("gc", """
declare struct Box(pub value: Random);
fn make() -> (items: array Random, draw: Fn() -> long, box: Box) {
let rng = random.new(42 as long);
let items: array Random = [rng];
let draw = fn [rng]() -> long { return random.next(rng); };
return (items: items, draw: draw, box: new Box(rng));
}
declare service Probe {
fn garbage() { random.new(1 as long); }
fn collect() { let marker = 314159; }
fn main() -> (a: long, b: long, c: long) {
let roots = make();
for i: int from 0 until 1100 { Probe.garbage(); }
Probe.collect();
if let rng = roots.items[0] {
let a = random.next(rng);
let draw = roots.draw;
let b = draw();
let c = random.next(roots.box.value);
return (a: a, b: b, c: c);
}
return (0 as long, 0 as long, 0 as long);
}
}
""");
}
@Test void opaqueValuesRejectFieldsAndStructuralAdaptation() throws Exception {
for (var source : new String[]{
"declare service Probe { fn main() -> long { let rng = random.new(42 as long); return rng.state; } }",
"declare struct Box(pub n: long); declare service Probe { fn main() -> Box { return random.new(42 as long); } }",
"declare contract Draw { fn draw() -> long; } declare service Probe { fn main() -> Draw { return random.new(42 as long); } }",
"declare contract Draw { fn draw() -> long; } declare service Probe { fn main() -> Draw { let rng = random.new(42 as long); return rng as Draw; } }"}) {
var failure = assertThrows(org.opentest4j.AssertionFailedError.class, () -> compile("invalid", source), source);
assertTrue(failure.getMessage().contains("E_SEM_"), failure.getMessage());
}
}
}
@@ -56,7 +56,7 @@ class PbsStructuredValuesTest {
// PBS sync/closure syntax belongs to AGD82. This test-only driver hook replaces
// an isolated marker assignment with FRAME_SYNC + NOPs, preserving every offset.
// All allocations, roots, field/array access and post-GC assertions are compiled PBS.
private static BytecodeModule withTestSafepoint(BytecodeModule module) {
static BytecodeModule withTestSafepoint(BytecodeModule module) {
byte[] code = module.code().clone();
var marker = java.nio.ByteBuffer.allocate(6).order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putShort((short) 0x17).putInt(314159).array();
@@ -0,0 +1,5 @@
Copied unchanged from runtime crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv
Runtime revision: f7d7c167531bb662a1af9d73fc326bb476bf8aa7
Provenance: runtime crates/console/prometeu-vm/tests/fixtures/random-oracle.md
48 rows: six seeds x eight draws. PBS tests project both signed words and Float bits.
No generator implementation is copied into the compiler.
@@ -0,0 +1,49 @@
seed draw word_hex signed float_bits
0 1 9B3184D7EE6BACDB -7263878661019030309 3FE366309AFDCD75
0 2 8B7B271AA4769FD4 -8396074084920287276 3FE16F64E3548ED3
0 3 9B4DB63DFE544AAB -7255943047247803733 3FE369B6C7BFCA89
0 4 E714BA3532308667 -1795605613775911321 3FECE29746A64610
0 5 64EAF919A9A040E2 7271898436958437602 3FD93ABE466A6810
0 6 325BCFFB862545B0 3628722603971397040 3FC92DE7FDC312A0
0 7 70180161DC24B6EC 8077207451505833708 3FDC06005877092C
0 8 39257F36B038F771 4117837307161671537 3FCC92BF9B581C78
1 1 3150032F5C48AC0A 3553343607941934090 3FC8A80197AE2454
1 2 099B2F21D97DB047 692198790160822343 3FA3365E43B2FB60
1 3 7539BA4A2ED012EB 8446987403885810411 3FDD4E6E928BB404
1 4 C842BA297694C455 -4016443230415174571 3FE90857452ED298
1 5 C8AE2BB397CD3537 -3986200569830361801 3FE915C57672F9A6
1 6 C2F1AF39457336BA -4399542700451088710 3FE85E35E728AE66
1 7 8710A37C51FEC0AD -8714285524614987603 3FE0E2146F8A3FD8
1 8 A4C73DCA70459C07 -6573217191447651321 3FE498E7B94E08B3
42 1 86B1DA1D72062B68 -8740965581747508376 3FE0D63B43AE40C5
42 2 1304AA46C9853D39 1370407407632858425 3FB304AA46C98538
42 3 A3670E9E0DD50358 -6672348250926415016 3FE46CE1D3C1BAA0
42 4 F9090E529A7DAE00 -501854135533064704 3FEF2121CA534FB5
42 5 C85B9FD837996F2C -4009435292248740052 3FE90B73FB06F32D
42 6 606121F8E3919196 6944869453235589526 3FD818487E38E464
42 7 7CE1C7FF478354BA 8998693429693338810 3FDF3871FFD1E0D4
42 8 CBC4AC70E541310E -3763693787692322546 3FE978958E1CA826
-1 1 EE89537ECBD16900 -1258382816822859520 3FEDD12A6FD97A2D
-1 2 DCBE53D8A6C852E6 -2540500949814193434 3FEB97CA7B14D90A
-1 3 561BA13FFCFD5094 6204730207832461460 3FD586E84FFF3F54
-1 4 76962EA43FCF9400 8545068625962177536 3FDDA58BA90FF3E4
-1 5 A2BF24C068F28D0D -6719611710200443635 3FE457E4980D1E51
-1 6 3D575F16AA0C40D8 4420106110234280152 3FCEABAF8B550620
-1 7 032B99D40D100946 228445342143613254 3F895CCEA0688040
-1 8 7053160AB14A824F 8093837190494847567 3FDC14C582AC52A0
-9223372036854775808 1 1C08F9C51E05B9F1 2020139057883232753 3FBC08F9C51E05B8
-9223372036854775808 2 4CC379FA6A441AFF 5531398883772734207 3FD330DE7E9A9106
-9223372036854775808 3 1E9926CF448F8AA7 2204836164224912039 3FBE9926CF448F88
-9223372036854775808 4 18ADD82F6DA7760F 1778315126095967759 3FB8ADD82F6DA770
-9223372036854775808 5 77DFD36640320B00 8637855046437047040 3FDDF7F4D9900C82
-9223372036854775808 6 CE09AC671D48BD0F -3600156868233085681 3FE9C1358CE3A917
-9223372036854775808 7 B15DBA0399E9E3D1 -5666168231532305455 3FE62BB740733D3C
-9223372036854775808 8 E88252991CF3E42C -1692699692368665556 3FED104A53239E7C
9223372036854775807 1 77D44C809FDF62DB 8634610500897825499 3FDDF5132027F7D8
9223372036854775807 2 05BCF3AED615466A 413473198052820586 3F96F3CEBB585500
9223372036854775807 3 693ED392E1CE694A 7583731450345580874 3FDA4FB4E4B8739A
9223372036854775807 4 83D248E707AC837B -8948009352528362629 3FE07A491CE0F590
9223372036854775807 5 5DD1D07026E00956 6760413695766956374 3FD774741C09B802
9223372036854775807 6 5713B8336C9A861C 6274561236862141980 3FD5C4EE0CDB26A0
9223372036854775807 7 4F2E7352ED7CCE69 5705624577933889129 3FD3CB9CD4BB5F32
9223372036854775807 8 DB109447225C784B -2661464346535888821 3FEB621288E44B8F
1 seed draw word_hex signed float_bits
2 0 1 9B3184D7EE6BACDB -7263878661019030309 3FE366309AFDCD75
3 0 2 8B7B271AA4769FD4 -8396074084920287276 3FE16F64E3548ED3
4 0 3 9B4DB63DFE544AAB -7255943047247803733 3FE369B6C7BFCA89
5 0 4 E714BA3532308667 -1795605613775911321 3FECE29746A64610
6 0 5 64EAF919A9A040E2 7271898436958437602 3FD93ABE466A6810
7 0 6 325BCFFB862545B0 3628722603971397040 3FC92DE7FDC312A0
8 0 7 70180161DC24B6EC 8077207451505833708 3FDC06005877092C
9 0 8 39257F36B038F771 4117837307161671537 3FCC92BF9B581C78
10 1 1 3150032F5C48AC0A 3553343607941934090 3FC8A80197AE2454
11 1 2 099B2F21D97DB047 692198790160822343 3FA3365E43B2FB60
12 1 3 7539BA4A2ED012EB 8446987403885810411 3FDD4E6E928BB404
13 1 4 C842BA297694C455 -4016443230415174571 3FE90857452ED298
14 1 5 C8AE2BB397CD3537 -3986200569830361801 3FE915C57672F9A6
15 1 6 C2F1AF39457336BA -4399542700451088710 3FE85E35E728AE66
16 1 7 8710A37C51FEC0AD -8714285524614987603 3FE0E2146F8A3FD8
17 1 8 A4C73DCA70459C07 -6573217191447651321 3FE498E7B94E08B3
18 42 1 86B1DA1D72062B68 -8740965581747508376 3FE0D63B43AE40C5
19 42 2 1304AA46C9853D39 1370407407632858425 3FB304AA46C98538
20 42 3 A3670E9E0DD50358 -6672348250926415016 3FE46CE1D3C1BAA0
21 42 4 F9090E529A7DAE00 -501854135533064704 3FEF2121CA534FB5
22 42 5 C85B9FD837996F2C -4009435292248740052 3FE90B73FB06F32D
23 42 6 606121F8E3919196 6944869453235589526 3FD818487E38E464
24 42 7 7CE1C7FF478354BA 8998693429693338810 3FDF3871FFD1E0D4
25 42 8 CBC4AC70E541310E -3763693787692322546 3FE978958E1CA826
26 -1 1 EE89537ECBD16900 -1258382816822859520 3FEDD12A6FD97A2D
27 -1 2 DCBE53D8A6C852E6 -2540500949814193434 3FEB97CA7B14D90A
28 -1 3 561BA13FFCFD5094 6204730207832461460 3FD586E84FFF3F54
29 -1 4 76962EA43FCF9400 8545068625962177536 3FDDA58BA90FF3E4
30 -1 5 A2BF24C068F28D0D -6719611710200443635 3FE457E4980D1E51
31 -1 6 3D575F16AA0C40D8 4420106110234280152 3FCEABAF8B550620
32 -1 7 032B99D40D100946 228445342143613254 3F895CCEA0688040
33 -1 8 7053160AB14A824F 8093837190494847567 3FDC14C582AC52A0
34 -9223372036854775808 1 1C08F9C51E05B9F1 2020139057883232753 3FBC08F9C51E05B8
35 -9223372036854775808 2 4CC379FA6A441AFF 5531398883772734207 3FD330DE7E9A9106
36 -9223372036854775808 3 1E9926CF448F8AA7 2204836164224912039 3FBE9926CF448F88
37 -9223372036854775808 4 18ADD82F6DA7760F 1778315126095967759 3FB8ADD82F6DA770
38 -9223372036854775808 5 77DFD36640320B00 8637855046437047040 3FDDF7F4D9900C82
39 -9223372036854775808 6 CE09AC671D48BD0F -3600156868233085681 3FE9C1358CE3A917
40 -9223372036854775808 7 B15DBA0399E9E3D1 -5666168231532305455 3FE62BB740733D3C
41 -9223372036854775808 8 E88252991CF3E42C -1692699692368665556 3FED104A53239E7C
42 9223372036854775807 1 77D44C809FDF62DB 8634610500897825499 3FDDF5132027F7D8
43 9223372036854775807 2 05BCF3AED615466A 413473198052820586 3F96F3CEBB585500
44 9223372036854775807 3 693ED392E1CE694A 7583731450345580874 3FDA4FB4E4B8739A
45 9223372036854775807 4 83D248E707AC837B -8948009352528362629 3FE07A491CE0F590
46 9223372036854775807 5 5DD1D07026E00956 6760413695766956374 3FD774741C09B802
47 9223372036854775807 6 5713B8336C9A861C 6274561236862141980 3FD5C4EE0CDB26A0
48 9223372036854775807 7 4F2E7352ED7CCE69 5705624577933889129 3FD3CB9CD4BB5F32
49 9223372036854775807 8 DB109447225C784B -2661464346535888821 3FEB621288E44B8F
@@ -175,7 +175,7 @@ final class PbsRuntimeTypes {
}
int id = switch(canonical(t)) {
case "int" -> 0x10; case "long" -> 0x11; case "float" -> 0x12;
case "bool" -> 0x13; case "str" -> 0x14;
case "bool" -> 0x13; case "str" -> 0x14; case "Random" -> 0x16;
case "color" -> 1; case "vec2" -> 2; case "pixel" -> 3;
default -> { if(enums.containsKey(t.name())) yield 0x10;
throw new UnsupportedOperationException("Unsupported PBS runtime type: "+t.name()); }
@@ -612,7 +612,7 @@ final class PbsDeclarationParser {
}
private PbsToken consumeCallableName() {
if (cursor.check(PbsTokenKind.IDENTIFIER)) {
if (cursor.check(PbsTokenKind.IDENTIFIER) || cursor.check(PbsTokenKind.NEW)) {
return cursor.advance();
}
final var token = cursor.peek();
@@ -41,7 +41,7 @@ final class PbsExprParserContext {
}
PbsToken consumeMemberName(final String message) {
if (cursor.check(PbsTokenKind.IDENTIFIER)) {
if (cursor.check(PbsTokenKind.IDENTIFIER) || cursor.check(PbsTokenKind.NEW)) {
return cursor.advance();
}
final var token = cursor.peek();
@@ -73,6 +73,19 @@ final class PbsFlowExpressionAnalyzer {
private ExprResult analyzeExpressionInternal(
final PbsAst.Expression expression,
final PbsFlowExpressionContext context) {
var result = analyzeExpressionUnchecked(expression, context);
if (context.use() == ExprUse.VALUE && context.expectedType() != null
&& (context.model().isOpaqueBuiltin(result.type()) || context.model().isOpaqueBuiltin(context.expectedType()))
&& !typeOps.compatible(result.type(), context.expectedType())) {
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(), "E_SEM_OPAQUE_BUILTIN_TYPE_MISMATCH",
"Opaque builtin references require their exact declared type", expression.span());
}
return result;
}
private ExprResult analyzeExpressionUnchecked(
final PbsAst.Expression expression,
final PbsFlowExpressionContext context) {
if (expression instanceof PbsAst.LambdaExpr lambda) return analyzeLambda(lambda, context);
final var structural = structuralExpressionAnalyzer.analyze(expression, context);
if (structural != null) {
@@ -240,6 +240,12 @@ final class PbsFlowSemanticSupport {
return model;
}
boolean isOpaqueBuiltin(TypeView type) {
if (type == null || !knownBuiltinTypeNames.contains(type.name())) return false;
var declaration = structs.get(type.name());
return declaration != null && declaration.fields().isEmpty();
}
private void registerKnownTopDecl(final PbsAst.TopDecl topDecl) {
if (topDecl instanceof PbsAst.StructDecl structDecl) {
knownStructNames.add(structDecl.name());
@@ -209,6 +209,12 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(TypeView.optional(payloadExpected == null ? payload : payloadExpected));
}
if (expression instanceof PbsAst.NewExpr newExpr) {
// Fieldless builtins are opaque provider references, not source constructors.
if (model.isOpaqueBuiltin(TypeView.struct(newExpr.typeName()))) {
Diagnostics.error(diagnostics, "E_SEM_OPAQUE_BUILTIN_CONSTRUCTION",
"Opaque builtin must be created by its provider operation", newExpr.span());
return ExprResult.type(TypeView.unknown());
}
if (model.structs.containsKey(newExpr.typeName())) {
return ExprResult.type(TypeView.struct(newExpr.typeName()));
}
@@ -223,6 +229,10 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(asExpr.contractName(), asExpr.span()), model, null));
}
if (model.contracts.containsKey(asExpr.contractName())) {
if (model.isOpaqueBuiltin(source)) {
Diagnostics.error(diagnostics, "E_SEM_OPAQUE_BUILTIN_TYPE_MISMATCH",
"Opaque builtin references cannot adapt to contracts", asExpr.span());
}
return ExprResult.type(TypeView.contract(asExpr.contractName()));
}
return ExprResult.type(TypeView.unknown());
@@ -0,0 +1,20 @@
[Doc(markdown = """
Opaque runtime-owned generator. Copies share state; equal seeds create independent streams.
""")]
[BuiltinType(name = "Random", version = 1)]
declare builtin type Random() {}
[Doc(markdown = """
Deterministic stateful random operations. Every draw advances the same generator.
Use explicit long seeds; no host entropy or implicit global generator is used.
""")]
declare service random {
[IntrinsicCall(name = "random.new", version = 1)]
fn new(seed: long) -> Random;
[IntrinsicCall(name = "random.next", version = 1)]
fn next(rng: Random) -> long;
[IntrinsicCall(name = "random.nextf", version = 1)]
fn nextf(rng: Random) -> float;
[IntrinsicCall(name = "random.range", version = 1)]
fn range(rng: Random, min: long, max: long) -> long;
}
@@ -0,0 +1,2 @@
pub struct Random;
pub service random;
@@ -0,0 +1,9 @@
import { Random, random } from @sdk:random;
// Copies share the same sequence. Call random.new again for an independent stream.
fn randomExample() -> long {
let generator: Random = random.new(42 as long);
let alias = generator;
random.next(generator);
return random.range(alias, 0 as long, 100 as long);
}
+36
View File
@@ -160,3 +160,39 @@ every run. Optional `CARGO_TARGET_DIR` can retain build artifacts outside the
runtime checkout. Each invocation prints runtime revision, platform, profile,
features, lockfile and provider catalog/oracle hashes. Local evidence qualifies
macOS/arm64 only; macOS/x86_64 and Linux/x86_64 remain pending.
## PBS explicit Random integration
`PbsRuntimeRandomTest` adds 226 source fixtures plus one real SDK import/alias
fixture. The 48 unchanged provider oracle rows produce 192 exact integer/Float
cases (six seeds, eight draws, two output kinds and two optimizer variants).
The remaining paired fixtures cover mixed/discarded draws, independent objects,
locals/globals/fields/arrays/parameters/results/captures, named/positional effects,
unit/extreme ranges, invalid limits, null and typed-null Dynamic storage, real
rejection followed by acceptance, and collection roots.
Each paired fixture runs with single-instruction budgets and twice with full
budgets, comparing exact result bits or faults, intrinsic charges and total
cycles. Explicit source `as long` conversions are charged separately. The GC
fixture reuses the existing test-only FRAME_SYNC marker hook; all allocations,
roots and post-collection draws are compiled PBS. At least 1,100 discarded Random
objects are reclaimed while array, field and closure references preserve the
same generator. The import fixture uses the production workspace builder and
lifecycle assembler. The focused driver calls file initializers before Probe.main;
it does not claim a new lifecycle API.
```sh
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeRandomTest'
python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only
python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only --release
```
The driver rejects an oracle copy that differs from the selected provider and
prints source/oracle/catalog/lockfile fingerprints and toolchain/profile details.
A complete run includes the Random corpus and keeps it separate from the older
114 input/type fixtures. Rare synthetic 64-attempt acceptance/cap/rollback,
malformed carriers and native provenance are provider tests, not PBS-produced
claims. Qualify those separately with the provider's `random_contract` suite and
`cargo test -p prometeu-vm --lib random` in debug/release. No alternate RNG or
public injection hook is used. Installed knowledge validation remains a separate
gate for packaged SDK/spec/example resources.
+114 -1
View File
@@ -36,8 +36,10 @@ impl NativeInterface for NoNative {
fn main() {
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory"));
if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; }
verify_pbs_math_fixtures(&root);
if std::env::args().any(|arg| arg == "--math-only") { return; }
verify_pbs_random_fixtures(&root);
verify_catalog_fixtures(&root);
verify_pbs_fixtures(&root);
verify_pbs_structured_fixtures(&root);
@@ -477,7 +479,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
for entry in std::fs::read_dir(root).unwrap() {
let path = entry.unwrap().path();
let name = path.file_stem().unwrap().to_str().unwrap();
if name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
count += 1;
let bytes = std::fs::read(&path).unwrap();
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
@@ -726,3 +728,114 @@ fn verify_pbs_math_fixtures(root: &std::path::Path) {
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "import: {report:?}");
println!("PBS MATH PASS: {count} exact bits/faults/cycle vectors; all 26 signatures; service constants");
}
fn verify_pbs_random_fixtures(root: &std::path::Path) {
use prometeu_vm::LogicalFrameEndingReason as End;
use prometeu_bytecode::isa::core::CoreOpCode as OpCode;
let corpus = std::fs::read_to_string(root.join("random-vectors.tsv")).expect("mandatory random seed corpus");
let mut cases: Vec<(String, Vec<String>, Vec<u64>, Option<u32>)> = Vec::new();
let mut names = std::collections::BTreeSet::new();
for row in corpus.lines() {
let p: Vec<_> = row.split_whitespace().collect();
assert!(names.insert(p[0]), "duplicate random fixture");
let draw: usize = p[2].parse().unwrap();
assert!((1..=8).contains(&draw));
let mut costs = vec![32];
costs.extend(std::iter::repeat_n(8, draw-1));
costs.push(if p[1].starts_with("f:") { 12 } else { 8 });
cases.push((p[0].to_string(), vec![p[1].to_string()], costs, None));
}
assert_eq!(cases.len(), 192, "six seeds, eight draws, two outputs, two optimizer variants required");
let words = [0x86B1DA1D72062B68u64, 0x1304AA46C9853D39, 0xA3670E9E0DD50358, 0xF9090E529A7DAE00];
let long = |word: u64| format!("l:{}",word as i64);
let mut add = |name: &str, expected: Vec<String>, costs: Vec<u64>, fault: Option<u32>| {
for suffix in ["", "-optimized"] {
cases.push((format!("pbs-random-{name}{suffix}"), expected.clone(), costs.clone(), fault));
}
};
add("mixed", vec![long(words[3]), "l:-7".into(), "f:3fb304aa46c98538".into()], vec![32,8,12,12,8], None);
add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,8,8,8,8,32,8], None);
for (name, trace) in [("named",312),("positional",123)] {
add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,8,8,12,8],None);
}
let bounds = [(0,1),(-10,-3),(-10,10),(0,16),(i64::MIN,0),(-1,i64::MAX),(i64::MIN,i64::MAX)];
for (index,(min,max)) in bounds.into_iter().enumerate() {
let span = (i128::from(max)-i128::from(min)) as u64;
// Independent provider fixture word, accepted for each of these spans.
let expected = i128::from(min)+i128::from(words[0]%span);
assert!(expected>=i128::from(min) && expected<i128::from(max));
add(&format!("range-{index}"),vec![format!("l:{expected}")],vec![32,12],None);
}
for index in [7,8] { add(&format!("range-{index}"),vec![],vec![32,4],Some(prometeu_bytecode::TRAP_NUMERIC_DOMAIN)); }
let rejected_then_accepted = i128::from(i64::MIN)+i128::from(words[2]%((1u64<<63)+1));
add("rejection",vec![long(words[3]),format!("l:{rejected_then_accepted}")],vec![32,8,20,8],None);
for name in ["null","typed-null"] { add(name,vec![],vec![8],Some(prometeu_bytecode::TRAP_NULL_REFERENCE)); }
let mut gc_costs=vec![32;1101]; gc_costs.extend([8,8,8]);
add("gc",vec![long(words[2]),long(words[1]),long(words[0])],gc_costs,None);
let mut cycles_by_name = std::collections::BTreeMap::new();
for (name,expected,costs,fault) in cases {
let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap_or_else(|e|panic!("{name}: {e}"));
let mut reference = None;
for budget in [1,100000,100000] {
let image = ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE)
.unwrap_or_else(|e|panic!("{name}: {e:?}"));
let code = image.code().to_vec();
let mut vm = VirtualMachine::from_image(image,Default::default());
vm.prepare_boot_call().unwrap();
let mut total=0;
let mut calls=0;
let ending = loop {
let pc=vm.pc();
let opcode=OpCode::try_from(u16::from_le_bytes(code[pc..pc+2].try_into().unwrap())).unwrap();
let report=vm.run_budget(budget,&mut NoNative,&mut HostContext::new(None)).unwrap();
if budget==1 && opcode==OpCode::Intrinsic {
let id=u32::from_le_bytes(code[pc+2..pc+6].try_into().unwrap());
if id == 0x3014 {
// Explicit source `as long` conversion; not a Random call.
assert_eq!(report.cycles_used,2,"{name}: explicit Int32 to Int64");
} else {
assert!((0x4000..=0x4003).contains(&id),"{name}: wrong intrinsic {id:x}");
assert_eq!(report.cycles_used,costs[calls],"{name}: call {calls} id={id:x}");
calls+=1;
}
}
total+=report.cycles_used;
if matches!(report.reason,End::Halted|End::EndOfRom|End::Trap(_)) { break report.reason; }
if matches!(report.reason,End::FrameSync) {
assert!(name.starts_with("pbs-random-gc"));
let snapshot=vm.resource_snapshot();
assert_eq!(snapshot.gc.collections,1);
assert!(snapshot.gc.reclaimed>=1100,"{name}: {:?}",snapshot.gc);
}
assert!(total<1000000,"{name}: nontermination");
};
if budget==1 { assert_eq!(calls,costs.len(),"{name}: missing or extra calls"); }
if let Some(fault)=fault {
assert!(matches!(ending,End::Trap(ref t) if t.code==fault),"{name}: {ending:?}");
} else {
assert!(matches!(ending,End::Halted|End::EndOfRom),"{name}: {ending:?}");
let actual:Vec<_>=vm.operand_stack_top(expected.len()).iter().map(|v|match v {
Value::Int64(v)=>format!("l:{v}"),Value::Int32(v)=>format!("i:{v}"),
Value::Float(v)=>format!("f:{:016x}",v.to_bits()),v=>panic!("{name}: {v:?}")
}).collect();
assert_eq!(actual,expected,"{name}: output bits/replay");
}
if let Some(reference)=reference { assert_eq!(total,reference,"{name}: replay/budget cycles"); }
reference=Some(total);
}
let total=reference.unwrap();
if let Some(original)=name.strip_suffix("-optimized") {
assert_eq!(cycles_by_name.get(original),Some(&total),"{name}: optimizer cycles");
} else { cycles_by_name.insert(name.clone(),total); }
println!("RANDOM PASS {name}: {total} cycles, exact bits/fault and replay");
}
let bytes=std::fs::read(root.join("pbs-random-import.pbx")).expect("mandatory real Random SDK import");
let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap();
let mut vm=VirtualMachine::from_image(image,Default::default());
vm.prepare_boot_call().unwrap();
let report=vm.run_budget(10000,&mut NoNative,&mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason,End::Halted|End::EndOfRom),"Random import: {report:?}");
println!("RANDOM PASS real SDK imports and aliases");
}
+13 -2
View File
@@ -13,12 +13,23 @@ parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prome
parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies")
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only")
parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only")
args = parser.parse_args()
runtime = args.runtime.resolve()
if not args.math_only:
provider_vectors = runtime / "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv"
consumer_vectors = pathlib.Path("prometeu-architecture-tests/src/test/resources/random/random-conformance.tsv")
if provider_vectors.read_bytes() != consumer_vectors.read_bytes():
raise SystemExit("Random oracle differs from the selected provider; update provenance and requalify")
print(subprocess.check_output(["rustc", "-Vv"], text=True).strip(), flush=True)
for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java"),
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs")]:
print("sha256", source, hashlib.sha256(source.read_bytes()).hexdigest(), flush=True)
print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True)
print("platform", platform.platform(), "limits=default capabilities=NONE", flush=True)
print("profile", "release" if args.release else "dev", "features=resource-diagnostics", flush=True)
for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUILTIN_CONSTANTS.csv", "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv"]:
for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUILTIN_CONSTANTS.csv", "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv", "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv"]:
print("sha256", relative, hashlib.sha256((runtime / relative).read_bytes()).hexdigest(), flush=True)
with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
root = pathlib.Path(directory)
@@ -31,4 +42,4 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
(root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text())
(root / "src").mkdir()
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else [])], check=True)
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else [])], check=True)