feat(vm): add VM-owned PCG64 random and coverage headroom
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

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.
This commit is contained in:
2026-10-09 12:51:05 +01:00
parent 9318cf7cd3
commit 3e39a90083
50 changed files with 2545 additions and 189 deletions
@@ -183,3 +183,7 @@ Zero budget begins no attempt; positive budget admits the complete operation
and retains the existing overshoot rule. Argument-producing bytecode costs
remain additional. Input/color and other intrinsic/opcode costs and accounting
remain unchanged. CPU timings never change guest-visible cycle weights.
## Random core integration
The [random core](02e-vm-owned-random-core.md) charges fixed calls before checks and bounded range calls as 4+8*N (at most 64 draws), retaining fault cycles and whole-instruction overshoot.
@@ -157,3 +157,7 @@ After charging the attempt, incomplete temporary operands trap with STACK_UNDERF
Publication and ownership follow [typed collection memory](03-memory-stack-heap-and-allocation.md); charging follows [time and cycles](01-time-model-and-cycles.md). See the [producer handoff](../../vm-arch/collection-producer-handoff.md) for independent byte oracles and construction examples. Production consumers must enter through the validated PBX v1 image boundary described in [Program Registry](02c-program-registry-and-pbx-v1.md).
Typed callable instructions are MAKE_CLOSURE `(FunctionId,FnTypeId)`, CALL_CLOSURE `(FnTypeId)`, GET_CAPTURE `(index)` and CALL_TRAIT `(TraitTypeId,method_index)`. Their groups, encodings and attempted costs are defined in the [Fn contract](02b-vm-function-values-and-closures.md). Numbers 0x54–0x56 stay reserved and reject anywhere at load.
## Random core integration
INTRINSIC also dispatches the [VM-owned random operations](02e-vm-owned-random-core.md), IDs 0x4000–0x4003. NEW cannot construct Random. TRAP_RANDOM_REJECTION_LIMIT is 0x00000015.
@@ -140,3 +140,7 @@ equality treats both zeros equally. Numeric overflow faults by range.
Exact Registry/intrinsic carriers prohibit implicit conversion; math/mathf
supplies explicit conversions with truncation/range and ties-even rules.
Existing arithmetic opcode promotions do not relax typed boundaries.
## Random core integration
[Random v1](02e-vm-owned-random-core.md) is BuiltinId 0x0016: one nullable HeapRef slot, eight-byte reference storage aligned to eight with GuestReference ownership. Copies alias; only random.new constructs the object.
@@ -98,3 +98,7 @@ callbacks are ordinary Fn calls in the main execution context.
See [memory](03-memory-stack-heap-and-allocation.md),
[Registry/PBX](02c-program-registry-and-pbx-v1.md) and
[host ABI](16-host-abi-and-syscalls.md).
## Random core integration
[Random references](02e-vm-owned-random-core.md) are valid capture, parameter and result groups. Existing roots retain the generator; copying captures aliases its state.
@@ -101,12 +101,13 @@ Value remains the generic stack/local representation. Structs/arrays are referen
| 0x0013 | Bool | 1 | 1 / 1 byte; canonical 0/1 |
| 0x0014 | String | 1 | native StringSlot size_of/align_of |
| 0x0015 | Dynamic | 2 | native DynamicSlot size_of/align_of |
| 0x0016 | Random | 1 | 8 / 8 bytes, nullable GuestReference |
Unlisted BuiltinIds, including zero and removed input IDs 0x0100–0x0102, cannot be imported. No implicit Int/Number/Void/Null aliases. `color` is numeric RGBA8888 `0xRRGGBBAA`; its stack carrier is Int64 constrained to u32 range. `vec2` stores f64 x/y at offsets 0/8. `pixel` stores i64 x/y at 0/8 and u32 color at 16 plus four padding bytes, with stack carriers [Int64,Int64,Int64]. Do not narrow coordinates or infer framebuffer byte order from the numeric color representation. These builtins contain no guest references/native ownership.
Unlisted BuiltinIds, including zero and removed input IDs 0x0100–0x0102, cannot be imported. No implicit Int/Number/Void/Null aliases. `color` is numeric RGBA8888 `0xRRGGBBAA`; its stack carrier is Int64 constrained to u32 range. `vec2` stores f64 x/y at offsets 0/8. `pixel` stores i64 x/y at 0/8 and u32 color at 16 plus four padding bytes, with stack carriers [Int64,Int64,Int64]. Do not narrow coordinates or infer framebuffer byte order from the numeric color representation. color, vec2 and pixel contain no guest references/native ownership. Random is an opaque reference builtin; its state is VM-owned.
Preserve declared field order; round each offset to field alignment and final payload size to maximum alignment. Empty Struct has payload zero, alignment one, but retains object identity/header. Array stride is aligned stored-element size; Array<Struct> stores references, not Struct payloads. Checked arithmetic precedes allocation. Padding is not data or a GC reference. Allocate truly aligned storage or use appropriate accesses; Vec<u8> does not justify unsafe casts. Native Arc/Value layouts are target-dependent and never a portable PBX ABI.
Defaults apply before publication/GC, including reused storage: Int32/Int64 zero, Float +0.0, Bool false, Struct/Array/Fn/String references null, vec2 (+0,+0), color transparent raw zero, pixel (0,0,transparent), trait absent, Dynamic untyped null. Do not instantiate referenced objects/subarrays or invoke source constructors. Empty arrays require no element values. Catalog defaults are resolved without arbitrary per-element callbacks. Native values must be constructed correctly rather than assumed valid after memset.
Defaults apply before publication/GC, including reused storage: Int32/Int64 zero, Float +0.0, Bool false, Struct/Array/Fn/String/Random references null, vec2 (+0,+0), color transparent raw zero, pixel (0,0,transparent), trait absent, Dynamic untyped null. Do not instantiate referenced objects/subarrays or invoke source constructors. Empty arrays require no element values. Catalog defaults are resolved without arbitrary per-element callbacks. Native values must be constructed correctly rather than assumed valid after memset.
Heap references: index:u32 + generation:u32, stored size/alignment 8, still one Value::HeapRef slot. Generation starts at one; zero is reserved. Compact null=(0,0), while index zero remains valid with a live generation. Other generation-zero pairs are invalid. Validate index/liveness/generation/type before dereference. Increment generation on reclamation; retire the slot after its maximum-generation incarnation rather than wrap. Handles belong to their heap/session; native boundaries preserve provenance without introducing a heap ID into this encoding.
@@ -197,6 +198,7 @@ Preserve typed reasons and available section/file offset, ID domain/record/membe
| TRAP_NUMERIC_DOMAIN | 0x00000012 | Invalid mathematical domain of finite arguments |
| TRAP_NUMERIC_RANGE | 0x00000013 | Finite result/destination outside representable range |
| TRAP_NON_FINITE | 0x00000014 | NaN/infinite input rejected before guest publication |
| TRAP_RANDOM_REJECTION_LIMIT | 0x00000015 | All 64 range candidates rejected; state rolls back |
Keep TrapInfo(code,opcode,pc,message,optional span) and current trap interruption behavior; no guest-catchable exception system. Untyped null to Int32 is TRAP_TYPE, not null dereference. Invalid handles never become false/null and are validated before following them. Preserve existing stack/function/return/intrinsic error categories. No promise to recover process/allocator abort; use fallible new allocation paths rather than operational panics.
@@ -255,3 +257,7 @@ No envelope/version change is introduced. Native signature import validates
complete layouts before checking Float finitude and publishing guest slots.
See [numeric semantics](02d-gameplay-math-and-numeric-semantics.md) for fault
precedence, conversions, catalog metadata and producer examples.
## Random core integration
[Random](02e-vm-owned-random-core.md) adds BuiltinId 0x0016 and intrinsic IDs 0x4000–0x4003 using existing PBX v1 encoding. Registry categories remain unchanged; unsupported identities are rejected, without fallback.
@@ -48,7 +48,9 @@ Mixed intrinsic carriers require explicit conversion.
[INTRINSICS.csv](../../vm-arch/INTRINSICS.csv) is generated from runtime
metadata: ID, owner/name/version, ordered ABI layout, parameter names,
total call cost and determinism/guest-allocation flags.
fixed cost or variable base/attempt/limit model, determinism, guest-allocation
and guest-state mutation flags. Math entries use fixed complete costs;
stateful random entries publish their variable model separately.
[BUILTIN_CONSTANTS.csv](../../vm-arch/BUILTIN_CONSTANTS.csv) publishes constant
slots and Float bits. Consumers MUST use these artifacts rather than duplicate
ID/cost maps. Math functions are pure and allocate no guest objects; runtime
@@ -305,3 +307,7 @@ crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv.
The versioned [local qualification record](../../vm-arch/NUMERIC_QUALIFICATION.md)
reports the executed configuration, source audit, observed precision and
timings, reproducible commands and pending host comparisons.
## Random core integration
The [random core](02e-vm-owned-random-core.md) uses this software binary64 backend for exact nextf values k/2^53. Its deterministic calls mutate guest state; exported metadata includes mutates_guest_state and fixed or random_rejection_v1 cost models.
@@ -0,0 +1,170 @@
# 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:
```text
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](02d-gameplay-math-and-numeric-semantics.md),
[Registry/PBX](02c-program-registry-and-pbx-v1.md),
[memory](03-memory-stack-heap-and-allocation.md) and
[cycles](01-time-model-and-cycles.md).
Producer examples and integration acceptance tests are published in the
[random handoff](../../vm-arch/random-producer-handoff.md). Executed evidence is
recorded in [random qualification](../../vm-arch/RANDOM_QUALIFICATION.md).
@@ -217,3 +217,7 @@ After validation, an attempt provisionally reserves net stack growth and constru
## Typed Fn and Root-Return Collection
Threshold GC opportunities are FRAME_SYNC and successful RET of the last root, after results are transferred and rooted. No automatic GC at ordinary callee RET, entry preparation or allocation/quota refusal. VM owns its single execution context directly. Roots include globals, all live operand values, Closures retained by every active CallFrame and legally retained native/host roots. Trace complete typed capture/cell graphs; unreachable cycles collect. Inspection snapshots and raw handle copies create no guest root or session import. Results remain roots until consumed/replaced/reset/unload. Scratch refusal preserves owners and prohibits partial sweep.
## Random core integration
[Random objects](02e-vm-owned-random-core.md) use ObjectKind tag 9 (tag 6 remains reserved), 32 logical payload bytes and quota-accounted headers/handles/auxiliary storage. They are opaque GC leaves; Dynamic holds their direct reference and exact TypeId.
@@ -3,7 +3,7 @@
Domain: portability contract
Function: normative
Didactic companion: [`../learn/mental-model-portability-and-cross-platform.md`](../runtime/learn/mental-model-portability-and-cross-platform.md)
Didactic companion: [Portability mental model](../../../discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0014-mental-model-portability-and-cross-platform.md)
## 1 Scope
@@ -295,3 +295,7 @@ after reset.
AI tooling may consume this generic host API from outside the machine. It does
not create an AI mode, testing mode, replay protocol, gameplay introspection
surface, or guest capability.
## Random core integration
[PCG64 random](02e-vm-owned-random-core.md) fixes unsigned wrapping state, seed-bit conversion and software Float output across targets. Qualification records only executed targets; no platform-selected RNG or host entropy is permitted.
+4
View File
@@ -128,3 +128,7 @@ In those cases:
- `docs/runtime/learn/` explains the why, the intuition, and the examples;
- the spec should point to the pedagogical companion near the top;
- the pedagogical guide should point back to the canonical spec.
## Random core integration
The [VM-owned random core](02e-vm-owned-random-core.md) defines opaque Random references, PCG64 and the random intrinsic surface.