From 8d2662dcd7be868ad6d3720680a9581f370630d4 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 09:56:31 -0500 Subject: [PATCH] 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.