shadow: a lost coverage is never forgotten (SHADOW-02 review B1) and the review notes

B1: after an outage of more than ten minutes flysim stops its trace for want of a
consumer and the live fly runs untraced. When the link heals the relay reported healthy
and, counted in trace lines, the box's lag fell under the catch-up bound before its
shadow reached the stop, so `check` could pass for about a minute. The relay now scans
the trace bytes it forwards for that stop and sets a sticky coverageLost in relay.json
(kept across a relay restart of the run; cleared only by a new shadow window, which
takes the stop as history) and reports itself not healthy. `check` refuses on
coverageLost, on a live trace not written for 90 s, and on a run id that is not the
drop-in's (also for a verdict that carries one without a remote drop-in).

Notes: the divergence files the box may send are bounded (after a diverged verdict, at
most three, capped in size); the saves queue holds twelve minutes and the relay unit
gets 1G; fly-shadow-remote-setup keeps authorized_keys in a root-owned home apart from
the mirror, never follows a symlink there as root and requires --from; the runbook
documents the clock-skew refusal, the recovered-stop rule and the first-hour RTF watch.
Also: the ingest lists the mirror's traces under its ledger lock (a file created between
the listing and the lock was marked finished).
This commit is contained in:
acamilo 2026-09-30 21:25:36 +00:00
parent 32df851c16
commit b39ee8e805
8 changed files with 648 additions and 55 deletions

View file

