fly-shadow: review fixes R1, R2, N3 (SHADOW-01)

R1: the verdict hashes flysim-session (SERVE-01's service) with the
other release binaries; check takes --current (default /opt/fly/current)
and --binary (default flysim-session) and requires the verdict's release
to be the directory the link resolves to, every shadowed binary
unchanged there. R2: a session that does not start, a restore-gate
refusal, a capture with no agent, an unrecorded transition and an
unbuildable trace line are divergences; skips carry a kind and only the
live side's own kinds (startup-save-gone, operator-reward-pulse,
trace-cap, no-transition) allow a cutover. N3: pass and the cutover rule
require one live save compared per 600 brain seconds and at most 10 %
unavailable, and the cutover rule a shadow at most 3,600 transitions
behind. N1: the shadow writes the consumer heartbeat, removes it when it
stops, and prunes history files. The coordinator's history is bounded
per segment. The test adds a gate refusal (a boot divergence) and waits
for the heartbeat; so does the rehearsal script.
This commit is contained in:
acamilo 2026-09-29 22:15:38 +00:00
parent 4bf664ee22
commit e085876d79
5 changed files with 396 additions and 94 deletions

View file

@ -30,11 +30,12 @@
//!
//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error.
//!
//! `check --verdict FILE [--binary FILE] [--compatibility STRING] [--max-age-seconds N]`: the
//! cutover rule of `fly_legacy_session::shadow::verdict`. `--binary` is the session-runtime binary
//! CUT-01 switches to (default: `fly-session` beside this executable); it must be one of the
//! shadowed release's binaries by name and SHA-256. `--compatibility` defaults to this build's
//! legacy compatibility string.
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
//! SERVE-01's service). `--compatibility` defaults to this build's legacy compatibility string.
use std::path::PathBuf;
use std::time::Duration;
@ -104,13 +105,19 @@ fn this_binary() -> PathBuf {
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}")))
}
/// SHA-256 of the release binaries beside this one, by name.
fn release_binaries() -> std::collections::BTreeMap<String, String> {
let dir = this_binary()
.parent()
.map(PathBuf::from)
.unwrap_or_default();
["fly-shadow", "fly-session", "flysim", "fly-edge"]
/// The release binaries a verdict vouches for: SERVE-01's service (`flysim-session`, what CUT-01
/// switches to), its worker program, the shadow itself, the legacy service and the edge.
const RELEASE_BINARIES: [&str; 5] = [
"flysim-session",
"fly-session",
"fly-shadow",
"flysim",
"fly-edge",
];
/// SHA-256 of the release binaries in `dir`, by name.
fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> {
RELEASE_BINARIES
.iter()
.filter_map(|name| {
let path = dir.join(name);
@ -120,6 +127,14 @@ fn release_binaries() -> std::collections::BTreeMap<String, String> {
.collect()
}
/// The resolved directory of this binary: the release it runs from.
fn this_release() -> PathBuf {
this_binary()
.parent()
.and_then(|d| d.canonicalize().ok())
.unwrap_or_default()
}
fn main() {
let mut argv: Vec<String> = std::env::args().skip(1).collect();
if argv.is_empty() {
@ -134,10 +149,15 @@ fn main() {
.value("--verdict")
.map(PathBuf::from)
.unwrap_or_else(|| usage());
let binary = args.value("--binary").map_or_else(
|| this_binary().with_file_name("fly-session"),
PathBuf::from,
);
// The release CUT-01 switches into (what `/opt/fly/current` resolves to now), and the
// binary in it that it switches to: SERVE-01's service.
let current = args
.value("--current")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/opt/fly/current"));
let binary = args
.value("--binary")
.unwrap_or_else(|| "flysim-session".to_owned());
let compatibility = args.value("--compatibility");
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
args.done();
@ -150,12 +170,16 @@ fn main() {
let value: serde_json::Value =
serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}")));
let now = verdict::parse_iso(&verdict::now_iso()).expect("now parses");
let name = binary
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let sha = file_sha256(&binary);
match verdict::allows_cutover(&value, (&name, &sha), &compatibility, now, max_age) {
let dir = current
.canonicalize()
.unwrap_or_else(|e| die(format!("{}: {e}", current.display())));
let binaries = binaries_in(&dir);
let dir_text = dir.display().to_string();
let release = verdict::Release {
dir: &dir_text,
binaries: &binaries,
};
match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) {
Ok(()) => println!("cutover allowed: {}", value["reason"]),
Err(reason) => {
println!("cutover refused: {reason}");
@ -276,12 +300,8 @@ fn run(mut args: Args) {
poll: Duration::from_millis(100),
lag_guard,
binary_sha256: file_sha256(&this_binary()),
binaries: release_binaries(),
release: this_binary()
.parent()
.and_then(|d| d.canonicalize().ok())
.map(|d| d.display().to_string())
.unwrap_or_default(),
binaries: binaries_in(&this_release()),
release: this_release().display().to_string(),
};
eprintln!(
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",

View file

@ -160,8 +160,9 @@ pub enum Ended {
enum SegmentEnd {
/// The process's file ended (the next one began).
Completed,
/// Nothing more could be compared in it.
Skipped(String),
/// Nothing more could be compared in it, for a reason outside the session runtime: the
/// kind (one of [`verdict::SKIP_KINDS`] or `trace-malformed`) and what happened.
Skipped(&'static str, String),
Diverged(Box<Divergence>),
Stop(Ended),
}
@ -247,6 +248,13 @@ pub fn parse_lag_seconds(text: &str) -> Option<f64> {
})
}
/// 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()) {
eprintln!("fly-shadow: could not write {}: {e}", path.display());
}
}
/// The live trace's capture ids: `g<N>`.
fn generation_of_capture(capture: &Value) -> Option<u64> {
capture["checkpointId"]
@ -283,6 +291,28 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
spool = spool.keep_all();
}
let spool_thread = spool.spawn(Duration::from_millis(250), Duration::from_secs(3 * 3600));
// The consumer heartbeat the live recorder needs to keep tracing (flysim `trace`): written
// now, before the live service is (re)started, and every 30 s; removed when the shadow stops,
// so a stopped, diverged or dead shadow turns the live trace off by itself.
let heartbeat = config.trace_dir.join(flysim::trace::CONSUMER_FILE);
touch(&heartbeat);
let beating = Arc::new(AtomicBool::new(true));
let heartbeat_thread = {
let (path, beating) = (heartbeat.clone(), Arc::clone(&beating));
std::thread::Builder::new()
.name("fly-shadow-heartbeat".to_owned())
.spawn(move || {
let mut last = Instant::now();
while beating.load(Ordering::Relaxed) {
if last.elapsed() >= Duration::from_secs(30) {
touch(&path);
last = Instant::now();
}
std::thread::sleep(Duration::from_millis(200));
}
})
.expect("the heartbeat thread starts")
};
let lag = config
.lag_guard
.as_ref()
@ -323,6 +353,9 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
};
shadow.write();
let ended = shadow.follow().await;
beating.store(false, Ordering::Relaxed);
let _ = heartbeat_thread.join();
let _ = std::fs::remove_file(&heartbeat);
shadow.spool.stop();
let _ = spool_thread.join();
let ended = ended?;
@ -406,12 +439,14 @@ impl Shadow {
None
} else {
// Only the newest file present at start: older processes are history whose startup
// saves are gone.
follow::trace_files(&dir)
.map_err(|e| format!("{}: {e}", dir.display()))?
.into_iter()
.rev()
.nth(1)
// saves are gone, and are pruned.
let files = follow::trace_files(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
if !self.config.keep_traces && files.len() > 1 {
for old in &files[..files.len() - 1] {
let _ = std::fs::remove_file(old);
}
}
files.into_iter().rev().nth(1)
};
loop {
let next = loop {
@ -442,11 +477,14 @@ impl Shadow {
let _ = std::fs::remove_file(&next);
}
}
SegmentEnd::Skipped(reason) => {
eprintln!("fly-shadow: {name} skipped after {compared} transitions: {reason}");
SegmentEnd::Skipped(kind, reason) => {
eprintln!(
"fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}"
);
self.verdict.skipped.push(Skipped {
trace: name,
transitions_compared: compared,
kind: kind.to_owned(),
reason,
});
if !self.config.keep_traces {
@ -470,7 +508,12 @@ impl Shadow {
match follower.next_line() {
Ok(Some(line)) => return Ok(Some(line)),
Ok(None) => {}
Err(e) => return Err(SegmentEnd::Skipped(format!("reading the trace: {e}"))),
Err(e) => {
return Err(SegmentEnd::Skipped(
"trace-malformed",
format!("reading the trace: {e}"),
));
}
}
if self.stop.requested() {
return Err(SegmentEnd::Stop(Ended::Stopped));
@ -481,7 +524,10 @@ impl Shadow {
tokio::time::sleep(Duration::from_millis(500)).await;
return match follower.next_line() {
Ok(line) => Ok(line),
Err(e) => Err(SegmentEnd::Skipped(format!("reading the trace: {e}"))),
Err(e) => Err(SegmentEnd::Skipped(
"trace-malformed",
format!("reading the trace: {e}"),
)),
};
}
self.verdict.lag_transitions = 0;
@ -497,27 +543,37 @@ impl Shadow {
.unwrap_or_default();
let mut follower = match Follower::open(path) {
Ok(f) => f,
Err(e) => return SegmentEnd::Skipped(format!("open: {e}")),
Err(e) => return SegmentEnd::Skipped("trace-malformed", format!("open: {e}")),
};
// The header.
let header: Value = match self.next_line(&mut follower).await {
Ok(Some(line)) => match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => return SegmentEnd::Skipped(format!("header: {e}")),
Err(e) => return SegmentEnd::Skipped("trace-malformed", format!("header: {e}")),
},
Ok(None) => return SegmentEnd::Skipped("an empty trace".to_owned()),
Ok(None) => return SegmentEnd::Skipped("no-transition", "an empty trace".to_owned()),
Err(end) => return end,
};
if header["format"] != trace::FORMAT {
return SegmentEnd::Skipped(format!("not {}: {}", trace::FORMAT, header["format"]));
return SegmentEnd::Skipped(
"trace-malformed",
format!("not {}: {}", trace::FORMAT, header["format"]),
);
}
// The start boundary and its startup save.
let start: Value = match self.next_line(&mut follower).await {
Ok(Some(line)) => match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => return SegmentEnd::Skipped(format!("start line: {e}")),
Err(e) => {
return SegmentEnd::Skipped("trace-malformed", format!("start line: {e}"));
}
},
Ok(None) => return SegmentEnd::Skipped("the process ran no transition".to_owned()),
Ok(None) => {
return SegmentEnd::Skipped(
"no-transition",
"the process ran no transition".to_owned(),
);
}
Err(end) => return end,
};
let Some(startup) = start["operational"]["captures"]
@ -526,7 +582,10 @@ impl Shadow {
.and_then(generation_of_capture)
.filter(|_| start.get("boundary").is_some())
else {
return SegmentEnd::Skipped("no startup save at the start boundary".to_owned());
return SegmentEnd::Skipped(
"trace-malformed",
"no startup save at the start boundary".to_owned(),
);
};
let bytes = {
let mut waited = Duration::ZERO;
@ -535,9 +594,12 @@ impl Shadow {
break bytes;
}
if waited >= Duration::from_secs(30) {
return SegmentEnd::Skipped(format!(
return SegmentEnd::Skipped(
"startup-save-gone",
format!(
"the startup save g{startup} is no longer in the stores or the spool"
));
),
);
}
tokio::time::sleep(Duration::from_millis(500)).await;
waited += Duration::from_millis(500);
@ -560,10 +622,13 @@ impl Shadow {
flybrain_gb::GameAdapter::migrates_from(&adapter),
);
if let Err(reason) = gate.check(&checkpoint) {
return SegmentEnd::Skipped(format!(
"the live process's startup save is not this candidate's to restore ({reason}): \
is the shadow the build the live service runs?"
));
return SegmentEnd::Diverged(Box::new(self.boot_failure(
&name,
format!(
"the live process's startup save g{startup} is refused by this candidate's \
restore gate ({reason}): is the shadow the build the live service runs?"
),
)));
}
let segment_dir = self.config.work_dir.join(format!("segment-{startup}"));
let _ = std::fs::remove_dir_all(&segment_dir);
@ -571,7 +636,11 @@ impl Shadow {
let mut session =
match LegacySession::start(&segment_dir, self.session_config.clone()).await {
Ok(s) => s,
Err(e) => return SegmentEnd::Skipped(format!("the session did not start: {e}")),
Err(e) => {
return SegmentEnd::Diverged(Box::new(
self.boot_failure(&name, format!("the session did not start: {e}")),
));
}
};
// A fresh start (the stores were empty): the live process ran the one-frame scaffold and
// the warm-up from power-on, and the shadow does the same (`Environment.Initialize`,
@ -646,6 +715,8 @@ impl Shadow {
self.verdict.segments_compared += 1;
// Rollbacks wait for the boundary's captures, as the host orders them (section 16).
session.coordinator.defer_rollbacks(true);
// A segment can run for days: keep the coordinator's in-memory history bounded.
session.coordinator.bound_history(4096);
let end = self
.run_segment(&name, &mut follower, &mut session, rank_since_ms)
.await;
@ -685,10 +756,15 @@ impl Shadow {
};
let live: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => return SegmentEnd::Skipped(format!("a trace line: {e}")),
Err(e) => {
return SegmentEnd::Skipped("trace-malformed", format!("a trace line: {e}"));
}
};
if live.get("truncated").is_some() {
return SegmentEnd::Skipped("the live trace reached its byte cap".to_owned());
return SegmentEnd::Skipped(
"trace-cap",
format!("the live trace stopped ({})", live["reason"]),
);
}
let Some(behaviour) = live.get("behaviour").cloned() else {
continue;
@ -699,18 +775,27 @@ impl Shadow {
match admission_line["kind"].as_str() {
Some("sugar") => {
let Some(duration) = admission_line["durationMs"].as_f64() else {
return SegmentEnd::Skipped("a sugar with no duration".to_owned());
return SegmentEnd::Skipped(
"trace-malformed",
"a sugar with no duration".to_owned(),
);
};
admission.replay_sugar(duration);
}
Some("reward") => {
return SegmentEnd::Skipped(format!(
return SegmentEnd::Skipped(
"operator-reward-pulse",
format!(
"an operator reward pulse at step {step:?} (declared \
operator-reward-pulse: not available on the session runtime)"
));
),
);
}
other => {
return SegmentEnd::Skipped(format!("an unknown admission {other:?}"));
return SegmentEnd::Skipped(
"trace-malformed",
format!("an unknown admission {other:?}"),
);
}
}
}
@ -789,7 +874,14 @@ impl Shadow {
match session.coordinator.capture_payloads(&checkpoint_id).await {
Ok((boundary, world_payload, agents)) => {
let Some((_, agent_payload)) = agents.into_iter().next() else {
return SegmentEnd::Skipped("a capture with no agent".to_owned());
return SegmentEnd::Diverged(Box::new(Divergence {
kind: "session-error".to_owned(),
trace: name.to_owned(),
step,
difference: None,
detail: "a capture with no agent".to_owned(),
context: context.into_iter().collect(),
}));
};
taken.push((
*generation,
@ -823,12 +915,28 @@ impl Shadow {
let records = session.task.take_records();
let elapsed = t0.elapsed().as_secs_f64() * 1000.0;
self.verdict.cost.record(elapsed);
let session_error = |detail: String, context: VecDeque<(Value, Value)>| {
SegmentEnd::Diverged(Box::new(Divergence {
kind: "session-error".to_owned(),
trace: name.to_owned(),
step,
difference: None,
detail,
context: context.into_iter().collect(),
}))
};
let (Some(details), [record]) = (details, records.as_slice()) else {
return SegmentEnd::Skipped("the session recorded no transition".to_owned());
return session_error(
format!(
"the session recorded no transition ({} task records)",
records.len()
),
context,
);
};
let mut shadow_line = match trace::line(&details, record) {
Ok(line) => line["behaviour"].clone(),
Err(e) => return SegmentEnd::Skipped(format!("the shadow's trace line: {e}")),
Err(e) => return session_error(format!("the shadow's trace line: {e}"), context),
};
if behaviour.get("ledgersDigest").is_some() {
shadow_line["ledgersDigest"] = Value::String(sha256_hex(record.ledgers.as_bytes()));
@ -921,6 +1029,12 @@ impl Shadow {
.unwrap_or(0.0);
if self.verdict.status == Status::Running
&& self.verdict.brain_seconds() >= self.config.required_brain_seconds
&& verdict::saves_suffice(
self.verdict.brain_seconds(),
self.verdict.checkpoints.identical + self.verdict.checkpoints.declared,
self.verdict.checkpoints.unavailable,
)
.is_ok()
{
self.verdict.status = Status::Pass;
self.verdict.passed_at = Some(verdict::now_iso());

View file

@ -19,12 +19,24 @@
//! before it passed (a `pass` stays `pass` when the shadow stops). `error` is the shadow's own
//! failure (it could not read its inputs), which proves nothing either way.
//!
//! **The cutover rule (for CUT-01).** Cut over only if, read at the moment of cutting over:
//! `format` is `fly-shadow-verdict-v1`; `status` is `pass`; `firstDivergence` is `null`;
//! the session-runtime binary being switched to is one of `candidate.binaries`, by name and
//! SHA-256 (the shadow proved the release it shipped in, not another build);
//! `candidate.compatibility` is the live service's `--print-compatibility`; and `updatedAt` is no
//! older than a few minutes (the shadow is still following). Anything else keeps the legacy fly.
//! **The cutover rule (for CUT-01), [`allows_cutover`].** Cut over only if, read at the moment of
//! cutting over, every one of these holds; anything else keeps the legacy fly:
//!
//! - `format` is `fly-shadow-verdict-v1`, `status` is `pass`, `firstDivergence` is `null`, and
//! `compared.brainSeconds` reaches `required.brainSeconds`;
//! - *the release*: `candidate.release` is the directory `/opt/fly/current` resolves to now,
//! every binary in `candidate.binaries` still has its recorded SHA-256 there, and the binary
//! being switched to (`flysim-session`, SERVE-01's service) is one of them -- the shadow
//! vouches for the release it ran in and nothing else;
//! - `candidate.compatibility` is the live service's `--print-compatibility`;
//! - *saves were compared*: at least one live save per [`BRAIN_SECONDS_PER_SAVE`] brain seconds
//! compared byte for byte, and no more than [`MAX_UNAVAILABLE_FRACTION`] of the saves the trace
//! named were unavailable (a shadow starved past its spool must not pass on transitions alone);
//! - *nothing was skipped for a reason inside the session runtime*: every `skipped` entry's `kind`
//! is one of [`SKIP_KINDS`] (the live side's own events); a session-side failure is a
//! divergence, never a skip;
//! - *the shadow is caught up and alive*: `updatedAt` is no older than `max_age_s`, and
//! `lagTransitions` is at most [`MAX_LAG_TRANSITIONS`].
use std::path::Path;
@ -34,6 +46,26 @@ 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, and a process that ran no transition.
pub const SKIP_KINDS: [&str; 4] = [
"operator-reward-pulse",
"startup-save-gone",
"trace-cap",
"no-transition",
];
/// At least one live save compared byte for byte per this many brain seconds (the live loop
/// saves every 5 s; 600 leaves room for a lagging shadow's spool evictions).
pub const BRAIN_SECONDS_PER_SAVE: f64 = 600.0;
/// At most this fraction of the saves the trace named may have been unavailable.
pub const MAX_UNAVAILABLE_FRACTION: f64 = 0.1;
/// The shadow at most about a minute behind the live trace.
pub const MAX_LAG_TRANSITIONS: u64 = 3_600;
/// The declared differences the comparison applies, by name (`legacy-gameboy-v1`).
pub const DECLARED: [(&str, &str); 5] = [
(
@ -100,6 +132,8 @@ pub struct Checkpoints {
pub struct Skipped {
pub trace: String,
pub transitions_compared: u64,
/// One of [`SKIP_KINDS`], or `trace-malformed`.
pub kind: String,
pub reason: String,
}
@ -274,7 +308,7 @@ impl Verdict {
},
},
"skipped": self.skipped.iter().map(|s| json!({
"trace": s.trace, "transitionsCompared": s.transitions_compared, "reason": s.reason,
"trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason,
})).collect::<Vec<_>>(),
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
"firstDivergence": self.divergence.as_ref().map(|d| {
@ -303,12 +337,39 @@ pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> {
std::fs::rename(&tmp, path)
}
/// 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> {
let needed = (brain_seconds / BRAIN_SECONDS_PER_SAVE).floor().max(1.0) as u64;
if compared < needed {
return Err(format!(
"{compared} live saves compared over {brain_seconds:.0} brain s; {needed} needed"
));
}
if unavailable as f64 > MAX_UNAVAILABLE_FRACTION * (compared + unavailable) as f64 {
return Err(format!(
"{unavailable} of {} live saves were unavailable to compare",
compared + unavailable
));
}
Ok(())
}
/// The release the cutover would switch into: its resolved directory and the SHA-256 of the
/// binaries in it, by file name.
pub struct Release<'a> {
pub dir: &'a str,
pub binaries: &'a std::collections::BTreeMap<String, String>,
}
/// Reads a verdict file and says whether it allows the cutover, by the rule in the module notes.
/// `binary` is the file name and SHA-256 of the session-runtime binary CUT-01 switches to, and
/// `compatibility` the live service's; `max_age_s` bounds `updatedAt`.
/// `binary` is the file name of the session-runtime binary CUT-01 switches to, inside `release`
/// (what `/opt/fly/current` resolves to now), and `compatibility` the live service's;
/// `max_age_s` bounds `updatedAt`.
pub fn allows_cutover(
verdict: &Value,
binary: (&str, &str),
binary: &str,
release: &Release<'_>,
compatibility: &str,
now_ms: i64,
max_age_s: i64,
@ -322,13 +383,28 @@ pub fn allows_cutover(
if !verdict["firstDivergence"].is_null() {
return Err("a divergence is recorded".to_owned());
}
let (name, sha256) = binary;
if verdict["candidate"]["binaries"][name] != sha256 {
let candidate = &verdict["candidate"];
if candidate["release"] != release.dir {
return Err(format!(
"the verdict is for another build: {name} {sha256} is not among the shadowed release's binaries"
"the verdict is for the release {}, not {}",
candidate["release"], release.dir
));
}
if verdict["candidate"]["compatibility"] != compatibility {
let shadowed = candidate["binaries"]
.as_object()
.ok_or("the verdict names no binaries")?;
if !shadowed.contains_key(binary) {
return Err(format!("{binary} was not in the shadowed release"));
}
for (name, sha) in shadowed {
if release.binaries.get(name).map(String::as_str) != sha.as_str() {
return Err(format!(
"{name} in {} is not the binary the shadow ran beside",
release.dir
));
}
}
if candidate["compatibility"] != compatibility {
return Err("the verdict is for another compatibility string".to_owned());
}
let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0);
@ -338,6 +414,27 @@ pub fn allows_cutover(
if compared < required {
return Err(format!("{compared} of {required} brain seconds compared"));
}
let saves = &verdict["compared"]["checkpoints"];
saves_suffice(
compared,
saves["identical"].as_u64().unwrap_or(0) + saves["declared"].as_u64().unwrap_or(0),
saves["unavailable"].as_u64().unwrap_or(u64::MAX / 2),
)?;
for skip in verdict["skipped"].as_array().into_iter().flatten() {
let kind = skip["kind"].as_str().unwrap_or("");
if !SKIP_KINDS.contains(&kind) {
return Err(format!(
"a segment was skipped for {kind:?}: {}",
skip["reason"]
));
}
}
let lag = verdict["lagTransitions"].as_u64().unwrap_or(u64::MAX);
if lag > MAX_LAG_TRANSITIONS {
return Err(format!(
"the shadow is {lag} transitions behind the live trace"
));
}
let updated = verdict["updatedAt"]
.as_str()
.and_then(parse_iso)
@ -388,7 +485,7 @@ mod tests {
status,
reason: String::new(),
binary_sha256: "b".repeat(64),
binaries: [("fly-session".to_owned(), "b".repeat(64))].into(),
binaries: [("flysim-session".to_owned(), "b".repeat(64))].into(),
release: "/opt/fly/releases/test".to_owned(),
compatibility: "c".to_owned(),
execution_mode: "in-process".to_owned(),
@ -397,7 +494,11 @@ mod tests {
agreement: Agreement::default(),
brain_ms,
ledger_checks: 0,
checkpoints: Checkpoints::default(),
checkpoints: Checkpoints {
identical: 2_000,
declared: 1,
unavailable: 5,
},
segments_compared: 1,
skipped: Vec::new(),
divergence: None,
@ -415,27 +516,62 @@ mod tests {
#[test]
fn the_cutover_rule() {
let now = parse_iso(&now_iso()).unwrap();
let sha = "b".repeat(64);
let bin = ("fly-session", sha.as_str());
let binaries: std::collections::BTreeMap<String, String> =
[("flysim-session".to_owned(), "b".repeat(64))].into();
let release = Release {
dir: "/opt/fly/releases/test",
binaries: &binaries,
};
let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300);
let pass = verdict(Status::Pass, 10_800_000.0);
assert_eq!(allows_cutover(&pass, bin, "c", now, 300), Ok(()));
let other = "a".repeat(64);
assert!(allows_cutover(&pass, ("fly-session", &other), "c", now, 300).is_err());
assert!(allows_cutover(&pass, ("fly-other", &sha), "c", now, 300).is_err());
assert!(allows_cutover(&pass, bin, "other", now, 300).is_err());
assert!(allows_cutover(&pass, bin, "c", now + 301_000, 300).is_err());
let short = verdict(Status::Pass, 10_799_000.0);
assert!(allows_cutover(&short, bin, "c", now, 300).is_err());
assert_eq!(ok(&pass), Ok(()));
// Another binary, another release, a changed file in it.
assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err());
let moved = Release {
dir: "/opt/fly/releases/other",
binaries: &binaries,
};
assert!(allows_cutover(&pass, "flysim-session", &moved, "c", now, 300).is_err());
let changed: std::collections::BTreeMap<String, String> =
[("flysim-session".to_owned(), "a".repeat(64))].into();
let rebuilt = Release {
dir: "/opt/fly/releases/test",
binaries: &changed,
};
assert!(allows_cutover(&pass, "flysim-session", &rebuilt, "c", now, 300).is_err());
assert!(allows_cutover(&pass, "flysim-session", &release, "other", now, 300).is_err());
assert!(
allows_cutover(&pass, "flysim-session", &release, "c", now + 301_000, 300).is_err()
);
assert!(ok(&verdict(Status::Pass, 10_799_000.0)).is_err());
for status in [
Status::Running,
Status::Diverged,
Status::Stopped,
Status::Error,
] {
assert!(allows_cutover(&verdict(status, 10_800_000.0), bin, "c", now, 300).is_err());
assert!(ok(&verdict(status, 10_800_000.0)).is_err());
}
let mut diverged = pass.clone();
diverged["firstDivergence"] = json!({"kind": "transition"});
assert!(allows_cutover(&diverged, bin, "c", now, 300).is_err());
assert!(ok(&diverged).is_err());
// Saves: none compared, or too many unavailable.
let mut starved = pass.clone();
starved["compared"]["checkpoints"] =
json!({"identical": 0, "declared": 0, "unavailable": 0});
assert!(ok(&starved).is_err());
starved["compared"]["checkpoints"] =
json!({"identical": 100, "declared": 0, "unavailable": 50});
assert!(ok(&starved).is_err());
// Skips: the live side's own are fine, anything else is not.
let mut skipped = pass.clone();
skipped["skipped"] = json!([{"kind": "startup-save-gone", "reason": "x"}]);
assert_eq!(ok(&skipped), Ok(()));
skipped["skipped"] = json!([{"kind": "trace-malformed", "reason": "x"}]);
assert!(ok(&skipped).is_err());
// Behind the live trace.
let mut behind = pass.clone();
behind["lagTransitions"] = json!(MAX_LAG_TRANSITIONS + 1);
assert!(ok(&behind).is_err());
}
}

View file

@ -242,9 +242,21 @@ fn diverges(
trace: &Path,
spool: &Path,
empty: &Path,
) -> shadow::verdict::Verdict {
diverges_with(rom, root, trace, spool, empty, |_| {})
}
fn diverges_with(
rom: &Path,
root: &Path,
trace: &Path,
spool: &Path,
empty: &Path,
edit: impl FnOnce(&mut ShadowConfig),
) -> shadow::verdict::Verdict {
let _ = std::fs::remove_dir_all(root.join("out"));
let config = config(rom, root, trace, (empty, empty), spool);
let mut config = config(rom, root, trace, (empty, empty), spool);
edit(&mut config);
let stop = StopFlag::default();
let handle = spawn_shadow(config, stop.clone());
let deadline = Instant::now() + Duration::from_secs(600);
@ -295,6 +307,13 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
let out = config.out_dir.clone();
let stop = StopFlag::default();
let handle = spawn_shadow(config, stop.clone());
// The live recorder starts no trace without the shadow's heartbeat.
let heartbeat = dirs.trace.join(flysim::trace::CONSUMER_FILE);
let deadline = Instant::now() + Duration::from_secs(60);
while !heartbeat.is_file() {
assert!(Instant::now() < deadline, "the shadow wrote no heartbeat");
std::thread::sleep(Duration::from_millis(50));
}
// Process one: a fresh fly (the stores are empty), two sugars, 25 brain seconds.
let live = start_live(&binary, &rom, &dirs, &root.join("flysim-1.log"));
@ -455,4 +474,14 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
let d = got.divergence.expect("a divergence");
assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at)));
assert!(d.detail.contains("rankSinceMs"), "{}", d.detail);
// A session-side failure is a divergence, never a skip: a candidate whose restore gate
// refuses the live startup save (another dataset profile, so another compatibility string).
let got = diverges_with(&rom, &neg.join("gate"), &dirs.trace, &spool, &empty, |c| {
c.profile = LegacyProfileKind::Production;
});
let d = got.divergence.expect("a divergence");
assert_eq!(d.kind, "boot", "{}", d.detail);
assert!(d.detail.contains("restore gate"), "{}", d.detail);
assert!(got.skipped.is_empty());
}

View file

@ -102,6 +102,9 @@ wall0=$(date +%s.%N)
--mode "$mode" --threads "$threads" --max-live-lag-seconds "$guard" \
--required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 &
shadow_pid=$!
# flysim starts no trace without the shadow's heartbeat.
for _ in $(seq 1 120); do [ -f "$live/trace/consumer" ] && break; sleep 0.5; done
[ -f "$live/trace/consumer" ] || die "fly-shadow wrote no heartbeat"
start_live
echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)"