diff --git a/crates/console/prometeu-vm/tests/producer_handoff.rs b/crates/console/prometeu-vm/tests/producer_handoff.rs new file mode 100644 index 0000000..67adb2f --- /dev/null +++ b/crates/console/prometeu-vm/tests/producer_handoff.rs @@ -0,0 +1,92 @@ +use prometeu_bytecode::load_limits::LoadBudget; +use prometeu_bytecode::registry::{ + BuiltinId, FunctionDecl, NamedType, Registry, RegistryDeclarations, Signature, TypeDecl, + TypeId, TypeKind, +}; +use prometeu_bytecode::registry_codec::PbxModule; +use prometeu_bytecode::{Value, assemble}; +use prometeu_hal::{HostContext, HostReturn, NativeInterface, syscalls::caps, vm_fault::VmFault}; +use prometeu_vm::{ + LogicalFrameEndingReason, ValidatedProgramImage, VirtualMachine, resource_budget::RuntimeLimits, +}; + +struct NoNative; +impl NativeInterface for NoNative { + fn syscall( + &mut self, + _id: u32, + _args: &[Value], + _ret: &mut HostReturn, + _ctx: &mut HostContext, + ) -> Result<(), VmFault> { + panic!("oracle has no native calls") + } +} + +#[test] +fn named_arguments_preserve_source_effect_order_and_call_in_signature_order_without_debug() { + // Frontend oracle: combine(y: effectY(20), x: effectX(10)). + // Trace appends Y=2 before X=1; combine(x,y) computes x*100+y. + let bodies=[ + assemble("PUSH_I32 0\nSET_GLOBAL 0\nCALL 2\nSET_LOCAL 0\nCALL 1\nSET_LOCAL 1\nGET_LOCAL 1\nGET_LOCAL 0\nCALL 3\nSET_GLOBAL 1\nGET_GLOBAL 0\nGET_GLOBAL 1\nHALT").unwrap(), + assemble("GET_GLOBAL 0\nPUSH_I32 10\nMUL\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nPUSH_I32 10\nRET").unwrap(), + assemble("GET_GLOBAL 0\nPUSH_I32 10\nMUL\nPUSH_I32 2\nADD\nSET_GLOBAL 0\nPUSH_I32 20\nRET").unwrap(), + assemble("GET_LOCAL 0\nPUSH_I32 100\nMUL\nGET_LOCAL 1\nADD\nRET").unwrap(), + ]; + let mut code = vec![]; + let mut functions = vec![]; + for (index, body) in bodies.iter().enumerate() { + let parameters = if index == 3 { + vec![ + NamedType { type_id: TypeId(0), name: Some("x".into()) }, + NamedType { type_id: TypeId(0), name: Some("y".into()) }, + ] + } else { + vec![] + }; + functions.push(FunctionDecl { + name: Some(["main", "effectX", "effectY", "combine"][index].into()), + signature: Signature { + parameters, + results: if index == 0 { vec![] } else { vec![TypeId(0)] }, + }, + code_offset: code.len() as u32, + code_len: body.len() as u32, + local_slots: if index == 0 { 2 } else { 0 }, + max_stack_slots: 2, + }); + code.extend_from_slice(body); + } + let registry = Registry::resolve( + RegistryDeclarations { + types: vec![TypeDecl { name: None, kind: TypeKind::Builtin(BuiltinId::INT32) }], + functions, + ..Default::default() + }, + code.len(), + &mut LoadBudget::new(Default::default()), + ) + .unwrap(); + let bytes = PbxModule { + registry: ®istry, + code: &code, + constants: &[], + debug: None, + exports: &[], + syscalls: &[], + } + .serialize(&mut LoadBudget::new(Default::default())) + .unwrap(); + let image = + ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), caps::NONE) + .unwrap(); + assert!(image.debug().is_none()); + let parameters = &image.registry().declarations().functions[3].signature.parameters; + assert_eq!(parameters[0].name.as_deref(), Some("x")); + assert_eq!(parameters[1].name.as_deref(), Some("y")); + let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default()); + vm.prepare_boot_call().unwrap(); + let report = vm.run_budget(10_000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert_eq!(report.reason, LogicalFrameEndingReason::Halted); + assert_eq!(vm.operand_stack_top(2), vec![Value::Int32(1020), Value::Int32(21)]); +} diff --git a/docs/vm-arch/registry-producer-handoff.md b/docs/vm-arch/registry-producer-handoff.md new file mode 100644 index 0000000..0cc5691 --- /dev/null +++ b/docs/vm-arch/registry-producer-handoff.md @@ -0,0 +1,129 @@ +# Registry v1 producer and consumer handoff + +This is an implementation handoff for DEC-0045 / PLN-0176. The normative contract +is [Program Registry and PBX v1](../specs/runtime/02c-program-registry-and-pbx-v1.md). +It does not approve the separate callable proposal or claim Studio propagation. + +## Publication state + +The bounded writer/owned decoder, sealed `ValidatedProgramImage::load`, shared +session factory, typed direct-call/return boundaries, Dynamic/reference execution, +fixed input catalogue and string accounting have executable tests. The production +`initialize` transition, removal of old unchecked entry points, all producer +migration and both regenerated runtime examples remain pending. Existing closure +receivers need the separate AGD-0055 contract; none of the four accepted Registry +categories may be used as a provisional closure type. + +The external Studio handoff targets are the build-pipeline +`backend/bytecode/BytecodeModule.java` and `backend/irvm/IRVMIntrinsicRegistry.java`, +compiler-core `source/tables/IntrinsicTableReader.java`, PBS +`lowering/PbsExecutableBodyLowerer.java`, `lowering/PbsExecutableCallsiteEmitter.java` +and `semantics/PbsBuiltinLayoutResolver.java`, with their producer tests. This +repository publishes requirements and oracles; those modules have not been edited. + +## Exact producer obligations + +Emit PBX version 1 only. The header is 32 bytes: magic at 0, u16 version at 4, +little-endian flag 0 at 6, reserved zero at 7, section count at 8 and twenty zero +bytes at 12. Directory entries are file-relative u32 kind/offset/length triples. +Mandatory kinds are 0, 1, 2, 4, 5, 6 and 7; debug kind 3 is optional. Keep empty +mandatory tables with count zero. Never skip unknown sections or retain a legacy +fallback. Use the canonical chapter's field order and UTF-8 rules, not Rust layouts. + +TypeId, FunctionId and ImplementationId are independent image-local table indices; +zero is valid. BuiltinIds are imports, not local TypeIds. Function records contain +optional name, ordered named parameters, ordered result TypeIds, code offset/length, +extra local slots and maximum temporary slots. Names are independent of debug. +Widths are derived from TypeIds; serialize no parameter/result width caches. +`max_stack_slots = 0` is a literal zero limit. Boot authority remains FunctionId 0. + +The nine BuiltinIds are color `0x0001`, vec2 `0x0002`, pixel `0x0003`, Int32 `0x0010`, +Int64 `0x0011`, Float `0x0012`, Bool `0x0013`, String `0x0014`, Dynamic `0x0015`. +Removed input BuiltinIds `0x0100`–`0x0102` have no aliases. Struct/Trait identity is +nominal; Array identity is its exact element TypeId. Do not deduplicate declarations +by name or shape, or introduce array covariance. Preserve complete multi-slot groups +and exact parameter/result order; use explicit accepted conversions at boundaries. + +HOSTCALL `0x0071` carries a syscall-declaration index. Declare canonical native +module/name/version and exact ABI counts; every declaration must be used. Loading +binds it to SYSCALL after capability/ABI validation. Raw SYSCALL in producer PBX, +unknown declarations, invalid indices and unused declarations are rejected. + +## Independent binary oracles + +The manually specified minimal executable in +`crates/console/prometeu-bytecode/tests/registry_v1.rs::minimal_bytes` is 173 bytes. +Its directory begins at 32; seven entries end at 116: + +| Kind | Offset | Length | Payload | +| --- | ---: | ---: | --- | +| constants | 116 | 4 | count 0 | +| functions | 120 | 29 | one unnamed zero-parameter/result function, offset 0, length 2, locals/max 0 | +| code | 149 | 2 | `01 00` (HALT) | +| exports | 151 | 4 | count 0 | +| syscalls | 155 | 4 | count 0 | +| types | 159 | 10 | one unnamed Bool import, BuiltinId `0x0013` | +| implementations | 169 | 4 | count 0 | + +The independent multi-slot fixture in the same suite declares `fn(vec2)->vec2` +with TypeId 0, no serialized widths, no extra locals and max 2. Its fourteen code +bytes are `42 00 00 00 00 00 42 00 01 00 00 00 51 00`: GET_LOCAL 0, +GET_LOCAL 1, RET. Both signature widths resolve to 2. Complement these oracles with +roundtrips; do not derive every expected byte from the producer under test. + +## Named arguments and observable evaluation order + +For a frontend whose expressions evaluate left to right, use this source-level +pseudocode oracle; it is not a claim that PBS syntax has already been implemented: + +```text +combine(x: Int32, y: Int32) -> Int32 = x * 100 + y +combine(y: effect("Y", 20), x: effect("X", 10)) +``` + +Expected effect order is **Y, X**. Evaluate `y` first into a temporary, then `x` into +another temporary. Load the temporaries in signature order **x=10, y=20** before +CALL. The result is **1020**. Reordering evaluation into parameter order would +produce the wrong effect trace; pushing source order would produce **2010**. +Parameter names resolve positions in the frontend; runtime CALL remains positional. +An absent name prevents name-only resolution from that metadata, while positional +execution remains valid. Names do not adapt trait method compatibility. + +## Endpoint-free input lowering + +The [complete 54-entry table](../specs/runtime/02c-program-registry-and-pbx-v1.md#input) +defines every accepted name/ID/result. Queries take zero guest arguments, read the +logical-frame snapshot and cost one intrinsic cycle. States return Bool; +hold/x/y return Int64. For example, `input.pad.a.down` lowers directly to +`72 00 12 21 00 00`; `input.touch.x` uses ID `0x2134`. Do not produce an endpoint +value, load it into a local or pass a selector. Removed intrinsic IDs are +`0x2000`/`0x2001`, `0x2010`–`0x201B`, `0x2020`–`0x2022`, `0x2030`–`0x2033`. +A removed/unknown ID differs from a known query whose platform is unavailable; +the latter raises TRAP_UNAVAILABLE, not a fabricated false/zero. + +## Diagnostics, ownership and consumer status + +Load failures preserve stable LOAD_* tags, typed reasons and available +section/offset/record/member/ID/function/PC/resource fields. Native binding preserves +its specific identity/capability/ABI context. Runtime resource faults preserve +resource/reason/requested/limit plus opcode/PC/source span. Headless and desktop +share initialization serialization; the strict +`devtools/headless-protocol/response.schema.json` is the machine shape. Never parse +human wording or manufacture runtime PCs for rejected loads. + +| Consumer | Accepted handoff | Status / remaining ownership | +| --- | --- | --- | +| Studio/PBS | PBX schema, signatures/names, effect-order and binary oracles, nine imports, all input IDs and diagnostics | External implementation and source-language tests pending; no external edits claimed | +| AGD-0054 collections | Typed aligned layouts/defaults, exact storage groups, reference/native maps and checked adapters | Internal containers are tested; future guest collection operations/costs/GC integration belong to its decision/plan | +| AGD-0055 callables | Function/implementation tables and direct-call contracts; exact trait views | Open Callable/capture/dispatch/coroutine contract; affected producer migration remains dependent on it | +| AGD-0057 strings/bytes/save | Arc strings, image/session Weak ledgers, bounded native writers and explicit import/export provenance | Existing string paths are integrated; new operations and their operation-specific evidence remain suggestions | +| AGD-0059 stability | Product ceilings, generational handles, fallible capacity reservations and structured faults | Focused ownership/quota rollback is core evidence; coordinated long-run/cross-host stress remains a suggestion | +| AGD-0060 reference game | Runtime contract, example migration requirement and technical measurements | Game workload/headroom/readiness acceptance remains a suggestion, not measured by unit tests | + +Image constant allocations are shared between sessions without a session-content +charge. New/imported runtime allocations belong to their session; equal text does +not merge independent allocations. Native owners retain provenance alongside their +Arc. `ValueSnapshot` keeps domain owners alive while tooling retains values and +serializes only the ordinary value list. Cross-session import copies external +content into the destination domain. Stored String slots remain `Option>`; +native ownership is not a guest GC reference or an input hardware carrier.