@ -64,7 +64,9 @@
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy and less than a minute old.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
#
# Files (all owned by fly):
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
@ -325,7 +327,7 @@ CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=512M
MemoryMax=1G
EOF
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
else
@ -494,36 +496,64 @@ check() {
exit 1
fi
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
# alive, the sync caught up), not just have relayed a pass lately.
if [ -f "$REMOTE_DROPIN" ]; then
local why rc=0
why="$(python3 - "$SHADOW_DIR/relay.json" <<'PY'
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
local why rc=0 run_id=""
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
import datetime, json, sys
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
def refuse(msg):
print(msg); sys.exit(1)
try:
r = json.load(open(sys.argv[1]))
v = json.load(open(verdict_path))
except Exception:
v = {}
if mode == "local":
if v.get("runId") is not None:
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
sys.exit(0)
if not run_id:
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
try:
r = json.load(open(relay_path))
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
print("no readable relay.json (%s)" % e); sys.exit(1)
refuse("no readable relay.json (%s)" % e)
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
print("relay.json is %.0f s old" % age); sys.exit(1)
refuse("relay.json is %.0f s old" % age)
if r.get("runId") != run_id:
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
if v.get("runId") != run_id:
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
if r.get("coverageLost"):
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
if not r.get("healthy"):
print("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or "")); sys.exit(1)
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
ta = r.get("traceAgeSeconds")
if ta is None:
refuse("no live trace file of this run")
if ta > 90:
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
PY
)" || rc=$?
if [ "$rc" != 0 ]; then
echo "cutover refused: remote shadow: $why"
exit 1
fi
fi
[ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string.
set -a
# shellcheck disable=SC1091
. /etc/fly/fly.env
. "${FLY_ENV_FILE:-/etc/fly/fly.env}"
set +a
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current "${FLY_CURRENT_DIR:-/opt/fly/current}" \
--binary flysim-session "$@"
}

View file

@ -3,7 +3,7 @@
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
# Idempotent: re-run it for every release the container runs.
#
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY [--from ADDRS] [--cpus LIST] [--threads N]
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
#
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
@ -13,29 +13,32 @@
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
# --from ADDRS restricts the key to the container's address (authorized_keys from=).
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
# live fly's NUMA node.
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
# clearly faster than real time: see the runbook's "Which box".
#
# What it sets up:
# - user flyshadow, home /srv/fly-shadow-remote (the mirror; 0750);
# - /srv/fly-shadow-remote/.ssh/authorized_keys, ROOT-owned (the user cannot change it), with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote"
# [,from="..."] <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# ignores what the client asks for; the ingest writes nothing outside the mirror;
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
# run id the relay brings).
# Nothing here knows or stores the release container's address; the relay dials out to the box.
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
set -euo pipefail
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
log() { echo "fly-shadow-remote-setup: $*"; }
[ "$(id -u)" = 0 ] || die "run as root on the build box"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY [--from ADDRS] [--cpus LIST] [--threads N]"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
from=""; cpus=""; threads=4
while [ $# -gt 0 ]; do
@ -48,6 +51,8 @@ while [ $# -gt 0 ]; do
done
here="$(cd "$(dirname "$0")" && pwd)"
ROOT=/srv/fly-shadow-remote
HOME_DIR=/srv/fly-shadow-remote-home
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
[ -f "$tarball" ] || die "no tarball $tarball"
[ -f "$rom" ] || die "no ROM $rom"
[ -f "$pubkey" ] || die "no public key $pubkey"
@ -76,16 +81,39 @@ fi
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
log "/opt/fly/current -> $release"
# The user and the mirror.
id flyshadow >/dev/null 2>&1 || useradd --system --home-dir "$ROOT" --shell /bin/sh --user-group flyshadow
install -d -o flyshadow -g flyshadow -m 0750 "$ROOT"
for d in trace hot durable out; do install -d -o flyshadow -g flyshadow -m 0750 "$ROOT/$d"; done
install -d -o root -g root -m 0755 "$ROOT/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\""
[ -n "$from" ] && line="$line,from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$ROOT/.ssh/authorized_keys.new"
chown root:root "$ROOT/.ssh/authorized_keys.new"; chmod 0644 "$ROOT/.ssh/authorized_keys.new"
mv -f "$ROOT/.ssh/authorized_keys.new" "$ROOT/.ssh/authorized_keys"
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
if id flyshadow >/dev/null 2>&1; then
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
else
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
fi
if [ -e "$ROOT" ]; then
[ -d "$ROOT" ] || die "$ROOT is not a directory"
else
mkdir -m 0750 "$ROOT"
chown -h flyshadow:flyshadow "$ROOT"
fi
for d in trace hot durable out; do
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
if [ -e "$ROOT/$d" ]; then
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
else
mkdir -m 0750 "$ROOT/$d"
chown -h flyshadow:flyshadow "$ROOT/$d"
fi
done
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
install -d -o root -g root -m 0755 "$HOME_DIR"
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
log "authorized_keys: the relay key may run only the ingest"
# The cartridge and this box's paths.

View file

@ -1,5 +1,5 @@
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
# by infra/bin/fly-shadow-remote-setup (SHADOW-02).
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
#
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the

View file

@ -587,6 +587,13 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
- the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
other shadowed binary unchanged;
- the shadow is caught up (at most about a minute behind);
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
a trace that is not being written while the shadow claims to follow refuses the check (a paused
flysim refuses too, until it runs);
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
refuse (safe, not silent). Run NTP on both;
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
(a clock stepped back must not keep an old pass fresh);
- no segment was skipped for a reason other than the live side's own.
@ -606,8 +613,16 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A
network blip shorter than the 10 minutes costs nothing: the relay resumes where the box's copy
ends.
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
until the box's shadow reaches the stop and diverges (`coverage`), or restarts (a new window,
which treats the stop as history). Catching up never clears it.
- **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:
@ -646,8 +661,9 @@ on the build box can reach the release container: the container dials out.
`infra/box/` and the public key there, then
`infra/box/fly-shadow-remote-setup flybrain-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
root-owned), a `flyshadow` user whose home is the mirror `/srv/fly-shadow-remote`, a
root-owned `authorized_keys` whose only line is
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
@ -659,7 +675,11 @@ on the build box can reach the release container: the container dials out.
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
it and runs in remote mode.
4. `fly-shadow-run start` as above. The ingest refuses a relay whose release directory or binaries
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
after an hour. The ingest refuses a relay whose release directory or binaries
differ from the box's (another release on the container: re-run step 2 with its tarball);
`journalctl -u flyshadow` on the container shows it.

View file

@ -736,20 +736,24 @@ rs_start "a remote file without its key" "FLY_SHADOW_REMOTE=user@box
FLY_SHADOW_REMOTE_KEY=$cs_tmp/missing-key
FLY_SHADOW_REMOTE_KNOWN_HOSTS=$cs_tmp/missing-known"
rm -rf "$cs_tmp"
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute old).
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute
# old), of this run (the drop-in's id, the verdict's too), without coverageLost (review B1: flysim
# stopped its trace for want of a consumer) and with a live trace written in the last 90 s.
if command -v python3 >/dev/null 2>&1; then
rc_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-relay.XXXXXX")"
mkdir -p "$rc_tmp/bin" "$rc_tmp/shadow" "$rc_tmp/flyshadow.d"
printf '#!/bin/sh\ncase "$1" in is-active) exit 0 ;; esac\nexit 0\n' > "$rc_tmp/bin/systemctl"
chmod +x "$rc_tmp/bin/systemctl"
: > "$rc_tmp/flyshadow.d/remote.conf"
printf '[Service]\nEnvironment=FLY_SHADOW_RUN_ID=1790000000000\n' > "$rc_tmp/flyshadow.d/remote.conf"
printf '{"rtfMean":1,"rtfSd":0,"lagRate":0,"samples":60,"margin":0.05}\n' > "$rc_tmp/shadow/baseline.json"
rc_check() { # name, expect (refused|passes-gates), relay.json (or none)
local rc=0 out
rc_check() { # name, expect (refused|passes-gates), relay.json (or none), verdict.json (default: this run's), [local]
local rc=0 out dropin_dir="$rc_tmp/flyshadow.d"
rm -f "$rc_tmp/shadow/relay.json"
[ "$3" = none ] || printf '%s\n' "$3" > "$rc_tmp/shadow/relay.json"
printf '%s\n' "${4:-{\"runId\":\"1790000000000\",\"status\":\"running\"\}}" > "$rc_tmp/shadow/verdict.json"
[ "${5:-}" = local ] && dropin_dir="$rc_tmp/none.d"
out="$(PATH="$rc_tmp/bin:$PATH" FLY_SHADOW_DIR="$rc_tmp/shadow" FLY_SHADOW_BIN="$rc_tmp/none" \
FLY_SHADOW_REMOTE_DROPIN_DIR="$rc_tmp/flyshadow.d" "$INFRA_DIR/bin/fly-shadow-run" check 2>&1)" || rc=$?
FLY_SHADOW_REMOTE_DROPIN_DIR="$dropin_dir" "$INFRA_DIR/bin/fly-shadow-run" check 2>&1)" || rc=$?
case "$2:$rc" in
refused:1) pass "fly-shadow-run check (remote), $1: ${out#cutover refused: }" ;;
passes-gates:2) pass "fly-shadow-run check (remote), $1: past the relay precondition" ;;
@ -758,10 +762,20 @@ if command -v python3 >/dev/null 2>&1; then
}
now="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
old="$(date -u -d '-5 min' +%Y-%m-%dT%H:%M:%S.000Z)"
good="\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":12"
rc_check "no relay.json" refused none
rc_check "relay not healthy" refused "{\"updatedAt\":\"$now\",\"healthy\":false,\"connected\":true,\"remoteAlive\":false,\"remoteWhy\":\"the shadow has no heartbeat\"}"
rc_check "relay.json 5 minutes old" refused "{\"updatedAt\":\"$old\",\"healthy\":true}"
rc_check "relay healthy and current" passes-gates "{\"updatedAt\":\"$now\",\"healthy\":true}"
rc_check "relay not healthy" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":false,\"connected\":true,\"remoteAlive\":false,\"remoteWhy\":\"the shadow has no heartbeat\"}"
rc_check "relay.json 5 minutes old" refused "{\"updatedAt\":\"$old\",\"runId\":\"1790000000000\",\"healthy\":true,\"traceAgeSeconds\":1}"
rc_check "relay healthy, run, trace current" passes-gates "{$good}"
# B1: healthy and caught up, but the live trace ended in a no-consumer stop the shadow has not reached.
rc_check "coverage lost while the relay reports healthy (B1)" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":{\"trace\":\"trace-1790000005000-4242.jsonl\",\"window\":\"w1\"},\"traceAgeSeconds\":12}"
rc_check "live trace not written for 5 minutes" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":300}"
rc_check "no live trace file" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":null}"
rc_check "relay.json of another run" refused "{\"updatedAt\":\"$now\",\"runId\":\"1789999999999\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":12}"
rc_check "verdict of another run" refused "{$good}" "{\"runId\":\"1789999999999\",\"status\":\"pass\"}"
rc_check "a local run's verdict (no run id) in remote mode" refused "{$good}" "{\"runId\":null,\"status\":\"pass\"}"
rc_check "a remote verdict without a remote drop-in" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}" local
rc_check "a local verdict and no drop-in" passes-gates none "{\"runId\":null,\"status\":\"pass\"}" local
rm -rf "$rc_tmp"
fi
# SHADOW-02: the build box's units live outside infra/units (05-deploy converges every unit there
@ -785,6 +799,25 @@ else
&& pass "flyshadow-remote.path starts the shadow on a new run id" \
|| fail "flyshadow-remote.path must watch /srv/fly-shadow-remote/run-id"
fi
SETUP="$INFRA_DIR/box/fly-shadow-remote-setup"
bash -n "$SETUP" && pass "fly-shadow-remote-setup parses" || fail "fly-shadow-remote-setup does not parse"
# Review N3: the key file is outside anything flyshadow owns; no symlink is followed as root; --from is required.
grep -qE '^HOME_DIR=/srv/fly-shadow-remote-home$' "$SETUP" \
&& grep -qF 'install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"' "$SETUP" \
&& grep -qF 'authorized_keys.new' "$SETUP" && ! grep -qF '"$ROOT/.ssh/authorized_keys' "$SETUP" \
&& pass "fly-shadow-remote-setup keeps authorized_keys in a root-owned home, not in the flyshadow-owned mirror" \
|| fail "fly-shadow-remote-setup must put .ssh in a root-owned home (HOME_DIR), not in the mirror"
if grep -nE '^[[:space:]]*(install -d|chown|chmod)[^#]*"\$ROOT' "$SETUP" | grep -v -- 'chown -h' | grep -q .; then
fail "fly-shadow-remote-setup must not install -d / chown / chmod under the flyshadow-owned mirror (it follows symlinks as root)"
else
pass "fly-shadow-remote-setup never chowns or chmods under the mirror without -h, nor installs into it"
fi
grep -qF '[ -L "$ROOT/$d" ] && die' "$SETUP" \
&& pass "fly-shadow-remote-setup refuses a symlink in the mirror on a re-run" \
|| fail "fly-shadow-remote-setup must refuse a symlink under the mirror"
grep -qF '[ -n "$from" ] || die "--from is required' "$SETUP" \
&& pass "fly-shadow-remote-setup requires --from" \
|| fail "fly-shadow-remote-setup must require --from"
grep -qF 'restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\"' "$INFRA_DIR/box/fly-shadow-remote-setup" \
&& pass "fly-shadow-remote-setup limits the relay key to the ingest (restrict, forced command)" \
|| fail "fly-shadow-remote-setup must write restrict,command=\"/opt/fly/current/fly-shadow ingest --root \$ROOT\""

View file

@ -356,9 +356,11 @@ fn status_loop(out: &Output, ledger: &Mutex<Ledger>, stop: &AtomicBool, config:
continue;
}
last = Instant::now();
let traces = trace_sizes(&layout.trace);
let (received, done, run_id) = {
let (traces, received, done, run_id) = {
let mut l = ledger.lock().unwrap_or_else(|p| p.into_inner());
// Listed under the lock: a file `apply_trace` creates (under the same lock) between a
// listing and this point would otherwise look removed, and be marked finished.
let traces = trace_sizes(&layout.trace);
let gone: Vec<String> = l
.created
.iter()
@ -372,7 +374,7 @@ fn status_loop(out: &Output, ledger: &Mutex<Ledger>, stop: &AtomicBool, config:
}
l.save(&layout.ledger);
}
(l.received, l.done.clone(), l.run_id.clone())
(traces, l.received, l.done.clone(), l.run_id.clone())
};
let (alive, why, verdict, status) = shadow_state(&layout, &run_id, config.alive_within);
let mut result = send(

View file

@ -39,6 +39,19 @@
//! catch-up and age bounds therefore cover the sync as well as the shadow. `relay.json` beside it
//! says whether the relay is healthy. A diverged verdict brings `divergence.json` and its
//! checkpoint files back, and then the relay exits with status 3, as a diverged local shadow does.
//! 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
//! 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
//! same run) and reports itself unhealthy, which stops the heartbeat and makes `check` refuse. It
//! clears only when the box's shadow starts a new window (a new `startedAt`: a restarted shadow
//! takes that stop as history, as the `trace-cap` skip), and it is never cleared by the shadow
//! catching up. `relay.json` also carries `traceAgeSeconds`, the age of the newest trace file, which
//! `check` bounds.
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom};
@ -119,8 +132,17 @@ pub enum RelayEnd {
Diverged,
}
/// Saves are read and queued for the box while less than this is waiting to be written.
pub const QUEUE_SAVES: u64 = 256 << 20;
/// Saves are read and queued for the box while less than this is waiting to be written. Hot saves
/// come at about [`SAVE_BYTES_PER_SECOND`], and flysim keeps the trace on for ten minutes of a
/// missing heartbeat, so this holds twelve minutes: a stall shorter than that loses no save the
/// shadow needs. The relay unit's `MemoryMax` (`fly-shadow-run`) leaves room for it.
pub const QUEUE_SAVES: u64 = 400 << 20;
/// What the live stores produce, measured (256 MiB is about 8 minutes).
pub const SAVE_BYTES_PER_SECOND: u64 = 560_000;
/// How long flysim keeps tracing without a heartbeat (`FLY_TRACE_CONSUMER_STALE_SECONDS`).
pub const STALE_WINDOW_SECONDS: u64 = 600;
/// Trace bytes (and the journal) are queued only while less than this is waiting.
pub const QUEUE_TRACE: u64 = 16 << 20;
@ -226,6 +248,75 @@ struct Relay {
diverged_at: Option<Instant>,
have_divergence: bool,
remote_lag: u64,
/// Divergence files taken from the box ([`DivergenceFiles`]).
files: DivergenceFiles,
/// The trace (and the box shadow's window) at which a no-consumer stop was forwarded.
coverage_lost: Option<CoverageLost>,
/// The `startedAt` of the latest relayed verdict: the box shadow's window.
window: Option<String>,
/// The end of the last scanned byte of each trace file and its tail, so a marker split between
/// two chunks is still found.
scan_tail: BTreeMap<String, (u64, Vec<u8>)>,
}
/// Coverage of the live fly was lost: flysim stopped its trace for want of a consumer.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CoverageLost {
trace: String,
/// The box shadow's window when it was seen; `None` when no verdict had arrived (never clears).
window: Option<String>,
at: String,
}
/// The marker flysim writes when it stops a trace for want of a consumer.
const NO_CONSUMER_MARKER: &[u8] = b"\"reason\":\"no-consumer\"";
/// Whether `bytes` hold a whole `{"truncated":true,"reason":"no-consumer"}` line.
fn has_no_consumer_marker(bytes: &[u8]) -> bool {
let mut from = 0;
while let Some(i) = bytes[from..]
.windows(NO_CONSUMER_MARKER.len())
.position(|w| w == NO_CONSUMER_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);
if bytes[start..end].windows(16).any(|w| w == b"\"truncated\":true") {
return true;
}
from = at + 1;
}
false
}
/// The divergence files the relay takes from the box: only after a diverged verdict of this run,
/// at most three (`divergence.json` and one checkpoint of each side), each of bounded size.
#[derive(Default)]
pub struct DivergenceFiles {
names: BTreeSet<String>,
}
impl DivergenceFiles {
pub const MAX_FILES: usize = 3;
pub const MAX_JSON: usize = 4 << 20;
pub const MAX_CHECKPOINT: usize = 16 << 20;
/// Whether a file of this name and size may be written now.
pub fn admit(&mut self, name: &str, len: usize, diverged: bool) -> bool {
if !diverged || !remote::is_divergence_file(name) {
return false;
}
let cap = if name == "divergence.json" {
Self::MAX_JSON
} else {
Self::MAX_CHECKPOINT
};
if len > cap || (!self.names.contains(name) && self.names.len() >= Self::MAX_FILES) {
return false;
}
self.names.insert(name.to_owned());
true
}
}
fn log(message: impl std::fmt::Display) {
@ -255,7 +346,12 @@ pub fn run(config: RelayConfig, stop: StopFlag) -> Result<RelayEnd, String> {
diverged_at: None,
have_divergence: false,
remote_lag: 0,
files: DivergenceFiles::default(),
coverage_lost: None,
window: None,
scan_tail: BTreeMap::new(),
};
relay.load_coverage_lost();
let heartbeat = relay.config.trace_dir.join(flysim::trace::CONSUMER_FILE);
let ended = relay.run_loop();
let _ = std::fs::remove_file(&heartbeat);
@ -543,7 +639,57 @@ impl Relay {
let alive = conn.last_status.as_ref().is_some_and(|(at, alive, _)| {
*alive && at.elapsed() <= self.config.alive_within
});
alive && conn.caught_up_at.elapsed() <= self.config.stall && self.diverged_at.is_none()
alive
&& conn.caught_up_at.elapsed() <= self.config.stall
&& self.diverged_at.is_none()
&& self.coverage_lost.is_none()
}
/// A previous relay of this run may have seen the stop: keep it (sticky).
fn load_coverage_lost(&mut self) {
let Ok(bytes) = std::fs::read(self.config.out_dir.join("relay.json")) else {
return;
};
let Ok(v) = serde_json::from_slice::<Value>(&bytes) else {
return;
};
if v["runId"].as_str() != Some(self.config.run_id.as_str()) {
return;
}
let lost = &v["coverageLost"];
if let Some(trace) = lost["trace"].as_str() {
self.coverage_lost = Some(CoverageLost {
trace: trace.to_owned(),
window: lost["window"].as_str().map(str::to_owned),
at: lost["at"].as_str().unwrap_or("").to_owned(),
});
self.window = lost["window"].as_str().map(str::to_owned);
}
}
/// Looks for flysim's no-consumer stop in trace bytes about to be sent.
fn scan_trace(&mut self, name: &str, offset: u64, chunk: &[u8]) {
let mut buf = match self.scan_tail.remove(name) {
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) {
log(format!(
"{name}: flysim stopped its trace for want of a consumer; coverage of the live fly \
is lost for this window"
));
self.coverage_lost = Some(CoverageLost {
trace: name.to_owned(),
window: self.window.clone(),
at: verdict::now_iso(),
});
// Say so at the next tick, not in up to five seconds.
self.last_relay_json = Instant::now() - Duration::from_secs(60);
}
let keep = buf.len().saturating_sub(256);
self.scan_tail
.insert(name.to_owned(), (offset + chunk.len() as u64, buf.split_off(keep)));
}
/// One tick's sends: saves, then trace bytes, then the journal read first.
@ -671,6 +817,7 @@ impl Relay {
file.read_exact(&mut chunk)?;
self.trace_bytes += chunk.len() as u64;
self.trace_lines += chunk.iter().filter(|b| **b == b'\n').count() as u64;
self.scan_trace(&name, offset, &chunk);
conn.send(json!({"t": "trace", "name": name, "offset": offset}), chunk)?;
offset += want as u64;
conn.sent.insert(name.clone(), offset);
@ -751,7 +898,15 @@ impl Relay {
"verdict" => self.relay_verdict(conn, &frame.body),
"file" => {
let name = h["name"].as_str().unwrap_or("");
if remote::is_divergence_file(name) {
if !self
.files
.admit(name, frame.body.len(), self.diverged_at.is_some())
{
log(format!(
"refused a file {name:?} ({} bytes) from the box",
frame.body.len()
));
} else {
let path = self.config.out_dir.join(name);
remote::atomic_write(&path, &frame.body)
.map_err(|e| format!("{}: {e}", path.display()))?;
@ -794,6 +949,25 @@ impl Relay {
(bytes, bytes.div_ceil(mean))
}
/// Seconds since the newest trace file of this run was written (`None`: there is none).
fn trace_age_seconds(&self) -> Option<u64> {
follow::trace_files(&self.config.trace_dir)
.unwrap_or_default()
.iter()
.filter(|path| {
!matches!((super::trace_start_ms(path), self.run_start_ms),
(Some(start), Some(run)) if start < run)
})
.filter_map(|path| std::fs::metadata(path).ok()?.modified().ok())
.max()
.map(|t| {
std::time::SystemTime::now()
.duration_since(t)
.unwrap_or_default()
.as_secs()
})
}
/// Writes the box's verdict here, when it is this run's, with the sync's backlog added.
fn relay_verdict(&mut self, conn: &Conn, bytes: &[u8]) {
let Ok(mut v) = serde_json::from_slice::<Value>(bytes) else {
@ -813,6 +987,16 @@ impl Relay {
"unsyncedBytes": unsynced_bytes,
"unsyncedTransitions": unsynced,
});
// A new shadow window takes an earlier stop as history (the `trace-cap` skip).
let window = v["startedAt"].as_str().map(str::to_owned);
if let (Some(lost), Some(now)) = (&self.coverage_lost, &window)
&& lost.window.as_ref().is_some_and(|w| w != now)
{
log("the box's shadow started a new window: the earlier trace stop is history");
self.coverage_lost = None;
self.last_relay_json = Instant::now() - Duration::from_secs(60);
}
self.window = window;
if v["status"] == "diverged" && self.diverged_at.is_none() {
self.diverged_at = Some(Instant::now());
}
@ -825,12 +1009,17 @@ impl Relay {
fn write_relay_json(&mut self, conn: Option<&Conn>, healthy: bool) {
self.last_relay_json = Instant::now();
let (unsynced_bytes, unsynced) = self.unsynced(conn);
let coverage_lost = self.coverage_lost.as_ref().map(|c| {
json!({"trace": c.trace, "window": c.window, "at": c.at})
});
let value = json!({
"format": "fly-shadow-relay-v1",
"updatedAt": verdict::now_iso(),
"runId": self.config.run_id,
"connected": conn.is_some(),
"healthy": healthy,
"coverageLost": coverage_lost,
"traceAgeSeconds": self.trace_age_seconds(),
"remoteAlive": conn.and_then(|c| c.last_status.as_ref()).map(|(_, alive, _)| *alive),
"remoteWhy": conn.and_then(|c| c.last_status.as_ref()).map(|(_, _, why)| why.clone()),
"caughtUpSecondsAgo": conn.map(|c| c.caught_up_at.elapsed().as_secs()),
@ -893,3 +1082,53 @@ pub fn ssh_command(
argv.push("fly-shadow-ingest".to_owned());
argv
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_no_consumer_stop_is_found_and_nothing_else_is() {
assert!(has_no_consumer_marker(
b"{\"a\":1}\n{\"reason\":\"no-consumer\",\"truncated\":true}\n"
));
assert!(has_no_consumer_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(
b"{\"reason\":\"byte-cap\",\"truncated\":true}\n"
));
// Not a marker line.
assert!(!has_no_consumer_marker(b"{\"note\":{\"reason\":\"no-consumer\"}}\n"));
assert!(!has_no_consumer_marker(b""));
}
#[test]
fn divergence_files_come_only_after_a_diverged_verdict_and_are_bounded() {
let mut files = DivergenceFiles::default();
assert!(!files.admit("divergence.json", 10, false), "not diverged yet");
assert!(!files.admit("../evil", 10, true));
assert!(!files.admit("divergence.json", DivergenceFiles::MAX_JSON + 1, true));
assert!(files.admit("divergence.json", 10, true));
assert!(files.admit("divergence.json", 10, true), "the same file again");
assert!(files.admit("divergence-live-g1.checkpoint", 1 << 20, true));
assert!(!files.admit(
"divergence-shadow-g1.checkpoint",
DivergenceFiles::MAX_CHECKPOINT + 1,
true
));
assert!(files.admit("divergence-shadow-g1.checkpoint", 1 << 20, true));
assert!(
!files.admit("divergence-shadow-g2.checkpoint", 1, true),
"a fourth file"
);
}
#[test]
fn the_saves_queue_holds_the_whole_stale_window() {
// Review N5: a stall of up to the trace's ten-minute stale window must not lose the saves
// the shadow needs (with a margin of a fifth).
const { assert!(QUEUE_SAVES >= STALE_WINDOW_SECONDS * SAVE_BYTES_PER_SECOND * 6 / 5) };
}
}

View file

@ -0,0 +1,241 @@
//! SHADOW-02 review B1, without a ROM: the real relay and the real `fly-shadow ingest` (over
//! pipes where production has ssh), with the box's shadow stood in for by a thread that keeps its
//! heartbeat and verdict fresh, as a healthy shadow does.
//!
//! After a long outage flysim stops its trace (`"reason":"no-consumer"`) and the live fly runs
//! untraced. When the link heals the box is alive and, counted in trace lines, caught up long
//! before its shadow reaches that stop. The relay must not call that healthy: it sets a sticky
//! `coverageLost`, stops the heartbeat, and clears it only when the shadow starts a new window.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use fly_legacy_session::shadow::{
StopFlag,
relay::{self, RelayConfig},
release,
};
const RUN_ID: &str = "1790000000000";
const TRACE: &str = "trace-1790000005000-4242.jsonl";
fn json_of(path: &Path) -> Value {
std::fs::read(path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or(Value::Null)
}
fn wait_for(what: &str, secs: u64, mut ok: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(secs);
while !ok() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(50));
}
}
fn append(path: &Path, bytes: &[u8]) {
use std::io::Write;
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap()
.write_all(bytes)
.unwrap();
}
struct Setup {
container: PathBuf,
mirror: PathBuf,
relay_stop: StopFlag,
relay: Option<std::thread::JoinHandle<Result<relay::RelayEnd, String>>>,
shadow_alive: Arc<AtomicBool>,
window: Arc<AtomicU64>,
fake_shadow: Option<std::thread::JoinHandle<()>>,
}
impl Setup {
fn start(root: &Path) -> Setup {
let container = root.join("container");
let mirror = root.join("box");
for d in ["trace", "hot", "durable", "shadow"] {
std::fs::create_dir_all(container.join(d)).unwrap();
}
let fly_shadow = PathBuf::from(env!("CARGO_BIN_EXE_fly-shadow"));
let script = format!("exec {} ingest --root {}", fly_shadow.display(), mirror.display());
let release_dir = release::this_release_of(&fly_shadow);
let mut config = RelayConfig::with_defaults(
container.join("trace"),
container.join("hot"),
container.join("durable"),
container.join("shadow"),
vec!["sh".to_owned(), "-c".to_owned(), script],
RUN_ID.to_owned(),
);
config.release = release_dir.display().to_string();
config.binaries = release::binaries_in(&release_dir).unwrap();
config.tick = Duration::from_millis(50);
config.beat_every = Duration::from_millis(300);
config.alive_within = Duration::from_secs(5);
config.stall = Duration::from_secs(5);
config.reconnect_after = Duration::from_secs(1);
let relay_stop = StopFlag::default();
let relay = {
let (config, stop) = (config, relay_stop.clone());
std::thread::spawn(move || relay::run(config, stop))
};
let shadow_alive = Arc::new(AtomicBool::new(true));
let window = Arc::new(AtomicU64::new(1));
let fake_shadow = {
let (mirror, alive, window) = (mirror.clone(), shadow_alive.clone(), window.clone());
std::thread::spawn(move || {
// Wait for the run the ingest announces, then behave as a healthy shadow does.
while fly_legacy_session::shadow::read_run_id(&mirror.join("run-id")).as_deref()
!= Some(RUN_ID)
{
std::thread::sleep(Duration::from_millis(50));
}
while alive.load(Ordering::Relaxed) {
let _ = std::fs::write(mirror.join("trace/consumer"), "beat");
let verdict = json!({
"runId": RUN_ID, "status": "running", "lagTransitions": 0,
"startedAt": format!("window-{}", window.load(Ordering::Relaxed)),
});
let _ = std::fs::write(
mirror.join("out/verdict.json"),
serde_json::to_vec(&verdict).unwrap(),
);
std::thread::sleep(Duration::from_millis(250));
}
})
};
Setup {
container,
mirror,
relay_stop,
relay: Some(relay),
shadow_alive,
window,
fake_shadow: Some(fake_shadow),
}
}
fn relay_json(&self) -> Value {
json_of(&self.container.join("shadow/relay.json"))
}
fn heartbeat_age(&self) -> Option<Duration> {
std::fs::metadata(self.container.join("trace/consumer"))
.ok()?
.modified()
.ok()?
.elapsed()
.ok()
}
}
impl Drop for Setup {
fn drop(&mut self) {
self.relay_stop.request();
self.shadow_alive.store(false, Ordering::Relaxed);
if let Some(h) = self.relay.take() {
let _ = h.join();
}
if let Some(h) = self.fake_shadow.take() {
let _ = h.join();
}
}
}
/// Reproduces review B1: the box is alive and caught up, yet the live trace ended in a
/// no-consumer stop that its shadow has not reached.
#[test]
fn a_no_consumer_stop_in_the_forwarded_trace_makes_the_relay_unhealthy_until_a_new_window() {
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{\"behaviour\":{\"step\":\"1\"}}\n");
wait_for("a healthy relay that follows the trace", 60, || {
let r = s.relay_json();
r["healthy"] == true
});
assert!(s.heartbeat_age().is_some(), "a healthy relay beats");
// The outage: flysim wrote its stop (here in two pieces, as a chunk boundary may cut it).
append(&trace, b"{\"reason\":\"no-con");
std::thread::sleep(Duration::from_millis(400));
append(&trace, b"sumer\",\"truncated\":true}\n");
std::thread::sleep(Duration::from_secs(3));
let r = s.relay_json();
assert_eq!(
r["healthy"], false,
"B1: the box is alive and caught up, but the live fly now runs untraced: {r}"
);
assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}");
assert!(r["traceAgeSeconds"].is_u64(), "{r}");
// The link is fine and the box is alive and caught up, for as long as we care to look: still
// not healthy, and no heartbeat (flysim would stop any later trace for want of one).
std::thread::sleep(Duration::from_secs(3));
let r = s.relay_json();
assert_eq!(r["remoteAlive"], true, "{r}");
assert_eq!(r["connected"], true, "{r}");
assert_eq!(r["healthy"], false, "caught up must not clear a lost coverage: {r}");
assert!(!r["coverageLost"].is_null(), "sticky: {r}");
assert!(
s.heartbeat_age().is_none_or(|age| age >= Duration::from_secs(2)),
"an unhealthy relay does not beat"
);
// Still in the same window after the shadow's own reports: sticky.
std::thread::sleep(Duration::from_secs(1));
assert!(!s.relay_json()["coverageLost"].is_null());
// A restarted shadow (a new window) takes the stop as history.
s.window.store(2, Ordering::Relaxed);
wait_for("the new window to clear the stop", 60, || {
let r = s.relay_json();
r["coverageLost"].is_null() && r["healthy"] == true
});
let _ = &s.mirror;
}
/// A stop of another kind (the byte cap) is an allowed skip and does not lose coverage.
#[test]
fn a_byte_cap_stop_is_not_a_lost_coverage() {
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));
let r = s.relay_json();
assert!(r["coverageLost"].is_null(), "{r}");
wait_for("a healthy relay", 60, || s.relay_json()["healthy"] == true);
}
/// A relay restart within the run keeps what the first relay saw.
#[test]
fn a_lost_coverage_survives_a_relay_restart_of_the_same_run() {
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\":\"no-consumer\",\"truncated\":true}\n",
);
wait_for("the relay to see the stop", 60, || !s.relay_json()["coverageLost"].is_null());
drop(s);
// The stopped relay wrote relay.json last; a new relay of the same run (the unit's restart)
// starts from it, reconnects to the same mirror, and is alive and caught up, but not healthy.
let s = Setup::start(tmp.path());
wait_for("the box reported alive", 60, || s.relay_json()["remoteAlive"] == true);
std::thread::sleep(Duration::from_secs(2));
let r = s.relay_json();
assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}");
assert_eq!(r["remoteAlive"], true, "{r}");
assert_eq!(r["healthy"], false, "{r}");
}