shadow: a live process that leaves no trace fails the verdict; the test builds the flysim it runs

tests/shadow.rs failed with 'one trace file per process' (0 vs 2) on a
build box because it ran a flysim binary that was not built from the
tree under test: cargo test -p fly-legacy-session does not build
flysim's binary, and the box's bx target directory was shared by name
with other trees, so the binary beside the test predated FLY_TRACE_DIR
and wrote no trace. Reproduced by running that test binary against its
stale flysim; not a timing or segment-handling bug. The test now builds
the flysim binary itself (cargo build -p flysim --bin flysim, same
target directory and profile), proved on a target another tree had
populated.

Production could miss a whole process the same way (a trace that
cannot be created, a failed consumer check), so the shadow now holds
every flysim boot header in the live sugar journal since it started to
a trace file created during that boot; an untraced process is a
coverage divergence and fails the verdict. In FLY_TRACE_DIR mode a trace
that cannot be created no longer stops flysim from starting (it runs
untraced and the shadow fails), and a heartbeat dated ahead of the
clock counts as fresh. The test adds an untraced third process and
expects the coverage divergence.
This commit is contained in:
acamilo 2026-09-30 04:57:50 +00:00
parent f7ca35ba2c
commit 0b56e03ae3
5 changed files with 262 additions and 18 deletions

View file

@ -630,6 +630,21 @@ The fixtures were already v8 on main.
- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file
and every newer one, including while the shadow is backed off.
**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not
a timing, load or segment-handling bug.
- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test.
`cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx
target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so
it wrote no trace at all. The failure was reproduced by running such a test binary against its
own stale `flysim`.
- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`,
with the same target directory and profile, which does nothing when the binary is current.
This was proved on a target that another tree's `flysim` had populated.
- *What production could miss, and now cannot.* A live process that runs without a trace is now
a `coverage` divergence (above). That covers a process whose consumer check failed, and one
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.

View file

