shadow: r3 notes: a reward skip still reads on for a stop; the relay flags a byte-cap stop; a window end takes back a pass; runbook: a new run after a long outage

N5: after an operator reward pulse the shadow reads the rest of the trace for its stop line, which ends the window. N4: the relay treats a byte-cap stop exactly like a no-consumer stop. N3: end_window turns a pass back into running and clears passedAt and reason. N2: the runbook says plainly that a long outage costs the run and gives the command to start a new one.
This commit is contained in:
acamilo 2026-10-01 04:42:02 +00:00
parent ff67e6cdd6
commit 01fae60e37
6 changed files with 183 additions and 47 deletions

View file

@ -629,10 +629,21 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
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.
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
new window has compared the required time.
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
would have to restart while the stopped trace is still the newest file and reach its stop before
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
one.
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
and the run is lost (safe: start a new run as above); do not rely on the fast case.
`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:

View file

@ -1064,6 +1064,11 @@ impl Shadow {
let mut rank_since_ms = rank_since_ms;
let mut context: VecDeque<(Value, Value)> = VecDeque::new();
let mut captures_taken: u64 = 0;
// After a declared reward pulse the rest of the trace cannot be compared, but it is still
// read for its stop line: a stop later in the same trace is a coverage gap and must end
// the window (SHADOW-02 r3 N5).
let mut reward_skipped = false;
let compared_before = self.verdict.agreement.transitions;
loop {
let line = match self.next_line(follower).await {
Ok(Some(line)) => line,
@ -1103,6 +1108,9 @@ impl Shadow {
format!("the live trace stopped ({})", live["reason"]),
);
}
if reward_skipped {
continue;
}
let Some(behaviour) = live.get("behaviour").cloned() else {
continue;
};
@ -1120,13 +1128,22 @@ impl Shadow {
admission.replay_sugar(duration);
}
Some("reward") => {
return SegmentEnd::Skipped(
"operator-reward-pulse",
format!(
let compared = self.verdict.agreement.transitions - compared_before;
eprintln!(
"fly-shadow: {name} skipped (operator-reward-pulse) after {compared} \
transitions; reading on for a stop"
);
self.verdict.skipped.push(Skipped {
trace: name.to_owned(),
transitions_compared: compared,
kind: "operator-reward-pulse".to_owned(),
reason: format!(
"an operator reward pulse at step {step:?} (declared \
operator-reward-pulse: not available on the session runtime)"
),
);
});
reward_skipped = true;
break;
}
other => {
return SegmentEnd::Skipped(
@ -1136,6 +1153,9 @@ impl Shadow {
}
}
}
if reward_skipped {
continue;
}
// Back off while the live fly is losing real time ([`LagGuard`]).
if let Some(lag) = self.lag.clone() {
let throttle = Instant::now();

View file

@ -42,8 +42,8 @@
//! The box may send at most three divergence files, and only after a diverged verdict of this run
//! ([`DivergenceFiles`]): a faulty box cannot fill the container's disk.
//!
//! **Coverage lost.** A trace that flysim stopped for want of a consumer (`"reason":"no-consumer"`,
//! after ten minutes without a heartbeat) leaves the live fly running untraced, and the box's
//! **Coverage lost.** A trace that flysim stopped (`"reason":"no-consumer"`, after ten minutes without a
//! heartbeat, or `"reason":"byte-cap"`) leaves the live fly running untraced, and the box's
//! catch-up bound counts trace *lines*, so a box that has not yet reached that line looks caught up
//! 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
@ -261,7 +261,7 @@ struct Relay {
scan_tail: BTreeMap<String, (u64, Vec<u8>)>,
}
/// Coverage of the live fly was lost: flysim stopped its trace for want of a consumer.
/// Coverage of the live fly was lost: flysim stopped its trace (no consumer, or the byte cap).
#[derive(Clone, Debug, PartialEq, Eq)]
struct CoverageLost {
trace: String,
@ -270,7 +270,6 @@ struct CoverageLost {
at: String,
}
/// 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 (
@ -282,15 +281,16 @@ fn trace_not_before(a: &str, b: &str) -> bool {
}
}
const NO_CONSUMER_MARKER: &[u8] = b"\"reason\":\"no-consumer\"";
/// The reasons for which flysim stops a trace, as written in its `{"truncated":true,"reason":..}`
/// line: no consumer (a stale heartbeat) and the byte cap. Both leave the live fly running
/// untraced, so the relay treats them alike (SHADOW-02 r3 N4).
const STOP_MARKERS: [&[u8]; 2] = [b"\"reason\":\"no-consumer\"", b"\"reason\":\"byte-cap\""];
/// Whether `bytes` hold a whole `{"truncated":true,"reason":"no-consumer"}` line.
fn has_no_consumer_marker(bytes: &[u8]) -> bool {
/// Whether `bytes` hold a whole `{"truncated":true,"reason":"no-consumer"|"byte-cap"}` line.
fn has_stop_marker(bytes: &[u8]) -> bool {
STOP_MARKERS.iter().any(|marker| {
let mut from = 0;
while let Some(i) = bytes[from..]
.windows(NO_CONSUMER_MARKER.len())
.position(|w| w == NO_CONSUMER_MARKER)
{
while let Some(i) = bytes[from..].windows(marker.len()).position(|w| w == *marker) {
let at = from + i;
let start = bytes[..at].iter().rposition(|b| *b == b'\n').map_or(0, |n| n + 1);
let end = bytes[at..].iter().position(|b| *b == b'\n').map_or(bytes.len(), |n| at + n);
@ -300,6 +300,7 @@ fn has_no_consumer_marker(bytes: &[u8]) -> bool {
from = at + 1;
}
false
})
}
/// The divergence files the relay takes from the box: only after a diverged verdict of this run,
@ -700,16 +701,16 @@ impl Relay {
}
}
/// Looks for flysim's no-consumer stop in trace bytes about to be sent.
/// Looks for flysim's stop (no consumer, byte cap) 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) {
Some((end, tail)) if end == offset => tail,
_ => Vec::new(),
};
buf.extend_from_slice(chunk);
if self.coverage_lost.is_none() && has_no_consumer_marker(&buf) {
if self.coverage_lost.is_none() && has_stop_marker(&buf) {
log(format!(
"{name}: flysim stopped its trace for want of a consumer; coverage of the live fly \
"{name}: flysim stopped its trace (no consumer or byte cap); coverage of the live fly \
is lost for this window"
));
self.coverage_lost = Some(CoverageLost {
@ -1127,19 +1128,21 @@ mod tests {
#[test]
fn the_no_consumer_stop_is_found_and_nothing_else_is() {
assert!(has_no_consumer_marker(
assert!(has_stop_marker(
b"{\"a\":1}\n{\"reason\":\"no-consumer\",\"truncated\":true}\n"
));
assert!(has_no_consumer_marker(
assert!(has_stop_marker(
b"{\"truncated\":true,\"reason\":\"no-consumer\"}"
));
// The byte cap is an allowed skip (`trace-cap`), not a lost consumer.
assert!(!has_no_consumer_marker(
// The byte cap is a stop like any other (N4).
assert!(has_stop_marker(
b"{\"reason\":\"byte-cap\",\"truncated\":true}\n"
));
assert!(!has_stop_marker(b"{\"reason\":\"other\",\"truncated\":true}\n"));
assert!(!has_stop_marker(b"{\"reason\":\"byte-cap\"}\n"));
// Not a marker line.
assert!(!has_no_consumer_marker(b"{\"note\":{\"reason\":\"no-consumer\"}}\n"));
assert!(!has_no_consumer_marker(b""));
assert!(!has_stop_marker(b"{\"note\":{\"reason\":\"no-consumer\"}}\n"));
assert!(!has_stop_marker(b""));
}
#[test]

View file

@ -298,6 +298,13 @@ impl Verdict {
self.last_stop_trace = Some(trace.to_owned());
self.brain_ms = 0.0;
self.checkpoints = Checkpoints::default();
// A pass belongs to the window it was reached in: the new one has not qualified yet
// (r3 N3). A diverged or errored verdict stays what it is.
if self.status == Status::Pass {
self.status = Status::Running;
self.passed_at = None;
self.reason = String::new();
}
}
pub fn brain_seconds(&self) -> f64 {
@ -591,11 +598,9 @@ 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,
fn verdict_struct(status: Status) -> Verdict {
Verdict {
status,
reason: String::new(),
binary_sha256: String::new(),
binaries: Default::default(),
@ -625,6 +630,18 @@ mod tests {
spool_evicted: 0,
cost: Cost::default(),
run_id: None,
}
}
#[test]
fn a_stop_ends_the_window() {
// B2: brain time compared before a coverage gap never counts toward a pass.
let mut v = verdict_struct(Status::Running);
v.brain_ms = 1_819_000.0;
v.checkpoints = Checkpoints {
identical: 400,
declared: 0,
unavailable: 0,
};
v.end_window("trace-1.jsonl", "no-consumer".to_owned());
assert_eq!(v.brain_seconds(), 0.0);
@ -638,6 +655,32 @@ mod tests {
assert!(!SKIP_KINDS.contains(&"trace-cap"));
}
#[test]
fn a_window_end_takes_back_a_pass_and_nothing_else() {
let mut v = verdict_struct(Status::Pass);
v.passed_at = Some(now_iso());
v.reason = "10800 s compared".to_owned();
v.brain_ms = 10_800_000.0;
v.end_window("trace-2.jsonl", "byte-cap".to_owned());
let j = v.to_json();
assert_eq!(j["status"], "running");
assert!(j["passedAt"].is_null());
assert_eq!(j["compared"]["brainSeconds"], 0.0);
assert_eq!(j["window"]["lastStopTrace"], "trace-2.jsonl");
// The cutover rule refuses it on any count.
let now = parse_iso(&now_iso()).unwrap();
let binaries: std::collections::BTreeMap<String, String> = Default::default();
let release = Release { dir: "/opt/fly/releases/test", binaries: &binaries };
assert!(allows_cutover(&j, "flysim-session", &release, "c", now, 300).is_err());
let mut forced = j.clone();
forced["status"] = json!("pass");
assert!(allows_cutover(&forced, "flysim-session", &release, "c", now, 300).is_err());
// Diverged stays diverged.
let mut d = verdict_struct(Status::Diverged);
d.end_window("trace-3.jsonl", "no-consumer".to_owned());
assert_eq!(d.status, Status::Diverged);
}
#[test]
fn the_cutover_rule() {
let now = parse_iso(&now_iso()).unwrap();

View file

@ -569,4 +569,57 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
assert_eq!(d.kind, "boot", "{}", d.detail);
assert!(d.detail.contains("restore gate"), "{}", d.detail);
assert!(got.skipped.is_empty());
// r3 N5: a declared reward pulse ends the comparison of its trace, but a stop later in the
// same trace (here the byte cap) must still end the window: what was compared before the
// pulse, and the untraced time after the stop, must not count toward a pass.
let full_brain_seconds = verdict.brain_seconds();
let at = tampered(&dirs.trace, &neg.join("reward/trace"), |n, v| {
(n == 100)
.then(|| v["behaviour"]["admissions"] = serde_json::json!([{"kind": "reward"}]))
.is_some()
});
let files = transitions(&neg.join("reward/trace"));
let (first_name, second_n) = (
files[0].0.file_name().unwrap().to_string_lossy().into_owned(),
files[1].1,
);
{
use std::io::Write;
let mut f = std::fs::OpenOptions::new().append(true).open(&files[0].0).unwrap();
writeln!(f, "{{\"truncated\":true,\"reason\":\"byte-cap\"}}").unwrap();
}
let _ = std::fs::remove_dir_all(neg.join("reward").join("out"));
let reward_config = self::config(&rom, &neg.join("reward"), &neg.join("reward/trace"), (&empty, &empty), &spool);
let out = reward_config.out_dir.clone();
let stop = StopFlag::default();
let handle = spawn_shadow(reward_config, stop.clone());
let deadline = Instant::now() + Duration::from_secs(600);
loop {
let v = verdict_of(&out);
let ended = !v["window"]["ends"].as_array().is_none_or(|e| e.is_empty());
if (ended && v["compared"]["transitions"].as_u64() >= Some(101 + second_n as u64))
|| handle.is_finished()
|| Instant::now() > deadline
{
break;
}
std::thread::sleep(Duration::from_millis(100));
}
stop.request();
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
assert_ne!(ended, Ended::Diverged, "{:?}", verdict.reason);
let j = verdict.to_json();
eprintln!("reward then stop (reward at step {at}): {j}");
assert_eq!(j["skipped"][0]["kind"], "operator-reward-pulse", "{j}");
assert_eq!(j["window"]["lastStopTrace"], first_name.as_str(), "{j}");
assert_eq!(j["window"]["ends"][0]["trace"], first_name.as_str(), "{j}");
assert!(j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap() > 0.0, "{j}");
// Only the second process counts, after the window ended: what the first one compared before
// the pulse is dropped and its uncompared remainder never was added, so less than the whole.
let whole = full_brain_seconds;
let after = j["compared"]["brainSeconds"].as_f64().unwrap();
let dropped = j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap();
assert!(after + dropped < whole - 1.0, "{after} + {dropped} against {whole}: {j}");
assert_ne!(j["status"], "pass", "{j}");
}

View file

@ -215,17 +215,23 @@ fn a_no_consumer_stop_in_the_forwarded_trace_makes_the_relay_unhealthy_until_a_n
let _ = &s.mirror;
}
/// A stop of another kind (the byte cap) is an allowed skip and does not lose coverage.
/// N4: the byte cap stops the trace like a missing consumer: the live fly runs untraced from
/// there, so the relay flags it the same way (sticky, durable, unhealthy).
#[test]
fn a_byte_cap_stop_is_not_a_lost_coverage() {
fn a_byte_cap_stop_is_a_lost_coverage_like_a_no_consumer_stop() {
let tmp = tempfile::tempdir().unwrap();
let s = Setup::start(tmp.path());
let trace = s.container.join("trace").join(TRACE);
append(&trace, b"{\"boot\":true}\n{\"reason\":\"byte-cap\",\"truncated\":true}\n");
std::thread::sleep(Duration::from_secs(3));
wait_for("the byte-cap stop to be flagged", 60, || {
!s.relay_json()["coverageLost"].is_null()
});
let r = s.relay_json();
assert!(r["coverageLost"].is_null(), "{r}");
wait_for("a healthy relay", 60, || s.relay_json()["healthy"] == true);
assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}");
assert_eq!(r["healthy"], false, "{r}");
// Durable: relay.json on disk says so (the same file a restarted relay reads).
std::thread::sleep(Duration::from_secs(2));
assert!(!s.relay_json()["coverageLost"].is_null(), "sticky: {}", s.relay_json());
}
/// A relay restart within the run keeps what the first relay saw.