From ff67e6cdd66109db32108664f6a05370743136a2 Mon Sep 17 00:00:00 2001 From: acamilo Date: Thu, 1 Oct 2026 03:49:18 +0000 Subject: [PATCH] shadow: a trace stop ends the verdict's window; a pass counts only brain time after the last coverage gap (SHADOW-02 review B2) A stopped trace (no consumer, byte cap) is no longer an allowed skip: the shadow drops the brain time and saves compared before it, so a restarted box shadow that replays a stopped trace cannot count pre-gap time. The relay closes coverageLost only when the verdict's window.lastStopTrace is the lost trace or later, persists coverageLost (fsync) before forwarding the stop, and check refuses a verdict without a window. Runbook: a mid-run relay restart costs the run. --- .../session-framework/implementation.md | 2 +- .../session-framework/legacy-gameboy-v1.md | 4 +- infra/bin/fly-shadow-run | 2 + infra/docs/runbook.md | 14 ++- infra/tests/lint.sh | 5 +- .../fly-legacy-session/src/shadow/mod.rs | 14 +++ .../fly-legacy-session/src/shadow/relay.rs | 58 +++++++-- .../fly-legacy-session/src/shadow/verdict.rs | 118 +++++++++++++++++- .../tests/shadow_relay_coverage.rs | 17 ++- .../fly-legacy-session/tests/shadow_remote.rs | 33 ++++- 10 files changed, 237 insertions(+), 30 deletions(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index f50a2eb..b303e63 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -726,7 +726,7 @@ back to 0.999-1.0 the moment the shadow was stopped. **Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow: a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops -the heartbeat and flysim's trace, and the new shadow skips that stop as history (`trace-cap`) and +the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index eff1fd4..9a6d8e5 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -800,7 +800,6 @@ several processes. - `startup-save-gone`: a process whose startup save was already gone when the shadow reached it, because the shadow started late or its spool evicted the file; - `operator-reward-pulse`; -- `trace-cap`: the live trace stopped at its byte cap, or with no consumer; - `no-transition`: a process that ran none. A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which @@ -919,7 +918,8 @@ verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`). (`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage` divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow - started is history and stays a `trace-cap` skip, and the byte cap stays a skip. The coverage + started, and the byte cap, end the verdict's window instead (`window.ends`): what was compared + before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). The coverage check reads the sugar journal before it lists the trace directory (a process creates its trace file before it writes its boot header, so a boot between the two reads could look untraced the other way round). diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run index 1fb8470..4635e39 100755 --- a/infra/bin/fly-shadow-run +++ b/infra/bin/fly-shadow-run @@ -531,6 +531,8 @@ if r.get("runId") != run_id: refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id)) if v.get("runId") != run_id: refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id)) +if v.get("window") is None: + refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted") if r.get("coverageLost"): refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"])) if not r.get("healthy"): diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 1e4e7fe..d232114 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -621,8 +621,18 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in `/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses - until the box's shadow reaches the stop and diverges (`coverage`), or restarts (a new window, - which treats the stop as history). Catching up never clears it. + until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that + stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage + gap, never a skip. The shadow discards the brain time and saves compared before it + (`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the + last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops + the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while + `coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or + a later one) and for a verdict without a `window`. Catching up and restarting never clear it. + **Never restart the relay (`systemctl restart flyshadow`) mid-run**: its stop removes the + heartbeat, flysim stops tracing within a minute, and that costs the run (a coverage loss: safe, + and the run starts over). `coverageLost` is synced to disk before the chunk with the stop is + forwarded. - **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network: diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 466f717..cc2a776 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -750,7 +750,7 @@ if command -v python3 >/dev/null 2>&1; then local rc=0 out dropin_dir="$rc_tmp/flyshadow.d" rm -f "$rc_tmp/shadow/relay.json" [ "$3" = none ] || printf '%s\n' "$3" > "$rc_tmp/shadow/relay.json" - printf '%s\n' "${4:-{\"runId\":\"1790000000000\",\"status\":\"running\"\}}" > "$rc_tmp/shadow/verdict.json" + printf '%s\n' "${4:-{\"runId\":\"1790000000000\",\"status\":\"running\",\"window\":{\"lastStopTrace\":null\}\}}" > "$rc_tmp/shadow/verdict.json" [ "${5:-}" = local ] && dropin_dir="$rc_tmp/none.d" out="$(PATH="$rc_tmp/bin:$PATH" FLY_SHADOW_DIR="$rc_tmp/shadow" FLY_SHADOW_BIN="$rc_tmp/none" \ FLY_SHADOW_REMOTE_DROPIN_DIR="$dropin_dir" "$INFRA_DIR/bin/fly-shadow-run" check 2>&1)" || rc=$? @@ -772,6 +772,9 @@ if command -v python3 >/dev/null 2>&1; then rc_check "live trace not written for 5 minutes" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":300}" rc_check "no live trace file" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":null}" rc_check "relay.json of another run" refused "{\"updatedAt\":\"$now\",\"runId\":\"1789999999999\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":12}" + # B2: a verdict that does not carry its window (an older shadow) may count time before a gap. + rc_check "a verdict without a window (B2)" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}" + rc_check "a verdict with a window, after a stop (B2)" passes-gates "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\",\"window\":{\"lastStopTrace\":\"trace-1790000005000-4242.jsonl\"}}" rc_check "verdict of another run" refused "{$good}" "{\"runId\":\"1789999999999\",\"status\":\"pass\"}" rc_check "a local run's verdict (no run id) in remote mode" refused "{$good}" "{\"runId\":null,\"status\":\"pass\"}" rc_check "a remote verdict without a remote drop-in" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}" local diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs index 156cb02..a5a95bc 100644 --- a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs +++ b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs @@ -525,6 +525,8 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict checkpoints: Checkpoints::default(), segments_compared: 0, skipped: Vec::new(), + window_ends: Vec::new(), + last_stop_trace: None, divergence: None, started_at: verdict::now_iso(), passed_at: None, @@ -774,6 +776,18 @@ impl Shadow { let _ = std::fs::remove_file(&next); } } + SegmentEnd::Skipped("trace-cap", reason) => { + // A stopped trace is a coverage gap: what was compared before it stops + // counting (SHADOW-02 B2). + eprintln!( + "fly-shadow: {name} stopped after {compared} transitions: {reason}; the \ + window restarts after it" + ); + self.verdict.end_window(&name, reason); + if !self.config.keep_traces { + let _ = std::fs::remove_file(&next); + } + } SegmentEnd::Skipped(kind, reason) => { eprintln!( "fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}" diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs b/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs index b9adeb8..30da169 100644 --- a/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs +++ b/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs @@ -48,9 +48,11 @@ //! once the link is back. The relay therefore scans the trace bytes it forwards for that marker; //! on finding it, it sets `coverageLost` in `relay.json` (sticky, also across a relay restart of the //! same run) and reports itself unhealthy, which stops the heartbeat and makes `check` refuse. It -//! clears only when the box's shadow starts a new window (a new `startedAt`: a restarted shadow -//! takes that stop as history, as the `trace-cap` skip), and it is never cleared by the shadow -//! catching up. `relay.json` also carries `traceAgeSeconds`, the age of the newest trace file, which +//! clears only when the box's verdict says its window starts after that stop (`window.lastStopTrace` +//! is the lost trace or a later one: the shadow ended its window at the stop, so its compared +//! brain time counts only from after the gap), never by the shadow catching up or restarting. A +//! relay that restarts mid-run ends the run's coverage (flysim stops tracing without a heartbeat) +//! and the loss is safe. `relay.json` also carries `traceAgeSeconds`, the age of the newest trace file, which //! `check` bounds. use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -269,6 +271,17 @@ struct CoverageLost { } /// The marker flysim writes when it stops a trace for want of a consumer. +/// Whether trace file `a` started at or after `b` (by the start in its name; else by name). +fn trace_not_before(a: &str, b: &str) -> bool { + match ( + super::trace_start_ms(Path::new(a)), + super::trace_start_ms(Path::new(b)), + ) { + (Some(x), Some(y)) => x >= y, + _ => a >= b, + } +} + const NO_CONSUMER_MARKER: &[u8] = b"\"reason\":\"no-consumer\""; /// Whether `bytes` hold a whole `{"truncated":true,"reason":"no-consumer"}` line. @@ -667,6 +680,26 @@ impl Relay { } } + /// Writes `coverageLost` into `relay.json` and syncs it (file and directory). + fn persist_coverage_lost(&self) { + let path = self.config.out_dir.join("relay.json"); + let mut value = std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .filter(|v| v["runId"].as_str() == Some(self.config.run_id.as_str())) + .unwrap_or_else(|| { + json!({"format": "fly-shadow-relay-v1", "runId": self.config.run_id, "healthy": false}) + }); + value["healthy"] = json!(false); + value["coverageLost"] = self.coverage_lost.as_ref().map_or( + Value::Null, + |c| json!({"trace": c.trace, "window": c.window, "at": c.at}), + ); + if let Err(e) = verdict::write_json_durable(&path, &value) { + log(format!("could not write {}: {e}", path.display())); + } + } + /// Looks for flysim's no-consumer stop in trace bytes about to be sent. fn scan_trace(&mut self, name: &str, offset: u64, chunk: &[u8]) { let mut buf = match self.scan_tail.remove(name) { @@ -684,7 +717,9 @@ impl Relay { window: self.window.clone(), at: verdict::now_iso(), }); - // Say so at the next tick, not in up to five seconds. + // Durable before the chunk that holds the stop is sent: a relay that dies after + // sending and before its next tick would otherwise resume past the stop unaware. + self.persist_coverage_lost(); self.last_relay_json = Instant::now() - Duration::from_secs(60); } let keep = buf.len().saturating_sub(256); @@ -987,16 +1022,19 @@ impl Relay { "unsyncedBytes": unsynced_bytes, "unsyncedTransitions": unsynced, }); - // A new shadow window takes an earlier stop as history (the `trace-cap` skip). - let window = v["startedAt"].as_str().map(str::to_owned); - if let (Some(lost), Some(now)) = (&self.coverage_lost, &window) - && lost.window.as_ref().is_some_and(|w| w != now) + // The loss clears only once the box's verdict counts from after it: its window's last + // trace stop is the lost trace or a later one (SHADOW-02 B2). A verdict that has not + // reached the stop, or a restarted shadow's that replays the stopped trace before its + // stop line, still counts the time before the gap, so the loss stays. + if let Some(lost) = &self.coverage_lost + && let Some(stop) = v["window"]["lastStopTrace"].as_str() + && trace_not_before(stop, &lost.trace) { - log("the box's shadow started a new window: the earlier trace stop is history"); + log("the box's verdict counts from after the trace stop: the coverage loss is closed"); self.coverage_lost = None; self.last_relay_json = Instant::now() - Duration::from_secs(60); } - self.window = window; + self.window = v["startedAt"].as_str().map(str::to_owned); if v["status"] == "diverged" && self.diverged_at.is_none() { self.diverged_at = Some(Instant::now()); } diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs index bb71a4d..de08d78 100644 --- a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs +++ b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs @@ -50,14 +50,13 @@ use crate::trace::{Agreement, Difference}; pub const FORMAT: &str = "fly-shadow-verdict-v1"; /// Skips that are the live side's own events, not the session runtime's failures: the operator -/// reward pulse (declared), a startup save rotated away before the shadow reached it, a trace -/// stopped at its byte cap (or for want of a consumer *before* this shadow started: one that stops -/// while the shadow follows it is a `coverage` divergence, SHADOW-02), and a process that ran no -/// transition. -pub const SKIP_KINDS: [&str; 4] = [ +/// reward pulse (declared), a startup save rotated away before the shadow reached it, and a +/// process that ran no transition. A trace that stopped (byte cap, or no consumer before this +/// shadow started) is a coverage gap, never a skip: it ends the window, see [`Verdict::end_window`] +/// (SHADOW-02 B2). +pub const SKIP_KINDS: [&str; 3] = [ "operator-reward-pulse", "startup-save-gone", - "trace-cap", "no-transition", ]; @@ -142,6 +141,14 @@ pub struct Skipped { pub reason: String, } +/// A coverage gap: the live trace stopped, so everything compared before it no longer counts. +#[derive(Clone, Debug)] +pub struct WindowEnd { + pub trace: String, + pub reason: String, + pub discarded_brain_seconds: f64, +} + /// The first divergence and its context. #[derive(Clone, Debug)] pub struct Divergence { @@ -230,6 +237,10 @@ pub struct Verdict { pub checkpoints: Checkpoints, pub segments_compared: u64, pub skipped: Vec, + /// Trace stops (coverage gaps) that ended a window: what they discarded. + pub window_ends: Vec, + /// The trace whose stop last ended the window (`None`: none yet). `compared` counts only after. + pub last_stop_trace: Option, pub divergence: Option, pub started_at: String, pub passed_at: Option, @@ -275,6 +286,20 @@ pub fn iso(ms: i64) -> String { } impl Verdict { + /// A coverage gap (a trace stopped, whatever the reason): the live fly may run untraced from + /// here, so the brain time and saves compared so far stop counting. A pass needs the whole + /// window after the last gap (SHADOW-02 B2). + pub fn end_window(&mut self, trace: &str, reason: String) { + self.window_ends.push(WindowEnd { + trace: trace.to_owned(), + reason, + discarded_brain_seconds: self.brain_ms / 1000.0, + }); + self.last_stop_trace = Some(trace.to_owned()); + self.brain_ms = 0.0; + self.checkpoints = Checkpoints::default(); + } + pub fn brain_seconds(&self) -> f64 { self.brain_ms / 1000.0 } @@ -317,6 +342,12 @@ impl Verdict { "skipped": self.skipped.iter().map(|s| json!({ "trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason, })).collect::>(), + "window": { + "lastStopTrace": self.last_stop_trace, + "ends": self.window_ends.iter().map(|w| json!({ + "trace": w.trace, "reason": w.reason, "discardedBrainSeconds": (w.discarded_brain_seconds * 1000.0).round() / 1000.0, + })).collect::>(), + }, "declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::>(), "firstDivergence": self.divergence.as_ref().map(|d| { let mut v = d.to_json(); @@ -345,6 +376,22 @@ pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> { std::fs::rename(&tmp, path) } +/// [`write_json`], synced to disk (file and directory) before it returns. +pub fn write_json_durable(path: &Path, value: &Value) -> std::io::Result<()> { + use std::io::Write; + let tmp = path.with_extension("json.tmp"); + let mut text = serde_json::to_string_pretty(value).expect("JSON serializes"); + text.push('\n'); + let mut f = std::fs::File::create(&tmp)?; + f.write_all(text.as_bytes())?; + f.sync_all()?; + std::fs::rename(&tmp, path)?; + if let Some(dir) = path.parent() { + std::fs::File::open(dir)?.sync_all()?; + } + Ok(()) +} + /// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`], /// [`MAX_UNAVAILABLE_FRACTION`]). pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> { @@ -418,6 +465,12 @@ pub fn allows_cutover( if candidate["compatibility"] != compatibility { return Err("the verdict is for another compatibility string".to_owned()); } + // Only a build that ends the window at a coverage gap counts brain time after it. + if verdict["window"].is_null() { + return Err( + "the verdict does not say where its window starts (an older shadow)".to_owned(), + ); + } let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0); // The operator's window is a floor the verdict cannot lower: a shadow run with a shorter // `--required-brain-seconds` (a rehearsal, a test) never arms the cutover. @@ -523,6 +576,8 @@ mod tests { }, segments_compared: 1, skipped: Vec::new(), + window_ends: Vec::new(), + last_stop_trace: None, divergence: None, started_at: now_iso(), passed_at: None, @@ -536,6 +591,53 @@ mod tests { .to_json() } + #[test] + fn a_stop_ends_the_window() { + // B2: brain time compared before a coverage gap never counts toward a pass. + let mut v = Verdict { + status: Status::Running, + reason: String::new(), + binary_sha256: String::new(), + binaries: Default::default(), + release: String::new(), + compatibility: String::new(), + execution_mode: String::new(), + agent_threads: 1, + required_brain_seconds: 10_800.0, + agreement: Agreement::default(), + brain_ms: 1_819_000.0, + ledger_checks: 0, + checkpoints: Checkpoints { + identical: 400, + declared: 0, + unavailable: 0, + }, + segments_compared: 1, + skipped: Vec::new(), + window_ends: Vec::new(), + last_stop_trace: None, + divergence: None, + started_at: now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + run_id: None, + }; + v.end_window("trace-1.jsonl", "no-consumer".to_owned()); + assert_eq!(v.brain_seconds(), 0.0); + v.brain_ms += 170_000.0; + let j = v.to_json(); + assert_eq!(j["compared"]["brainSeconds"], 170.0); + assert_eq!(j["compared"]["checkpoints"]["identical"], 0); + assert_eq!(j["window"]["lastStopTrace"], "trace-1.jsonl"); + assert_eq!(j["window"]["ends"][0]["discardedBrainSeconds"], 1819.0); + // A gap is not an allowed skip. + assert!(!SKIP_KINDS.contains(&"trace-cap")); + } + #[test] fn the_cutover_rule() { let now = parse_iso(&now_iso()).unwrap(); @@ -548,6 +650,10 @@ mod tests { let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300); let pass = verdict(Status::Pass, 10_800_000.0); assert_eq!(ok(&pass), Ok(())); + // A verdict that does not say where its window starts is an older shadow's (B2). + let mut undated = pass.clone(); + undated.as_object_mut().unwrap().remove("window"); + assert!(ok(&undated).is_err()); // Another binary, another release, a changed file in it. assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err()); let moved = Release { diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs b/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs index 7245625..75a7001 100644 --- a/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs +++ b/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs @@ -5,7 +5,7 @@ //! After a long outage flysim stops its trace (`"reason":"no-consumer"`) and the live fly runs //! untraced. When the link heals the box is alive and, counted in trace lines, caught up long //! before its shadow reaches that stop. The relay must not call that healthy: it sets a sticky -//! `coverageLost`, stops the heartbeat, and clears it only when the shadow starts a new window. +//! `coverageLost`, stops the heartbeat, and clears it only when the verdict's window starts after the stop (a restart alone does not). use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -102,9 +102,14 @@ impl Setup { } while alive.load(Ordering::Relaxed) { let _ = std::fs::write(mirror.join("trace/consumer"), "beat"); + // 1: a window that has not ended at the stop; 2: a new window (a restart) + // that replays the stopped trace and has not reached its stop; 3: one whose + // verdict counts from after the stop. + let w = window.load(Ordering::Relaxed); let verdict = json!({ "runId": RUN_ID, "status": "running", "lagTransitions": 0, - "startedAt": format!("window-{}", window.load(Ordering::Relaxed)), + "startedAt": format!("window-{}", w.min(2)), + "window": {"lastStopTrace": if w >= 3 { json!(TRACE) } else { Value::Null }}, }); let _ = std::fs::write( mirror.join("out/verdict.json"), @@ -195,8 +200,14 @@ fn a_no_consumer_stop_in_the_forwarded_trace_makes_the_relay_unhealthy_until_a_n std::thread::sleep(Duration::from_secs(1)); assert!(!s.relay_json()["coverageLost"].is_null()); - // A restarted shadow (a new window) takes the stop as history. + // B2: a restarted shadow (a new window) that has not ended its window at the stop still + // counts the time before the gap: the loss stays. s.window.store(2, Ordering::Relaxed); + std::thread::sleep(Duration::from_secs(2)); + assert!(!s.relay_json()["coverageLost"].is_null()); + assert_eq!(s.relay_json()["healthy"], false); + // Its verdict counts from after the stop: closed. + s.window.store(3, Ordering::Relaxed); wait_for("the new window to clear the stop", 60, || { let r = s.relay_json(); r["coverageLost"].is_null() && r["healthy"] == true diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs b/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs index cb1631b..41fac76 100644 --- a/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs +++ b/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs @@ -10,7 +10,7 @@ //! 1. A fresh fly and a restart, with sugar: the box's `pass` arrives on the container side with //! this run's id, and finished trace files are removed on the container too. //! 2. The remote shadow dies: the relay stops the heartbeat and flysim stops its trace; a new -//! shadow starts a new window, reports that stop (which predates it) as a `trace-cap` skip, +//! shadow starts a new window, ends its window at that stop (which predates it; B2), //! and follows the next process. //! 3. The sync stalls (the ingest is stopped): the heartbeat goes stale, flysim stops its trace //! (`no-consumer`); once the sync is back the box sees the gap and fails the verdict as a @@ -369,18 +369,41 @@ fn the_remote_shadow_follows_through_the_relay_and_fails_closed() { json_of(&verdict_path)["startedAt"] != started_before }); live.stop(); - // The stop happened before this shadow: history, an allowed skip, not a coverage gap. - wait_for("the stopped file skipped as trace-cap", 120, || { + // The stop happened before this shadow: it ends the window (nothing before it counts), it is + // not a skip. + wait_for("the stopped file to end the window", 120, || { + json_of(&verdict_path)["window"]["ends"] + .as_array() + .is_some_and(|e| !e.is_empty()) + }); + assert!( json_of(&verdict_path)["skipped"] .as_array() - .is_some_and(|s| s.iter().any(|k| k["kind"] == "trace-cap")) - }); + .is_some_and(|s| s.iter().all(|k| k["kind"] != "trace-cap")) + ); let live = Live::start(&flysim, &rom, &container, &root.join("flysim-4.log")); live.run_for(3_000.0); wait_for("the new window comparing the next process", 120, || { json_of(&verdict_path)["compared"]["transitions"].as_u64() > Some(0) }); assert!(json_of(&verdict_path)["firstDivergence"].is_null()); + // B2: the replayed stopped trace's brain time was discarded at its stop; the verdict counts + // only the process after the gap. + { + let v = json_of(&verdict_path); + let discarded = v["window"]["ends"][0]["discardedBrainSeconds"] + .as_f64() + .unwrap(); + let compared = v["compared"]["brainSeconds"].as_f64().unwrap(); + assert!( + discarded > 0.0, + "the stopped trace had brain time before the gap: {v}" + ); + assert!( + compared < discarded, + "{compared} s counted after the gap, {discarded} s before it must not count: {v}" + ); + } // 3. The sync stalls: the ingest stops reading. let pid = std::fs::read_to_string(&pid_file).unwrap().trim().to_owned();