@ -792,7 +792,14 @@ failure, which is **never** a skip:
- a session that does not start;
- a startup save the candidate's restore gate refuses or the session runtime cannot restore;
- a step, capture or rollback error;
- a transition the session did not record.
- a transition the session did not record;
- *coverage*: a live flysim process that booted while the shadow ran and left no trace
(amended 2026-09-30).
The shadow reads every boot header in the live sugar journal. Every flysim process writes one,
traced or not. It holds each header to a trace file created after the previous boot and before
this one. A process that ran untraced can never be compared, so the verdict fails. It does not
pass on the processes that were traced.
A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference.
@ -802,7 +809,10 @@ make sure of it:
- *The trace is on only while a shadow consumes it.* The shadow writes a heartbeat
(`<trace dir>/consumer`) every 30 s and removes it when it stops. flysim starts no trace without
a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than
10 minutes old, and keeps the directory under 8 GiB.
10 minutes old, and keeps the directory under 8 GiB. A heartbeat dated ahead of flysim's clock
counts as fresh. A trace flysim cannot create (a full disk, the directory's permissions) never
stops the live fly from starting: that process runs untraced, and the shadow reports it as a
coverage divergence.
- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace
before the shadow existed. The live fly does not always keep real time: the release container
has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start`

View file

@ -370,6 +370,57 @@ pub fn parse_lag_seconds(text: &str) -> Option<f64> {
})
}
/// Unix milliseconds now.
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64)
}
/// The start wall ms a trace file's name carries (`trace-<ms>-<pid>.jsonl`).
pub fn trace_start_ms(path: &Path) -> Option<u64> {
path.file_name()?
.to_str()?
.strip_prefix("trace-")?
.split('-')
.next()?
.parse()
.ok()
}
/// The live processes that booted after `since` and have no trace file, in the sugar journal's
/// boot headers (every flysim process writes one, traced or not) against the trace files seen.
/// A process's trace file is created during its boot, after the previous process's boot header
/// and before its own, so each boot owns the trace files started in that interval. Returns the
/// untraced boots' headers; `checked` collects the boots matched, so each is judged once.
pub fn untraced_boots(
boots: &[Value],
traces_seen: &std::collections::BTreeSet<u64>,
since: u64,
checked: &mut std::collections::BTreeSet<u64>,
) -> Vec<Value> {
let mut walls: Vec<(u64, &Value)> = boots
.iter()
.filter(|b| b["runtime"] == "flysim")
.filter_map(|b| Some((b["wallMs"].as_u64()?, b)))
.collect();
walls.sort_by_key(|(w, _)| *w);
walls.dedup_by_key(|(w, _)| *w);
let mut untraced = Vec::new();
let mut previous = 0u64;
for (wall, boot) in walls {
if wall > since && !checked.contains(&wall) {
if traces_seen.range(previous + 1..=wall).next().is_some() {
checked.insert(wall);
} else {
untraced.push(boot.clone());
}
}
previous = wall;
}
untraced
}
/// Writes the heartbeat file (its modification time is what counts).
fn touch(path: &Path) {
if let Err(e) = std::fs::write(path, verdict::now_iso()) {
@ -473,6 +524,10 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
stop,
last_write: Instant::now() - Duration::from_secs(60),
following: None,
started_wall_ms: now_ms(),
traces_seen: Default::default(),
boots_checked: Default::default(),
last_coverage: Instant::now() - Duration::from_secs(60),
};
shadow.write();
let ended = shadow.follow().await;
@ -513,6 +568,12 @@ struct Shadow {
last_write: Instant,
/// The file being compared, the bytes and lines of it compared so far.
following: Option<(PathBuf, u64, u64)>,
/// Coverage: when this shadow started (Unix ms), every trace file it has seen (start ms),
/// the live boots already matched to one, and when it last looked.
started_wall_ms: u64,
traces_seen: std::collections::BTreeSet<u64>,
boots_checked: std::collections::BTreeSet<u64>,
last_coverage: Instant,
}
impl Shadow {
@ -533,6 +594,44 @@ impl Shadow {
self.last_write = Instant::now();
}
/// Every live process since the shadow started must have left a trace: one that ran untraced
/// (its trace could not be created, or its consumer check failed) can never be compared, so
/// it fails the verdict as a `coverage` divergence rather than letting the window pass on the
/// processes that were traced. Looked at every 5 s.
fn coverage(&mut self) -> Option<Divergence> {
if self.last_coverage.elapsed() < Duration::from_secs(5) {
return None;
}
self.last_coverage = Instant::now();
if let Ok(files) = follow::trace_files(&self.config.trace_dir) {
self.traces_seen
.extend(files.iter().filter_map(|f| trace_start_ms(f)));
}
let segments = flysim::journal::read_segments(&self.config.hot_dir).ok()?;
let boots: Vec<Value> = segments.into_iter().filter_map(|s| s.boot).collect();
let untraced = untraced_boots(
&boots,
&self.traces_seen,
self.started_wall_ms,
&mut self.boots_checked,
);
let boot = untraced.first()?;
Some(Divergence {
kind: "coverage".to_owned(),
trace: String::new(),
step: boot["startFrame"].as_str().and_then(|s| s.parse().ok()),
difference: None,
detail: format!(
"a live flysim process booted at {} ({}, frame {}) left no trace while the shadow \
was running: its transitions can never be compared",
verdict::iso(boot["wallMs"].as_i64().unwrap_or(0)),
boot["origin"].as_str().unwrap_or("?"),
boot["startFrame"].as_str().unwrap_or("?"),
),
context: Vec::new(),
})
}
fn write_if_due(&mut self) {
if self.last_write.elapsed() >= Duration::from_secs(5) {
self.write();
@ -587,6 +686,10 @@ impl Shadow {
Ok(None) => {}
Err(e) => return Err(format!("{}: {e}", dir.display())),
}
if let Some(divergence) = self.coverage() {
self.diverged(divergence);
return Ok(Ended::Diverged);
}
self.write_if_due();
tokio::time::sleep(self.config.poll).await;
};
@ -595,6 +698,7 @@ impl Shadow {
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
eprintln!("fly-shadow: following {name}");
self.traces_seen.extend(trace_start_ms(&next));
self.verdict.current_trace = Some(name.clone());
let compared_before = self.verdict.agreement.transitions;
let end = self.segment(&next).await;
@ -659,6 +763,9 @@ impl Shadow {
)),
};
}
if let Some(divergence) = self.coverage() {
return Err(SegmentEnd::Diverged(Box::new(divergence)));
}
self.write_if_due();
tokio::time::sleep(self.config.poll).await;
}
@ -1185,6 +1292,9 @@ impl Shadow {
{
return SegmentEnd::Stop(Ended::Limit);
}
if let Some(divergence) = self.coverage() {
return SegmentEnd::Diverged(Box::new(divergence));
}
self.write_if_due();
}
}
@ -1257,6 +1367,26 @@ mod tests {
assert!(!j.observe(t0 + Duration::from_secs(84), 0.0));
}
#[test]
fn every_boot_after_the_start_owns_a_trace() {
let boot = |wall: u64| serde_json::json!({"runtime": "flysim", "wallMs": wall, "startFrame": "1", "origin": "x"});
let boots = vec![boot(1_000), boot(2_000), boot(3_000), boot(4_000)];
let mut checked = Default::default();
// Traces created during boots 2 and 4 (the one at 1,000 predates the shadow).
let traces: std::collections::BTreeSet<u64> = [1_950, 3_990].into();
let untraced = untraced_boots(&boots, &traces, 1_500, &mut checked);
assert_eq!(untraced.len(), 1);
assert_eq!(untraced[0]["wallMs"], 3_000);
assert_eq!(checked, [2_000u64, 4_000].into());
// A session-runtime boot is not this shadow's to follow; a boot before the start neither.
let other = vec![serde_json::json!({"runtime": "fly-session", "wallMs": 5_000})];
assert!(untraced_boots(&other, &traces, 1_500, &mut checked).is_empty());
assert_eq!(
trace_start_ms(Path::new("/x/trace-0001790741297310-444741.jsonl")),
Some(1_790_741_297_310)
);
}
#[test]
fn capture_ids() {
assert_eq!(

View file

@ -25,11 +25,45 @@ use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use flysim::snapshot::MacroMode;
/// The `flysim` binary built from *this* tree, in this test's own target directory and profile.
///
/// `cargo test -p fly-legacy-session` does not build `flysim`'s binary, so a binary found beside the
/// test can be stale -- built from another tree that shared the target directory -- and a stale
/// flysim that predates `FLY_TRACE_DIR` writes no trace at all (the "one trace file per process"
/// failure, 0 files, seen on a build box whose target directory other trees shared). So the test
/// builds it: `cargo build -p flysim --bin flysim` with the same target directory, profile and
/// flags, a no-op when it is current. `None` (skip) only when cargo is not reachable.
fn flysim_binary() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
let release = exe.parent()?.parent()?;
let path = release.join("flysim");
path.is_file().then_some(path)
let profile_dir = exe.parent()?.parent()?; // <target>/<profile>/deps/<test>
let target = profile_dir.parent()?;
let release = profile_dir.file_name()? == "release";
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let mut build = Command::new(cargo);
build
.args(["build", "-p", "flysim", "--bin", "flysim"])
.env("CARGO_TARGET_DIR", target)
.current_dir(env!("CARGO_MANIFEST_DIR"));
if release {
build.arg("--release");
}
match build.status() {
Ok(status) => assert!(
status.success(),
"building the flysim binary under test failed"
),
Err(e) => {
eprintln!("skipping: cargo is not reachable to build flysim ({e})");
return None;
}
}
let path = profile_dir.join("flysim");
assert!(
path.is_file(),
"no flysim binary at {} after the build",
path.display()
);
Some(path)
}
fn free_port() -> u16 {
@ -72,6 +106,17 @@ struct LiveDirs {
}
fn start_live(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path) -> Live {
start_live_traced(binary, rom, dirs, log, true)
}
/// `traced = false` starts the service with no `FLY_TRACE_DIR`: a live process that leaves no
/// trace, as one whose trace cannot be created would.
fn start_live_traced(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path, traced: bool) -> Live {
let trace_dir = if traced {
dirs.trace.clone()
} else {
PathBuf::new()
};
let control = free_port();
let child = Command::new(binary)
.env("FLY_ROM", rom)
@ -88,7 +133,7 @@ fn start_live(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path) -> Live {
.env("FLYSIM_LOOP_HOT_SECONDS", "1")
.env("FLYSIM_LOOP_CHECKPOINT_SECONDS", "4")
.env("RAYON_NUM_THREADS", "1")
.env("FLY_TRACE_DIR", &dirs.trace)
.env("FLY_TRACE_DIR", &trace_dir)
.env("FLY_TRACE_LEDGERS", "1")
.env_remove("FLY_TRACE")
.env_remove("NOTIFY_SOCKET")
@ -330,7 +375,13 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
live.stop();
let files = transitions(&dirs.trace);
assert_eq!(files.len(), 2, "one trace file per process");
assert_eq!(
files.len(),
2,
"one trace file per process; the shadow's verdict: {}; divergence: {}",
verdict_of(&out),
std::fs::read_to_string(out.join("divergence.json")).unwrap_or_default()
);
let total: usize = files.iter().map(|(_, n)| n).sum();
let deadline = Instant::now() + Duration::from_secs(600);
loop {
@ -344,20 +395,43 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
);
std::thread::sleep(Duration::from_millis(200));
}
stop.request();
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
let v = verdict_of(&out);
let passed = verdict_of(&out);
eprintln!(
"shadow: {ended:?} {}",
serde_json::to_string_pretty(&v).unwrap()
"shadow after both processes: {}",
serde_json::to_string_pretty(&passed).unwrap()
);
assert_eq!(ended, Ended::Stopped);
assert!(verdict.divergence.is_none());
assert_eq!(
verdict.status,
Status::Pass,
passed["status"], "pass",
"40 brain seconds against a 30 s window"
);
assert!(passed["firstDivergence"].is_null());
// Process three runs untraced while the shadow follows: it can never be compared, so the
// shadow must fail its verdict (coverage), not keep a pass built on the traced processes.
let live = start_live_traced(&binary, &rom, &dirs, &root.join("flysim-3.log"), false);
live.run_for(3_000.0);
live.stop();
let deadline = Instant::now() + Duration::from_secs(120);
while !handle.is_finished() {
if Instant::now() > deadline {
stop.request();
}
std::thread::sleep(Duration::from_millis(200));
}
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
assert_eq!(
ended,
Ended::Diverged,
"an untraced live process fails the verdict"
);
let coverage = verdict.divergence.as_ref().expect("a divergence");
assert_eq!(coverage.kind, "coverage", "{}", coverage.detail);
assert_eq!(verdict.status, Status::Diverged);
assert_eq!(
transitions(&dirs.trace).len(),
2,
"process three left no trace"
);
assert_eq!(verdict.agreement.transitions, total as u64);
assert_eq!(verdict.segments_compared, 2);
assert!(verdict.skipped.is_empty(), "{:?}", verdict.skipped);

View file

@ -101,7 +101,12 @@ pub fn consumer_alive(dir: &Path, stale: std::time::Duration) -> bool {
std::fs::metadata(dir.join(CONSUMER_FILE))
.and_then(|m| m.modified())
.ok()
.and_then(|t| std::time::SystemTime::now().duration_since(t).ok())
// A heartbeat dated ahead of this clock (a clock stepped back) is fresh, not missing.
.map(|t| {
std::time::SystemTime::now()
.duration_since(t)
.unwrap_or_default()
})
.is_some_and(|age| age <= stale)
}
@ -285,7 +290,17 @@ impl FrameTrace {
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64);
let path = dir.join(dir_file_name(wall_ms, std::process::id()));
let mut trace = Self::create_with(&path, Some(cap), ledgers_every)?;
// A trace the live service cannot create (a full disk, a missing directory, its
// permissions) never stops the live fly from starting: it runs untraced, and the
// shadow, which checks every boot header in the sugar journal against the trace
// files, reports that process as a coverage gap and fails its verdict.
let mut trace = match Self::create_with(&path, Some(cap), ledgers_every) {
Ok(trace) => trace,
Err(error) => {
tracing::error!(%error, path = %path.display(), "could not create the frame trace: this run is untraced");
return Ok(None);
}
};
trace.consumer = Some((dir.to_owned(), stale));
return Ok(Some(trace));
}