From 63e371955a89135937f72df4af1fc7a8a83dc681 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Wed, 7 Oct 2026 21:13:59 +0100 Subject: [PATCH] feat(diagnostics): preserve Registry and resource fault context for PLN-0176 step 28 --- crates/console/prometeu-bytecode/src/abi.rs | 2 + crates/console/prometeu-bytecode/src/lib.rs | 2 + .../prometeu-bytecode/src/load_limits.rs | 18 +- .../prometeu-bytecode/src/program_image.rs | 2 +- .../prometeu-bytecode/src/resource_failure.rs | 40 + .../firmware/firmware_step_crash_screen.rs | 1 + .../prometeu-hal/src/debugger_protocol.rs | 6 + .../console/prometeu-hal/src/host_return.rs | 28 +- .../prometeu-hal/src/syscalls/resolver.rs | 3 +- crates/console/prometeu-hal/src/vm_fault.rs | 1 + .../prometeu-system/src/crash_report.rs | 15 + .../src/crash_report/init_diagnostic.rs | 132 ++++ .../prometeu-vm/src/local_addressing.rs | 1 + .../prometeu-vm/src/resource_budget.rs | 38 +- .../prometeu-vm/src/virtual_machine.rs | 3 + .../prometeu-vm/src/virtual_machine/stack.rs | 5 +- .../src/virtual_machine/strings.rs | 5 +- .../src/virtual_machine/typed_tests.rs | 2 +- .../src/debugger.rs | 7 + .../src/automation/wire.rs | 20 +- .../src/automation/wire/fault_tests.rs | 47 ++ .../tests/registry_fault_schema.rs | 46 ++ .../headless-protocol/response.schema.json | 733 +++++++++++++++++- .../11a-headless-automation-protocol.md | 13 + 24 files changed, 1085 insertions(+), 85 deletions(-) create mode 100644 crates/console/prometeu-bytecode/src/resource_failure.rs create mode 100644 crates/console/prometeu-system/src/crash_report/init_diagnostic.rs create mode 100644 crates/host/prometeu-host-headless/src/automation/wire/fault_tests.rs create mode 100644 crates/tools/prometeu-cli/tests/registry_fault_schema.rs diff --git a/crates/console/prometeu-bytecode/src/abi.rs b/crates/console/prometeu-bytecode/src/abi.rs index 2746ae2..be47c9a 100644 --- a/crates/console/prometeu-bytecode/src/abi.rs +++ b/crates/console/prometeu-bytecode/src/abi.rs @@ -56,4 +56,6 @@ pub struct TrapInfo { pub pc: u32, /// Optional source span information if debug symbols are available. pub span: Option, + /// Machine-readable quota context; messages are not its serialization. + pub resource: Option, } diff --git a/crates/console/prometeu-bytecode/src/lib.rs b/crates/console/prometeu-bytecode/src/lib.rs index ab087b1..cae9779 100644 --- a/crates/console/prometeu-bytecode/src/lib.rs +++ b/crates/console/prometeu-bytecode/src/lib.rs @@ -8,6 +8,7 @@ pub mod model; mod opcode; mod opcode_spec; mod program_image; +mod resource_failure; mod value; pub use abi::{ @@ -22,6 +23,7 @@ pub use disassembler::disassemble; pub use layout::{compute_function_layouts, FunctionLayout}; pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC}; pub use program_image::ProgramImage; +pub use resource_failure::{ResourceFailure, ResourceReason, RuntimeResource}; pub use value::{string_materialization_count, HeapRef, Value}; pub mod load_limits; diff --git a/crates/console/prometeu-bytecode/src/load_limits.rs b/crates/console/prometeu-bytecode/src/load_limits.rs index 217af09..77bb0c5 100644 --- a/crates/console/prometeu-bytecode/src/load_limits.rs +++ b/crates/console/prometeu-bytecode/src/load_limits.rs @@ -1,17 +1,25 @@ //! Shared PBX v1 resource limits and structured validation failures. //! Counters are deterministic; a failed reservation never changes usage. +use serde::{Deserialize, Serialize}; use std::fmt; const MIB: u64 = 1_048_576; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum LoadCode { + #[serde(rename = "LOAD_INVALID_FORMAT")] InvalidFormat, + #[serde(rename = "LOAD_UNSUPPORTED_FORMAT")] UnsupportedFormat, + #[serde(rename = "LOAD_INVALID_REFERENCE")] InvalidReference, + #[serde(rename = "LOAD_INVALID_REGISTRY")] InvalidRegistry, + #[serde(rename = "LOAD_INVALID_CODE")] InvalidCode, + #[serde(rename = "LOAD_RESOURCE_LIMIT")] ResourceLimit, + #[serde(rename = "LOAD_INVALID_ENTRYPOINT")] InvalidEntrypoint, } impl LoadCode { @@ -27,7 +35,7 @@ impl LoadCode { } } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum LoadReason { Magic, Version, @@ -80,7 +88,7 @@ pub enum LoadReason { InvalidYield, TypeMismatch, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[repr(usize)] pub enum LoadResource { PbxBytes, @@ -98,14 +106,14 @@ pub enum LoadResource { } const RESOURCE_COUNT: usize = 12; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum IdDomain { Type, Function, Implementation, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LoadFailure { pub code: LoadCode, pub reason: LoadReason, diff --git a/crates/console/prometeu-bytecode/src/program_image.rs b/crates/console/prometeu-bytecode/src/program_image.rs index 1f57ebc..036a60c 100644 --- a/crates/console/prometeu-bytecode/src/program_image.rs +++ b/crates/console/prometeu-bytecode/src/program_image.rs @@ -50,7 +50,7 @@ impl ProgramImage { } } - TrapInfo { code, opcode, message, pc, span } + TrapInfo { code, opcode, message, pc, span, resource: None } } pub fn find_function_index(&self, pc: u32) -> Option { diff --git a/crates/console/prometeu-bytecode/src/resource_failure.rs b/crates/console/prometeu-bytecode/src/resource_failure.rs new file mode 100644 index 0000000..1e46ac2 --- /dev/null +++ b/crates/console/prometeu-bytecode/src/resource_failure.rs @@ -0,0 +1,40 @@ +//! Resource fault context shared by the VM, native boundary and host tooling. +//! Accounting and product ceilings remain owned by the runtime budget. +use serde::{Deserialize, Serialize}; +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[repr(usize)] +pub enum RuntimeResource { + GuestBytes, + HandleSlots, + AuxiliaryBytes, + TemporaryBytes, + StringBytes, + StringAllocations, + IndividualStringBytes, + CallDepth, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ResourceReason { + Limit, + SizeOverflow, + AllocationFailed, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceFailure { + pub resource: RuntimeResource, + pub reason: ResourceReason, + pub requested: u64, + pub limit: u64, +} +impl fmt::Display for ResourceFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{:?}: {:?}, requested {}, limit {}", + self.resource, self.reason, self.requested, self.limit + ) + } +} +impl std::error::Error for ResourceFailure {} diff --git a/crates/console/prometeu-firmware/src/firmware/firmware_step_crash_screen.rs b/crates/console/prometeu-firmware/src/firmware/firmware_step_crash_screen.rs index be2f6d2..432020a 100644 --- a/crates/console/prometeu-firmware/src/firmware/firmware_step_crash_screen.rs +++ b/crates/console/prometeu-firmware/src/firmware/firmware_step_crash_screen.rs @@ -55,6 +55,7 @@ mod tests { message: "type mismatch".into(), pc: 0x44, span: None, + resource: None, }, }, }; diff --git a/crates/console/prometeu-hal/src/debugger_protocol.rs b/crates/console/prometeu-hal/src/debugger_protocol.rs index 99942ec..15d7daa 100644 --- a/crates/console/prometeu-hal/src/debugger_protocol.rs +++ b/crates/console/prometeu-hal/src/debugger_protocol.rs @@ -79,6 +79,9 @@ pub enum DebugEvent { pc: Option, trap_code: Option, opcode: Option, + span: Option, + resource: Option, + init: Option, }, #[serde(rename = "cert")] Cert { rule: String, used: u64, limit: u64, frame_index: u64 }, @@ -138,6 +141,9 @@ mod tests { pc: Some(12), trap_code: Some(4), opcode: Some(0x70), + span: None, + resource: None, + init: None, }; let json = serde_json::to_string(&event).unwrap(); diff --git a/crates/console/prometeu-hal/src/host_return.rs b/crates/console/prometeu-hal/src/host_return.rs index 6050d66..468b357 100644 --- a/crates/console/prometeu-hal/src/host_return.rs +++ b/crates/console/prometeu-hal/src/host_return.rs @@ -5,6 +5,7 @@ use std::sync::Arc; /// Native producers describe their output before materializing guest content. /// The VM provides the session allocator; HAL does not own guest quotas. pub trait GuestStringAllocator { + fn byte_limit(&self) -> u64; fn build( &mut self, length: usize, @@ -23,6 +24,16 @@ pub struct HostReturn<'a> { } impl<'a> HostReturn<'a> { + fn size_overflow(&mut self) -> VmFault { + let error = VmFault::ResourceLimit(prometeu_bytecode::ResourceFailure { + resource: prometeu_bytecode::RuntimeResource::StringBytes, + reason: prometeu_bytecode::ResourceReason::SizeOverflow, + requested: u64::MAX, + limit: self.strings.byte_limit(), + }); + self.failure = Some(error.clone()); + error + } pub fn new( stack: &'a mut Vec, result_slots: usize, @@ -97,14 +108,14 @@ impl<'a> HostReturn<'a> { length = length.checked_add(part.len()).ok_or(std::fmt::Error)?; Ok(()) }) - .map_err(|_| size_overflow())?; + .map_err(|_| self.size_overflow())?; self.push_string_with_len(length, &mut |writer| { lossy_chunks(bytes, &mut |part| writer.write_str(part)) }) } pub fn push_hex(&mut self, bytes: &[u8]) -> Result<(), VmFault> { const HEX: &[u8; 16] = b"0123456789abcdef"; - let length = bytes.len().checked_mul(2).ok_or_else(size_overflow)?; + let length = bytes.len().checked_mul(2).ok_or_else(|| self.size_overflow())?; self.push_string_with_len(length, &mut |writer| { for &byte in bytes { let pair = [HEX[(byte >> 4) as usize], HEX[(byte & 15) as usize]]; @@ -121,9 +132,9 @@ impl<'a> HostReturn<'a> { let mut length = 0usize; for (index, part) in parts.clone().enumerate() { if index > 0 { - length = length.checked_add(separator.len()).ok_or_else(size_overflow)?; + length = length.checked_add(separator.len()).ok_or_else(|| self.size_overflow())?; } - length = length.checked_add(part.len()).ok_or_else(size_overflow)?; + length = length.checked_add(part.len()).ok_or_else(|| self.size_overflow())?; } self.push_string_with_len(length, &mut |writer| { for (index, part) in parts.clone().enumerate() { @@ -137,9 +148,6 @@ impl<'a> HostReturn<'a> { } } -fn size_overflow() -> VmFault { - VmFault::Trap(prometeu_bytecode::TRAP_RESOURCE_LIMIT, "Native string length overflow".into()) -} fn lossy_chunks( mut bytes: &[u8], emit: &mut dyn FnMut(&str) -> std::fmt::Result, @@ -169,6 +177,9 @@ mod tests { use super::*; struct RejectStrings; impl GuestStringAllocator for RejectStrings { + fn byte_limit(&self) -> u64 { + 0 + } fn build( &mut self, _length: usize, @@ -198,6 +209,9 @@ mod tests { struct Collect; impl GuestStringAllocator for Collect { + fn byte_limit(&self) -> u64 { + u64::MAX + } fn build( &mut self, length: usize, diff --git a/crates/console/prometeu-hal/src/syscalls/resolver.rs b/crates/console/prometeu-hal/src/syscalls/resolver.rs index 2f774e0..be3aade 100644 --- a/crates/console/prometeu-hal/src/syscalls/resolver.rs +++ b/crates/console/prometeu-hal/src/syscalls/resolver.rs @@ -39,7 +39,8 @@ pub enum LoadError { } /// Load-time error for PBX-declared syscall resolution. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "reason", rename_all = "snake_case")] pub enum DeclaredLoadError { UnknownSyscall { module: String, diff --git a/crates/console/prometeu-hal/src/vm_fault.rs b/crates/console/prometeu-hal/src/vm_fault.rs index afd62dc..b49d8a4 100644 --- a/crates/console/prometeu-hal/src/vm_fault.rs +++ b/crates/console/prometeu-hal/src/vm_fault.rs @@ -1,6 +1,7 @@ #[derive(Debug, PartialEq, Clone)] pub enum VmFault { Trap(u32, String), + ResourceLimit(prometeu_bytecode::ResourceFailure), Panic(String), Unavailable, } diff --git a/crates/console/prometeu-system/src/crash_report.rs b/crates/console/prometeu-system/src/crash_report.rs index 7283866..a686efd 100644 --- a/crates/console/prometeu-system/src/crash_report.rs +++ b/crates/console/prometeu-system/src/crash_report.rs @@ -1,6 +1,7 @@ use prometeu_bytecode::TrapInfo; use prometeu_vm::VmInitError; use std::fmt; +mod init_diagnostic; #[derive(Debug, Clone, PartialEq, Eq)] pub enum CrashReport { @@ -10,6 +11,20 @@ pub enum CrashReport { } impl CrashReport { + /// The same machine fields serve headless and desktop transports. + pub fn init_diagnostic(&self) -> Option { + match self { + Self::VmInit { error } => Some(init_diagnostic::serialize(error)), + _ => None, + } + } + pub fn resource_failure(&self) -> Option { + match self { + Self::VmTrap { trap } => trap.resource, + Self::VmInit { error: VmInitError::RuntimeResourceLimit(resource) } => Some(*resource), + _ => None, + } + } pub fn kind(&self) -> &'static str { match self { Self::VmTrap { .. } => "vm_trap", diff --git a/crates/console/prometeu-system/src/crash_report/init_diagnostic.rs b/crates/console/prometeu-system/src/crash_report/init_diagnostic.rs new file mode 100644 index 0000000..912d25b --- /dev/null +++ b/crates/console/prometeu-system/src/crash_report/init_diagnostic.rs @@ -0,0 +1,132 @@ +use prometeu_vm::VmInitError; +use serde_json::{Value, json}; + +pub(super) fn serialize(error: &VmInitError) -> Value { + let code = match error { + VmInitError::RegistryLoadFailed(_) => "registry_load_failed", + VmInitError::RuntimeResourceLimit(_) => "runtime_resource_limit", + VmInitError::InvalidFormat => "invalid_format", + VmInitError::UnsupportedFormat => "unsupported_format", + VmInitError::ImageLoadFailed(_) => "image_load_failed", + VmInitError::LoaderPatchFailed(_) => "loader_patch_failed", + VmInitError::EntrypointNotFound => "entrypoint_not_found", + VmInitError::EntrypointArgumentsInvalid { .. } => "entrypoint_arguments_invalid", + VmInitError::VerificationFailed(_) => "verification_failed", + }; + let mut result = json!({"code":code,"message":format!("{error:?}")}); + match error { + VmInitError::RegistryLoadFailed(load) => { + result["load"] = json!(load); + result["load"]["code"] = json!(load.code.tag()); + } + VmInitError::RuntimeResourceLimit(resource) => result["resource"] = json!(resource), + VmInitError::EntrypointArgumentsInvalid { function, slot, trap_code } => { + result["entry"] = json!({"function":function,"slot":slot,"trapCode":trap_code}); + } + VmInitError::LoaderPatchFailed(patch) => { + use prometeu_vm::LoaderPatchError as P; + result["binding"] = match patch { + P::ResolveFailed(native) => json!(native), + P::HostcallIndexOutOfBounds { pc, sysc_index, syscalls_len } => { + json!({"reason":"hostcall_index_out_of_bounds","pc":pc,"syscallIndex":sysc_index,"syscallsLength":syscalls_len}) + } + P::RawSyscallInPreloadArtifact { pc, syscall_id } => { + json!({"reason":"raw_syscall","pc":pc,"syscallId":syscall_id}) + } + P::UnusedSyscallDecl { sysc_index, module, name, version } => { + json!({"reason":"unused_syscall","syscallIndex":sysc_index,"module":module,"name":name,"version":version}) + } + P::HostcallRemaining { pc, sysc_index } => { + json!({"reason":"hostcall_remaining","pc":pc,"syscallIndex":sysc_index}) + } + P::DecodeFailed(_) => json!({"reason":"decode_failed"}), + }; + } + _ => {} + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::CrashReport; + use prometeu_bytecode::{ + ResourceFailure, ResourceReason, RuntimeResource, + load_limits::{IdDomain, LoadCode, LoadFailure, LoadReason}, + }; + #[test] + fn load_tag_and_reference_context_survive_without_fabricating_runtime_pc() { + let error = LoadFailure::new(LoadCode::InvalidReference, LoadReason::TypeId) + .at(6, 159) + .record(4) + .member(2) + .reference(IdDomain::Type, 77) + .in_function(3, Some(18)); + let report = CrashReport::VmInit { error: VmInitError::RegistryLoadFailed(error) }; + assert_eq!(report.pc(), None); + let wire = report.init_diagnostic().unwrap(); + assert_eq!(wire["code"], "registry_load_failed"); + assert_eq!(wire["load"]["code"], "LOAD_INVALID_REFERENCE"); + for (field, value) in [ + ("section", 6), + ("offset", 159), + ("record", 4), + ("member", 2), + ("referenced_id", 77), + ("function", 3), + ("pc", 18), + ] { + assert_eq!(wire["load"][field], value); + } + assert_eq!(wire["load"]["id_domain"], "Type"); + assert_eq!(wire["load"]["reason"], "TypeId"); + } + #[test] + fn native_abi_and_resource_context_are_machine_fields() { + let native = prometeu_hal::syscalls::DeclaredLoadError::AbiMismatch { + module: "system".into(), + name: "has_cart".into(), + version: 1, + declared_arg_slots: 0, + declared_ret_slots: 2, + expected_arg_slots: 0, + expected_ret_slots: 1, + }; + let wire = serialize(&VmInitError::LoaderPatchFailed( + prometeu_vm::LoaderPatchError::ResolveFailed(native), + )); + assert_eq!(wire["binding"]["reason"], "abi_mismatch"); + assert_eq!(wire["binding"]["module"], "system"); + assert_eq!(wire["binding"]["declared_ret_slots"], 2); + assert_eq!(wire["binding"]["expected_ret_slots"], 1); + let resource = ResourceFailure { + resource: RuntimeResource::CallDepth, + reason: ResourceReason::Limit, + requested: 3, + limit: 2, + }; + let report = CrashReport::VmInit { error: VmInitError::RuntimeResourceLimit(resource) }; + assert_eq!(report.resource_failure(), Some(resource)); + let wire = report.init_diagnostic().unwrap(); + assert_eq!(wire["resource"]["resource"], "CallDepth"); + assert_eq!(wire["resource"]["reason"], "Limit"); + assert_eq!(wire["resource"]["requested"], 3); + assert_eq!(wire["resource"]["limit"], 2); + } + #[test] + fn all_load_codes_serialize_to_the_normative_tags() { + for code in [ + LoadCode::InvalidFormat, + LoadCode::UnsupportedFormat, + LoadCode::InvalidReference, + LoadCode::InvalidRegistry, + LoadCode::InvalidCode, + LoadCode::ResourceLimit, + LoadCode::InvalidEntrypoint, + ] { + assert_eq!(json!(code), code.tag()); + assert_eq!(serde_json::from_value::(json!(code)).unwrap(), code); + } + } +} diff --git a/crates/console/prometeu-vm/src/local_addressing.rs b/crates/console/prometeu-vm/src/local_addressing.rs index aee132e..5d403b6 100644 --- a/crates/console/prometeu-vm/src/local_addressing.rs +++ b/crates/console/prometeu-vm/src/local_addressing.rs @@ -30,6 +30,7 @@ pub fn check_local_slot( message: format!("Local slot {} out of bounds for function (limit {})", slot, limit), pc, span: None, + resource: None, }) } } diff --git a/crates/console/prometeu-vm/src/resource_budget.rs b/crates/console/prometeu-vm/src/resource_budget.rs index a4efdb7..6f2c705 100644 --- a/crates/console/prometeu-vm/src/resource_budget.rs +++ b/crates/console/prometeu-vm/src/resource_budget.rs @@ -1,21 +1,9 @@ //! Session accounting shared by owners, with reservations refunded on failure/drop. //! These quotas account VM domains, not process RSS or allocator metadata. use std::collections::VecDeque; -use std::fmt; use std::sync::{Arc, Mutex, MutexGuard}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(usize)] -pub enum RuntimeResource { - GuestBytes, - HandleSlots, - AuxiliaryBytes, - TemporaryBytes, - StringBytes, - StringAllocations, - IndividualStringBytes, - CallDepth, -} +pub use prometeu_bytecode::{ResourceFailure, ResourceReason, RuntimeResource}; const COUNT: usize = 8; const MIB: u64 = 1_048_576; const CEILINGS: [u64; COUNT] = @@ -51,30 +39,6 @@ impl RuntimeLimits { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ResourceReason { - Limit, - SizeOverflow, - AllocationFailed, -} -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ResourceFailure { - pub resource: RuntimeResource, - pub reason: ResourceReason, - pub requested: u64, - pub limit: u64, -} -impl fmt::Display for ResourceFailure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{:?}: {:?}, requested {}, limit {}", - self.resource, self.reason, self.requested, self.limit - ) - } -} -impl std::error::Error for ResourceFailure {} - #[derive(Debug)] struct State { limits: RuntimeLimits, diff --git a/crates/console/prometeu-vm/src/virtual_machine.rs b/crates/console/prometeu-vm/src/virtual_machine.rs index 584c756..c60dafa 100644 --- a/crates/console/prometeu-vm/src/virtual_machine.rs +++ b/crates/console/prometeu-vm/src/virtual_machine.rs @@ -1264,6 +1264,9 @@ impl VirtualMachine { self.operand_stack.truncate(stack_height_before); } native_result.map_err(|fault| match fault { + VmFault::ResourceLimit(resource) => { + self.resource_trap(resource, opcode, pc_at_syscall) + } VmFault::Trap(code, msg) => { self.trap(code, OpCode::Syscall as u16, msg, pc_at_syscall) } diff --git a/crates/console/prometeu-vm/src/virtual_machine/stack.rs b/crates/console/prometeu-vm/src/virtual_machine/stack.rs index 387490c..f209c85 100644 --- a/crates/console/prometeu-vm/src/virtual_machine/stack.rs +++ b/crates/console/prometeu-vm/src/virtual_machine/stack.rs @@ -18,7 +18,10 @@ impl VirtualMachine { opcode: OpCode, pc: u32, ) -> LogicalFrameEndingReason { - self.trap(TRAP_RESOURCE_LIMIT, opcode as u16, error.to_string(), pc) + let mut trap = + self.program.create_trap(TRAP_RESOURCE_LIMIT, opcode as u16, error.to_string(), pc); + trap.resource = Some(error); + LogicalFrameEndingReason::Trap(trap) } pub fn trap( diff --git a/crates/console/prometeu-vm/src/virtual_machine/strings.rs b/crates/console/prometeu-vm/src/virtual_machine/strings.rs index 60515bb..b1b18bc 100644 --- a/crates/console/prometeu-vm/src/virtual_machine/strings.rs +++ b/crates/console/prometeu-vm/src/virtual_machine/strings.rs @@ -7,6 +7,9 @@ pub(super) struct SessionStringAllocator<'a> { pub budget: RuntimeBudget, } impl prometeu_hal::host_return::GuestStringAllocator for SessionStringAllocator<'_> { + fn byte_limit(&self) -> u64 { + self.budget.limit(RuntimeResource::StringBytes) + } fn build( &mut self, length: usize, @@ -24,7 +27,7 @@ impl prometeu_hal::host_return::GuestStringAllocator for SessionStringAllocator< } } fn resource_fault(resource: ResourceFailure) -> VmFault { - VmFault::Trap(TRAP_RESOURCE_LIMIT, resource.to_string()) + VmFault::ResourceLimit(resource) } impl VirtualMachine { diff --git a/crates/console/prometeu-vm/src/virtual_machine/typed_tests.rs b/crates/console/prometeu-vm/src/virtual_machine/typed_tests.rs index fb921a6..fa53045 100644 --- a/crates/console/prometeu-vm/src/virtual_machine/typed_tests.rs +++ b/crates/console/prometeu-vm/src/virtual_machine/typed_tests.rs @@ -527,7 +527,7 @@ fn native_string_failures_cannot_publish_partial_results_even_if_handler_ignores // This synthetic native implementation tests the bounded writer, not the // has-cart handler's ordinary Boolean semantic contract. assert!( - matches!(report.reason,LogicalFrameEndingReason::Trap(info) if info.code==TRAP_RESOURCE_LIMIT && info.pc==0) + matches!(report.reason,LogicalFrameEndingReason::Trap(info) if info.code==TRAP_RESOURCE_LIMIT && info.pc==0 && info.resource.is_some_and(|resource|resource.resource==RuntimeResource::StringBytes && resource.requested==3 && resource.limit==2)) ); assert!(vm.operand_stack.is_empty()); assert_eq!(vm.budget.used(RuntimeResource::StringBytes), 0); diff --git a/crates/host/prometeu-host-desktop-winit/src/debugger.rs b/crates/host/prometeu-host-desktop-winit/src/debugger.rs index fac30e5..2982961 100644 --- a/crates/host/prometeu-host-desktop-winit/src/debugger.rs +++ b/crates/host/prometeu-host-desktop-winit/src/debugger.rs @@ -379,6 +379,10 @@ impl HostDebugger { CrashReport::VmTrap { trap } => (Some(trap.code), Some(trap.opcode)), CrashReport::VmPanic { .. } | CrashReport::VmInit { .. } => (None, None), }; + let span = match report { + CrashReport::VmTrap { trap } => trap.span.clone(), + _ => None, + }; self.send_event(DebugEvent::Fault { kind: report.kind().to_string(), @@ -386,6 +390,9 @@ impl HostDebugger { pc: report.pc(), trap_code, opcode, + span, + resource: report.resource_failure(), + init: report.init_diagnostic(), }); self.last_fault_summary = Some(summary); } diff --git a/crates/host/prometeu-host-headless/src/automation/wire.rs b/crates/host/prometeu-host-headless/src/automation/wire.rs index a82795a..d6df215 100644 --- a/crates/host/prometeu-host-headless/src/automation/wire.rs +++ b/crates/host/prometeu-host-headless/src/automation/wire.rs @@ -2,10 +2,11 @@ use base64::{Engine as _, engine::general_purpose::STANDARD}; use prometeu_bytecode::Value as VmValue; use prometeu_hal::InputSignals; use prometeu_system::CrashReport; -use prometeu_vm::VmInitError; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::io; +#[cfg(test)] +mod fault_tests; use crate::{CapturedFrame, HostError, HostExecutionStatus, HostState}; @@ -282,24 +283,13 @@ pub(super) fn fault(report: &CrashReport) -> Value { match report { CrashReport::VmTrap { trap } => { result["trap"] = json!({"code":trap.code,"opcode":trap.opcode, - "message":trap.message,"pc":trap.pc,"span":trap.span}); + "message":trap.message,"pc":trap.pc,"span":trap.span,"resource":trap.resource}); } CrashReport::VmPanic { message, .. } => { result["message"] = json!(message); } - CrashReport::VmInit { error } => { - let code = match error { - VmInitError::RegistryLoadFailed(_) => "registry_load_failed", - VmInitError::RuntimeResourceLimit(_) => "runtime_resource_limit", - VmInitError::InvalidFormat => "invalid_format", - VmInitError::UnsupportedFormat => "unsupported_format", - VmInitError::ImageLoadFailed(_) => "image_load_failed", - VmInitError::LoaderPatchFailed(_) => "loader_patch_failed", - VmInitError::EntrypointNotFound => "entrypoint_not_found", - VmInitError::EntrypointArgumentsInvalid { .. } => "entrypoint_arguments_invalid", - VmInitError::VerificationFailed(_) => "verification_failed", - }; - result["initError"] = json!({"code":code,"message":format!("{error:?}")}); + CrashReport::VmInit { .. } => { + result["initError"] = report.init_diagnostic().expect("initialization report"); } } result diff --git a/crates/host/prometeu-host-headless/src/automation/wire/fault_tests.rs b/crates/host/prometeu-host-headless/src/automation/wire/fault_tests.rs new file mode 100644 index 0000000..4a6955a --- /dev/null +++ b/crates/host/prometeu-host-headless/src/automation/wire/fault_tests.rs @@ -0,0 +1,47 @@ +use super::*; +use prometeu_bytecode::{ + ResourceFailure, ResourceReason, RuntimeResource, SourceSpan, TRAP_RESOURCE_LIMIT, TrapInfo, +}; + +#[test] +fn resource_trap_wire_preserves_native_fields_and_source_span() { + let report = CrashReport::VmTrap { + trap: TrapInfo { + code: TRAP_RESOURCE_LIMIT, + opcode: 0x90, + pc: 18, + message: "localized human wording".into(), + span: Some(SourceSpan { file_id: 7, start: 4, end: 9 }), + resource: Some(ResourceFailure { + resource: RuntimeResource::HandleSlots, + reason: ResourceReason::Limit, + requested: 3, + limit: 2, + }), + }, + }; + let wire = fault(&report); + assert_eq!(wire["trap"]["code"], 0x10); + assert_eq!(wire["trap"]["opcode"], 0x90); + assert_eq!(wire["trap"]["pc"], 18); + assert_eq!(wire["trap"]["span"]["file_id"], 7); + assert_eq!(wire["trap"]["resource"]["resource"], "HandleSlots"); + assert_eq!(wire["trap"]["resource"]["requested"], 3); + assert_eq!(wire["trap"]["resource"]["limit"], 2); +} + +#[test] +fn load_failure_wire_uses_shared_structured_serializer_and_no_runtime_pc() { + use prometeu_bytecode::load_limits::{LoadCode, LoadFailure, LoadReason, LoadResource}; + let mut error = LoadFailure::resource(LoadResource::Work, 23, 22).in_function(1, Some(6)); + error.code = LoadCode::ResourceLimit; + error.reason = LoadReason::Limit; + let report = CrashReport::VmInit { error: prometeu_vm::VmInitError::RegistryLoadFailed(error) }; + let wire = fault(&report); + assert_eq!(wire["pc"], Value::Null); + assert_eq!(wire["initError"], report.init_diagnostic().unwrap()); + assert_eq!(wire["initError"]["load"]["code"], "LOAD_RESOURCE_LIMIT"); + assert_eq!(wire["initError"]["load"]["resource"], "Work"); + assert_eq!(wire["initError"]["load"]["requested"], 23); + assert_eq!(wire["initError"]["load"]["limit"], 22); +} diff --git a/crates/tools/prometeu-cli/tests/registry_fault_schema.rs b/crates/tools/prometeu-cli/tests/registry_fault_schema.rs new file mode 100644 index 0000000..0ad46b5 --- /dev/null +++ b/crates/tools/prometeu-cli/tests/registry_fault_schema.rs @@ -0,0 +1,46 @@ +use serde_json::{Value, json}; + +fn schema() -> jsonschema::Validator { + let full: Value = serde_json::from_str(include_str!( + "../../../../devtools/headless-protocol/response.schema.json" + )) + .unwrap(); + jsonschema::validator_for(&json!({"$defs":full["$defs"],"$ref":"#/$defs/fault"})).unwrap() +} + +#[test] +fn published_schema_accepts_structured_resource_fields_and_rejects_unknown_or_negative_values() { + let schema = schema(); + let valid = json!({"kind":"vm_trap","pc":18,"summary":"human wording","trap":{ + "code":16,"opcode":144,"pc":18,"message":"unrelated localized text","span":{"file_id":7,"start":4,"end":9}, + "resource":{"resource":"HandleSlots","reason":"Limit","requested":3,"limit":2}}}); + schema.validate(&valid).unwrap(); + for (field, value) in [ + ("resource", json!("Bogus")), + ("requested", json!(-1)), + ("reason", json!("arbitrary text")), + ] { + let mut invalid = valid.clone(); + invalid["trap"]["resource"][field] = value; + assert!(schema.validate(&invalid).is_err()); + } +} + +#[test] +fn published_load_schema_requires_tag_context_and_the_matching_init_payload() { + let schema = schema(); + let valid = json!({"kind":"vm_init","pc":null,"summary":"human wording","initError":{ + "code":"registry_load_failed","message":"unrelated human text","load":{ + "code":"LOAD_INVALID_REFERENCE","reason":"TypeId","section":6,"offset":159,"record":4,"member":2, + "id_domain":"Type","referenced_id":77,"function":3,"pc":18,"resource":null,"requested":null,"limit":null}}}); + schema.validate(&valid).unwrap(); + let mut invalid = valid.clone(); + invalid["initError"]["load"]["referenced_id"] = json!(4294967296u64); + assert!(schema.validate(&invalid).is_err()); + let mut invalid = valid.clone(); + invalid["initError"]["load"]["code"] = json!("InvalidReference"); + assert!(schema.validate(&invalid).is_err()); + let mut invalid = valid.clone(); + invalid["initError"]["code"] = json!("invalid_format"); + assert!(schema.validate(&invalid).is_err()); +} diff --git a/devtools/headless-protocol/response.schema.json b/devtools/headless-protocol/response.schema.json index b0187dc..2d4c952 100644 --- a/devtools/headless-protocol/response.schema.json +++ b/devtools/headless-protocol/response.schema.json @@ -396,9 +396,23 @@ "minimum": 0 }, "span": { - "type": [ - "object", - "null" + "anyOf": [ + { + "$ref": "#/$defs/sourceSpan" + }, + { + "type": "null" + } + ] + }, + "resource": { + "anyOf": [ + { + "$ref": "#/$defs/resourceFailure" + }, + { + "type": "null" + } ] } }, @@ -407,7 +421,8 @@ "opcode", "message", "pc", - "span" + "span", + "resource" ], "additionalProperties": false } @@ -465,20 +480,191 @@ "const": "vm_init" }, "initError": { - "type": "object", - "properties": { - "code": { - "type": "string" + "oneOf": [ + { + "type": "object", + "properties": { + "code": { + "const": "registry_load_failed" + }, + "message": { + "type": "string" + }, + "load": { + "$ref": "#/$defs/loadFailure" + } + }, + "required": [ + "code", + "message", + "load" + ], + "additionalProperties": false }, - "message": { - "type": "string" + { + "type": "object", + "properties": { + "code": { + "const": "runtime_resource_limit" + }, + "message": { + "type": "string" + }, + "resource": { + "$ref": "#/$defs/resourceFailure" + } + }, + "required": [ + "code", + "message", + "resource" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "entrypoint_arguments_invalid" + }, + "message": { + "type": "string" + }, + "entry": { + "type": "object", + "properties": { + "function": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + "slot": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + "trapCode": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "function", + "slot", + "trapCode" + ], + "additionalProperties": false + } + }, + "required": [ + "code", + "message", + "entry" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "loader_patch_failed" + }, + "message": { + "type": "string" + }, + "binding": { + "$ref": "#/$defs/bindingFailure" + } + }, + "required": [ + "code", + "message", + "binding" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "invalid_format" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "unsupported_format" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "image_load_failed" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "entrypoint_not_found" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "code": { + "const": "verification_failed" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false } - }, - "required": [ - "code", - "message" - ], - "additionalProperties": false + ] } }, "required": [ @@ -661,6 +847,521 @@ "shutdownTimeoutMs" ], "additionalProperties": false + }, + "resourceFailure": { + "type": "object", + "properties": { + "resource": { + "enum": [ + "GuestBytes", + "HandleSlots", + "AuxiliaryBytes", + "TemporaryBytes", + "StringBytes", + "StringAllocations", + "IndividualStringBytes", + "CallDepth" + ] + }, + "reason": { + "enum": [ + "Limit", + "SizeOverflow", + "AllocationFailed" + ] + }, + "requested": { + "type": "integer", + "minimum": 0 + }, + "limit": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "resource", + "reason", + "requested", + "limit" + ], + "additionalProperties": false + }, + "sourceSpan": { + "type": "object", + "properties": { + "file_id": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + "start": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + "end": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "file_id", + "start", + "end" + ], + "additionalProperties": false + }, + "loadFailure": { + "type": "object", + "properties": { + "code": { + "enum": [ + "LOAD_INVALID_FORMAT", + "LOAD_UNSUPPORTED_FORMAT", + "LOAD_INVALID_REFERENCE", + "LOAD_INVALID_REGISTRY", + "LOAD_INVALID_CODE", + "LOAD_RESOURCE_LIMIT", + "LOAD_INVALID_ENTRYPOINT" + ] + }, + "reason": { + "enum": [ + "Magic", + "Version", + "Endianness", + "Reserved", + "SectionKind", + "MissingSection", + "DuplicateSection", + "Overlap", + "Truncated", + "TrailingBytes", + "InvalidFlag", + "Utf8", + "Category", + "Builtin", + "TypeId", + "FunctionId", + "OwnerCategory", + "TraitCategory", + "DuplicateBuiltin", + "DuplicateArray", + "ArrayCycle", + "DuplicateImplementation", + "MethodCount", + "Signature", + "CodeRange", + "FrameSlots", + "ReturnSlots", + "Overflow", + "Limit", + "Allocation", + "ConstantTag", + "DebugRange", + "DuplicateSyscall", + "UnknownOpcode", + "LocalSlot", + "JumpTarget", + "InstructionBoundary", + "BooleanImmediate", + "ConstantIndex", + "NativeId", + "UnpatchedHostcall", + "StackUnderflow", + "StackOverflow", + "StackJoin", + "ReturnHeight", + "UnterminatedPath", + "UnknownClosureCallee", + "NotClosure", + "InvalidYield", + "TypeMismatch" + ] + }, + "section": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "record": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "member": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "referenced_id": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "function": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "pc": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + { + "type": "null" + } + ] + }, + "offset": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "null" + } + ] + }, + "id_domain": { + "enum": [ + "Type", + "Function", + "Implementation", + null + ] + }, + "resource": { + "enum": [ + "PbxBytes", + "CodeBytes", + "Types", + "Functions", + "Implementations", + "NestedRecords", + "NameBytes", + "RegistryBytes", + "TemporaryBytes", + "Work", + "ConstantEntries", + "ConstantStringBytes", + null + ] + }, + "requested": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "null" + } + ] + }, + "limit": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "code", + "reason", + "section", + "record", + "member", + "referenced_id", + "function", + "pc", + "offset", + "id_domain", + "resource", + "requested", + "limit" + ], + "additionalProperties": false + }, + "bindingFailure": { + "oneOf": [ + { + "type": "object", + "properties": { + "reason": { + "const": "unknown_syscall" + }, + "module": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + } + }, + "required": [ + "reason", + "module", + "name", + "version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "missing_capability" + }, + "module": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "required": { + "type": "integer", + "minimum": 0 + }, + "provided": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "reason", + "module", + "name", + "version", + "required", + "provided" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "abi_mismatch" + }, + "module": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "declared_arg_slots": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "declared_ret_slots": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "expected_arg_slots": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "expected_ret_slots": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + } + }, + "required": [ + "reason", + "module", + "name", + "version", + "declared_arg_slots", + "declared_ret_slots", + "expected_arg_slots", + "expected_ret_slots" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "hostcall_index_out_of_bounds" + }, + "pc": { + "type": "integer", + "minimum": 0 + }, + "syscallIndex": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + }, + "syscallsLength": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "reason", + "pc", + "syscallIndex", + "syscallsLength" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "raw_syscall" + }, + "pc": { + "type": "integer", + "minimum": 0 + }, + "syscallId": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "reason", + "pc", + "syscallId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "unused_syscall" + }, + "module": { + "type": "string" + }, + "name": { + "type": "string" + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + "syscallIndex": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "reason", + "module", + "name", + "version", + "syscallIndex" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "hostcall_remaining" + }, + "pc": { + "type": "integer", + "minimum": 0 + }, + "syscallIndex": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "reason", + "pc", + "syscallIndex" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "reason": { + "const": "decode_failed" + } + }, + "required": [ + "reason" + ], + "additionalProperties": false + } + ] } } } diff --git a/docs/specs/runtime/11a-headless-automation-protocol.md b/docs/specs/runtime/11a-headless-automation-protocol.md index a1ff959..a4eb74f 100644 --- a/docs/specs/runtime/11a-headless-automation-protocol.md +++ b/docs/specs/runtime/11a-headless-automation-protocol.md @@ -94,6 +94,19 @@ exact round-trippable string (including non-finite values). Faults expose kind, pc, summary and structural trap code/opcode/message/source span or init-error code. No client must parse a summary to distinguish trap, panic or initialization failure. +Resource traps include a nullable `trap.resource` object with `resource`, `reason`, +`requested` and `limit`; resource and reason are enumerated machine values. +`initError` is discriminated by `code`: `registry_load_failed` includes `load`, +`runtime_resource_limit` includes `resource`, `entrypoint_arguments_invalid` +includes `entry`, and `loader_patch_failed` includes `binding`. Other initialization +codes carry only their code and human message. `load.code` uses the stable +`LOAD_*` tag and retains typed reason, section/offset, record/member, ID domain, +referenced ID, function/PC and quota context, with null for unavailable fields. +Binding context preserves canonical native identity, version, capabilities or +declared/expected ABI counts as applicable. A load-relative PC remains nested +inside its diagnostic; initialization failure does not invent a runtime PC. +The published response schema rejects unknown fields and invalid contexts. + ## Ordering, cancellation and lifecycle Only one host operation is admitted at a time. Conflicting work, including state