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:
parent
4bf664ee22
commit
e085876d79
5 changed files with 396 additions and 94 deletions
|
|
@ -30,11 +30,12 @@
|
||||||
//!
|
//!
|
||||||
//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error.
|
//! 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
|
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
|
||||||
//! cutover rule of `fly_legacy_session::shadow::verdict`. `--binary` is the session-runtime binary
|
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
|
||||||
//! CUT-01 switches to (default: `fly-session` beside this executable); it must be one of the
|
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
|
||||||
//! shadowed release's binaries by name and SHA-256. `--compatibility` defaults to this build's
|
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
|
||||||
//! legacy compatibility string.
|
//! 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::path::PathBuf;
|
||||||
use std::time::Duration;
|
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}")))
|
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SHA-256 of the release binaries beside this one, by name.
|
/// The release binaries a verdict vouches for: SERVE-01's service (`flysim-session`, what CUT-01
|
||||||
fn release_binaries() -> std::collections::BTreeMap<String, String> {
|
/// switches to), its worker program, the shadow itself, the legacy service and the edge.
|
||||||
let dir = this_binary()
|
const RELEASE_BINARIES: [&str; 5] = [
|
||||||
.parent()
|
"flysim-session",
|
||||||
.map(PathBuf::from)
|
"fly-session",
|
||||||
.unwrap_or_default();
|
"fly-shadow",
|
||||||
["fly-shadow", "fly-session", "flysim", "fly-edge"]
|
"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()
|
.iter()
|
||||||
.filter_map(|name| {
|
.filter_map(|name| {
|
||||||
let path = dir.join(name);
|
let path = dir.join(name);
|
||||||
|
|
@ -120,6 +127,14 @@ fn release_binaries() -> std::collections::BTreeMap<String, String> {
|
||||||
.collect()
|
.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() {
|
fn main() {
|
||||||
let mut argv: Vec<String> = std::env::args().skip(1).collect();
|
let mut argv: Vec<String> = std::env::args().skip(1).collect();
|
||||||
if argv.is_empty() {
|
if argv.is_empty() {
|
||||||
|
|
@ -134,10 +149,15 @@ fn main() {
|
||||||
.value("--verdict")
|
.value("--verdict")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.unwrap_or_else(|| usage());
|
.unwrap_or_else(|| usage());
|
||||||
let binary = args.value("--binary").map_or_else(
|
// The release CUT-01 switches into (what `/opt/fly/current` resolves to now), and the
|
||||||
|| this_binary().with_file_name("fly-session"),
|
// binary in it that it switches to: SERVE-01's service.
|
||||||
PathBuf::from,
|
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 compatibility = args.value("--compatibility");
|
||||||
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
|
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
|
||||||
args.done();
|
args.done();
|
||||||
|
|
@ -150,12 +170,16 @@ fn main() {
|
||||||
let value: serde_json::Value =
|
let value: serde_json::Value =
|
||||||
serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}")));
|
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 now = verdict::parse_iso(&verdict::now_iso()).expect("now parses");
|
||||||
let name = binary
|
let dir = current
|
||||||
.file_name()
|
.canonicalize()
|
||||||
.map(|n| n.to_string_lossy().into_owned())
|
.unwrap_or_else(|e| die(format!("{}: {e}", current.display())));
|
||||||
.unwrap_or_default();
|
let binaries = binaries_in(&dir);
|
||||||
let sha = file_sha256(&binary);
|
let dir_text = dir.display().to_string();
|
||||||
match verdict::allows_cutover(&value, (&name, &sha), &compatibility, now, max_age) {
|
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"]),
|
Ok(()) => println!("cutover allowed: {}", value["reason"]),
|
||||||
Err(reason) => {
|
Err(reason) => {
|
||||||
println!("cutover refused: {reason}");
|
println!("cutover refused: {reason}");
|
||||||
|
|
@ -276,12 +300,8 @@ fn run(mut args: Args) {
|
||||||
poll: Duration::from_millis(100),
|
poll: Duration::from_millis(100),
|
||||||
lag_guard,
|
lag_guard,
|
||||||
binary_sha256: file_sha256(&this_binary()),
|
binary_sha256: file_sha256(&this_binary()),
|
||||||
binaries: release_binaries(),
|
binaries: binaries_in(&this_release()),
|
||||||
release: this_binary()
|
release: this_release().display().to_string(),
|
||||||
.parent()
|
|
||||||
.and_then(|d| d.canonicalize().ok())
|
|
||||||
.map(|d| d.display().to_string())
|
|
||||||
.unwrap_or_default(),
|
|
||||||
};
|
};
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
|
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
|
||||||
|
|
|
||||||
|
|
@ -160,8 +160,9 @@ pub enum Ended {
|
||||||
enum SegmentEnd {
|
enum SegmentEnd {
|
||||||
/// The process's file ended (the next one began).
|
/// The process's file ended (the next one began).
|
||||||
Completed,
|
Completed,
|
||||||
/// Nothing more could be compared in it.
|
/// Nothing more could be compared in it, for a reason outside the session runtime: the
|
||||||
Skipped(String),
|
/// kind (one of [`verdict::SKIP_KINDS`] or `trace-malformed`) and what happened.
|
||||||
|
Skipped(&'static str, String),
|
||||||
Diverged(Box<Divergence>),
|
Diverged(Box<Divergence>),
|
||||||
Stop(Ended),
|
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>`.
|
/// The live trace's capture ids: `g<N>`.
|
||||||
fn generation_of_capture(capture: &Value) -> Option<u64> {
|
fn generation_of_capture(capture: &Value) -> Option<u64> {
|
||||||
capture["checkpointId"]
|
capture["checkpointId"]
|
||||||
|
|
@ -283,6 +291,28 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
|
||||||
spool = spool.keep_all();
|
spool = spool.keep_all();
|
||||||
}
|
}
|
||||||
let spool_thread = spool.spawn(Duration::from_millis(250), Duration::from_secs(3 * 3600));
|
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
|
let lag = config
|
||||||
.lag_guard
|
.lag_guard
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
@ -323,6 +353,9 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
|
||||||
};
|
};
|
||||||
shadow.write();
|
shadow.write();
|
||||||
let ended = shadow.follow().await;
|
let ended = shadow.follow().await;
|
||||||
|
beating.store(false, Ordering::Relaxed);
|
||||||
|
let _ = heartbeat_thread.join();
|
||||||
|
let _ = std::fs::remove_file(&heartbeat);
|
||||||
shadow.spool.stop();
|
shadow.spool.stop();
|
||||||
let _ = spool_thread.join();
|
let _ = spool_thread.join();
|
||||||
let ended = ended?;
|
let ended = ended?;
|
||||||
|
|
@ -406,12 +439,14 @@ impl Shadow {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
// Only the newest file present at start: older processes are history whose startup
|
// Only the newest file present at start: older processes are history whose startup
|
||||||
// saves are gone.
|
// saves are gone, and are pruned.
|
||||||
follow::trace_files(&dir)
|
let files = follow::trace_files(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||||
.map_err(|e| format!("{}: {e}", dir.display()))?
|
if !self.config.keep_traces && files.len() > 1 {
|
||||||
.into_iter()
|
for old in &files[..files.len() - 1] {
|
||||||
.rev()
|
let _ = std::fs::remove_file(old);
|
||||||
.nth(1)
|
}
|
||||||
|
}
|
||||||
|
files.into_iter().rev().nth(1)
|
||||||
};
|
};
|
||||||
loop {
|
loop {
|
||||||
let next = loop {
|
let next = loop {
|
||||||
|
|
@ -442,11 +477,14 @@ impl Shadow {
|
||||||
let _ = std::fs::remove_file(&next);
|
let _ = std::fs::remove_file(&next);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SegmentEnd::Skipped(reason) => {
|
SegmentEnd::Skipped(kind, reason) => {
|
||||||
eprintln!("fly-shadow: {name} skipped after {compared} transitions: {reason}");
|
eprintln!(
|
||||||
|
"fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}"
|
||||||
|
);
|
||||||
self.verdict.skipped.push(Skipped {
|
self.verdict.skipped.push(Skipped {
|
||||||
trace: name,
|
trace: name,
|
||||||
transitions_compared: compared,
|
transitions_compared: compared,
|
||||||
|
kind: kind.to_owned(),
|
||||||
reason,
|
reason,
|
||||||
});
|
});
|
||||||
if !self.config.keep_traces {
|
if !self.config.keep_traces {
|
||||||
|
|
@ -470,7 +508,12 @@ impl Shadow {
|
||||||
match follower.next_line() {
|
match follower.next_line() {
|
||||||
Ok(Some(line)) => return Ok(Some(line)),
|
Ok(Some(line)) => return Ok(Some(line)),
|
||||||
Ok(None) => {}
|
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() {
|
if self.stop.requested() {
|
||||||
return Err(SegmentEnd::Stop(Ended::Stopped));
|
return Err(SegmentEnd::Stop(Ended::Stopped));
|
||||||
|
|
@ -481,7 +524,10 @@ impl Shadow {
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
return match follower.next_line() {
|
return match follower.next_line() {
|
||||||
Ok(line) => Ok(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;
|
self.verdict.lag_transitions = 0;
|
||||||
|
|
@ -497,27 +543,37 @@ impl Shadow {
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let mut follower = match Follower::open(path) {
|
let mut follower = match Follower::open(path) {
|
||||||
Ok(f) => f,
|
Ok(f) => f,
|
||||||
Err(e) => return SegmentEnd::Skipped(format!("open: {e}")),
|
Err(e) => return SegmentEnd::Skipped("trace-malformed", format!("open: {e}")),
|
||||||
};
|
};
|
||||||
// The header.
|
// The header.
|
||||||
let header: Value = match self.next_line(&mut follower).await {
|
let header: Value = match self.next_line(&mut follower).await {
|
||||||
Ok(Some(line)) => match serde_json::from_str(&line) {
|
Ok(Some(line)) => match serde_json::from_str(&line) {
|
||||||
Ok(v) => v,
|
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,
|
Err(end) => return end,
|
||||||
};
|
};
|
||||||
if header["format"] != trace::FORMAT {
|
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.
|
// The start boundary and its startup save.
|
||||||
let start: Value = match self.next_line(&mut follower).await {
|
let start: Value = match self.next_line(&mut follower).await {
|
||||||
Ok(Some(line)) => match serde_json::from_str(&line) {
|
Ok(Some(line)) => match serde_json::from_str(&line) {
|
||||||
Ok(v) => v,
|
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,
|
Err(end) => return end,
|
||||||
};
|
};
|
||||||
let Some(startup) = start["operational"]["captures"]
|
let Some(startup) = start["operational"]["captures"]
|
||||||
|
|
@ -526,7 +582,10 @@ impl Shadow {
|
||||||
.and_then(generation_of_capture)
|
.and_then(generation_of_capture)
|
||||||
.filter(|_| start.get("boundary").is_some())
|
.filter(|_| start.get("boundary").is_some())
|
||||||
else {
|
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 bytes = {
|
||||||
let mut waited = Duration::ZERO;
|
let mut waited = Duration::ZERO;
|
||||||
|
|
@ -535,9 +594,12 @@ impl Shadow {
|
||||||
break bytes;
|
break bytes;
|
||||||
}
|
}
|
||||||
if waited >= Duration::from_secs(30) {
|
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"
|
"the startup save g{startup} is no longer in the stores or the spool"
|
||||||
));
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
waited += Duration::from_millis(500);
|
waited += Duration::from_millis(500);
|
||||||
|
|
@ -560,10 +622,13 @@ impl Shadow {
|
||||||
flybrain_gb::GameAdapter::migrates_from(&adapter),
|
flybrain_gb::GameAdapter::migrates_from(&adapter),
|
||||||
);
|
);
|
||||||
if let Err(reason) = gate.check(&checkpoint) {
|
if let Err(reason) = gate.check(&checkpoint) {
|
||||||
return SegmentEnd::Skipped(format!(
|
return SegmentEnd::Diverged(Box::new(self.boot_failure(
|
||||||
"the live process's startup save is not this candidate's to restore ({reason}): \
|
&name,
|
||||||
is the shadow the build the live service runs?"
|
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 segment_dir = self.config.work_dir.join(format!("segment-{startup}"));
|
||||||
let _ = std::fs::remove_dir_all(&segment_dir);
|
let _ = std::fs::remove_dir_all(&segment_dir);
|
||||||
|
|
@ -571,7 +636,11 @@ impl Shadow {
|
||||||
let mut session =
|
let mut session =
|
||||||
match LegacySession::start(&segment_dir, self.session_config.clone()).await {
|
match LegacySession::start(&segment_dir, self.session_config.clone()).await {
|
||||||
Ok(s) => s,
|
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
|
// 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`,
|
// 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;
|
self.verdict.segments_compared += 1;
|
||||||
// Rollbacks wait for the boundary's captures, as the host orders them (section 16).
|
// Rollbacks wait for the boundary's captures, as the host orders them (section 16).
|
||||||
session.coordinator.defer_rollbacks(true);
|
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
|
let end = self
|
||||||
.run_segment(&name, &mut follower, &mut session, rank_since_ms)
|
.run_segment(&name, &mut follower, &mut session, rank_since_ms)
|
||||||
.await;
|
.await;
|
||||||
|
|
@ -685,10 +756,15 @@ impl Shadow {
|
||||||
};
|
};
|
||||||
let live: Value = match serde_json::from_str(&line) {
|
let live: Value = match serde_json::from_str(&line) {
|
||||||
Ok(v) => v,
|
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() {
|
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 {
|
let Some(behaviour) = live.get("behaviour").cloned() else {
|
||||||
continue;
|
continue;
|
||||||
|
|
@ -699,18 +775,27 @@ impl Shadow {
|
||||||
match admission_line["kind"].as_str() {
|
match admission_line["kind"].as_str() {
|
||||||
Some("sugar") => {
|
Some("sugar") => {
|
||||||
let Some(duration) = admission_line["durationMs"].as_f64() else {
|
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);
|
admission.replay_sugar(duration);
|
||||||
}
|
}
|
||||||
Some("reward") => {
|
Some("reward") => {
|
||||||
return SegmentEnd::Skipped(format!(
|
return SegmentEnd::Skipped(
|
||||||
|
"operator-reward-pulse",
|
||||||
|
format!(
|
||||||
"an operator reward pulse at step {step:?} (declared \
|
"an operator reward pulse at step {step:?} (declared \
|
||||||
operator-reward-pulse: not available on the session runtime)"
|
operator-reward-pulse: not available on the session runtime)"
|
||||||
));
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
other => {
|
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 {
|
match session.coordinator.capture_payloads(&checkpoint_id).await {
|
||||||
Ok((boundary, world_payload, agents)) => {
|
Ok((boundary, world_payload, agents)) => {
|
||||||
let Some((_, agent_payload)) = agents.into_iter().next() else {
|
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((
|
taken.push((
|
||||||
*generation,
|
*generation,
|
||||||
|
|
@ -823,12 +915,28 @@ impl Shadow {
|
||||||
let records = session.task.take_records();
|
let records = session.task.take_records();
|
||||||
let elapsed = t0.elapsed().as_secs_f64() * 1000.0;
|
let elapsed = t0.elapsed().as_secs_f64() * 1000.0;
|
||||||
self.verdict.cost.record(elapsed);
|
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 {
|
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) {
|
let mut shadow_line = match trace::line(&details, record) {
|
||||||
Ok(line) => line["behaviour"].clone(),
|
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() {
|
if behaviour.get("ledgersDigest").is_some() {
|
||||||
shadow_line["ledgersDigest"] = Value::String(sha256_hex(record.ledgers.as_bytes()));
|
shadow_line["ledgersDigest"] = Value::String(sha256_hex(record.ledgers.as_bytes()));
|
||||||
|
|
@ -921,6 +1029,12 @@ impl Shadow {
|
||||||
.unwrap_or(0.0);
|
.unwrap_or(0.0);
|
||||||
if self.verdict.status == Status::Running
|
if self.verdict.status == Status::Running
|
||||||
&& self.verdict.brain_seconds() >= self.config.required_brain_seconds
|
&& 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.status = Status::Pass;
|
||||||
self.verdict.passed_at = Some(verdict::now_iso());
|
self.verdict.passed_at = Some(verdict::now_iso());
|
||||||
|
|
|
||||||
|
|
@ -19,12 +19,24 @@
|
||||||
//! before it passed (a `pass` stays `pass` when the shadow stops). `error` is the shadow's own
|
//! 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.
|
//! 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:
|
//! **The cutover rule (for CUT-01), [`allows_cutover`].** Cut over only if, read at the moment of
|
||||||
//! `format` is `fly-shadow-verdict-v1`; `status` is `pass`; `firstDivergence` is `null`;
|
//! cutting over, every one of these holds; anything else keeps the legacy fly:
|
||||||
//! 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);
|
//! - `format` is `fly-shadow-verdict-v1`, `status` is `pass`, `firstDivergence` is `null`, and
|
||||||
//! `candidate.compatibility` is the live service's `--print-compatibility`; and `updatedAt` is no
|
//! `compared.brainSeconds` reaches `required.brainSeconds`;
|
||||||
//! older than a few minutes (the shadow is still following). Anything else keeps the legacy fly.
|
//! - *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;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|
@ -34,6 +46,26 @@ use crate::trace::{Agreement, Difference};
|
||||||
|
|
||||||
pub const FORMAT: &str = "fly-shadow-verdict-v1";
|
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`).
|
/// The declared differences the comparison applies, by name (`legacy-gameboy-v1`).
|
||||||
pub const DECLARED: [(&str, &str); 5] = [
|
pub const DECLARED: [(&str, &str); 5] = [
|
||||||
(
|
(
|
||||||
|
|
@ -100,6 +132,8 @@ pub struct Checkpoints {
|
||||||
pub struct Skipped {
|
pub struct Skipped {
|
||||||
pub trace: String,
|
pub trace: String,
|
||||||
pub transitions_compared: u64,
|
pub transitions_compared: u64,
|
||||||
|
/// One of [`SKIP_KINDS`], or `trace-malformed`.
|
||||||
|
pub kind: String,
|
||||||
pub reason: String,
|
pub reason: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -274,7 +308,7 @@ impl Verdict {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"skipped": self.skipped.iter().map(|s| json!({
|
"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<_>>(),
|
})).collect::<Vec<_>>(),
|
||||||
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
|
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
|
||||||
"firstDivergence": self.divergence.as_ref().map(|d| {
|
"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)
|
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.
|
/// 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
|
/// `binary` is the file name of the session-runtime binary CUT-01 switches to, inside `release`
|
||||||
/// `compatibility` the live service's; `max_age_s` bounds `updatedAt`.
|
/// (what `/opt/fly/current` resolves to now), and `compatibility` the live service's;
|
||||||
|
/// `max_age_s` bounds `updatedAt`.
|
||||||
pub fn allows_cutover(
|
pub fn allows_cutover(
|
||||||
verdict: &Value,
|
verdict: &Value,
|
||||||
binary: (&str, &str),
|
binary: &str,
|
||||||
|
release: &Release<'_>,
|
||||||
compatibility: &str,
|
compatibility: &str,
|
||||||
now_ms: i64,
|
now_ms: i64,
|
||||||
max_age_s: i64,
|
max_age_s: i64,
|
||||||
|
|
@ -322,13 +383,28 @@ pub fn allows_cutover(
|
||||||
if !verdict["firstDivergence"].is_null() {
|
if !verdict["firstDivergence"].is_null() {
|
||||||
return Err("a divergence is recorded".to_owned());
|
return Err("a divergence is recorded".to_owned());
|
||||||
}
|
}
|
||||||
let (name, sha256) = binary;
|
let candidate = &verdict["candidate"];
|
||||||
if verdict["candidate"]["binaries"][name] != sha256 {
|
if candidate["release"] != release.dir {
|
||||||
return Err(format!(
|
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());
|
return Err("the verdict is for another compatibility string".to_owned());
|
||||||
}
|
}
|
||||||
let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0);
|
let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0);
|
||||||
|
|
@ -338,6 +414,27 @@ pub fn allows_cutover(
|
||||||
if compared < required {
|
if compared < required {
|
||||||
return Err(format!("{compared} of {required} brain seconds compared"));
|
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"]
|
let updated = verdict["updatedAt"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.and_then(parse_iso)
|
.and_then(parse_iso)
|
||||||
|
|
@ -388,7 +485,7 @@ mod tests {
|
||||||
status,
|
status,
|
||||||
reason: String::new(),
|
reason: String::new(),
|
||||||
binary_sha256: "b".repeat(64),
|
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(),
|
release: "/opt/fly/releases/test".to_owned(),
|
||||||
compatibility: "c".to_owned(),
|
compatibility: "c".to_owned(),
|
||||||
execution_mode: "in-process".to_owned(),
|
execution_mode: "in-process".to_owned(),
|
||||||
|
|
@ -397,7 +494,11 @@ mod tests {
|
||||||
agreement: Agreement::default(),
|
agreement: Agreement::default(),
|
||||||
brain_ms,
|
brain_ms,
|
||||||
ledger_checks: 0,
|
ledger_checks: 0,
|
||||||
checkpoints: Checkpoints::default(),
|
checkpoints: Checkpoints {
|
||||||
|
identical: 2_000,
|
||||||
|
declared: 1,
|
||||||
|
unavailable: 5,
|
||||||
|
},
|
||||||
segments_compared: 1,
|
segments_compared: 1,
|
||||||
skipped: Vec::new(),
|
skipped: Vec::new(),
|
||||||
divergence: None,
|
divergence: None,
|
||||||
|
|
@ -415,27 +516,62 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn the_cutover_rule() {
|
fn the_cutover_rule() {
|
||||||
let now = parse_iso(&now_iso()).unwrap();
|
let now = parse_iso(&now_iso()).unwrap();
|
||||||
let sha = "b".repeat(64);
|
let binaries: std::collections::BTreeMap<String, String> =
|
||||||
let bin = ("fly-session", sha.as_str());
|
[("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);
|
let pass = verdict(Status::Pass, 10_800_000.0);
|
||||||
assert_eq!(allows_cutover(&pass, bin, "c", now, 300), Ok(()));
|
assert_eq!(ok(&pass), Ok(()));
|
||||||
let other = "a".repeat(64);
|
// Another binary, another release, a changed file in it.
|
||||||
assert!(allows_cutover(&pass, ("fly-session", &other), "c", now, 300).is_err());
|
assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err());
|
||||||
assert!(allows_cutover(&pass, ("fly-other", &sha), "c", now, 300).is_err());
|
let moved = Release {
|
||||||
assert!(allows_cutover(&pass, bin, "other", now, 300).is_err());
|
dir: "/opt/fly/releases/other",
|
||||||
assert!(allows_cutover(&pass, bin, "c", now + 301_000, 300).is_err());
|
binaries: &binaries,
|
||||||
let short = verdict(Status::Pass, 10_799_000.0);
|
};
|
||||||
assert!(allows_cutover(&short, bin, "c", now, 300).is_err());
|
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 [
|
for status in [
|
||||||
Status::Running,
|
Status::Running,
|
||||||
Status::Diverged,
|
Status::Diverged,
|
||||||
Status::Stopped,
|
Status::Stopped,
|
||||||
Status::Error,
|
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();
|
let mut diverged = pass.clone();
|
||||||
diverged["firstDivergence"] = json!({"kind": "transition"});
|
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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -242,9 +242,21 @@ fn diverges(
|
||||||
trace: &Path,
|
trace: &Path,
|
||||||
spool: &Path,
|
spool: &Path,
|
||||||
empty: &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 {
|
) -> shadow::verdict::Verdict {
|
||||||
let _ = std::fs::remove_dir_all(root.join("out"));
|
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 stop = StopFlag::default();
|
||||||
let handle = spawn_shadow(config, stop.clone());
|
let handle = spawn_shadow(config, stop.clone());
|
||||||
let deadline = Instant::now() + Duration::from_secs(600);
|
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 out = config.out_dir.clone();
|
||||||
let stop = StopFlag::default();
|
let stop = StopFlag::default();
|
||||||
let handle = spawn_shadow(config, stop.clone());
|
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.
|
// 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"));
|
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");
|
let d = got.divergence.expect("a divergence");
|
||||||
assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at)));
|
assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at)));
|
||||||
assert!(d.detail.contains("rankSinceMs"), "{}", d.detail);
|
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());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -102,6 +102,9 @@ wall0=$(date +%s.%N)
|
||||||
--mode "$mode" --threads "$threads" --max-live-lag-seconds "$guard" \
|
--mode "$mode" --threads "$threads" --max-live-lag-seconds "$guard" \
|
||||||
--required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 &
|
--required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 &
|
||||||
shadow_pid=$!
|
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
|
start_live
|
||||||
echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)"
|
echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)"
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue