From 89101d1b202dad7c9acec93b7c50782184bd4198 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Wed, 23 Sep 2026 07:09:46 +0100 Subject: [PATCH] harden deterministic headless runtime control --- README.md | 2 + crates/console/prometeu-bytecode/src/lib.rs | 6 +- .../prometeu-system/src/os/facades/vm.rs | 9 + .../src/services/vm_runtime/mod.rs | 2 +- .../src/services/vm_runtime/tick.rs | 37 +- .../host/prometeu-host-headless/src/host.rs | 254 +++++++---- crates/host/prometeu-host-headless/src/lib.rs | 5 +- .../tests/deterministic_control.rs | 411 +++++++++++++++++- discussion/index.ndjson | 3 +- ...rvation-must-follow-the-active-producer.md | 134 ++++++ docs/specs/runtime/04-gfx-peripheral.md | 11 +- .../10-debug-inspection-and-profiling.md | 19 + ...ortability-and-cross-platform-execution.md | 77 +++- .../config/runtime-edge-coverage-domains.json | 7 +- 14 files changed, 856 insertions(+), 121 deletions(-) create mode 100644 discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md diff --git a/README.md b/README.md index 8bbf483..be78993 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ Current canonical domains: - `asset/bank` - `firmware` - `host-dependent` +- `host/headless` Global coverage artifacts: @@ -157,6 +158,7 @@ Domain-oriented evidence helpers: make coverage-domain-list make coverage-domain-evidence DOMAIN=firmware make coverage-domain-evidence DOMAIN=host-dependent +make coverage-domain-evidence DOMAIN=host/headless ``` Per-domain baselines currently start around `60`. diff --git a/crates/console/prometeu-bytecode/src/lib.rs b/crates/console/prometeu-bytecode/src/lib.rs index 247d266..9b316d9 100644 --- a/crates/console/prometeu-bytecode/src/lib.rs +++ b/crates/console/prometeu-bytecode/src/lib.rs @@ -11,9 +11,9 @@ mod program_image; mod value; pub use abi::{ - TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_ILLEGAL_INSTRUCTION, - TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_OOB, - TRAP_STACK_UNDERFLOW, TRAP_TYPE, + SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, + TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, + TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE, }; pub use assembler::{assemble, AsmError}; pub use decoder::{decode_next, DecodeError}; diff --git a/crates/console/prometeu-system/src/os/facades/vm.rs b/crates/console/prometeu-system/src/os/facades/vm.rs index a76b167..b530311 100644 --- a/crates/console/prometeu-system/src/os/facades/vm.rs +++ b/crates/console/prometeu-system/src/os/facades/vm.rs @@ -159,6 +159,15 @@ impl<'a> VmFacade<'a> { self.os.vm_runtime.debug_step_request = true; } + pub fn clear_debug_step_request(&mut self) { + if let Some(session) = self.active_session_mut() { + session.runtime.debug_step_request = false; + return; + } + + self.os.vm_runtime.debug_step_request = false; + } + pub fn debug_step_requested(&self) -> bool { self.active_session() .map(|session| session.runtime.debug_step_request) diff --git a/crates/console/prometeu-system/src/services/vm_runtime/mod.rs b/crates/console/prometeu-system/src/services/vm_runtime/mod.rs index 7f1cf23..e37f580 100644 --- a/crates/console/prometeu-system/src/services/vm_runtime/mod.rs +++ b/crates/console/prometeu-system/src/services/vm_runtime/mod.rs @@ -65,7 +65,7 @@ pub struct VirtualMachineRuntime { impl VirtualMachineRuntime { pub const CYCLES_PER_LOGICAL_FRAME: u64 = 1_500_000; - pub const SLICE_PER_TICK: u64 = 1_500_000; + pub const SLICE_PER_TICK: u64 = 250_000; pub const MAX_LOG_LEN: usize = 256; pub const MAX_LOGS_PER_FRAME: u32 = 10; diff --git a/crates/console/prometeu-system/src/services/vm_runtime/tick.rs b/crates/console/prometeu-system/src/services/vm_runtime/tick.rs index 86716bb..ac2104e 100644 --- a/crates/console/prometeu-system/src/services/vm_runtime/tick.rs +++ b/crates/console/prometeu-system/src/services/vm_runtime/tick.rs @@ -76,6 +76,9 @@ impl VirtualMachineRuntime { vm: &mut VirtualMachine, platform: &mut dyn RuntimePlatform, ) -> Option { + if vm.call_stack_is_empty() { + vm.prepare_boot_call(); + } let step_result = { let mut ctx = HostContext::new_platform(Some(platform)); let mut fs = VirtualFS::new(); @@ -96,18 +99,28 @@ impl VirtualMachineRuntime { }; match step_result { - Ok(_) => None, - Err(e) => { - let report = match e { - LogicalFrameEndingReason::Trap(trap) => CrashReport::VmTrap { trap }, - LogicalFrameEndingReason::Panic(message) => { - CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) } - } - other => CrashReport::VmPanic { - message: format!("Unexpected fault during step: {:?}", other), - pc: Some(vm.pc() as u32), - }, - }; + Ok(()) + | Err( + LogicalFrameEndingReason::FrameSync + | LogicalFrameEndingReason::BudgetExhausted + | LogicalFrameEndingReason::Halted + | LogicalFrameEndingReason::EndOfRom + | LogicalFrameEndingReason::Breakpoint, + ) => None, + Err(LogicalFrameEndingReason::Trap(trap)) => { + let report = CrashReport::VmTrap { trap }; + self.log( + log_service, + LogLevel::Error, + LogSource::Vm, + report.log_tag(), + format!("PVM Fault during Step: {}", report), + ); + self.last_crash_report = Some(report.clone()); + Some(report) + } + Err(LogicalFrameEndingReason::Panic(message)) => { + let report = CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) }; self.log( log_service, LogLevel::Error, diff --git a/crates/host/prometeu-host-headless/src/host.rs b/crates/host/prometeu-host-headless/src/host.rs index 51b2949..571fb80 100644 --- a/crates/host/prometeu-host-headless/src/host.rs +++ b/crates/host/prometeu-host-headless/src/host.rs @@ -2,20 +2,19 @@ use std::fmt; use std::sync::Arc; use prometeu_bytecode::Value; +use prometeu_drivers::MemoryBanks; use prometeu_drivers::hardware::Hardware; -use prometeu_drivers::{LocalFramebufferRenderBackend, MemoryBanks}; use prometeu_firmware::firmware_state::{AppCrashesStep, ResetStep}; use prometeu_firmware::{BootTarget, Firmware, FirmwareState}; use prometeu_hal::{ AssetBridge, AudioBridge, FrameId, Game2DFrameComposer, InputPlatform, InputSignals, OwnedRgba8888Frame, RenderBackend, RenderSubmission, RenderSubmissionSink, RenderSubmitError, - RenderWorkerError, RuntimePlatform, TelemetryPlatform, + RuntimePlatform, TelemetryPlatform, }; -use prometeu_system::{CrashReport, LatestRenderFrameStore, RenderWorkerConfig}; +use prometeu_system::{CrashReport, LatestRenderFrameStore}; const BOOT_TICK_LIMIT: usize = 64; const LOGICAL_FRAME_TICK_LIMIT: usize = 100_000; -const FRAME_PUBLISH_SPINS: usize = 10_000; /// One published logical frame plus the automation counter. #[derive(Debug, Clone, PartialEq, Eq)] @@ -30,26 +29,65 @@ pub struct HostState { pub pc: usize, pub stack_top: Vec, pub frame_index: u64, + pub tick_index: u64, pub app_id: u32, + pub status: HostExecutionStatus, } -#[derive(Debug)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostExecutionStatus { + Running, + Paused, + Terminated, + Faulted, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AdvanceFrameOutcome { + FrameCompleted { logical_frame_index: u64, frame_id: FrameId }, + Faulted(CrashReport), + Terminated, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AdvanceFramesStop { + Completed, + Faulted(CrashReport), + Terminated, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdvanceFramesOutcome { + pub requested: u64, + pub completed: u64, + pub stop: AdvanceFramesStop, +} + +#[derive(Debug, Clone, PartialEq, Eq)] pub enum HostError { - BootFailed(String), + AlreadyBooted, + BootFailed { reason: String, report: Option }, + InvalidState { operation: &'static str, status: HostExecutionStatus }, LogicalFrameDidNotClose, - FrameNotPublished, - RenderWorker(RenderWorkerError), + FrameNotPublished { previous: Option }, + NoFrameAvailable, } impl fmt::Display for HostError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::BootFailed(reason) => write!(f, "boot failed: {reason}"), + Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"), + Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"), + Self::InvalidState { operation, status } => { + write!(f, "{operation} is invalid while execution is {status:?}") + } Self::LogicalFrameDidNotClose => { write!(f, "logical frame did not reach FrameSync, end of ROM, or a fault") } - Self::FrameNotPublished => write!(f, "logical frame closed without a published frame"), - Self::RenderWorker(error) => write!(f, "render worker failed: {error:?}"), + Self::FrameNotPublished { .. } => { + write!(f, "logical frame closed without its canonical published frame") + } + Self::NoFrameAvailable => write!(f, "no completed frame is available for capture"), } } } @@ -61,8 +99,14 @@ pub struct HeadlessHost { firmware: Firmware, platform: HeadlessPlatform, signals: InputSignals, - /// Frame id observed before the logical frame that `capture_frame` should return. - previous_frame_id: Option, + boot_attempted: bool, + last_completed_frame: Option, +} + +#[derive(Debug, Clone, Copy)] +struct CompletedFrame { + logical_frame_index: u64, + frame_id: FrameId, } struct HeadlessPlatform { @@ -79,7 +123,8 @@ impl HeadlessHost { firmware: Firmware::new(None), platform: HeadlessPlatform { hardware, store }, signals: InputSignals::default(), - previous_frame_id: None, + boot_attempted: false, + last_completed_frame: None, } } @@ -88,26 +133,30 @@ impl HeadlessHost { /// The transition into `GameRunning` is the last tick. The first game /// logical frame stays available for [`Self::advance_frame`]. pub fn boot(&mut self, path: impl Into) -> Result<(), HostError> { + if self.boot_attempted { + return Err(HostError::AlreadyBooted); + } + self.boot_attempted = true; let path = path.into(); self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 }; - self.ensure_worker()?; - if matches!(self.firmware.state, FirmwareState::GameRunning(_)) { - return Ok(()); - } for _ in 0..BOOT_TICK_LIMIT { if matches!(self.firmware.state, FirmwareState::GameRunning(_)) { return Ok(()); } if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) { - let detail = self - .get_fault() - .map(|report| report.summary()) + let report = self.get_fault(); + let reason = report + .as_ref() + .map(CrashReport::summary) .unwrap_or_else(|| "cartridge crashed during boot".to_string()); - return Err(HostError::BootFailed(detail)); + return Err(HostError::BootFailed { reason, report }); } if matches!(self.firmware.state, FirmwareState::HubHome(_)) { - return Err(HostError::BootFailed("cartridge did not load".to_string())); + return Err(HostError::BootFailed { + reason: "cartridge did not load".to_string(), + report: None, + }); } self.tick_once(); } @@ -115,7 +164,10 @@ impl HeadlessHost { if matches!(self.firmware.state, FirmwareState::GameRunning(_)) { Ok(()) } else { - Err(HostError::BootFailed("boot did not reach the game".to_string())) + Err(HostError::BootFailed { + reason: "boot did not reach the game".to_string(), + report: self.get_fault(), + }) } } @@ -126,51 +178,101 @@ impl HeadlessHost { &self.signals, &mut self.platform, ); - self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id); + self.platform.store = LatestRenderFrameStore::default(); + self.boot_attempted = false; + self.last_completed_frame = None; } - pub fn pause(&mut self) { + pub fn pause(&mut self) -> Result<(), HostError> { + self.require_active("pause")?; self.firmware.os.vm().set_paused(true); + Ok(()) } - pub fn resume(&mut self) { + pub fn resume(&mut self) -> Result<(), HostError> { + self.require_active("resume")?; self.firmware.os.vm().set_paused(false); + Ok(()) } /// Execute one VM instruction. This does not close a logical frame. - pub fn step(&mut self) -> Option { + pub fn step(&mut self) -> Result, HostError> { + self.require_active("step")?; self.firmware.os.vm().set_paused(true); let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform); self.platform.hardware.audio.clear_commands(); - report + Ok(report) } - pub fn advance_frame(&mut self) -> Result<(), HostError> { + pub fn advance_frame(&mut self) -> Result { + if let Some(report) = self.get_fault() { + return Ok(AdvanceFrameOutcome::Faulted(report)); + } + if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) { + return Ok(AdvanceFrameOutcome::Terminated); + } + let start = self.firmware.os.vm().logical_frame_index(); - self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id); + let previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id); self.firmware.os.vm().set_paused(false); self.firmware.os.vm().request_debug_step(); for _ in 0..LOGICAL_FRAME_TICK_LIMIT { self.tick_once(); - if self.fault_is_visible() { - self.firmware.os.vm().set_paused(true); - return Ok(()); + if let Some(report) = self.get_fault() { + self.finish_frame_step(); + return Ok(AdvanceFrameOutcome::Faulted(report)); } - if self.firmware.os.vm().logical_frame_index() > start { - self.firmware.os.vm().set_paused(true); - return Ok(()); + if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) { + return Ok(AdvanceFrameOutcome::Terminated); + } + + let logical_frame_index = self.firmware.os.vm().logical_frame_index(); + if logical_frame_index > start { + self.finish_frame_step(); + let frame = self + .platform + .store + .latest_frame() + .ok_or(HostError::FrameNotPublished { previous: previous_frame_id })?; + if Some(frame.frame_id) == previous_frame_id { + return Err(HostError::FrameNotPublished { previous: previous_frame_id }); + } + self.last_completed_frame = + Some(CompletedFrame { logical_frame_index, frame_id: frame.frame_id }); + return Ok(AdvanceFrameOutcome::FrameCompleted { + logical_frame_index, + frame_id: frame.frame_id, + }); } } + self.finish_frame_step(); Err(HostError::LogicalFrameDidNotClose) } - pub fn advance_frames(&mut self, count: u64) -> Result<(), HostError> { + pub fn advance_frames(&mut self, count: u64) -> Result { + let mut completed = 0; for _ in 0..count { - self.advance_frame()?; + match self.advance_frame()? { + AdvanceFrameOutcome::FrameCompleted { .. } => completed += 1, + AdvanceFrameOutcome::Faulted(report) => { + return Ok(AdvanceFramesOutcome { + requested: count, + completed, + stop: AdvanceFramesStop::Faulted(report), + }); + } + AdvanceFrameOutcome::Terminated => { + return Ok(AdvanceFramesOutcome { + requested: count, + completed, + stop: AdvanceFramesStop::Terminated, + }); + } + } } - Ok(()) + Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed }) } pub fn set_input(&mut self, signals: InputSignals) { @@ -185,20 +287,24 @@ impl HeadlessHost { self.signals.right_signal = down; } - pub fn capture_frame(&mut self) -> Result { - let frame = self.wait_for_published_frame(self.previous_frame_id)?; - Ok(CapturedFrame { - logical_frame_index: self.firmware.os.vm().logical_frame_index(), - frame, - }) + pub fn capture_frame(&self) -> Result { + let completed = self.last_completed_frame.ok_or(HostError::NoFrameAvailable)?; + let frame = self.platform.store.latest_frame().ok_or(HostError::NoFrameAvailable)?; + if frame.frame_id != completed.frame_id { + return Err(HostError::FrameNotPublished { previous: Some(completed.frame_id) }); + } + Ok(CapturedFrame { logical_frame_index: completed.logical_frame_index, frame }) } pub fn get_state(&mut self) -> HostState { + let status = self.execution_status(); HostState { pc: self.firmware.os.vm().active_pc().unwrap_or(0), stack_top: self.firmware.os.vm().active_operand_stack_top(10), frame_index: self.firmware.os.vm().logical_frame_index(), + tick_index: self.firmware.os.vm().tick_index(), app_id: self.firmware.os.vm().current_app_id(), + status, } } @@ -217,49 +323,35 @@ impl HeadlessHost { self.platform.hardware.audio.clear_commands(); } + fn execution_status(&mut self) -> HostExecutionStatus { + if self.fault_is_visible() { + HostExecutionStatus::Faulted + } else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) { + HostExecutionStatus::Terminated + } else if self.firmware.os.vm().paused() { + HostExecutionStatus::Paused + } else { + HostExecutionStatus::Running + } + } + fn fault_is_visible(&mut self) -> bool { self.firmware.os.vm().last_crash_report().is_some() || matches!(self.firmware.state, FirmwareState::AppCrashes(_)) } - fn ensure_worker(&mut self) -> Result<(), HostError> { - if self.firmware.os.vm().render_worker_controller().is_some() { - return Ok(()); + fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> { + let status = self.execution_status(); + if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) { + Ok(()) + } else { + Err(HostError::InvalidState { operation, status }) } - - let backend = LocalFramebufferRenderBackend::new_with_memory_banks( - Hardware::W, - Hardware::H, - Arc::clone(&self.platform.hardware.memory_banks), - self.platform.hardware.assets.glyph_asset_slot_index(), - ); - let store = self.platform.store.clone(); - self.firmware.os.vm().start_render_worker(RenderWorkerConfig::default(), backend, store); - Ok(()) } - fn wait_for_published_frame( - &mut self, - previous: Option, - ) -> Result { - for _ in 0..FRAME_PUBLISH_SPINS { - if let Some(error) = self - .firmware - .os - .vm() - .render_worker_controller() - .and_then(|worker| worker.last_error()) - { - return Err(HostError::RenderWorker(error)); - } - if let Some(frame) = self.platform.store.latest_frame() - && Some(frame.frame_id) != previous - { - return Ok(frame); - } - std::hint::spin_loop(); - } - Err(HostError::FrameNotPublished) + fn finish_frame_step(&mut self) { + self.firmware.os.vm().set_paused(true); + self.firmware.os.vm().clear_debug_step_request(); } } diff --git a/crates/host/prometeu-host-headless/src/lib.rs b/crates/host/prometeu-host-headless/src/lib.rs index 0bdfa23..785e8f0 100644 --- a/crates/host/prometeu-host-headless/src/lib.rs +++ b/crates/host/prometeu-host-headless/src/lib.rs @@ -8,4 +8,7 @@ mod host; -pub use host::{CapturedFrame, HeadlessHost, HostError, HostState}; +pub use host::{ + AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost, + HostError, HostExecutionStatus, HostState, +}; diff --git a/crates/host/prometeu-host-headless/tests/deterministic_control.rs b/crates/host/prometeu-host-headless/tests/deterministic_control.rs index 42be5fc..87b5faf 100644 --- a/crates/host/prometeu-host-headless/tests/deterministic_control.rs +++ b/crates/host/prometeu-host-headless/tests/deterministic_control.rs @@ -2,21 +2,151 @@ use std::fs; use std::path::Path; use std::time::{Duration, Instant}; +use prometeu_bytecode::SourceSpan; use prometeu_bytecode::assembler::assemble; use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl}; +use prometeu_hal::InputSignals; +use prometeu_hal::app_mode::AppMode; use prometeu_hal::color::Color; -use prometeu_host_headless::{CapturedFrame, HeadlessHost, HostState}; +use prometeu_host_headless::{ + AdvanceFrameOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost, HostError, + HostExecutionStatus, HostState, +}; use prometeu_system::CrashReport; const RED: u32 = Color::RED.raw(); const BLUE: u32 = Color::BLUE.raw(); +const GREEN: u32 = Color::GREEN.raw(); +const BLACK: u32 = Color::BLACK.raw(); + +#[test] +fn headless_source_has_no_timing_wait_or_interactive_backend_dependency() { + let source = include_str!("../src/host.rs"); + let manifest = include_str!("../Cargo.toml"); + + for forbidden in + ["FRAME_PUBLISH_SPINS", "spin_loop", "thread::sleep", "ensure_worker", "RenderWorkerConfig"] + { + assert!(!source.contains(forbidden), "headless source contains {forbidden}"); + } + for forbidden in ["winit", "pixels", "cpal"] { + assert!(!manifest.contains(forbidden), "headless manifest contains {forbidden}"); + } +} + +#[test] +fn lifecycle_state_and_preconditions_are_structural() { + let mut host = HeadlessHost::new(); + assert_eq!(host.get_state().status, HostExecutionStatus::Terminated); + assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable)); + assert_eq!( + host.pause(), + Err(HostError::InvalidState { + operation: "pause", + status: HostExecutionStatus::Terminated, + }) + ); + + let cartridge = color_cartridge(); + host.boot(&cartridge).expect("boot"); + let booted = host.get_state(); + assert_eq!(booted.status, HostExecutionStatus::Running); + assert_eq!(booted.pc, 0, "boot must not execute the first game instruction"); + assert_eq!(host.boot(&cartridge), Err(HostError::AlreadyBooted)); + + host.pause().expect("pause"); + assert_eq!(host.get_state().status, HostExecutionStatus::Paused); + host.resume().expect("resume"); + assert_eq!(host.get_state().status, HostExecutionStatus::Running); +} #[test] fn step_does_not_complete_a_logical_frame() { let mut host = boot_color(); + let before = host.get_state(); + assert_eq!(host.step().expect("step"), None); + let after = host.get_state(); + assert_eq!(after.frame_index, before.frame_index); + assert_ne!(after.pc, before.pc); + assert_eq!(after.status, HostExecutionStatus::Paused); +} + +#[test] +fn stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame() { + let dir = temp_cart("step-frame-sync"); + write_cartridge(&dir, 51, "Step Frame Sync", &module(asm("FRAME_SYNC\nRET\n"), vec![]), &[]); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot frame-sync cartridge"); let before = host.get_state().frame_index; - host.step(); + + assert_eq!(host.step().expect("step frame sync"), None); assert_eq!(host.get_state().frame_index, before); + assert!(host.get_fault().is_none()); + assert_eq!(host.get_state().status, HostExecutionStatus::Paused); +} + +#[test] +fn one_logical_frame_may_span_multiple_internal_ticks() { + let dir = temp_cart("multi-tick"); + write_cartridge(&dir, 47, "Multi Tick", &multi_tick_program(), &[]); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot multi-tick cartridge"); + let before = host.get_state(); + + completed(host.advance_frame().expect("multi-tick frame")); + + let after = host.get_state(); + assert_eq!(after.frame_index, before.frame_index + 1); + assert!(after.tick_index >= before.tick_index + 2); +} + +#[test] +fn outer_frame_limit_is_a_host_error_and_finishes_paused() { + let dir = temp_cart("frame-limit"); + write_cartridge(&dir, 50, "Frame Limit", &module(asm("JMP 0\n"), vec![]), &[]); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot non-closing cartridge"); + + assert_eq!(host.advance_frame(), Err(HostError::LogicalFrameDidNotClose)); + assert_eq!(host.get_state().status, HostExecutionStatus::Paused); + assert!(host.get_fault().is_none()); +} + +#[test] +fn one_frame_returns_and_captures_the_exact_published_frame() { + let mut host = boot_color(); + let before = host.get_state().frame_index; + let (logical_frame_index, frame_id) = completed(host.advance_frame().expect("frame")); + let captured = host.capture_frame().expect("capture"); + + assert_eq!(logical_frame_index, before + 1); + assert_eq!(captured.logical_frame_index, logical_frame_index); + assert_eq!(captured.frame.frame_id, frame_id); + assert_eq!(captured.frame.ownership.app_mode, AppMode::Game); + assert_eq!(captured.frame.ownership.app_id, 41); + assert_eq!(captured.frame.stride_pixels, captured.frame.width); + assert_eq!(captured.frame.pixels.len(), 480 * 270); + assert_eq!(host.capture_frame().expect("repeat capture"), captured); + + let mut mutated_clone = captured.clone(); + mutated_clone.frame.pixels[0] = GREEN; + assert_ne!(host.capture_frame().expect("owned capture").frame.pixels[0], GREEN); + assert_eq!(host.get_state().status, HostExecutionStatus::Paused); +} + +#[test] +fn zero_frames_is_an_explicit_noop() { + let mut host = boot_color(); + let before = host.get_state(); + let outcome = host.advance_frames(0).expect("zero frames"); + + assert_eq!(outcome.requested, 0); + assert_eq!(outcome.completed, 0); + assert_eq!(outcome.stop, AdvanceFramesStop::Completed); + let after = host.get_state(); + assert_eq!(after.frame_index, before.frame_index); + assert_eq!(after.tick_index, before.tick_index); + assert_eq!(after.status, before.status); } #[test] @@ -24,7 +154,7 @@ fn clear_input_drops_right() { let mut host = boot_color(); host.set_right(true); host.clear_input(); - host.advance_frame().expect("frame"); + completed(host.advance_frame().expect("frame")); assert_color(&host.capture_frame().expect("frame"), BLUE); } @@ -34,20 +164,68 @@ fn right_hold_then_release_changes_pixels() { let before = host.get_state().frame_index; host.set_right(true); - host.advance_frames(60).expect("hold"); + assert_completed(host.advance_frames(60).expect("hold"), 60); let held = host.capture_frame().expect("held frame"); assert_eq!(host.get_state().frame_index, before + 60); assert_color(&held, RED); assert!(host.get_fault().is_none()); host.set_right(false); - host.advance_frames(1).expect("release"); + assert_completed(host.advance_frames(1).expect("release"), 1); let released = host.capture_frame().expect("released frame"); assert_eq!(released.logical_frame_index, before + 61); assert_color(&released, BLUE); assert!(host.get_fault().is_none()); } +#[test] +fn normalized_button_press_hold_release_and_clear_are_observable() { + let mut host = boot_input_edges(); + + let mut signals = InputSignals { right_signal: true, ..InputSignals::default() }; + host.set_input(signals); + completed(host.advance_frame().expect("press")); + assert_color(&host.capture_frame().expect("pressed"), RED); + + completed(host.advance_frame().expect("hold")); + assert_color(&host.capture_frame().expect("held"), BLUE); + + signals.right_signal = false; + host.set_input(signals); + completed(host.advance_frame().expect("release")); + assert_color(&host.capture_frame().expect("released"), GREEN); + + host.set_input(InputSignals { + right_signal: true, + f_signal: true, + x_pos: 123, + y_pos: 45, + ..InputSignals::default() + }); + host.clear_input(); + completed(host.advance_frame().expect("clear")); + assert_color(&host.capture_frame().expect("cleared"), BLACK); +} + +#[test] +fn normalized_touch_edges_and_coordinates_use_the_same_input_surface() { + let mut host = boot_touch_edges(); + let mut signals = + InputSignals { f_signal: true, x_pos: 123, y_pos: 45, ..InputSignals::default() }; + + host.set_input(signals); + completed(host.advance_frame().expect("touch press")); + assert_color(&host.capture_frame().expect("touch pressed"), RED); + + completed(host.advance_frame().expect("touch hold")); + assert_color(&host.capture_frame().expect("touch held"), BLUE); + + signals.f_signal = false; + host.set_input(signals); + completed(host.advance_frame().expect("touch release")); + assert_color(&host.capture_frame().expect("touch released"), GREEN); +} + #[test] fn two_runs_match_oracle() { let first = run_color_sequence(); @@ -67,6 +245,8 @@ fn reset_matches_fresh_host() { let mut host = boot_color(); let _ = run_on(&mut host); host.reset(); + assert_eq!(host.get_state().status, HostExecutionStatus::Terminated); + assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable)); host.boot(color_cartridge()).expect("reboot"); let after_reset = run_on(&mut host); let fresh = run_color_sequence(); @@ -86,28 +266,101 @@ fn trap_is_structured() { write_cartridge(&dir, 42, "Fault", &fault_program(), &[]); let mut host = HeadlessHost::new(); host.boot(&dir).expect("boot fault cartridge"); - host.advance_frame().expect("faulting frame"); + let outcome = host.advance_frame().expect("faulting frame"); - match host.get_fault() { - Some(report @ CrashReport::VmTrap { .. }) => { - assert!(report.pc().is_some()); + match outcome { + AdvanceFrameOutcome::Faulted(CrashReport::VmTrap { trap }) => { + assert_eq!(trap.code, prometeu_bytecode::TRAP_EXPLICIT); + assert_eq!(trap.opcode, prometeu_bytecode::isa::core::CoreOpCode::Trap as u16); + assert_eq!(trap.pc, 0); + assert_eq!(trap.span, Some(SourceSpan { file_id: 7, start: 11, end: 15 })); + assert!(trap.message.contains("main")); } - other => panic!("expected VmTrap, got {other:?}"), + other => panic!("expected VmTrap outcome, got {other:?}"), } + assert!(matches!(host.get_fault(), Some(CrashReport::VmTrap { .. }))); + assert_eq!(host.get_state().status, HostExecutionStatus::Faulted); +} + +#[test] +fn instruction_step_fault_remains_structured() { + let dir = temp_cart("step-fault"); + write_cartridge(&dir, 48, "Step Fault", &fault_program(), &[]); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot fault cartridge"); + + let report = host.step().expect("step result").expect("structured step fault"); + assert!(matches!(report, CrashReport::VmTrap { .. })); + assert_eq!(host.get_fault(), Some(report)); + assert_eq!(host.get_state().status, HostExecutionStatus::Faulted); +} + +#[test] +fn batch_stops_early_on_fault_and_reports_partial_progress() { + let dir = temp_cart("fault-batch"); + write_cartridge(&dir, 43, "Fault Batch", &delayed_fault_program(), &gfx_syscalls()); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot fault cartridge"); + + let outcome = host.advance_frames(5).expect("batch outcome"); + assert_eq!(outcome.requested, 5); + assert_eq!(outcome.completed, 2); + assert!(matches!(outcome.stop, AdvanceFramesStop::Faulted(CrashReport::VmTrap { .. }))); +} + +#[test] +fn advance_after_reset_reports_termination_without_ticking() { + let mut host = boot_color(); + host.reset(); + let before = host.get_state().tick_index; + + assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated); + assert_eq!(host.get_state().tick_index, before); + let batch = host.advance_frames(3).expect("terminated batch"); + assert_eq!(batch.completed, 0); + assert_eq!(batch.stop, AdvanceFramesStop::Terminated); +} + +#[test] +fn vm_init_failure_is_returned_as_structured_boot_failure() { + let dir = temp_cart("bad-pbx"); + write_cartridge(&dir, 44, "Bad PBX", b"not a pbx", &[]); + let mut host = HeadlessHost::new(); + + let error = host.boot(&dir).expect_err("invalid PBX must fail boot"); + assert!(matches!( + error, + HostError::BootFailed { report: Some(CrashReport::VmInit { .. }), .. } + )); + assert_eq!(host.get_state().status, HostExecutionStatus::Faulted); + assert!(matches!(host.get_fault(), Some(CrashReport::VmInit { .. }))); +} + +#[test] +fn end_of_rom_completes_a_logical_frame() { + let dir = temp_cart("end-of-rom"); + write_cartridge(&dir, 45, "End Of Rom", &module(asm("RET\n"), vec![]), &[]); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot end-of-rom cartridge"); + + let first = completed(host.advance_frame().expect("first frame")); + let second = completed(host.advance_frame().expect("second frame")); + assert_eq!(second.0, first.0 + 1); + assert_ne!(second.1, first.1); } #[test] fn three_hundred_frames_finish_without_refresh_sleep() { let mut host = boot_color(); let started = Instant::now(); - host.advance_frames(300).expect("fast frames"); + assert_completed(host.advance_frames(300).expect("fast frames"), 300); assert!(started.elapsed() < Duration::from_secs(2)); } #[test] fn audio_play_does_not_need_a_device() { let mut host = boot_color(); - host.advance_frame().expect("frame with audio.play"); + completed(host.advance_frame().expect("frame with audio.play")); assert!(host.get_fault().is_none()); assert_color(&host.capture_frame().expect("frame"), BLUE); } @@ -125,6 +378,22 @@ fn boot_color() -> HeadlessHost { host } +fn boot_input_edges() -> HeadlessHost { + let dir = temp_cart("input-edges"); + write_cartridge(&dir, 46, "Input Edges", &input_edge_program(), &gfx_syscalls()); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot input cartridge"); + host +} + +fn boot_touch_edges() -> HeadlessHost { + let dir = temp_cart("touch-edges"); + write_cartridge(&dir, 49, "Touch Edges", &touch_edge_program(), &gfx_syscalls()); + let mut host = HeadlessHost::new(); + host.boot(&dir).expect("boot touch cartridge"); + host +} + fn color_cartridge() -> String { let dir = temp_cart("color"); write_cartridge(&dir, 41, "Right Pixel", &color_program(), &color_syscalls()); @@ -138,16 +407,31 @@ fn run_color_sequence() -> ColorOracle { fn run_on(host: &mut HeadlessHost) -> ColorOracle { host.set_right(true); - host.advance_frames(60).expect("hold"); + assert_completed(host.advance_frames(60).expect("hold"), 60); let held = host.capture_frame().expect("held"); host.set_right(false); - host.advance_frames(1).expect("release"); + assert_completed(host.advance_frames(1).expect("release"), 1); let released = host.capture_frame().expect("released"); let state = host.get_state(); let fault = host.get_fault(); ColorOracle { held, released, state, fault } } +fn completed(outcome: AdvanceFrameOutcome) -> (u64, prometeu_hal::FrameId) { + match outcome { + AdvanceFrameOutcome::FrameCompleted { logical_frame_index, frame_id } => { + (logical_frame_index, frame_id) + } + other => panic!("expected completed frame, got {other:?}"), + } +} + +fn assert_completed(outcome: prometeu_host_headless::AdvanceFramesOutcome, expected: u64) { + assert_eq!(outcome.requested, expected); + assert_eq!(outcome.completed, expected); + assert_eq!(outcome.stop, AdvanceFramesStop::Completed); +} + fn assert_color(captured: &CapturedFrame, color: u32) { assert_eq!(captured.frame.width, 480); assert_eq!(captured.frame.height, 270); @@ -157,7 +441,9 @@ fn assert_color(captured: &CapturedFrame, color: u32) { fn assert_same_state(left: &HostState, right: &HostState) { assert_eq!(left.pc, right.pc); assert_eq!(left.frame_index, right.frame_index); + assert_eq!(left.tick_index, right.tick_index); assert_eq!(left.app_id, right.app_id); + assert_eq!(left.status, right.status); assert_eq!(format!("{:?}", left.stack_top), format!("{:?}", right.stack_top)); } @@ -207,12 +493,91 @@ fn color_program() -> Vec { module(rom, color_syscalls()) } +fn input_edge_program() -> Vec { + let mut rom = Vec::new(); + let pressed_jump = emit_right_predicate(&mut rom, 0x2030); + rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let released_at = rom.len() as u32; + rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes()); + + let released_jump = emit_right_predicate(&mut rom, 0x2031); + rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let down_at = rom.len() as u32; + rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes()); + + let down_jump = emit_right_predicate(&mut rom, 0x2032); + rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let idle_at = rom.len() as u32; + rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes()); + rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + + module(rom, gfx_syscalls()) +} + +fn emit_right_predicate(rom: &mut Vec, predicate: u32) -> usize { + rom.extend(asm(&format!("INTRINSIC 0x2000\nINTRINSIC 0x2013\nINTRINSIC {predicate:#x}\n"))); + let target = rom.len() + 2; + rom.extend(asm("JMP_IF_FALSE 0\n")); + target +} + +fn touch_edge_program() -> Vec { + let mut rom = Vec::new(); + let pressed_jump = emit_touch_predicate(&mut rom, 0x2030); + rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let released_at = rom.len() as u32; + rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes()); + + let released_jump = emit_touch_predicate(&mut rom, 0x2031); + rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let down_at = rom.len() as u32; + rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes()); + + let down_jump = emit_touch_predicate(&mut rom, 0x2032); + rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + let idle_at = rom.len() as u32; + rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes()); + rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + + module(rom, gfx_syscalls()) +} + +fn emit_touch_predicate(rom: &mut Vec, predicate: u32) -> usize { + rom.extend(asm(&format!( + "INTRINSIC 0x2001\nINTRINSIC 0x2020\nINTRINSIC {predicate:#x}\n\ + INTRINSIC 0x2001\nINTRINSIC 0x2021\nPUSH_I64 123\nEQ\nAND\n\ + INTRINSIC 0x2001\nINTRINSIC 0x2022\nPUSH_I64 45\nEQ\nAND\n" + ))); + let target = rom.len() + 2; + rom.extend(asm("JMP_IF_FALSE 0\n")); + target +} + fn fault_program() -> Vec { // `INTRINSIC 0xDEADBEEF` is rejected by the loader as `VerificationFailed`. // `TRAP` is a legal instruction that becomes `CrashReport::VmTrap` at runtime. module(asm("TRAP\nFRAME_SYNC\nRET\n"), vec![]) } +fn delayed_fault_program() -> Vec { + let mut rom = + asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I32 3\nEQ\n"); + let continue_jump = rom.len() + 2; + rom.extend(asm("JMP_IF_FALSE 0\nTRAP\n")); + let continue_at = rom.len() as u32; + rom[continue_jump..continue_jump + 4].copy_from_slice(&continue_at.to_le_bytes()); + rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n"))); + module(rom, gfx_syscalls()) +} + +fn multi_tick_program() -> Vec { + let mut rom = asm("PUSH_I32 30000\nSET_LOCAL 0\n"); + let loop_at = rom.len() as u32; + rom.extend(asm("GET_LOCAL 0\nPUSH_I32 1\nSUB\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 0\nGT\n")); + rom.extend(asm(&format!("JMP_IF_TRUE {loop_at}\nFRAME_SYNC\nRET\n"))); + module_with_locals(rom, vec![], 1) +} + fn color_syscalls() -> Vec { vec![ SyscallDecl { @@ -232,7 +597,21 @@ fn color_syscalls() -> Vec { ] } +fn gfx_syscalls() -> Vec { + vec![SyscallDecl { + module: "gfx2d".into(), + name: "clear".into(), + version: 1, + arg_slots: 1, + ret_slots: 0, + }] +} + fn module(code: Vec, syscalls: Vec) -> Vec { + module_with_locals(code, syscalls, 0) +} + +fn module_with_locals(code: Vec, syscalls: Vec, local_slots: u16) -> Vec { BytecodeModule { version: 0, const_pool: vec![], @@ -240,13 +619,13 @@ fn module(code: Vec, syscalls: Vec) -> Vec { code_offset: 0, code_len: code.len() as u32, param_slots: 0, - local_slots: 0, + local_slots, return_slots: 0, max_stack_slots: 8, }], code, debug_info: Some(DebugInfo { - pc_to_span: vec![], + pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 11, end: 15 })], function_names: vec![(0, "main".into())], }), exports: vec![Export { symbol: "main".into(), func_idx: 0 }], diff --git a/discussion/index.ndjson b/discussion/index.ndjson index 4b121e6..d4144eb 100644 --- a/discussion/index.ndjson +++ b/discussion/index.ndjson @@ -1,4 +1,5 @@ -{"type":"meta","next_id":{"DSC":50,"AGD":53,"DEC":44,"PLN":175,"LSN":58,"CLSN":1}} +{"type":"meta","next_id":{"DSC":51,"AGD":54,"DEC":45,"PLN":176,"LSN":59,"CLSN":1}} +{"type":"discussion","id":"DSC-0050","status":"done","ticket":"headless-automation-host-hardening","title":"AGD-0052 Hardening — Headless Automation Host and Deterministic Runtime Control","created_at":"2026-09-22","updated_at":"2026-09-23","tags":["runtime","host","headless","automation","deterministic","concurrency","testing"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0058","file":"discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md","status":"done","created_at":"2026-09-23","updated_at":"2026-09-23"}]} {"type":"discussion","id":"DSC-0049","status":"done","ticket":"headless-automation-host-and-deterministic-runtime-control","title":"Headless Automation Host and Deterministic Runtime Control","created_at":"2026-09-22","updated_at":"2026-09-22","tags":["runtime","host","headless","automation","testing","ai","deterministic","input","framebuffer","debugger"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0049-headless-automation-host-and-deterministic-runtime-control/LSN-0057-deterministic-host-control-follows-logical-runtime-boundaries.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]} {"type":"discussion","id":"DSC-0044","status":"done","ticket":"hub-suspended-game-kill-affordance","title":"Hub Suspended Game Kill Affordance","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["hub","lifecycle","game","ui"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0044-hub-suspended-game-kill-affordance/LSN-0054-manual-hub-kill-must-share-game-termination-cleanup.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]} {"type":"discussion","id":"DSC-0043","status":"done","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0043-system-os-cartridge-switch-orchestrator/LSN-0053-game-switching-is-lifecycle-replacement-not-loader-work.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]} diff --git a/discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md b/discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md new file mode 100644 index 0000000..7f338b9 --- /dev/null +++ b/discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md @@ -0,0 +1,134 @@ +--- +id: LSN-0058 +ticket: headless-automation-host-hardening +title: Deterministic Observation Must Follow the Active Producer +created: 2026-09-23 +tags: [runtime, host, headless, deterministic, rendering, testing, debugger] +--- + +## Context + +The first headless automation host appeared to synchronize frame capture with a +render worker: it started a worker, remembered the latest published frame id, +and spun for a bounded number of iterations after logical execution. Source +revalidation showed that this story did not match the running system. A Game +cartridge executes inside an active `VmSession`, and that session selected the +existing `LocalSynchronous` render consumer. The worker started on the global +fallback runtime never consumed the active session's submissions. + +The visible frame was already published synchronously through the normal +platform sink. The spin was therefore redundant in successful runs and would +still have been incorrect for a future asynchronous path because it waited for +"any different frame" rather than the specific frame requested by automation. + +## Key Decisions + +### The Observation Contract Follows the Active Execution Owner + +**What:** The headless host intentionally uses the active session's local +synchronous consumer and removes the unused global worker and bounded spin. + +**Why:** Synchronization must be defined against the component that actually +produces the observed value. Waiting on an unrelated worker creates accidental +success and makes the architecture harder to reason about. + +**Trade-offs:** The deterministic headless host does not exercise worker +concurrency on every cartridge run. Worker equivalence remains a separate +runtime conformance concern rather than part of each game's oracle. + +### Completion Carries Exact Identity + +**What:** Successful frame advancement retains the explicit +`{logical_frame_index, FrameId}` pair and capture validates that exact published +frame before cloning its `OwnedRgba8888Frame`. + +**Why:** A generation change only proves that something was published. It does +not prove which logical operation produced it. Exact identity makes stale or +mis-associated observations detectable. + +**Trade-offs:** Logical frame numbers and render frame ids remain separate +domains. Callers compare the explicit pair rather than assuming equality or a +fixed offset. + +### A Tick Slice Must Be Smaller Than the Logical Budget + +**What:** The runtime's per-firmware-tick execution slice is smaller than the +total logical-frame cycle budget. Headless advancement loops across slices +until the frame closes or a terminal outcome occurs. + +**Why:** When both limits were equal, `BudgetExhausted` left zero remaining +logical budget, so another tick could not make progress. The documented +multi-tick contract existed only nominally. Separating the limits makes a tick +an implementation slice and keeps a logical frame as the automation unit. + +**Trade-offs:** A computation-heavy logical frame can span several firmware +ticks. This is observable through deterministic tick counters but does not +change guest frame semantics. + +### Debug Instruction Step Must Prime the Entry Call + +**What:** The shared debugger instruction-step primitive prepares the VM entry +call when the call stack is empty before executing one instruction. + +**Why:** Direct boot intentionally stops before the first game instruction. A +debug step at that point previously encountered the coroutine safepoint and +reported `FrameSync` as an unexpected panic instead of executing the first +instruction. + +**Trade-offs:** Entry preparation remains shared runtime behavior. No +headless-specific VM branch is introduced. + +## Patterns and Algorithms + +### Deterministic Frame Advance + +1. Record the current logical-frame index and latest canonical frame id. +2. Release pause and request the same one-frame stop used by debugger control. +3. Tick firmware while feeding the retained normalized `InputSignals`. +4. Continue through internal cycle-slice exhaustion. +5. Stop on exactly one logical-frame increment, structured fault, lifecycle + termination, or a typed host safety-limit error. +6. Clear the frame-step request and finish paused. +7. On success, require a new canonical frame and retain its exact identity with + the completed logical index. + +### Deterministic Oracle Boundary + +Include observations that describe simulated execution: logical frame and +frame identity, canonical pixels and layout, guest-visible state, structured +status/faults, and deterministic machine counters. + +Exclude observations of the host running the simulation: wall time, CPU time, +thread scheduling, presentation cadence, worker timing, and host-only +identities. + +## Pitfalls + +- A worker created by a host may not own the active session being automated. +- Bounded spinning is neither an acknowledgement nor an identity check. +- "Latest changed" is weaker than "the requested frame was published." +- Equal slice and logical budgets can make multi-tick continuation impossible + even when the control loop appears to support it. +- A debug step from a pristine boot boundary must establish the same entry-call + precondition as normal execution. +- Human-readable fault summaries are useful diagnostics but are not a stable + automation interface; retain structured `CrashReport` values. + +## References + +- Decision: `DEC-0044` (Deterministic Headless Automation Host Contract) +- Prior lesson: `LSN-0057` (Deterministic Host Control Follows Logical Runtime Boundaries) +- Render worker lesson: `LSN-0049` (Render Workers Publish Frames, Hosts Present Them) +- Graphics contract: `docs/specs/runtime/04-gfx-peripheral.md` +- Debug contract: `docs/specs/runtime/10-debug-inspection-and-profiling.md` +- Portability and headless contract: `docs/specs/runtime/11-portability-and-cross-platform-execution.md` + +## Takeaways + +- Revalidate ownership and data flow from source before hardening a wait. +- Deterministic observation requires exact completion identity, not timing luck. +- Keep logical-frame control above internal execution slices. +- Use one production runtime path for interactive debugging and headless + automation; vary host transport and pacing, not machine semantics. +- Test infrastructure boundaries with counters and structured outcomes instead + of sleeps or log parsing. diff --git a/docs/specs/runtime/04-gfx-peripheral.md b/docs/specs/runtime/04-gfx-peripheral.md index a64ada9..8f75102 100644 --- a/docs/specs/runtime/04-gfx-peripheral.md +++ b/docs/specs/runtime/04-gfx-peripheral.md @@ -75,7 +75,9 @@ palette, host presentation, or compatibility contract. ### Published owned frame -The canonical worker-published frame value is `OwnedRgba8888Frame`. +The canonical published frame value is `OwnedRgba8888Frame`. It is produced by +either the local synchronous consumer or the asynchronous render worker; the +consumer path does not change the frame contract. `OwnedRgba8888Frame` contains: @@ -184,6 +186,13 @@ producer path MUST remain non-blocking with respect to worker rasterization and host present. A slow worker can cause replacement/drop telemetry, but it MUST NOT create an unbounded queue or stall VM logical frame production. +A local synchronous consumer consumes the same immutable `RenderSubmission` +through the same render backend and publishes the same canonical +`OwnedRgba8888Frame` before returning. It does not use the asynchronous +single-slot handoff and therefore does not weaken or reinterpret the worker's +non-blocking producer contract. A host may select this path when an explicit +synchronous observation boundary is part of its host contract. + ### 4.4 Frame pacing Game logical frames are paced by the runtime frame scheduler, not by render diff --git a/docs/specs/runtime/10-debug-inspection-and-profiling.md b/docs/specs/runtime/10-debug-inspection-and-profiling.md index 47c7445..e7bd2bc 100644 --- a/docs/specs/runtime/10-debug-inspection-and-profiling.md +++ b/docs/specs/runtime/10-debug-inspection-and-profiling.md @@ -81,6 +81,25 @@ When the host activates instruction-level inspection, it may observe: - operand stack - call stack +### 3.3 Debugger and Headless Semantic Alignment + +Interactive debugging and deterministic headless automation share runtime +meanings even though their transports and pacing differ: + +| Runtime meaning | Debugger command/observation | Headless operation | +| --- | --- | --- | +| Pause active VM execution | `pause` | `pause()` | +| Resume active VM execution | `resume` | `resume()` | +| Execute one VM instruction and remain paused | `step` | `step()` | +| Complete one logical frame and remain paused | `stepFrame` | `advance_frame()` | +| Read overlapping execution state | `getState` | `get_state()` | +| Observe structured current fault | event/current state | `get_fault()` | +| Inject normalized input | not defined by the debugger protocol | `set_input()` | +| Reset the machine execution | not defined by the debugger protocol | `reset()` | +| Capture the canonical published frame | not defined by the debugger protocol | `capture_frame()` | + +The headless API does not define or extend an external automation protocol. + ## 4 State Inspection Boundary Detailed state inspection is a host-owned concern. The runtime may expose deterministic machine state to host tooling, but this chapter does not define a general guest ABI for introspection convenience. diff --git a/docs/specs/runtime/11-portability-and-cross-platform-execution.md b/docs/specs/runtime/11-portability-and-cross-platform-execution.md index 82c9601..53d1dbb 100644 --- a/docs/specs/runtime/11-portability-and-cross-platform-execution.md +++ b/docs/specs/runtime/11-portability-and-cross-platform-execution.md @@ -118,8 +118,8 @@ Hardware differences: The graphics system: - produces typed logical render submissions that render to RGBA8888 output -- may consume Game submissions through a render worker that publishes owned - `OwnedRgba8888Frame` values +- consumes Game submissions through either a local synchronous consumer or a + render worker, both of which publish owned `OwnedRgba8888Frame` values - uses an indexed palette - does not depend on a specific GPU @@ -128,8 +128,8 @@ The platform layer: - exposes typed service facades for render submission, render backend execution, Game 2D composition, input, audio, assets, and telemetry - consumes closed render submissions through a render-surface implementation -- transports published RGBA8888 output or worker-published - `OwnedRgba8888Frame` pixels into a host presentation surface without +- transports published `OwnedRgba8888Frame` pixels into a host presentation + surface without injecting host-owned debug overlay pixels - is the runtime-facing portability boundary; runtime and firmware code must not depend on a monolithic hardware bridge or on a concrete hardware aggregate @@ -216,3 +216,72 @@ PROMETEU promises: - **identical logical behavior** - **reproducible technical decisions** + +## 13 Deterministic Headless Control + +The headless host is a separate, generic Prometeu host for in-process +automation. It runs the same directory cartridge, firmware, active VM session, +capability checks, normalized input, render submissions, and fault model as an +interactive host. A cartridge cannot detect or request headless execution, and +headless execution grants no additional guest capability. + +The headless host requires no native window, display server, physical input, +physical audio device, or realtime frame pacing. It uses the explicit local +synchronous Game render consumer. A successful logical-frame advance returns +only after the exact canonical `OwnedRgba8888Frame` for that advance has been +published. It does not start or wait for an asynchronous render worker, and +publication correctness does not use spinning, yielding, sleeping, or a +wall-clock timeout. + +### 13.1 Control contract + +- `boot(path)` loads a normal directory cartridge and stops on entry to + `GameRunning`, before the first game instruction. A second boot attempt + requires `reset()` and otherwise returns `AlreadyBooted`. +- `reset()` enters the normal firmware reset boundary and clears input, active + sessions, structured faults, and headless frame correlation. Capture is + unavailable until the new run completes a frame. +- `pause()` and `resume()` control the active VM session. `step()` executes one + VM instruction and finishes paused without reporting a completed logical + frame. +- `set_input()` retains one complete `InputSignals` snapshot, including the + digital pad and touch signal/coordinates. `clear_input()` restores its + default. The normal begin-frame input sampling defined by the input + peripheral derives `pressed`, `released`, `down`, and `hold` state. +- `advance_frame()` advances internal firmware ticks until exactly one logical + frame closes through `FrameSync` or `EndOfRom`, or until a structured fault or + lifecycle termination prevents completion. Internal cycle-slice exhaustion + continues the same frame; it is not itself a frame boundary. +- `advance_frames(n)` is repeated `advance_frame()`. It reports the requested + and completed counts plus completed-all, fault, or termination. Zero is a + no-op; fault or termination preserves partial completed progress. +- A frame advance finishes paused. Guest faults are outcomes represented by + `CrashReport`; host precondition, publication, and safety-limit failures are + host errors. +- `capture_frame()` returns an owned clone of the canonical frame paired with + the latest successful advance. The explicit `{logical_frame_index, FrameId}` + pair is authoritative; no numeric equality or fixed offset is implied. +- `get_state()` classifies execution as running, paused, terminated, or faulted + and exposes the overlapping debugger state. `get_fault()` returns structured + `CrashReport` data rather than requiring log or summary parsing. +- Valid audio commands pass through normal runtime semantics. The headless host + drains them into a null/discard sink; it does not synthesize PCM or require an + output device. + +### 13.2 Deterministic oracle + +Deterministic comparison includes the logical-frame index and paired `FrameId`, +canonical framebuffer pixels (or a stable pixel hash) and dimensions/stride, +guest-visible PC/stack/app state, structured execution status and fault data, +and deterministic counters describing simulated execution. + +The oracle excludes wall-clock or boot-time timestamps, real elapsed duration, +host CPU time, thread-scheduling measurements, presentation cadence, +render-worker timing telemetry, and host-owned identities without simulated +machine meaning. The same cartridge, initial machine state, and per-frame input +timeline must produce the same included observations on independent runs and +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. diff --git a/files/config/runtime-edge-coverage-domains.json b/files/config/runtime-edge-coverage-domains.json index 5398f79..92b2d5a 100644 --- a/files/config/runtime-edge-coverage-domains.json +++ b/files/config/runtime-edge-coverage-domains.json @@ -48,7 +48,12 @@ "host-dependent": { "baseline_percent": 35, "paths": [ - "crates/host/prometeu-host-desktop-winit/src/", + "crates/host/prometeu-host-desktop-winit/src/" + ] + }, + "host/headless": { + "baseline_percent": 80, + "paths": [ "crates/host/prometeu-host-headless/src/" ] }