From d33a7c694173aae8e1ebc3b1c7f5c74cb68c6011 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 00:23:04 -0500 Subject: [PATCH 1/3] Report trusted fixture startup progress Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 1 + crates/cli/src/runner.rs | 103 +++++++-- crates/cli/src/startup_report.rs | 342 +++++++++++++++++++++++++++++ crates/cli/tests/startup_report.rs | 65 ++++++ docs/interfaces.md | 23 ++ 5 files changed, 519 insertions(+), 15 deletions(-) create mode 100644 crates/cli/src/startup_report.rs create mode 100644 crates/cli/tests/startup_report.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index af426af..f0a2179 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ remains unsupported. - Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### Added +- Added opt-in `betterxen run --startup-report ` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255). - Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation. - Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline, diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index 45b2a4a..c2db69c 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -5,7 +5,7 @@ use std::ffi::OsString; use std::fs::{self, File}; use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode, Stdio}; +use std::process::{Child, Command, ExitCode, Stdio}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -16,6 +16,10 @@ use xenora_loader::{ use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; +#[path = "startup_report.rs"] +mod startup_report; +use startup_report::{Events, Journal, Termination}; + const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe"); const WALL_LIMIT: Duration = Duration::from_secs(15); @@ -27,7 +31,7 @@ const TICKET: u64 = 17; const DRAW_RESULT: u64 = 0x42; const EXTENT: [usize; 2] = [4, 3]; const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255]; -const USAGE: &str = "usage: betterxen run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]"; +const USAGE: &str = "usage: betterxen run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report ]"; struct Options { path: PathBuf, @@ -35,6 +39,8 @@ struct Options { worker: bool, trace: bool, hud: bool, + report: Option, + journal: Option, } impl Options { @@ -42,6 +48,8 @@ impl Options { let mut args = args.into_iter(); let mut path = None; let mut max_steps = None; + let mut report = None; + let mut journal = None; let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false); while let Some(arg) = args.next() { match arg.to_str() { @@ -56,6 +64,16 @@ impl Options { .ok_or("--max-steps must be in 1..=10000")?, ); } + Some("--startup-report") if report.is_none() => { + report = Some(PathBuf::from( + args.next().ok_or("missing --startup-report path")?, + )); + } + Some("--startup-journal") if journal.is_none() => { + journal = Some(PathBuf::from( + args.next().ok_or("missing worker journal path")?, + )); + } Some("--experimental") if !experimental => experimental = true, Some("--trace") if !trace => trace = true, Some("--metal-hud") if !hud => hud = true, @@ -66,12 +84,17 @@ impl Options { if !experimental { return Err("run requires --experimental".into()); } + if (worker && report.is_some()) || (!worker && journal.is_some()) { + return Err("invalid startup report option for this process".into()); + } Ok(Self { path: path.ok_or("missing --pe path")?, max_steps: max_steps.unwrap_or(DEFAULT_STEPS), worker, trace, hud, + report, + journal, }) } } @@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } }; let result = if options.worker { - run_worker(&options).map(|()| ExitCode::SUCCESS) + worker_command(&options).map(|()| ExitCode::SUCCESS) } else { launch_worker(&options) }; @@ -99,8 +122,14 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } fn launch_worker(options: &Options) -> Result> { + let journal = options + .report + .as_ref() + .map(|_| Journal::create()) + .transpose()?; let started = Instant::now(); - let mut child = Command::new(std::env::current_exe()?) + let mut command = Command::new(std::env::current_exe()?); + command .args([ "run", "--experimental", @@ -112,29 +141,55 @@ fn launch_worker(options: &Options) -> Result> { .arg(options.max_steps.to_string()) .arg("--pe") .arg(&options.path) - .stdin(Stdio::null()) - .spawn()?; + .stdin(Stdio::null()); + if let Some(journal) = &journal { + command.arg("--startup-journal").arg(journal.path()); + } + let termination = command + .spawn() + .and_then(|child| supervise(child, started, WALL_LIMIT)); + if let (Some(journal), Some(path)) = (&journal, &options.report) { + journal + .finish(path, &termination) + .map_err(|error| format!("could not write startup report: {error}"))?; + } + match termination? { + Termination::Exited(status) => match status.code() { + Some(code) => Ok(ExitCode::from(u8::try_from(code)?)), + None => Err(format!("worker terminated: {status}").into()), + }, + Termination::Deadline => { + Err("experimental worker exceeded its 15 second wall deadline".into()) + } + } +} + +fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result { loop { match child.try_wait() { - Ok(Some(status)) => { - return match status.code() { - Some(code) => Ok(ExitCode::from(u8::try_from(code)?)), - None => Err(format!("worker terminated: {status}").into()), - }; - } - Ok(None) if started.elapsed() < WALL_LIMIT => { + Ok(Some(status)) => return Ok(Termination::Exited(status)), + Ok(None) if started.elapsed() < limit => { std::thread::sleep(Duration::from_millis(10)); } status => { let _ = child.kill(); child.wait()?; status?; - return Err("experimental worker exceeded its 15 second wall deadline".into()); + return Ok(Termination::Deadline); } } } } +fn worker_command(options: &Options) -> Result<(), Box> { + let mut events = options.journal.as_deref().map(Events::open).transpose()?; + let result = run_worker(options, events.as_mut()); + if let (Some(events), Err(error)) = (events.as_mut(), &result) { + events.failure(error.as_ref()); + } + result +} + fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { let valid_metadata = |metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64; @@ -158,7 +213,7 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { .ok_or_else(|| rejection.into()) } -fn run_worker(options: &Options) -> Result<(), Box> { +fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box> { std::thread::Builder::new() .name("xenora-deadline".into()) .spawn(|| { @@ -232,6 +287,16 @@ fn run_worker(options: &Options) -> Result<(), Box> { imports, options.max_steps, |event| { + if let Some(events) = events.as_deref_mut() { + events.stage(match &event { + StartupEvent::Parsed { .. } => "parsed", + StartupEvent::Mapped { .. } => "mapped", + StartupEvent::Relocated { .. } => "relocated", + StartupEvent::ImportsBound { .. } => "imports_bound", + StartupEvent::TlsCompleted { .. } => "tls_completed", + StartupEvent::Entering { .. } => "entry", + }); + } if options.trace { trace_startup(event); } @@ -244,6 +309,11 @@ fn run_worker(options: &Options) -> Result<(), Box> { .take(); let exit = startup.execution.exit_reason; let rax = startup.execution.final_state.get(Register::Rax); + if exit == ExitReason::Halt + && let Some(events) = events.as_deref_mut() + { + events.stage("exit"); + } if options.trace { println!( "trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}", @@ -264,6 +334,9 @@ fn run_worker(options: &Options) -> Result<(), Box> { return Err("trusted fixture startup or result differs from the expected values".into()); } let frame = result.ok_or("guest halted without a draw")??; + if let Some(events) = events { + events.stage("framebuffer"); + } if options.trace { println!( "trace stage=framebuffer extent={}x{} verified_pixels={}", diff --git a/crates/cli/src/startup_report.rs b/crates/cli/src/startup_report.rs new file mode 100644 index 0000000..960ee5e --- /dev/null +++ b/crates/cli/src/startup_report.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::fmt::Write as _; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::process::ExitStatus; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const VERSION: &str = "1"; +const RECORD_SEPARATOR: char = '\t'; +const MAX_BYTES: usize = 8192; +const MAX_ERROR_BYTES: usize = 2048; +const STAGES: [&str; 8] = [ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", + "exit", + "framebuffer", +]; + +pub(super) struct Journal(PathBuf); + +impl Journal { + pub(super) fn create() -> io::Result { + static NEXT: AtomicUsize = AtomicUsize::new(0); + loop { + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let directory = + std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id())); + match fs::DirBuilder::new().mode(0o700).create(&directory) { + Ok(()) => return Ok(Self(directory)), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + } + + pub(super) fn path(&self) -> PathBuf { + self.0.join("events") + } + + fn read(&self) -> Report { + let mut bytes = Vec::new(); + match File::open(self.path()) + .and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes)) + { + Ok(_) => Report::parse(&bytes), + Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(), + Err(_) => Report { + integrity: "unreadable", + ..Report::default() + }, + } + } + + pub(super) fn finish( + &self, + path: &Path, + termination: &io::Result, + ) -> io::Result<()> { + let report = self.read().json(termination); + OpenOptions::new() + .write(true) + .create_new(true) + .open(path)? + .write_all(report.as_bytes()) + } +} + +impl Drop for Journal { + fn drop(&mut self) { + let _ = fs::remove_file(self.path()); + let _ = fs::remove_dir(&self.0); + } +} + +pub(super) struct Events(File); + +impl Events { + pub(super) fn open(path: &Path) -> io::Result { + OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map(Self) + } + + pub(super) fn stage(&mut self, stage: &str) { + let _ = writeln!(self.0, "{VERSION}\t{stage}"); + } + + pub(super) fn failure(&mut self, error: &dyn std::error::Error) { + let message = error.to_string(); + let end = message.floor_char_boundary(MAX_ERROR_BYTES); + let mut encoded = String::with_capacity(end * 2); + for byte in message[..end].bytes() { + write!(encoded, "{byte:02x}").unwrap(); + } + let _ = writeln!( + self.0, + "{VERSION}\tfailure\t{}\t{encoded}", + u8::from(end < message.len()) + ); + } +} + +pub(super) enum Termination { + Exited(ExitStatus), + Deadline, +} + +struct Report { + completed: usize, + error: Option, + error_truncated: bool, + integrity: &'static str, +} + +impl Default for Report { + fn default() -> Self { + Self { + completed: 0, + error: None, + error_truncated: false, + integrity: "complete", + } + } +} + +impl Report { + fn parse(bytes: &[u8]) -> Self { + let mut report = Self::default(); + let bounded = &bytes[..bytes.len().min(MAX_BYTES)]; + for line in bounded.split_inclusive(|&byte| byte == b'\n') { + let Some(line) = line.strip_suffix(b"\n") else { + report.integrity = "truncated"; + break; + }; + if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) { + report.integrity = "malformed"; + break; + } + } + if bytes.len() > MAX_BYTES { + report.integrity = "oversized"; + } + report + } + + fn record(&mut self, line: &str) -> bool { + let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else { + return false; + }; + if self.error.is_some() || self.completed == STAGES.len() { + return false; + } + if STAGES.get(self.completed) == Some(&record) { + self.completed += 1; + return true; + } + let Some((truncated, encoded)) = record + .strip_prefix("failure\t") + .and_then(|s| s.split_once('\t')) + else { + return false; + }; + if !matches!(truncated, "0" | "1") + || encoded.len() > MAX_ERROR_BYTES * 2 + || !encoded.len().is_multiple_of(2) + || !encoded.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return false; + } + let (pairs, _) = encoded.as_bytes().as_chunks::<2>(); + let Some(message) = pairs + .iter() + .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()) + .collect::>>() + .and_then(|bytes| String::from_utf8(bytes).ok()) + else { + return false; + }; + self.error = Some(message); + self.error_truncated = truncated == "1"; + true + } + + fn json(&self, termination: &io::Result) -> String { + let (outcome, status, detail) = match termination { + Ok(Termination::Deadline) => ( + "timeout", + None, + Some("worker exceeded the wall deadline".into()), + ), + Err(error) => ("unknown", None, Some(error.to_string())), + Ok(Termination::Exited(status)) if status.code() == Some(124) => ( + "timeout", + Some(status), + Some("worker watchdog expired".into()), + ), + Ok(Termination::Exited(status)) + if status.success() + && self.completed == STAGES.len() + && self.integrity == "complete" => + { + ("verified", Some(status), None) + } + Ok(Termination::Exited(status)) if !status.success() && self.error.is_some() => { + ("stage_failure", Some(status), None) + } + Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => { + ("early_exit", Some(status), Some(status.to_string())) + } + Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())), + }; + let stages = &STAGES[..self.completed]; + let records = stages + .iter() + .map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#)) + .collect::>() + .join(","); + let last = json_string(stages.last().copied()); + let error = json_string(self.error.as_deref()); + let detail = json_string(detail.as_deref()); + let code = status + .and_then(|status| status.code()) + .map_or("null".into(), |code| code.to_string()); + format!( + "{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n", + self.integrity, self.error_truncated + ) + } +} + +fn json_string(value: Option<&str>) -> String { + let Some(value) = value else { + return String::from("null"); + }; + let mut escaped = String::from("\""); + for ch in value.chars() { + match ch { + '"' => escaped.push_str("\\\""), + '\\' => escaped.push_str("\\\\"), + '\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(), + _ => escaped.push(ch), + } + } + escaped.push('"'); + escaped +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + use std::time::{Duration, Instant}; + + #[test] + fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() { + for (script, limit, outcome, code) in [ + ("exit 9", Duration::from_secs(2), "early_exit", "9"), + ("exit 124", Duration::from_secs(2), "timeout", "124"), + ("kill -TERM $$", Duration::from_secs(2), "unknown", "null"), + ( + "exec sleep 5", + Duration::from_millis(250), + "timeout", + "null", + ), + ] { + let journal = Journal::create().unwrap(); + let started = Instant::now(); + let child = Command::new("/bin/sh") + .args([ + "-c", + &format!("printf '1\\tparsed\\n' > \"$1\"; {script}"), + "worker", + ]) + .arg(journal.path()) + .spawn() + .unwrap(); + let termination = super::super::supervise(child, started, limit); + let report = journal.read().json(&termination); + assert!( + report.contains(&format!(r#""outcome":"{outcome}""#)), + "{report}" + ); + assert!( + report.contains(&format!(r#""worker_exit_code":{code}"#)), + "{report}" + ); + assert!( + report.contains(r#""last_completed_stage":"parsed""#), + "{report}" + ); + } + } + + #[test] + fn invalid_records_keep_only_the_valid_prefix() { + let mut oversized = b"1\tparsed\n1\tmapped".to_vec(); + oversized.resize(MAX_BYTES + 1, b'x'); + for (bytes, integrity) in [ + (&b"1\tparsed\n1\tmapped"[..], "truncated"), + (&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"), + (&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"), + (oversized.as_slice(), "oversized"), + ] { + let journal = Journal::create().unwrap(); + fs::write(journal.path(), bytes).unwrap(); + let report = journal.read(); + assert_eq!(report.completed, 1); + assert_eq!(report.integrity, integrity); + assert!(report.error.is_none()); + } + } + + #[test] + fn failure_preserves_original_context_with_bounded_utf8() { + let journal = Journal::create().unwrap(); + let mut events = Events::open(&journal.path()).unwrap(); + events.stage("parsed"); + let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES)); + events.failure(&io::Error::other(&message[..])); + let report = journal.read(); + assert_eq!( + report.error.as_deref(), + Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)]) + ); + assert!(report.error_truncated); + let json = report.json(&Ok(Termination::Deadline)); + assert!( + json.contains(r#"line\u000awith \"quote\" and \\"#), + "{json}" + ); + } +} diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs new file mode 100644 index 0000000..058f902 --- /dev/null +++ b/crates/cli/tests/startup_report.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::process::Command; + +#[test] +fn trusted_fixture_reports_verified_progress_and_step_failure() { + let folder = std::env::temp_dir().join(format!("betterxen-report-test-{}", std::process::id())); + std::fs::create_dir(&folder).unwrap(); + let fixture = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/pe/trusted-runner.exe" + ); + for (steps, outcome, last, success) in [ + ("100", "verified", "framebuffer", true), + ("1", "stage_failure", "entry", false), + ] { + let path = folder.join(steps); + let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + fixture, + "--max-steps", + steps, + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let report = std::fs::read_to_string(&path); + assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); + let report = report.unwrap(); + assert!( + report.contains(&format!(r#""outcome":"{outcome}""#)), + "{report}" + ); + assert!( + report.contains(&format!(r#""last_completed_stage":"{last}""#)), + "{report}" + ); + assert!(report.contains(r#""schema_version":1"#), "{report}"); + let mut remaining = report.as_str(); + for stage in [ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", + ] { + remaining = remaining + .split_once(&format!(r#""stage":"{stage}""#)) + .unwrap() + .1; + } + if success { + assert!(remaining.contains(r#""stage":"exit""#)); + assert!(remaining.contains(r#""stage":"framebuffer""#)); + } else { + assert!(report.contains("step budget exhausted"), "{report}"); + } + } + std::fs::remove_dir_all(folder).unwrap(); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index bee1b6a..7e0990e 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -141,6 +141,29 @@ pages count toward the 256 MiB mapping budget of one image, which is checked before anything is mapped. `ParsedPe::parse` does not make these checks, so static inspection of a file is unchanged. +`betterxen run --experimental --pe --startup-report ` +writes a versioned JSON summary after the worker stops. The path must be new. +The report is optional and uses the same exact-byte fixture admission, startup +observer and wall deadline as an ordinary run. + +Schema version 1 lists the observed stages in order in `stages` and copies +the last valid stage to `last_completed_stage` (null if none). The order is +`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`, +`exit`, and `framebuffer`. `entry` records the handoff to guest entry. +`exit` records the fixture halt, and `framebuffer` records verification of its +offscreen readback. The supervisor reports an `outcome` of `verified`, +`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the +worker exit code when available, termination detail when applicable, and the +original reported error when available. Errors are capped at 2 KiB of UTF-8 +and carry an `error_truncated` flag. + +The supervisor reads at most 8 KiB plus one byte from the worker journal. +`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized` +or `unreadable`. Only the valid ordered prefix counts toward progress. A +complete journal may still contain only a partial startup if the worker +stopped between records. These records describe runtime observations from +the trusted fixtures. + `betterxen probe --mode static` inventories ordinary and delay-loaded PE imports without guest execution. Without `--report` it writes to `diagnostics/probe`, where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys From e4ddb05a1a0ce5d7c9b282d011594c2459dbb1b1 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 00:27:42 -0500 Subject: [PATCH 2/3] Run startup draw check on native Metal hardware Signed-off-by: Adeeb Rahman --- crates/cli/tests/startup_report.rs | 122 ++++++++++++++++------------- 1 file changed, 68 insertions(+), 54 deletions(-) diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs index 058f902..983c21c 100644 --- a/crates/cli/tests/startup_report.rs +++ b/crates/cli/tests/startup_report.rs @@ -2,64 +2,78 @@ use std::process::Command; +const STARTUP_STAGES: &[&str] = &[ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", +]; + #[test] -fn trusted_fixture_reports_verified_progress_and_step_failure() { - let folder = std::env::temp_dir().join(format!("betterxen-report-test-{}", std::process::id())); - std::fs::create_dir(&folder).unwrap(); +fn trusted_fixture_preserves_step_failure() { + let report = run_fixture("1", false); + assert!(report.contains(r#""outcome":"stage_failure""#), "{report}"); + assert!( + report.contains(r#""last_completed_stage":"entry""#), + "{report}" + ); + assert!(report.contains("step budget exhausted"), "{report}"); + assert_stages(&report, STARTUP_STAGES); + assert!(!report.contains(r#""stage":"exit""#), "{report}"); +} + +#[test] +#[ignore = "requires a native Metal device with Apple family 7 capabilities"] +fn trusted_fixture_reports_verified_progress() { + let report = run_fixture("100", true); + assert!(report.contains(r#""outcome":"verified""#), "{report}"); + assert!( + report.contains(r#""last_completed_stage":"framebuffer""#), + "{report}" + ); + let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat(); + assert_stages(&report, &stages); +} + +fn run_fixture(steps: &str, success: bool) -> String { + let path = std::env::temp_dir().join(format!( + "betterxen-report-test-{}-{steps}.json", + std::process::id() + )); let fixture = concat!( env!("CARGO_MANIFEST_DIR"), "/../../fixtures/pe/trusted-runner.exe" ); - for (steps, outcome, last, success) in [ - ("100", "verified", "framebuffer", true), - ("1", "stage_failure", "entry", false), - ] { - let path = folder.join(steps); - let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) - .args([ - "run", - "--experimental", - "--pe", - fixture, - "--max-steps", - steps, - "--startup-report", - ]) - .arg(&path) - .output() - .unwrap(); - let report = std::fs::read_to_string(&path); - assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); - let report = report.unwrap(); - assert!( - report.contains(&format!(r#""outcome":"{outcome}""#)), - "{report}" - ); - assert!( - report.contains(&format!(r#""last_completed_stage":"{last}""#)), - "{report}" - ); - assert!(report.contains(r#""schema_version":1"#), "{report}"); - let mut remaining = report.as_str(); - for stage in [ - "parsed", - "mapped", - "relocated", - "imports_bound", - "tls_completed", - "entry", - ] { - remaining = remaining - .split_once(&format!(r#""stage":"{stage}""#)) - .unwrap() - .1; - } - if success { - assert!(remaining.contains(r#""stage":"exit""#)); - assert!(remaining.contains(r#""stage":"framebuffer""#)); - } else { - assert!(report.contains("step budget exhausted"), "{report}"); - } + let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + fixture, + "--max-steps", + steps, + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let report = std::fs::read_to_string(&path); + if report.is_ok() { + std::fs::remove_file(&path).unwrap(); + } + assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); + report.unwrap() +} + +fn assert_stages(report: &str, stages: &[&str]) { + assert!(report.contains(r#""schema_version":1"#), "{report}"); + let mut remaining = report; + for stage in stages { + remaining = remaining + .split_once(&format!(r#""stage":"{stage}""#)) + .unwrap() + .1; } - std::fs::remove_dir_all(folder).unwrap(); } From 8d2662dcd7be868ad6d3720680a9581f370630d4 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 09:56:31 -0500 Subject: [PATCH 3/3] Preserve startup report delivery and worker errors Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 1 + crates/cli/src/runner.rs | 58 ++++++++++++++----- crates/cli/src/startup_report.rs | 91 ++++++++++++++++++++++++------ crates/cli/tests/startup_report.rs | 30 ++++++++++ docs/interfaces.md | 8 ++- 5 files changed, 154 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35eefcd..ef49423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Fixed +- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination. - Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command. - DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported. - Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version. diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index c2db69c..0c02761 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -2,7 +2,7 @@ use std::error::Error; use std::ffi::OsString; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitCode, Stdio}; @@ -18,7 +18,7 @@ use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile #[path = "startup_report.rs"] mod startup_report; -use startup_report::{Events, Journal, Termination}; +use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe"); @@ -108,7 +108,7 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } }; let result = if options.worker { - worker_command(&options).map(|()| ExitCode::SUCCESS) + worker_command(&options) } else { launch_worker(&options) }; @@ -127,8 +127,20 @@ fn launch_worker(options: &Options) -> Result> { .as_ref() .map(|_| Journal::create()) .transpose()?; + let executable = std::env::current_exe()?; + let destination = options + .report + .as_ref() + .map(|path| { + OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| format!("could not create startup report: {error}")) + }) + .transpose()?; let started = Instant::now(); - let mut command = Command::new(std::env::current_exe()?); + let mut command = Command::new(executable); command .args([ "run", @@ -148,10 +160,13 @@ fn launch_worker(options: &Options) -> Result> { let termination = command .spawn() .and_then(|child| supervise(child, started, WALL_LIMIT)); - if let (Some(journal), Some(path)) = (&journal, &options.report) { - journal - .finish(path, &termination) - .map_err(|error| format!("could not write startup report: {error}"))?; + if let (Some(journal), Some(destination)) = (&journal, destination) + && let Err(error) = journal.finish(destination, &termination) + { + eprintln!("could not write startup report: {error}"); + if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) { + return Ok(ExitCode::FAILURE); + } } match termination? { Termination::Exited(status) => match status.code() { @@ -181,13 +196,28 @@ fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Re } } -fn worker_command(options: &Options) -> Result<(), Box> { - let mut events = options.journal.as_deref().map(Events::open).transpose()?; +fn worker_command(options: &Options) -> Result> { + let mut events = match options.journal.as_deref().map(Events::open).transpose() { + Ok(events) => events, + Err(error) => { + eprintln!("could not open startup journal: {error}"); + return Ok(ExitCode::from(JOURNAL_ERROR_EXIT)); + } + }; let result = run_worker(options, events.as_mut()); - if let (Some(events), Err(error)) = (events.as_mut(), &result) { - events.failure(error.as_ref()); + if let Some(events) = events.as_mut() { + if let Err(error) = &result { + events.failure(error.as_ref()); + } + if let Some(error) = events.write_error() { + if let Err(error) = result { + eprintln!("run failed: {error}"); + } + eprintln!("could not write startup journal: {error}"); + return Ok(ExitCode::from(JOURNAL_ERROR_EXIT)); + } } - result + result.map(|()| ExitCode::SUCCESS) } fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { @@ -220,7 +250,7 @@ fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), std::thread::sleep(WALL_LIMIT); // The supervisor also enforces this deadline. The worker retains // its own deadline if it is invoked directly. - std::process::exit(124); + std::process::exit(i32::from(WATCHDOG_EXIT)); })?; let fixture = verify_fixture(&options.path)?; let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE { diff --git a/crates/cli/src/startup_report.rs b/crates/cli/src/startup_report.rs index 960ee5e..7451986 100644 --- a/crates/cli/src/startup_report.rs +++ b/crates/cli/src/startup_report.rs @@ -8,6 +8,8 @@ use std::path::{Path, PathBuf}; use std::process::ExitStatus; use std::sync::atomic::{AtomicUsize, Ordering}; +pub(super) const WATCHDOG_EXIT: u8 = 124; +pub(super) const JOURNAL_ERROR_EXIT: u8 = 125; const VERSION: &str = "1"; const RECORD_SEPARATOR: char = '\t'; const MAX_BYTES: usize = 8192; @@ -60,15 +62,10 @@ impl Journal { pub(super) fn finish( &self, - path: &Path, + mut destination: File, termination: &io::Result, ) -> io::Result<()> { - let report = self.read().json(termination); - OpenOptions::new() - .write(true) - .create_new(true) - .open(path)? - .write_all(report.as_bytes()) + destination.write_all(self.read().json(termination).as_bytes()) } } @@ -79,7 +76,7 @@ impl Drop for Journal { } } -pub(super) struct Events(File); +pub(super) struct Events(File, Option); impl Events { pub(super) fn open(path: &Path) -> io::Result { @@ -87,11 +84,11 @@ impl Events { .write(true) .create_new(true) .open(path) - .map(Self) + .map(|file| Self(file, None)) } pub(super) fn stage(&mut self, stage: &str) { - let _ = writeln!(self.0, "{VERSION}\t{stage}"); + self.record(format_args!("{VERSION}\t{stage}")); } pub(super) fn failure(&mut self, error: &dyn std::error::Error) { @@ -101,11 +98,19 @@ impl Events { for byte in message[..end].bytes() { write!(encoded, "{byte:02x}").unwrap(); } - let _ = writeln!( - self.0, + self.record(format_args!( "{VERSION}\tfailure\t{}\t{encoded}", u8::from(end < message.len()) - ); + )); + } + fn record(&mut self, arguments: std::fmt::Arguments<'_>) { + if self.1.is_none() { + self.1 = writeln!(self.0, "{arguments}").err(); + } + } + + pub(super) fn write_error(&self) -> Option<&io::Error> { + self.1.as_ref() } } @@ -156,7 +161,7 @@ impl Report { let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else { return false; }; - if self.error.is_some() || self.completed == STAGES.len() { + if self.error.is_some() { return false; } if STAGES.get(self.completed) == Some(&record) { @@ -191,6 +196,13 @@ impl Report { } fn json(&self, termination: &io::Result) -> String { + let unwritable = matches!(termination, Ok(Termination::Exited(status)) + if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT))); + let integrity = if unwritable { + "unwritable" + } else { + self.integrity + }; let (outcome, status, detail) = match termination { Ok(Termination::Deadline) => ( "timeout", @@ -198,19 +210,27 @@ impl Report { Some("worker exceeded the wall deadline".into()), ), Err(error) => ("unknown", None, Some(error.to_string())), - Ok(Termination::Exited(status)) if status.code() == Some(124) => ( + Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => ( "timeout", Some(status), Some("worker watchdog expired".into()), ), + Ok(Termination::Exited(status)) if unwritable => ( + "unknown", + Some(status), + Some("worker could not write its startup journal".into()), + ), Ok(Termination::Exited(status)) if status.success() + && self.error.is_none() && self.completed == STAGES.len() && self.integrity == "complete" => { ("verified", Some(status), None) } - Ok(Termination::Exited(status)) if !status.success() && self.error.is_some() => { + Ok(Termination::Exited(status)) + if status.code().is_some() && !status.success() && self.error.is_some() => + { ("stage_failure", Some(status), None) } Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => { @@ -232,7 +252,7 @@ impl Report { .map_or("null".into(), |code| code.to_string()); format!( "{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n", - self.integrity, self.error_truncated + integrity, self.error_truncated ) } } @@ -260,6 +280,43 @@ mod tests { use std::process::Command; use std::time::{Duration, Instant}; + #[test] + fn journal_write_error_surfaces_in_report() { + use std::os::unix::process::ExitStatusExt; + let journal = Journal::create().unwrap(); + fs::write(journal.path(), b"1\tparsed\n").unwrap(); + let mut events = Events(File::open(journal.path()).unwrap(), None); + events.stage("mapped"); + assert!(events.write_error().is_some()); + let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8); + let result = journal.read().json(&Ok(Termination::Exited(status))); + assert!( + result.contains(r#""record_integrity":"unwritable""#), + "{result}" + ); + assert!( + result.contains(r#""last_completed_stage":"parsed""#), + "{result}" + ); + } + + #[test] + fn terminal_failure_keeps_signal_detail_after_all_stages() { + use std::os::unix::process::ExitStatusExt; + let journal = Journal::create().unwrap(); + let mut events = Events::open(&journal.path()).unwrap(); + for stage in STAGES { + events.stage(stage); + } + events.failure(&io::Error::other("late error")); + let report = journal.read(); + assert_eq!(report.integrity, "complete"); + let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15)))); + assert!(result.contains(r#""outcome":"unknown""#), "{result}"); + assert!(result.contains(r#""error":"late error""#), "{result}"); + assert!(result.contains("signal: 15"), "{result}"); + } + #[test] fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() { for (script, limit, outcome, code) in [ diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs index 983c21c..af812cb 100644 --- a/crates/cli/tests/startup_report.rs +++ b/crates/cli/tests/startup_report.rs @@ -77,3 +77,33 @@ fn assert_stages(report: &str, stages: &[&str]) { .1; } } + +#[test] +fn existing_report_path_prevents_worker_launch() { + let path = std::env::temp_dir().join(format!( + "betterxen-report-existing-{}.json", + std::process::id() + )); + std::fs::write(&path, "previous report").unwrap(); + let result = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + "missing-fixture", + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents, "previous report"); + assert!(!result.status.success()); + let stderr = String::from_utf8(result.stderr).unwrap(); + assert!( + stderr.contains("could not create startup report"), + "{stderr}" + ); + assert!(!stderr.contains("No such file or directory"), "{stderr}"); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index 7e0990e..533e053 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -142,7 +142,7 @@ before anything is mapped. `ParsedPe::parse` does not make these checks, so static inspection of a file is unchanged. `betterxen run --experimental --pe --startup-report ` -writes a versioned JSON summary after the worker stops. The path must be new. +writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker. The report is optional and uses the same exact-byte fixture admission, startup observer and wall deadline as an ordinary run. @@ -158,8 +158,10 @@ original reported error when available. Errors are capped at 2 KiB of UTF-8 and carry an `error_truncated` flag. The supervisor reads at most 8 KiB plus one byte from the worker journal. -`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized` -or `unreadable`. Only the valid ordered prefix counts toward progress. A +`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`, +`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for +its watchdog and journal I/O errors, respectively. `--startup-journal` is an +internal worker option. Only the valid ordered prefix counts toward progress. A complete journal may still contain only a partial startup if the worker stopped between records. These records describe runtime observations from the trusted fixtures.