diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md
index 2cd8c2d..e516265 100644
--- a/docs/design/session-framework/legacy-gameboy-v1.md
+++ b/docs/design/session-framework/legacy-gameboy-v1.md
@@ -878,3 +878,50 @@ over:
`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when
it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is
CUT-01's.
+
+**Amendment, 2026-09-30 (SHADOW-02): the shadow runs on a build box.** On the release container
+the shadow cost the live fly real time: SCHED_IDLE on the page and encoder CPUs, sharing them with
+the encoder and the browser and the memory bandwidth of flysim's NUMA node, it took about 27 ms a
+frame, fell further behind every hour (so it could never meet the catch-up bound), and the live
+realtime factor fell from 0.9998 to 0.93-0.98. It recovered to 0.999-1.0 the moment the shadow
+stopped. The comparison itself is unchanged: the shadow is the same binary of the same release,
+following the same trace. What moves is where it runs, and so how its inputs reach it and its
+verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
+
+- *The relay* (`fly-shadow relay`, the container's `flyshadow.service` with the drop-in
+ `fly-shadow-run start` writes) opens one ssh connection to the box and streams, every quarter
+ second: the new live saves of both stores, then the new bytes of every trace file of this run
+ (oldest first; a file's size read after the directory listing, so an older file is complete
+ when a newer one reaches the box), then the sugar journal as read before the listing. Trace files
+ that started before the run (`FLY_SHADOW_RUN_ID`, the start's Unix ms) and saves older than a
+ minute before it are not sent.
+- *The ingest* (`fly-shadow ingest --root
`) is the forced command of the relay's key on the
+ box (`authorized_keys` `restrict,command=`); the box holds no credential for the container. It
+ refuses a relay whose release directory or binary SHA-256 differ from its own, so the box runs the
+ container's release, installed from the same tarball at the same path, and the verdict's
+ `candidate` is exactly what `check` recomputes on the container. A new run id resets the mirror
+ and restarts the box's shadow (it exits with status 4; `--run-id-file`).
+- *The heartbeat.* flysim's `/consumer` on the container is now the relay's. The relay
+ touches it only while it is healthy: connected; the box reported within 30 s that the shadow of
+ this run is alive (its own heartbeat fresh and its verdict this run's, running or passed); and
+ the box has acknowledged every byte that was on the container's disk a minute earlier. A dead box,
+ shadow or link, and a stalled sync, therefore stop the live trace exactly as a dead local shadow
+ does. The relay removes the file when it stops.
+- *The verdict* on the container is the box's `verdict.json`, written back only when its new
+ `runId` member is this run's, with two changes: `lagTransitions` is the box's plus the live
+ trace not yet acknowledged by the box, so the catch-up bound covers the sync; and a `relay`
+ member (`relayedAt`, `remoteLagTransitions`, `unsyncedBytes`, `unsyncedTransitions`). A diverged
+ verdict brings `divergence.json` and the checkpoint files back, and the relay exits with status 3.
+- *Coverage, tightened for both placements.* A trace that stops for want of a consumer
+ (`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage`
+ divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with
+ a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow
+ started is history and stays a `trace-cap` skip, and the byte cap stays a skip. The coverage
+ check reads the sugar journal before it lists the trace directory (a process creates its trace
+ file before it writes its boot header, so a boot between the two reads could look untraced
+ the other way round).
+- *`fly-shadow-run check`*, remote: in addition to everything above, `/srv/fly/shadow/relay.json`
+ must be less than a minute old and say `healthy`. `fly-shadow check` (the Rust rule) is
+ unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
+- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
+ cost, which is a few file reads and one ssh stream.
diff --git a/infra/02-base.sh b/infra/02-base.sh
index 12cbb28..11709a7 100755
--- a/infra/02-base.sh
+++ b/infra/02-base.sh
@@ -18,7 +18,10 @@ need pct
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \
ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
-fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo"
+fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo \
+openssh-client"
+# openssh-client (SHADOW-02): the remote shadow's relay dials OUT to a build box. The client only;
+# the container still runs no sshd (below).
# Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three
diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run
index 18195ca..fbe288e 100755
--- a/infra/bin/fly-shadow-run
+++ b/infra/bin/fly-shadow-run
@@ -5,7 +5,9 @@
# agent at a time).
#
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
-# and the live-impact guard, restart flysim once
+# and the live-impact guard, restart flysim once. The shadow runs on a
+# build box (SHADOW-02, below); --local runs it on this container
+# instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
# restart; --restart-flysim restarts it now), remove trace and spool
# fly-shadow-run status the verdict in one screen
@@ -51,6 +53,19 @@
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
#
+# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
+# FLY_SHADOW_REMOTE=@, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
+# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
+# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
+# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
+# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
+# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
+# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
+# 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.
+#
# Files (all owned by fly):
# /srv/fly/shadow/trace/trace--.jsonl flysim's per-process trace (4 GiB each, 8 in all)
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
@@ -59,11 +74,18 @@
# /srv/fly/shadow/divergence.json the first divergence with its context
# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl)
# /srv/fly/shadow/guard-state.json the guard's recent samples
+# /srv/fly/shadow/relay.json remote mode: the relay's health
set -euo pipefail
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
DROPIN_DIR=/etc/systemd/system/flysim.service.d
DROPIN="$DROPIN_DIR/shadow-trace.conf"
+REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
+REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
+REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
+# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
+# restarts for the new run and the ingest hashes the release first).
+HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
@@ -235,10 +257,35 @@ if both:
esac
}
+# Remote mode's prerequisites, checked before anything changes.
+check_remote() {
+ [ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
+ local target key known
+ target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
+ key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
+ known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
+ [ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
+ { [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
+ { [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
+ [ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
+ command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
+}
+
start() {
need_root
+ local mode=remote
+ for arg in "$@"; do
+ case "$arg" in
+ --local) mode=local ;;
+ *) die "start: unknown option $arg" ;;
+ esac
+ done
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
+ if [ "$mode" = remote ]; then
+ [ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
+ check_remote
+ fi
check_cpuset
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
# A previous run's verdict is kept beside, never read as this run's.
@@ -261,7 +308,30 @@ start() {
printf '{}\n' > "$SHADOW_DIR/guard-state.json"
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
log "baseline: $base"
- mkdir -p "$DROPIN_DIR"
+ mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
+ if [ "$mode" = remote ]; then
+ local run_id
+ run_id="$(date +%s%3N)"
+ [ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
+ cat > "$REMOTE_DROPIN" < "$DROPIN" </dev/null || true
systemctl stop flyshadow.service 2>/dev/null || true
- rm -f "$DROPIN"
+ rm -f "$DROPIN" "$REMOTE_DROPIN"
systemctl daemon-reload
log "stopped the shadow: $1"
}
@@ -375,6 +447,15 @@ status() {
systemctl is-active flyshadow.service || true
systemctl is-active flyshadow-guard.timer || true
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
+ if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
+ python3 - "$SHADOW_DIR/relay.json" <<'PY'
+import json, sys
+r = json.load(open(sys.argv[1]))
+print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
+ f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
+ f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
+PY
+ fi
[ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
python3 - "$SHADOW_DIR/verdict.json" <<'PY'
import json, sys
@@ -412,6 +493,29 @@ check() {
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
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'
+import datetime, json, sys
+try:
+ r = json.load(open(sys.argv[1]))
+ t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
+except Exception as e:
+ print("no readable relay.json (%s)" % e); sys.exit(1)
+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)
+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)
+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
@@ -426,12 +530,12 @@ check() {
cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
- start) start ;;
+ start) start "$@" ;;
stop) stop "$@" ;;
status) status ;;
check) check "$@" ;;
guard) guard ;;
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
- *) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
+ *) echo "usage: fly-shadow-run start [--local]|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
esac
diff --git a/infra/box/fly-shadow-remote-setup b/infra/box/fly-shadow-remote-setup
new file mode 100755
index 0000000..eb8c6ac
--- /dev/null
+++ b/infra/box/fly-shadow-remote-setup
@@ -0,0 +1,111 @@
+#!/usr/bin/env bash
+# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
+# 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]
+#
+# RELEASE_TARBALL the exact flybrain-.tar.gz deployed to the release container. It is
+# installed at the SAME path, /opt/fly/releases/, MANIFEST-verified,
+# root-owned, and /opt/fly/current points to it: the shadow's verdict names
+# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
+# refuses a relay whose release differs.
+# 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=).
+# --cpus LIST AllowedCPUs for the shadow (e.g. 3 cores of this box), a drop-in.
+#
+# 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="..."] . 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.
+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]"
+tarball="$1"; rom="$2"; pubkey="$3"; shift 3
+from=""; cpus=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --from) from="$2"; shift 2 ;;
+ --cpus) cpus="$2"; shift 2 ;;
+ *) die "unknown option $1" ;;
+ esac
+done
+here="$(cd "$(dirname "$0")" && pwd)"
+ROOT=/srv/fly-shadow-remote
+[ -f "$tarball" ] || die "no tarball $tarball"
+[ -f "$rom" ] || die "no ROM $rom"
+[ -f "$pubkey" ] || die "no public key $pubkey"
+base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
+[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
+[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
+[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
+key="$(head -n 1 "$pubkey")"
+[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
+command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
+
+# The release, exactly as 05-deploy installs it on the container (but root-owned here).
+release="/opt/fly/releases/${version}"
+if [ -f "$release/MANIFEST" ]; then
+ log "release $version already at $release"
+else
+ install -d -m 0755 "$release"
+ tar -xzf "$tarball" -C "$release"
+ chown -R root:root "$release"
+fi
+(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
+[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
+"$release/fly-shadow" ingest 2>&1 | grep -q 'needs --root' \
+ || die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
+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"
+log "authorized_keys: the relay key may run only the ingest"
+
+# The cartridge and this box's paths.
+rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
+install -d -m 0755 /srv/fly/rom
+install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
+install -d -m 0755 /etc/fly
+cat > /etc/fly/fly-shadow-remote.env < /etc/systemd/system/flyshadow-remote.service.d/cpuset.conf
+ log "AllowedCPUs=$cpus"
+fi
+systemctl daemon-reload
+systemctl enable --now flyshadow-remote.path
+systemctl enable flyshadow-remote.service
+# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
+systemctl try-restart flyshadow-remote.service || true
+log "ready: the container's fly-shadow-run start brings the first run id"
diff --git a/infra/box/flyshadow-remote.path b/infra/box/flyshadow-remote.path
new file mode 100644
index 0000000..9bb96b8
--- /dev/null
+++ b/infra/box/flyshadow-remote.path
@@ -0,0 +1,13 @@
+# infra/box/flyshadow-remote.path — installed on a BUILD BOX with flyshadow-remote.service
+# (SHADOW-02). A new run id (the container's `fly-shadow-run start`, written by the ingest) starts
+# the shadow when it is down: the first run, or after a divergence (exit 3 is not restarted). A
+# running shadow restarts itself on the change (exit 4, Restart=always).
+[Unit]
+Description=Start the remote shadow for a new run (SHADOW-02)
+
+[Path]
+PathChanged=/srv/fly-shadow-remote/run-id
+Unit=flyshadow-remote.service
+
+[Install]
+WantedBy=multi-user.target
diff --git a/infra/box/flyshadow-remote.service b/infra/box/flyshadow-remote.service
new file mode 100644
index 0000000..5aa2d66
--- /dev/null
+++ b/infra/box/flyshadow-remote.service
@@ -0,0 +1,55 @@
+# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
+# by infra/bin/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
+# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
+# the SAME release (installed from the same tarball at the same /opt/fly/releases/ path,
+# so the verdict's release and binary hashes are the container's), on this box's own cores, at
+# normal priority.
+#
+# Its input is the mirror /srv/fly-shadow-remote, written by `fly-shadow ingest`, the forced
+# command of the one key the container's relay (`fly-shadow relay`, flyshadow.service there) holds;
+# the relay writes this shadow's verdict back to the container, where `fly-shadow-run check`, its
+# guard and CUT-01 read it as before. REPORT-ONLY: it reads the mirror, writes /out and its
+# runtime directory, and serves nothing.
+#
+# The run: `fly-shadow-run start` on the container gives each run an id; the ingest writes it to
+# /run-id (after resetting the mirror). A running shadow sees the change within 5 s and exits
+# with status 4, and Restart=always starts the new run; a shadow that is down (it diverged: exit 3,
+# which is not restarted, so the diverged verdict stays) is started by flyshadow-remote.path.
+[Unit]
+Description=flyshadow-remote: the session runtime shadowing the live fly from a build box (SHADOW-02, report only)
+ConditionPathExists=/opt/fly/current/fly-shadow
+ConditionPathExists=/srv/fly-shadow-remote/run-id
+
+[Service]
+Type=simple
+User=flyshadow
+# The live composition's settings, as the relay forwarded them (game, macro mode, accepted
+# adapters, pins; never a path or a secret), then this box's own paths: FLY_ROM (the cartridge,
+# with the container's ROM_SHA256) and FLY_DATASET (the release's connectome).
+EnvironmentFile=-/srv/fly-shadow-remote/live.env
+EnvironmentFile=/etc/fly/fly-shadow-remote.env
+Environment=FLY_TRACE_DIR=/srv/fly-shadow-remote/trace
+Environment=FLY_STATE_HOT=/srv/fly-shadow-remote/hot
+Environment=FLY_STATE=/srv/fly-shadow-remote/durable
+Environment=FLY_SHADOW_DIR=/srv/fly-shadow-remote/out
+Environment=FLY_SHADOW_WORK=/run/flyshadow-remote
+RuntimeDirectory=flyshadow-remote
+# 3 sweep threads (the SHADOW-01 measurements: 13-15 ms a frame against 16.7 ms of real time).
+Environment=FLY_SHADOW_THREADS=3
+# No lag back-off: the live fly is on another machine. The spool holds a long catch-up.
+ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0 --spool-max-mib 4096
+Restart=always
+RestartSec=2
+RestartPreventExitStatus=3
+# Dedicated cores (fly-shadow-remote-setup --cpus writes AllowedCPUs= in a drop-in) at a weight
+# above anything else on the box: a build must not starve the shadow.
+CPUWeight=1000
+Nice=-5
+MemoryMax=6G
+TimeoutStopSec=30
+
+[Install]
+WantedBy=multi-user.target
diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md
index 3d8047c..ba6bcc5 100644
--- a/infra/docs/runbook.md
+++ b/infra/docs/runbook.md
@@ -527,18 +527,30 @@ report-only: it presses no button, serves no port, and only reads flysim's store
the release container in the host log first, as for any host work.
```
-pct exec -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, shadow + guard, one flysim restart
-pct exec -- /opt/fly/bin/fly-shadow-run status # the verdict (and a guard trip) in one screen
+pct exec -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, remote shadow + guard, one flysim restart
+pct exec -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (and a guard trip) in one screen
pct exec -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
```
+- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
+ live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
+ to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
+ further behind every hour. `start` refuses without the remote configuration below; `start --local`
+ runs it on the container anyway. In remote mode `flyshadow.service` on the container is the
+ *relay* (`fly-shadow relay`, from a drop-in `start` writes): normal scheduling off flysim's CPUs,
+ a few file reads and one outbound ssh stream that carries the trace, the new saves and the sugar
+ journal to the box and brings the box shadow's verdict back to `/srv/fly/shadow/verdict.json`.
+ The guard, `check` and CUT-01 see the unit and the files they always did. Set-up below
+ ("Remote shadow set-up").
- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty
10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth
rate. It refuses unless flysim ran normally for most of that time. Then it:
1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
- `FLY_TRACE_LEDGERS=60`);
- 2. starts `flyshadow.service` and waits for its heartbeat;
+ `FLY_TRACE_LEDGERS=60`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this
+ run's id: the start's Unix ms);
+ 2. starts `flyshadow.service` and waits for its heartbeat (remote: up to 5 minutes, while the
+ box resets its mirror, restarts its shadow for the new run and reports it alive);
3. restarts `flysim.service` once;
4. starts `flyshadow-guard.timer`.
@@ -569,6 +581,9 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
- at least 10,800 brain seconds, whatever window the shadow was started with;
- the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and
`baseline.json` exists (a run no guard watched is never cut over);
+ - remote: `/srv/fly/shadow/relay.json` is less than a minute old and `healthy` (connected, the
+ box's shadow of this run alive, the sync caught up), and the verdict is this run's (`runId`);
+ its `lagTransitions` counts the live trace not yet on the box as well;
- 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);
@@ -586,18 +601,69 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
- deletes every file it has compared.
-- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It
- runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its
- `cpuset.conf`). It pauses for a minute while flysim's lag grows faster than its baseline rate, and
- it stops pausing when a pause does not help. Disk: about
- 160 MB of trace per live hour, and a spool of at most 512 MiB.
+ deletes every file it has compared (remote: the box deletes its copy, and the relay then deletes
+ the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is
+ 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.
+- **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: a few ms of CPU a second, about 2.1 GB an hour over the network
+ (the hot save every 5 s is 2.7 MB; the trace about 160 MB an hour), and the trace writer inside
+ flysim. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
+ writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
+ baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
+ on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the
unit's `AllowedCPUs` (`systemctl show`) is disjoint from flysim.service's (05-deploy skips every
cpuset drop-in when the CT conf and CPUSET disagree).
-- **Stop** stops the unit and the guard, removes the drop-in, and deletes the trace and the spool
+- **Stop** stops the unit and the guard, removes the drop-ins, and deletes the trace and the spool
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
- within a minute, because its consumer is gone.
+ within a minute, because its consumer is gone. Remote, the box's shadow keeps running idle until
+ the next `start`, which resets its mirror and restarts it for the new run.
+- **Remote divergence**: the box's shadow stops (exit 3); the relay brings `divergence.json` and
+ both checkpoint files back to `/srv/fly/shadow/`, writes the diverged verdict and exits with
+ status 3 (the unit stays stopped, the guard stops itself). Pull the files from the container as
+ for a local divergence.
+
+### Remote shadow set-up (SHADOW-02)
+
+Once per build box, and again for every release the container runs. The real values (the box's
+address, the key's path) go in the operator's private files, never in this repository. Nothing
+on the build box can reach the release container: the container dials out.
+
+1. **The relay's key**, on the release container (as root, claimed):
+ `install -d -o root -g fly -m 0750 /etc/fly/shadow-remote`, then
+ `ssh-keygen -t ed25519 -N '' -C fly-shadow-relay -f /etc/fly/shadow-remote/id_ed25519` and
+ `chown fly:fly /etc/fly/shadow-remote/id_ed25519*`. The private half never leaves the container.
+ The container needs an ssh client (`openssh-client`; `02-base.sh` installs it) and no sshd.
+2. **The box** (as root on the box): copy the release tarball the container runs, the cartridge,
+ `infra/box/` and the public key there, then
+ `infra/box/fly-shadow-remote-setup flybrain-.tar.gz id_ed25519.pub --from --cpus <3 of the box's cores>`.
+ It installs the release at the same `/opt/fly/releases/` 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
+ `restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" `,
+ `/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
+ `/etc/fly/shadow-remote/known_hosts` on the container (`ssh-keyscan` from the host, checked by
+ hand).
+3. **The container's remote file**, `/etc/fly/shadow-remote.env` (root, 0600):
+ `FLY_SHADOW_REMOTE=flyshadow@`,
+ `FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
+ `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
+ 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.
+
+Which box: one whose cores the live fly does not share, preferably on the other NUMA node or
+another host (flysim is memory-bandwidth-bound). Keep other heavy work off the shadow's cores for
+the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`). The shadow must run faster than real
+time to catch up after a restart: measured in the SHADOW-02 report.
## Cutover to the session runtime (CUT-01)
@@ -609,7 +675,8 @@ container in the host log first, as for any host work.
```
# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy.
# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy)
-# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact:
+# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact; on a build box
+# (Remote shadow set-up above, once per box and release):
pct exec $CTID -- /opt/fly/bin/fly-shadow-run start
pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass
# 3. Cutover: the shadow's gate, then the switch. One command line:
diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh
index 4b1f94c..3bc2ec5 100755
--- a/infra/tests/lint.sh
+++ b/infra/tests/lint.sh
@@ -683,7 +683,8 @@ cs_start() { # name, expect (refuse|proceed), shadow cpus, sim cpus, drop-in (ye
out="$(PATH="$cs_tmp/bin:$PATH" CS_DIR="$cs_tmp" CS_SHADOW_CPUS="$3" CS_SIM_CPUS="$4" \
FLY_SHADOW_DIR="$cs_tmp/shadow" FLY_SHADOW_BIN="$cs_tmp/fly-shadow" \
FLY_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_BASELINE_SECONDS=1 \
- FLY_METRICS_URL=http://127.0.0.1:1 "$INFRA_DIR/bin/fly-shadow-run" start 2>&1)" || rc=$?
+ FLY_SHADOW_REMOTE_ENV="$cs_tmp/no-remote.env" \
+ FLY_METRICS_URL=http://127.0.0.1:1 "$INFRA_DIR/bin/fly-shadow-run" start --local 2>&1)" || rc=$?
case "$2" in
refuse)
if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \
@@ -710,7 +711,83 @@ if command -v python3 >/dev/null 2>&1; then
else
fail "python3 is needed to test fly-shadow-run's cpuset check"
fi
+# SHADOW-02: the shadow runs on a build box. `start` without the operator's remote file refuses
+# (unless --local); with one whose key is missing it refuses too, starting nothing either way.
+rs_start() { # name, remote env file content (or "none")
+ local rc=0 out
+ : > "$cs_tmp/systemctl.log"
+ rm -f "$cs_tmp/remote.env"
+ [ "$2" = none ] || printf '%s\n' "$2" > "$cs_tmp/remote.env"
+ out="$(PATH="$cs_tmp/bin:$PATH" CS_DIR="$cs_tmp" CS_SHADOW_CPUS="0 2" CS_SIM_CPUS="1 3" \
+ FLY_SHADOW_DIR="$cs_tmp/shadow" FLY_SHADOW_BIN="$cs_tmp/fly-shadow" \
+ FLY_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_REMOTE_ENV="$cs_tmp/remote.env" \
+ FLY_SHADOW_REMOTE_DROPIN_DIR="$cs_tmp/flyshadow.d" \
+ "$INFRA_DIR/bin/fly-shadow-run" start 2>&1)" || rc=$?
+ if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \
+ && [ ! -e "$cs_tmp/flyshadow.d/remote.conf" ]; then
+ pass "fly-shadow-run start refuses, $1: ${out#fly-shadow-run: }"
+ else
+ fail "fly-shadow-run start must refuse and start nothing, $1 (rc=$rc): $out"
+ fi
+}
+: > "$cs_tmp/dropin.conf"
+rs_start "no remote file (the shadow runs on a build box; --local to override)" none
+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).
+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 '{"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
+ rm -f "$rc_tmp/shadow/relay.json"
+ [ "$3" = none ] || printf '%s\n' "$3" > "$rc_tmp/shadow/relay.json"
+ 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=$?
+ 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" ;;
+ *) fail "fly-shadow-run check (remote), $1: expected $2, got exit $rc: $out" ;;
+ esac
+ }
+ now="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
+ old="$(date -u -d '-5 min' +%Y-%m-%dT%H:%M:%S.000Z)"
+ 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}"
+ rm -rf "$rc_tmp"
+fi
+# SHADOW-02: the build box's units live outside infra/units (05-deploy converges every unit there
+# onto the release container) and keep the remote shadow's semantics.
+BOX_UNIT="$INFRA_DIR/box/flyshadow-remote.service"
+if ls "$INFRA_DIR"/units/flyshadow-remote* >/dev/null 2>&1; then
+ fail "the build box's flyshadow-remote units must not be in infra/units (05-deploy would install them on the release container)"
+elif [ ! -f "$BOX_UNIT" ] || [ ! -f "$INFRA_DIR/box/flyshadow-remote.path" ]; then
+ fail "infra/box/flyshadow-remote.service and .path are missing"
+else
+ grep -qE '^ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0( |$)' "$BOX_UNIT" \
+ && pass "flyshadow-remote.service runs the release's fly-shadow on the mirror, for the relay's run" \
+ || fail "flyshadow-remote.service must run /opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0"
+ { grep -qE '^Restart=always$' "$BOX_UNIT" && grep -qE '^RestartPreventExitStatus=3$' "$BOX_UNIT"; } \
+ && pass "flyshadow-remote.service restarts for a new run (exit 4) and stays stopped after a divergence (exit 3)" \
+ || fail "flyshadow-remote.service needs Restart=always and RestartPreventExitStatus=3"
+ grep -qE '^CPUSchedulingPolicy=idle' "$BOX_UNIT" \
+ && fail "flyshadow-remote.service must not be idle-scheduled: it has its own cores" \
+ || pass "flyshadow-remote.service runs at normal priority on its own cores"
+ grep -qE '^PathChanged=/srv/fly-shadow-remote/run-id$' "$INFRA_DIR/box/flyshadow-remote.path" \
+ && 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
+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\""
if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then
pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs"
else
diff --git a/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
index f669945..fb48a3a 100644
--- a/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
+++ b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs
@@ -1,8 +1,11 @@
//! `fly-shadow`: SHADOW-01, the session runtime run beside the live fly.
//!
//! ```text
-//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit)
-//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook)
+//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit)
+//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook)
+//! fly-shadow relay SHADOW-02, on the release container: stream the trace and the
+//! saves to a build box's ingest, write its verdict back here
+//! fly-shadow ingest --root DIR SHADOW-02, on the build box: the relay key's forced command
//! ```
//!
//! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through
@@ -27,8 +30,20 @@
//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) |
//! | `--exit-on-pass` | exit once the verdict is `pass` |
//! | `--max-transitions N` | stop after N compared transitions |
+//! | `--run-id-file FILE` | a remote shadow (SHADOW-02): the run id `fly-shadow ingest` writes; it goes into the verdict, and a change stops the shadow with exit status 4 so its unit starts the new run |
//!
-//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error.
+//! Exit status: 0 passed or stopped, 3 diverged, 4 a new run, 2 the shadow's own error.
+//!
+//! `relay` (SHADOW-02) reads the live service's configuration like `run` (`FLY_TRACE_DIR`, the
+//! stores, `FLY_SHADOW_DIR`) and these: `FLY_SHADOW_RUN_ID` (required, `fly-shadow-run start`
+//! sets it: the start's Unix ms); `FLY_SHADOW_REMOTE` (the box's ssh destination),
+//! `FLY_SHADOW_REMOTE_KEY`, `FLY_SHADOW_REMOTE_KNOWN_HOSTS`, `FLY_SHADOW_REMOTE_PORT` (all from the
+//! operator's private `/etc/fly/shadow-remote.env`); `FLY_SHADOW_REMOTE_COMMAND` replaces the
+//! whole ssh command (tests); `FLY_SHADOW_RELAY_STALL_SECONDS` (60). Exit status: 0 stopped,
+//! 3 the remote shadow diverged, 2 an error.
+//!
+//! `ingest --root DIR [--keep-mib N]` (SHADOW-02) serves one relay connection on stdin and stdout
+//! and writes nothing outside DIR; N bounds the mirrored saves (3072).
//!
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
@@ -40,7 +55,9 @@
use std::path::PathBuf;
use std::time::Duration;
-use fly_legacy_session::shadow::{self, LagGuard, ShadowConfig, StopFlag, verdict};
+use fly_legacy_session::shadow::{
+ self, LagGuard, ShadowConfig, StopFlag, ingest, relay, release, remote, verdict,
+};
use fly_session::ExecutionMode;
fn usage() -> ! {
@@ -97,42 +114,20 @@ fn env_path(name: &str) -> Option {
}
fn file_sha256(path: &std::path::Path) -> String {
- let bytes = std::fs::read(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display())));
- shadow::sha256_hex(&bytes)
+ release::file_sha256(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display())))
}
fn this_binary() -> PathBuf {
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}")))
}
-/// The release binaries a verdict vouches for: SERVE-01's service (`flysim-session`, what CUT-01
-/// switches to), its worker program, the shadow itself, the legacy service and the edge.
-const RELEASE_BINARIES: [&str; 5] = [
- "flysim-session",
- "fly-session",
- "fly-shadow",
- "flysim",
- "fly-edge",
-];
-
/// SHA-256 of the release binaries in `dir`, by name.
fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap {
- RELEASE_BINARIES
- .iter()
- .filter_map(|name| {
- let path = dir.join(name);
- path.is_file()
- .then(|| ((*name).to_owned(), file_sha256(&path)))
- })
- .collect()
+ release::binaries_in(dir).unwrap_or_else(|e| die(format!("{}: {e}", dir.display())))
}
-/// 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()
+ release::this_release()
}
fn main() {
@@ -144,6 +139,11 @@ fn main() {
let mut args = Args(argv);
match command.as_str() {
"run" => run(args),
+ "relay" => {
+ args.done();
+ relay_main()
+ }
+ "ingest" => ingest_main(args),
"check" => {
let verdict_path: PathBuf = args
.value("--verdict")
@@ -244,6 +244,7 @@ fn run(mut args: Args) {
let keep_spool = args.flag("--keep-spool");
let exit_on_pass = args.flag("--exit-on-pass");
let max_transitions: Option = args.parsed("--max-transitions");
+ let run_id_file = args.value("--run-id-file").map(PathBuf::from);
// Undocumented: the toy connectome, for tests only.
let profile = match args.value("--profile") {
None => fly_session::legacy_agent::LegacyProfileKind::Production,
@@ -305,6 +306,7 @@ fn run(mut args: Args) {
binary_sha256: file_sha256(&this_binary()),
binaries: binaries_in(&this_release()),
release: this_release().display().to_string(),
+ run_id_file,
};
eprintln!(
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
@@ -337,6 +339,10 @@ fn run(mut args: Args) {
});
match ended {
Ok((shadow::Ended::Diverged, _)) => std::process::exit(3),
+ Ok((shadow::Ended::NewRun, _)) => {
+ eprintln!("fly-shadow: a new run was started; exiting for the unit to start it");
+ std::process::exit(4)
+ }
Ok((ended, verdict)) => {
eprintln!(
"fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}",
@@ -348,3 +354,111 @@ fn run(mut args: Args) {
Err(e) => die(e),
}
}
+
+/// Signals set the stop flag.
+fn stop_on_signals(stop: &StopFlag) {
+ let stop = stop.clone();
+ std::thread::Builder::new()
+ .name("fly-shadow-signals".to_owned())
+ .spawn(move || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("a signal runtime");
+ runtime.block_on(async {
+ use tokio::signal::unix::{SignalKind, signal};
+ let mut term = signal(SignalKind::terminate()).expect("SIGTERM");
+ let mut int = signal(SignalKind::interrupt()).expect("SIGINT");
+ tokio::select! {
+ _ = term.recv() => {}
+ _ = int.recv() => {}
+ }
+ });
+ stop.request();
+ })
+ .expect("the signal thread starts");
+}
+
+/// `fly-shadow relay`: the release container's half of a remote shadow (SHADOW-02).
+fn relay_main() {
+ let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}")));
+ let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
+ let out_dir = env_path("FLY_SHADOW_DIR").unwrap_or_else(|| die("FLY_SHADOW_DIR is required"));
+ let trace_dir = env_path(flysim::trace::DIR_ENV)
+ .unwrap_or_else(|| die("FLY_TRACE_DIR is required"));
+ let run_id = var("FLY_SHADOW_RUN_ID").unwrap_or_else(|| {
+ die("FLY_SHADOW_RUN_ID is required (fly-shadow-run start sets it)")
+ });
+ let command: Vec = match var("FLY_SHADOW_REMOTE_COMMAND") {
+ Some(command) => command.split_whitespace().map(str::to_owned).collect(),
+ None => {
+ let target = var("FLY_SHADOW_REMOTE")
+ .unwrap_or_else(|| die("FLY_SHADOW_REMOTE (the box's ssh destination) is required"));
+ let key = env_path("FLY_SHADOW_REMOTE_KEY")
+ .unwrap_or_else(|| die("FLY_SHADOW_REMOTE_KEY is required"));
+ let known = env_path("FLY_SHADOW_REMOTE_KNOWN_HOSTS")
+ .unwrap_or_else(|| die("FLY_SHADOW_REMOTE_KNOWN_HOSTS is required"));
+ let port = var("FLY_SHADOW_REMOTE_PORT").map(|p| {
+ p.parse::()
+ .unwrap_or_else(|_| die(format!("FLY_SHADOW_REMOTE_PORT {p:?}")))
+ });
+ relay::ssh_command(&target, &key, &known, port)
+ }
+ };
+ let mut relay_config = relay::RelayConfig::with_defaults(
+ trace_dir,
+ config.paths.hot_dir.clone(),
+ config.paths.save_dir.clone(),
+ out_dir,
+ command,
+ run_id,
+ );
+ relay_config.release = this_release().display().to_string();
+ relay_config.binaries = binaries_in(&this_release());
+ relay_config.env = remote::FORWARDED_ENV
+ .iter()
+ .filter_map(|name| Some(((*name).to_owned(), var(name)?)))
+ .collect();
+ if let Some(seconds) = var("FLY_SHADOW_RELAY_STALL_SECONDS") {
+ relay_config.stall = Duration::from_secs(
+ seconds
+ .parse()
+ .unwrap_or_else(|_| die(format!("FLY_SHADOW_RELAY_STALL_SECONDS {seconds:?}"))),
+ );
+ }
+ eprintln!(
+ "fly-shadow relay: run {}, release {}, following {} (stores {} and {}, read only)",
+ relay_config.run_id,
+ relay_config.release,
+ relay_config.trace_dir.display(),
+ relay_config.hot_dir.display(),
+ relay_config.durable_dir.display()
+ );
+ let stop = StopFlag::default();
+ stop_on_signals(&stop);
+ match relay::run(relay_config, stop) {
+ Ok(relay::RelayEnd::Stopped) => eprintln!("fly-shadow relay: stopped"),
+ Ok(relay::RelayEnd::Diverged) => std::process::exit(3),
+ Err(e) => die(e),
+ }
+}
+
+/// `fly-shadow ingest --root DIR`: the build box's half (SHADOW-02), one connection on stdio.
+fn ingest_main(mut args: Args) {
+ let root = args
+ .value("--root")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| die("ingest needs --root DIR"));
+ let keep_mib: u64 = args.parsed("--keep-mib").unwrap_or(3072);
+ args.done();
+ let mut config = ingest::IngestConfig::new(
+ root,
+ this_release().display().to_string(),
+ binaries_in(&this_release()),
+ );
+ config.keep_checkpoint_bytes = keep_mib << 20;
+ let input = std::io::BufReader::with_capacity(1 << 20, std::io::stdin());
+ if let Err(e) = ingest::serve(input, Box::new(std::io::stdout()), config) {
+ die(e);
+ }
+}
diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/ingest.rs b/services/flysim/crates/fly-legacy-session/src/shadow/ingest.rs
new file mode 100644
index 0000000..81b28fc
--- /dev/null
+++ b/services/flysim/crates/fly-legacy-session/src/shadow/ingest.rs
@@ -0,0 +1,536 @@
+//! `fly-shadow ingest`: the build box's half of the remote shadow (SHADOW-02; the protocol is
+//! [`super::remote`]). It is the forced command of the one key the release container's relay
+//! holds, so it is the only thing that key can run: it reads frames on stdin, writes the mirror
+//! under its root and nothing else, and answers on stdout.
+//!
+//! The mirror, which `flyshadow-remote.service` (`fly-shadow run`) reads exactly as the shadow on
+//! the container reads the live directories:
+//!
+//! | Path | What |
+//! | --- | --- |
+//! | `/trace/` | the live trace files, appended as they grow; the shadow's heartbeat `consumer` |
+//! | `/hot/`, `/durable/` | the live saves (`.checkpoint`), bounded; the sugar journal in `hot/` |
+//! | `/out/` | the shadow's verdict, divergence and spool |
+//! | `/run-id` | the relay's run: a new one resets the mirror and restarts the shadow |
+//! | `/live.env` | the live composition's settings ([`super::remote::FORWARDED_ENV`]) |
+//! | `/ingest.json` | the trace files it created, and the ones the shadow has finished |
+//!
+//! Every name is checked before it becomes a path, and the release is checked at the handshake:
+//! the relay's release directory and binary hashes must be this binary's own, so the box shadows
+//! the exact release the container runs, installed at the same path (the verdict binds to it).
+//!
+//! It reports the shadow *alive* only while the shadow's heartbeat is fresh and its verdict is
+//! this run's and running or passed: that is what the relay turns into the container's
+//! heartbeat, the one flysim's trace needs.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::io::{BufRead, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+use super::remote::{self, Frame};
+
+/// How the ingest runs.
+#[derive(Clone, Debug)]
+pub struct IngestConfig {
+ pub root: PathBuf,
+ /// This binary's release directory and binaries ([`super::release`]).
+ pub release: String,
+ pub binaries: BTreeMap,
+ /// The mirrored saves are kept under this many bytes, oldest generation first.
+ pub keep_checkpoint_bytes: u64,
+ /// The shadow's heartbeat may be at most this old for the shadow to count as alive.
+ pub alive_within: Duration,
+ pub status_every: Duration,
+}
+
+impl IngestConfig {
+ pub fn new(root: PathBuf, release: String, binaries: BTreeMap) -> Self {
+ IngestConfig {
+ root,
+ release,
+ binaries,
+ keep_checkpoint_bytes: 3 << 30,
+ alive_within: Duration::from_secs(90),
+ status_every: Duration::from_secs(2),
+ }
+ }
+}
+
+/// The mirror's directories.
+pub struct Layout {
+ pub trace: PathBuf,
+ pub hot: PathBuf,
+ pub durable: PathBuf,
+ pub out: PathBuf,
+ pub run_id: PathBuf,
+ pub live_env: PathBuf,
+ pub ledger: PathBuf,
+}
+
+impl Layout {
+ pub fn of(root: &Path) -> Layout {
+ Layout {
+ trace: root.join("trace"),
+ hot: root.join("hot"),
+ durable: root.join("durable"),
+ out: root.join("out"),
+ run_id: root.join("run-id"),
+ live_env: root.join("live.env"),
+ ledger: root.join("ingest.json"),
+ }
+ }
+}
+
+/// What both threads share.
+#[derive(Default)]
+struct Ledger {
+ run_id: String,
+ /// Body bytes applied on this connection.
+ received: u64,
+ /// Trace files this ingest created and still has, and those the shadow has since removed
+ /// (finished or skipped): a finished file is never written again.
+ created: BTreeSet,
+ done: BTreeSet,
+}
+
+impl Ledger {
+ fn to_json(&self) -> Value {
+ json!({"runId": self.run_id, "created": self.created, "done": self.done})
+ }
+
+ fn load(path: &Path) -> Ledger {
+ let v: Value = std::fs::read(path)
+ .ok()
+ .and_then(|b| serde_json::from_slice(&b).ok())
+ .unwrap_or(Value::Null);
+ let names = |key: &str| -> BTreeSet {
+ v[key]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|n| n.as_str())
+ .filter(|n| remote::is_trace_name(n))
+ .map(str::to_owned)
+ .collect()
+ };
+ Ledger {
+ run_id: v["runId"].as_str().unwrap_or("").to_owned(),
+ received: 0,
+ created: names("created"),
+ done: names("done"),
+ }
+ }
+
+ fn save(&self, path: &Path) {
+ if let Err(e) = remote::atomic_write(path, self.to_json().to_string().as_bytes()) {
+ eprintln!("fly-shadow ingest: {}: {e}", path.display());
+ }
+ }
+}
+
+type Output = Arc>>;
+
+fn send(out: &Output, header: Value, body: &[u8]) -> std::io::Result<()> {
+ let mut out = out.lock().unwrap_or_else(|p| p.into_inner());
+ remote::write_frame(&mut **out, header, body)
+}
+
+/// The trace files in `dir` and their sizes.
+fn trace_sizes(dir: &Path) -> BTreeMap {
+ std::fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .filter_map(|e| {
+ let name = e.file_name().to_string_lossy().into_owned();
+ remote::is_trace_name(&name).then_some((name, e.metadata().ok()?.len()))
+ })
+ .collect()
+}
+
+/// The generations of `.checkpoint` files in `dir`, with their sizes.
+fn gens_in(dir: &Path) -> BTreeMap {
+ std::fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .filter_map(|e| {
+ let generation = super::spool::generation_of(e.file_name().to_str()?)?;
+ Some((generation, e.metadata().ok()?.len()))
+ })
+ .collect()
+}
+
+/// Removes every file in `dir` (not directories) whose name `pick` accepts.
+fn remove_files(dir: &Path, pick: impl Fn(&str) -> bool) {
+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if entry.file_type().is_ok_and(|t| t.is_file()) && pick(&name) {
+ let _ = std::fs::remove_file(entry.path());
+ }
+ }
+}
+
+/// A new run: the previous run's mirror, verdict and spool go.
+fn reset(layout: &Layout) {
+ remove_files(&layout.trace, remote::is_trace_name);
+ for dir in [&layout.hot, &layout.durable] {
+ remove_files(dir, |n| {
+ super::spool::generation_of(n).is_some() || remote::is_journal_name(n)
+ });
+ }
+ remove_files(&layout.out, |n| {
+ n == "verdict.json" || remote::is_divergence_file(n)
+ });
+ let _ = std::fs::remove_dir_all(layout.out.join("spool"));
+}
+
+/// The shadow's liveness as the relay needs it: its heartbeat fresh, and its verdict this run's
+/// and running or passed. Returns `(alive, why, verdict bytes if this run's, its status)`.
+fn shadow_state(
+ layout: &Layout,
+ run_id: &str,
+ alive_within: Duration,
+) -> (bool, String, Option>, String) {
+ let heartbeat_age = std::fs::metadata(layout.trace.join(flysim::trace::CONSUMER_FILE))
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .map(|t| {
+ std::time::SystemTime::now()
+ .duration_since(t)
+ .unwrap_or_default()
+ });
+ let bytes = std::fs::read(layout.out.join("verdict.json")).ok();
+ let verdict: Value = bytes
+ .as_deref()
+ .and_then(|b| serde_json::from_slice(b).ok())
+ .unwrap_or(Value::Null);
+ let status = verdict["status"].as_str().unwrap_or("").to_owned();
+ if verdict["runId"].as_str() != Some(run_id) {
+ return (
+ false,
+ "the shadow has not started this run yet".to_owned(),
+ None,
+ status,
+ );
+ }
+ let alive = match heartbeat_age {
+ None => (false, "the shadow has no heartbeat".to_owned()),
+ Some(age) if age > alive_within => (
+ false,
+ format!("the shadow's heartbeat is {} s old", age.as_secs()),
+ ),
+ Some(_) if status == "running" || status == "pass" => (true, String::new()),
+ Some(_) => (false, format!("the shadow's verdict is {status}")),
+ };
+ (alive.0, alive.1, bytes, status)
+}
+
+/// Serves one relay connection until it ends. `Err` for a refused handshake or a broken stream.
+pub fn serve(
+ mut input: R,
+ output: Box,
+ config: IngestConfig,
+) -> Result<(), String> {
+ let layout = Layout::of(&config.root);
+ for dir in [&layout.trace, &layout.hot, &layout.durable, &layout.out] {
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ }
+ let out: Output = Arc::new(Mutex::new(output));
+ let refuse = |message: String| -> Result<(), String> {
+ let _ = send(&out, json!({"t": "error", "message": message}), b"");
+ Err(message)
+ };
+ let hello = match remote::read_frame(&mut input) {
+ Ok(Some(frame)) if frame.kind() == "hello" => frame,
+ Ok(Some(frame)) => return refuse(format!("expected hello, got {:?}", frame.kind())),
+ Ok(None) => return Ok(()),
+ Err(e) => return Err(format!("reading hello: {e}")),
+ };
+ let h = &hello.header;
+ if h["protocol"] != remote::PROTOCOL {
+ return refuse(format!(
+ "protocol {} is not {}",
+ h["protocol"],
+ remote::PROTOCOL
+ ));
+ }
+ if h["release"].as_str() != Some(config.release.as_str()) {
+ return refuse(format!(
+ "the container runs the release {}, this box {}: install the same release tarball at \
+ the same path",
+ h["release"], config.release
+ ));
+ }
+ let theirs: BTreeMap =
+ serde_json::from_value(h["binaries"].clone()).unwrap_or_default();
+ if theirs.is_empty() || theirs != config.binaries {
+ return refuse(format!(
+ "the release binaries differ (container {theirs:?}, box {:?})",
+ config.binaries
+ ));
+ }
+ let run_id = h["runId"].as_str().unwrap_or("").to_owned();
+ if run_id.is_empty()
+ || run_id.len() > 64
+ || !run_id
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
+ {
+ return refuse(format!("a bad run id {}", h["runId"]));
+ }
+
+ let mut ledger = Ledger::load(&layout.ledger);
+ let current = super::read_run_id(&layout.run_id).unwrap_or_default();
+ if current != run_id || ledger.run_id != run_id {
+ eprintln!("fly-shadow ingest: a new run {run_id} (was {current:?}): the mirror is reset");
+ reset(&layout);
+ ledger = Ledger {
+ run_id: run_id.clone(),
+ ..Ledger::default()
+ };
+ ledger.save(&layout.ledger);
+ let mut env = String::new();
+ for (key, value) in h["env"].as_object().into_iter().flatten() {
+ if let Some(value) = value.as_str()
+ && remote::FORWARDED_ENV.contains(&key.as_str())
+ && remote::env_value_ok(value)
+ {
+ env.push_str(&format!("{key}={value}\n"));
+ }
+ }
+ remote::atomic_write(&layout.live_env, env.as_bytes())
+ .map_err(|e| format!("{}: {e}", layout.live_env.display()))?;
+ // Last: the run id is what restarts the shadow (it watches the file; a path unit starts
+ // one that is down).
+ remote::atomic_write(&layout.run_id, format!("{run_id}\n").as_bytes())
+ .map_err(|e| format!("{}: {e}", layout.run_id.display()))?;
+ }
+ let gens: Vec = gens_in(&layout.hot)
+ .into_keys()
+ .chain(gens_in(&layout.durable).into_keys())
+ .collect();
+ send(
+ &out,
+ json!({"t": "state", "runId": run_id, "traces": trace_sizes(&layout.trace),
+ "done": ledger.done, "gens": gens}),
+ b"",
+ )
+ .map_err(|e| format!("writing state: {e}"))?;
+
+ let ledger = Arc::new(Mutex::new(ledger));
+ let stop = Arc::new(AtomicBool::new(false));
+ let status_thread = {
+ let (out, ledger, stop, config) = (
+ Arc::clone(&out),
+ Arc::clone(&ledger),
+ Arc::clone(&stop),
+ config.clone(),
+ );
+ std::thread::Builder::new()
+ .name("fly-shadow-ingest-status".to_owned())
+ .spawn(move || status_loop(&out, &ledger, &stop, &config))
+ .expect("the status thread starts")
+ };
+ let result = apply_loop(&mut input, &out, &ledger, &layout, &config);
+ stop.store(true, Ordering::Relaxed);
+ let _ = status_thread.join();
+ result
+}
+
+/// Every `status_every`: acks, finished files, the shadow's liveness, and its verdict and
+/// divergence files when they change.
+fn status_loop(out: &Output, ledger: &Mutex, stop: &AtomicBool, config: &IngestConfig) {
+ let layout = Layout::of(&config.root);
+ let mut sent_verdict: Option> = None;
+ let mut sent_files: BTreeSet = BTreeSet::new();
+ let mut last = Instant::now() - config.status_every;
+ while !stop.load(Ordering::Relaxed) {
+ if last.elapsed() < config.status_every {
+ std::thread::sleep(Duration::from_millis(50));
+ continue;
+ }
+ last = Instant::now();
+ let traces = trace_sizes(&layout.trace);
+ let (received, done, run_id) = {
+ let mut l = ledger.lock().unwrap_or_else(|p| p.into_inner());
+ let gone: Vec = l
+ .created
+ .iter()
+ .filter(|n| !traces.contains_key(*n))
+ .cloned()
+ .collect();
+ if !gone.is_empty() {
+ for name in gone {
+ l.created.remove(&name);
+ l.done.insert(name);
+ }
+ l.save(&layout.ledger);
+ }
+ (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(
+ out,
+ json!({"t": "status", "received": received, "traces": traces, "done": done,
+ "alive": alive, "why": why, "verdictStatus": status}),
+ b"",
+ );
+ if result.is_ok()
+ && let Some(bytes) = verdict
+ && sent_verdict.as_ref() != Some(&bytes)
+ {
+ result = send(out, json!({"t": "verdict"}), &bytes);
+ sent_verdict = Some(bytes);
+ }
+ if result.is_ok() && status == "diverged" {
+ for entry in std::fs::read_dir(&layout.out).into_iter().flatten().flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if remote::is_divergence_file(&name)
+ && !sent_files.contains(&name)
+ && let Ok(bytes) = std::fs::read(entry.path())
+ {
+ result = send(out, json!({"t": "file", "name": name}), &bytes);
+ sent_files.insert(name);
+ }
+ }
+ }
+ if result.is_err() {
+ stop.store(true, Ordering::Relaxed);
+ }
+ }
+}
+
+fn apply_loop(
+ input: &mut R,
+ out: &Output,
+ ledger: &Mutex,
+ layout: &Layout,
+ config: &IngestConfig,
+) -> Result<(), String> {
+ let mut since_prune = 0u64;
+ loop {
+ let frame: Frame = match remote::read_frame(input) {
+ Ok(Some(frame)) => frame,
+ Ok(None) => return Ok(()),
+ Err(e) => return Err(format!("reading a frame: {e}")),
+ };
+ let bytes = frame.body.len() as u64;
+ match frame.kind() {
+ "trace" => apply_trace(&frame, out, ledger, layout)?,
+ "ckpt" => {
+ let store = match frame.header["store"].as_str() {
+ Some("hot") => &layout.hot,
+ Some("durable") => &layout.durable,
+ other => return Err(format!("a checkpoint for the store {other:?}")),
+ };
+ let generation = frame.header["gen"]
+ .as_u64()
+ .ok_or("a checkpoint with no generation")?;
+ remote::atomic_write(
+ &store.join(format!("{generation}.checkpoint")),
+ &frame.body,
+ )
+ .map_err(|e| format!("writing g{generation}: {e}"))?;
+ since_prune += bytes;
+ if since_prune >= 64 << 20 {
+ since_prune = 0;
+ prune_saves(layout, config.keep_checkpoint_bytes);
+ }
+ }
+ "journal" => {
+ let name = frame.header["name"].as_str().unwrap_or("");
+ if !remote::is_journal_name(name) {
+ return Err(format!("a journal named {name:?}"));
+ }
+ remote::atomic_write(&layout.hot.join(name), &frame.body)
+ .map_err(|e| format!("writing {name}: {e}"))?;
+ }
+ "journal-set" => {
+ let keep: BTreeSet<&str> = frame.header["names"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|n| n.as_str())
+ .collect();
+ remove_files(&layout.hot, |n| {
+ remote::is_journal_name(n) && !keep.contains(n)
+ });
+ }
+ "ping" => {}
+ "bye" => return Ok(()),
+ other => return Err(format!("an unknown frame {other:?}")),
+ }
+ ledger.lock().unwrap_or_else(|p| p.into_inner()).received += bytes;
+ }
+}
+
+/// Appends a trace chunk where it belongs, or asks the relay to resend from what is here.
+fn apply_trace(
+ frame: &Frame,
+ out: &Output,
+ ledger: &Mutex,
+ layout: &Layout,
+) -> Result<(), String> {
+ let name = frame.header["name"].as_str().unwrap_or("");
+ if !remote::is_trace_name(name) {
+ return Err(format!("a trace named {name:?}"));
+ }
+ let offset = frame.header["offset"]
+ .as_u64()
+ .ok_or("a trace chunk with no offset")?;
+ let path = layout.trace.join(name);
+ let size = std::fs::metadata(&path).ok().map(|m| m.len());
+ {
+ let mut l = ledger.lock().unwrap_or_else(|p| p.into_inner());
+ // Finished by the shadow (or created here and removed since): never written again.
+ if l.done.contains(name) || (size.is_none() && l.created.contains(name)) {
+ return Ok(());
+ }
+ if size.is_none() && offset == 0 {
+ std::fs::File::create(&path).map_err(|e| format!("{}: {e}", path.display()))?;
+ l.created.insert(name.to_owned());
+ l.save(&layout.ledger);
+ }
+ }
+ let size = size.unwrap_or(0);
+ if size != offset {
+ return send(
+ out,
+ json!({"t": "resync", "name": name, "size": size}),
+ b"",
+ )
+ .map_err(|e| format!("writing resync: {e}"));
+ }
+ let mut file = std::fs::OpenOptions::new()
+ .append(true)
+ .open(&path)
+ .map_err(|e| format!("{}: {e}", path.display()))?;
+ file.write_all(&frame.body)
+ .map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Keeps the mirrored saves under `keep` bytes, dropping the oldest generations first.
+pub fn prune_saves(layout: &Layout, keep: u64) {
+ let mut all: Vec<(u64, PathBuf, u64)> = Vec::new();
+ for dir in [&layout.hot, &layout.durable] {
+ for (generation, len) in gens_in(dir) {
+ all.push((generation, dir.join(format!("{generation}.checkpoint")), len));
+ }
+ }
+ all.sort();
+ let mut total: u64 = all.iter().map(|(_, _, len)| len).sum();
+ for (_, path, len) in all {
+ if total <= keep {
+ break;
+ }
+ if std::fs::remove_file(&path).is_ok() {
+ total -= len;
+ }
+ }
+}
diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs
index e48f662..156cb02 100644
--- a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs
+++ b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs
@@ -30,6 +30,10 @@
pub mod checkpoint;
pub mod follow;
+pub mod ingest;
+pub mod relay;
+pub mod release;
+pub mod remote;
pub mod spool;
pub mod verdict;
@@ -105,6 +109,12 @@ pub struct ShadowConfig {
/// The release binaries beside it, by name, and their directory (the verdict's `candidate`).
pub binaries: std::collections::BTreeMap,
pub release: String,
+ /// SHADOW-02, a remote shadow on a build box: the file `fly-shadow ingest` writes the relay's
+ /// run id into. The id is read at start and written into the verdict (`runId`), which is how
+ /// the relay on the release container knows the verdict is this run's; when the file changes
+ /// (the coordinator ran `fly-shadow-run start` again), the shadow stops with
+ /// [`Ended::NewRun`] and its unit starts a fresh one. `None` on the release container itself.
+ pub run_id_file: Option,
}
/// The back-off that keeps the shadow from costing the live fly real time, judged against the
@@ -278,6 +288,8 @@ pub enum Ended {
Diverged,
Stopped,
Limit,
+ /// The run id changed ([`ShadowConfig::run_id_file`]): a new run was started.
+ NewRun,
}
/// Why a segment ended.
@@ -454,6 +466,12 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
record: true,
};
let compatibility = crate::composition::compatibility_of(&session_config);
+ let run_id = match &config.run_id_file {
+ Some(path) => Some(read_run_id(path).ok_or_else(|| {
+ format!("{}: no run id (the relay has not connected yet)", path.display())
+ })?),
+ None => None,
+ };
let mut spool = Spool::new(
&config.spool_dir,
vec![config.hot_dir.clone(), config.durable_dir.clone()],
@@ -515,7 +533,18 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
live_lag_seconds: None,
spool_evicted: 0,
cost: Cost::default(),
+ run_id: run_id.clone(),
},
+ run_id,
+ last_run_check: Instant::now(),
+ initial_sizes: follow::trace_files(&config.trace_dir)
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|path| {
+ let size = std::fs::metadata(&path).ok()?.len();
+ Some((path.file_name()?.to_string_lossy().into_owned(), size))
+ })
+ .collect(),
config,
session_config,
compatibility,
@@ -540,11 +569,12 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
match ended {
Ended::Diverged => {}
Ended::Pass => {}
- Ended::Stopped | Ended::Limit => {
+ Ended::Stopped | Ended::Limit | Ended::NewRun => {
if shadow.verdict.status == Status::Running {
shadow.verdict.status = Status::Stopped;
shadow.verdict.reason = match ended {
Ended::Limit => "stopped at the transition limit".to_owned(),
+ Ended::NewRun => "a new run was started (the run id changed)".to_owned(),
_ => "stopped before the window was complete".to_owned(),
};
}
@@ -574,9 +604,36 @@ struct Shadow {
traces_seen: std::collections::BTreeSet,
boots_checked: std::collections::BTreeSet,
last_coverage: Instant,
+ /// The run id this shadow started with, and when the file was last looked at.
+ run_id: Option,
+ last_run_check: Instant,
+ /// The size of every trace file present when this shadow started: a trace that stopped for
+ /// want of a consumer *before* then is history; one that stopped while this shadow ran is a
+ /// coverage gap.
+ initial_sizes: std::collections::BTreeMap,
+}
+
+/// The run id in `path` (trimmed), if the file exists and is not empty.
+pub fn read_run_id(path: &Path) -> Option {
+ let text = std::fs::read_to_string(path).ok()?;
+ let id = text.trim();
+ (!id.is_empty()).then(|| id.to_owned())
}
impl Shadow {
+ /// Whether the run id file names another run now (looked at every 5 s).
+ fn new_run(&mut self) -> bool {
+ let Some(path) = self.config.run_id_file.clone() else {
+ return false;
+ };
+ if self.last_run_check.elapsed() < Duration::from_secs(5) {
+ return false;
+ }
+ self.last_run_check = Instant::now();
+ // A file that cannot be read is not a new run: the relay rewrites it atomically.
+ read_run_id(&path).is_some_and(|id| Some(&id) != self.run_id.as_ref())
+ }
+
fn write(&mut self) {
self.verdict.spool_evicted = self.spool.evicted();
// Refreshed on every write, backed off or not, so the verdict's catch-up bound is current.
@@ -603,11 +660,15 @@ impl Shadow {
return None;
}
self.last_coverage = Instant::now();
+ // The journal first, then the trace directory: a process creates its trace file before it
+ // writes its boot header, so every boot read here already has its file on disk when the
+ // directory is listed after it (read the other way round, a boot between the two reads
+ // would look untraced). A remote shadow's mirror is written in the same order.
+ let segments = flysim::journal::read_segments(&self.config.hot_dir).ok()?;
if let Ok(files) = follow::trace_files(&self.config.trace_dir) {
self.traces_seen
.extend(files.iter().filter_map(|f| trace_start_ms(f)));
}
- let segments = flysim::journal::read_segments(&self.config.hot_dir).ok()?;
let boots: Vec = segments.into_iter().filter_map(|s| s.boot).collect();
let untraced = untraced_boots(
&boots,
@@ -681,6 +742,9 @@ impl Shadow {
if self.stop.requested() {
return Ok(Ended::Stopped);
}
+ if self.new_run() {
+ return Ok(Ended::NewRun);
+ }
match follow::next_file(&dir, current.as_deref()) {
Ok(Some(path)) => break path,
Ok(None) => {}
@@ -751,6 +815,9 @@ impl Shadow {
if self.stop.requested() {
return Err(SegmentEnd::Stop(Ended::Stopped));
}
+ if self.new_run() {
+ return Err(SegmentEnd::Stop(Ended::NewRun));
+ }
if follow::superseded(follower.path()) {
// The next process exists, so this one has exited and flushed: one more read for
// a final flush racing the directory listing, then the segment is over.
@@ -996,6 +1063,27 @@ impl Shadow {
}
};
if live.get("truncated").is_some() {
+ // A trace stopped for want of a consumer while this shadow was following means its
+ // heartbeat did not reach flysim (a remote shadow's relay stalled, SHADOW-02): the
+ // rest of that live process runs uncompared, so it fails the verdict like an
+ // untraced process. One that had stopped before this shadow started is history.
+ let before_start = self
+ .initial_sizes
+ .get(name)
+ .is_some_and(|size| follower.consumed <= *size);
+ if live["reason"] == "no-consumer" && !before_start {
+ return SegmentEnd::Diverged(Box::new(Divergence {
+ kind: "coverage".to_owned(),
+ trace: name.to_owned(),
+ step: None,
+ difference: None,
+ detail: "the live trace stopped for want of a consumer while the shadow \
+ was following it (a stale heartbeat: a stalled relay or a hung \
+ shadow): the rest of that live process can never be compared"
+ .to_owned(),
+ context: context.into_iter().collect(),
+ }));
+ }
return SegmentEnd::Skipped(
"trace-cap",
format!("the live trace stopped ({})", live["reason"]),
@@ -1295,6 +1383,9 @@ impl Shadow {
if let Some(divergence) = self.coverage() {
return SegmentEnd::Diverged(Box::new(divergence));
}
+ if self.new_run() {
+ return SegmentEnd::Stop(Ended::NewRun);
+ }
self.write_if_due();
}
}
diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs b/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs
new file mode 100644
index 0000000..536dc1d
--- /dev/null
+++ b/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs
@@ -0,0 +1,765 @@
+//! `fly-shadow relay`: the release container's half of the remote shadow (SHADOW-02; the protocol
+//! is [`super::remote`]). It runs as `flyshadow.service` in place of the local shadow, so
+//! `fly-shadow-run check`, its guard and CUT-01 see the unit they always did, and it is a few
+//! file reads and one ssh stream instead of a second brain on the stream's CPUs.
+//!
+//! Every tick (a quarter second) it pushes, in this order:
+//!
+//! 1. the new live saves in both stores (a hot one lives about ten seconds), so a trace line never
+//! arrives on the box before the save it names;
+//! 2. the new bytes of every trace file of this run, oldest file first, listed *after* reading the
+//! sugar journal, and a file's size read after the listing: when a newer file exists the older
+//! process has exited and flushed, so the older file is complete when the newer one appears on
+//! the box;
+//! 3. the sugar journal it read at the start of the tick, so every boot header the box sees has
+//! its trace file there already (the shadow's coverage check).
+//!
+//! Trace files older than the run (`FLY_SHADOW_RUN_ID` is the start's Unix ms) and saves written
+//! more than a minute before it are not sent: they belong to processes this run never follows.
+//!
+//! **The heartbeat.** flysim traces only while `/consumer` is fresh. The relay touches
+//! it every 10 s only while it is *healthy*: connected; the box reported within the last 30 s that
+//! the shadow of this run is alive; and the box has acknowledged everything that was on the
+//! container's disk a minute ago (`received` against the bytes sent by the end of each tick). A
+//! dead box, a dead shadow, a broken or a stalled connection all stop the heartbeat, and flysim
+//! then stops its trace as it would for a dead local shadow. The relay removes the file when it
+//! stops.
+//!
+//! **The verdict.** The box's `verdict.json` is written to `/srv/fly/shadow/verdict.json` only
+//! when it is this run's (`runId`), with `lagTransitions` raised by the live trace not yet on the
+//! box and a `relay` member (the `fly-shadow-verdict-v1` amendment of 2026-09-30); `check`'s
+//! 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.
+
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom};
+use std::path::{Path, PathBuf};
+use std::process::{Child, ChildStdin, Command, Stdio};
+use std::sync::mpsc;
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+use super::remote::{self, Frame};
+use super::spool::generation_of;
+use super::{StopFlag, follow, verdict};
+
+/// How the relay runs.
+#[derive(Clone, Debug)]
+pub struct RelayConfig {
+ /// The live service's `FLY_TRACE_DIR` (and the heartbeat in it), its stores, and where the
+ /// verdict goes (`FLY_SHADOW_DIR`).
+ pub trace_dir: PathBuf,
+ pub hot_dir: PathBuf,
+ pub durable_dir: PathBuf,
+ pub out_dir: PathBuf,
+ /// The command whose stdin and stdout are the box's ingest: `ssh ... `.
+ pub command: Vec,
+ pub run_id: String,
+ pub release: String,
+ pub binaries: BTreeMap,
+ /// [`remote::FORWARDED_ENV`] as the live service has them.
+ pub env: BTreeMap,
+ /// The sync may be at most this far behind the container's disk for the relay to be healthy.
+ pub stall: Duration,
+ /// The box's last report that the shadow is alive may be at most this old.
+ pub alive_within: Duration,
+ pub beat_every: Duration,
+ pub tick: Duration,
+ pub reconnect_after: Duration,
+ /// How long to wait for the box's answer to `hello`.
+ pub handshake: Duration,
+}
+
+impl RelayConfig {
+ /// The defaults beside the directories, command and release.
+ pub fn with_defaults(
+ trace_dir: PathBuf,
+ hot_dir: PathBuf,
+ durable_dir: PathBuf,
+ out_dir: PathBuf,
+ command: Vec,
+ run_id: String,
+ ) -> RelayConfig {
+ RelayConfig {
+ trace_dir,
+ hot_dir,
+ durable_dir,
+ out_dir,
+ command,
+ run_id,
+ release: String::new(),
+ binaries: BTreeMap::new(),
+ env: BTreeMap::new(),
+ stall: Duration::from_secs(60),
+ alive_within: Duration::from_secs(30),
+ beat_every: Duration::from_secs(10),
+ tick: Duration::from_millis(250),
+ reconnect_after: Duration::from_secs(5),
+ handshake: Duration::from_secs(120),
+ }
+ }
+}
+
+/// How the relay ended.
+#[derive(Debug, PartialEq, Eq)]
+pub enum RelayEnd {
+ Stopped,
+ /// The remote shadow diverged; its verdict and divergence files are in `out_dir`.
+ Diverged,
+}
+
+/// One connection to the box.
+struct Conn {
+ child: Child,
+ stdin: BufWriter,
+ frames: mpsc::Receiver>,
+ /// Bytes of each trace file the box has (sent, or reported at the handshake).
+ sent: BTreeMap,
+ /// Sizes the box last acknowledged.
+ acked: BTreeMap,
+ /// Journal files sent: (length, modification ms), and the set last announced.
+ journal_sent: BTreeMap,
+ journal_names: BTreeSet,
+ /// Body bytes sent on this connection, the ends of recent ticks, and the latest tick start
+ /// whose bytes the box has all received.
+ sent_total: u64,
+ ticks: VecDeque<(Instant, u64)>,
+ caught_up_at: Instant,
+ /// The box's last status: when, and whether this run's shadow is alive.
+ last_status: Option<(Instant, bool, String)>,
+ last_frame_sent: Instant,
+}
+
+impl Conn {
+ fn send(&mut self, header: Value, body: &[u8]) -> std::io::Result<()> {
+ remote::write_frame(&mut self.stdin, header, body)?;
+ self.sent_total += body.len() as u64;
+ self.last_frame_sent = Instant::now();
+ Ok(())
+ }
+
+ fn close(mut self) {
+ let _ = remote::write_frame(&mut self.stdin, json!({"t": "bye"}), b"");
+ drop(self.stdin);
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < deadline {
+ if let Ok(Some(_)) = self.child.try_wait() {
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// The relay's state across connections.
+struct Relay {
+ config: RelayConfig,
+ stop: StopFlag,
+ run_start_ms: Option,
+ /// Trace files the box has finished with (its shadow deleted them): deleted here too.
+ done: BTreeSet,
+ /// Generations sent (or held by the box, or older than the run).
+ sent_gens: BTreeSet,
+ /// Trace bytes and lines sent, for the mean line length.
+ trace_bytes: u64,
+ trace_lines: u64,
+ last_beat: Option,
+ last_relay_json: Instant,
+ diverged_at: Option,
+ have_divergence: bool,
+ remote_lag: u64,
+}
+
+fn log(message: impl std::fmt::Display) {
+ eprintln!("fly-shadow relay: {message}");
+}
+
+/// Runs the relay until it is stopped or the remote shadow diverges.
+pub fn run(config: RelayConfig, stop: StopFlag) -> Result {
+ if config.command.is_empty() {
+ return Err("no command to reach the box".to_owned());
+ }
+ for dir in [&config.out_dir, &config.trace_dir] {
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ }
+ let mut relay = Relay {
+ run_start_ms: config.run_id.parse().ok(),
+ config,
+ stop,
+ done: BTreeSet::new(),
+ sent_gens: BTreeSet::new(),
+ trace_bytes: 0,
+ trace_lines: 0,
+ last_beat: None,
+ last_relay_json: Instant::now() - Duration::from_secs(60),
+ diverged_at: None,
+ have_divergence: false,
+ remote_lag: 0,
+ };
+ let heartbeat = relay.config.trace_dir.join(flysim::trace::CONSUMER_FILE);
+ let ended = relay.run_loop();
+ let _ = std::fs::remove_file(&heartbeat);
+ relay.write_relay_json(None, false);
+ ended
+}
+
+impl Relay {
+ fn run_loop(&mut self) -> Result {
+ loop {
+ if self.stop.requested() {
+ return Ok(RelayEnd::Stopped);
+ }
+ let conn = match self.connect() {
+ Ok(conn) => conn,
+ Err((message, wait)) => {
+ log(format!("{message}; retrying in {} s", wait.as_secs()));
+ self.write_relay_json(None, false);
+ if self.sleep(wait) {
+ return Ok(RelayEnd::Stopped);
+ }
+ continue;
+ }
+ };
+ log("connected; following the live trace");
+ match self.session(conn) {
+ Ok(Some(end)) => return Ok(end),
+ Ok(None) => {}
+ Err(message) => log(format!("the connection ended: {message}")),
+ }
+ if self.stop.requested() {
+ return Ok(RelayEnd::Stopped);
+ }
+ self.write_relay_json(None, false);
+ if self.sleep(self.config.reconnect_after) {
+ return Ok(RelayEnd::Stopped);
+ }
+ }
+ }
+
+ /// Sleeps `d`, or less when stopped (then `true`).
+ fn sleep(&self, d: Duration) -> bool {
+ let until = Instant::now() + d;
+ while Instant::now() < until {
+ if self.stop.requested() {
+ return true;
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ self.stop.requested()
+ }
+
+ /// Starts the command, says hello and reads the box's state.
+ fn connect(&mut self) -> Result {
+ let retry = self.config.reconnect_after;
+ let mut child = Command::new(&self.config.command[0])
+ .args(&self.config.command[1..])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::inherit())
+ .spawn()
+ .map_err(|e| (format!("{}: {e}", self.config.command[0]), retry))?;
+ let stdin = child.stdin.take().expect("piped stdin");
+ let stdout = child.stdout.take().expect("piped stdout");
+ let (tx, frames) = mpsc::channel();
+ std::thread::Builder::new()
+ .name("fly-shadow-relay-read".to_owned())
+ .spawn(move || {
+ let mut reader = BufReader::with_capacity(1 << 20, stdout);
+ loop {
+ match remote::read_frame(&mut reader) {
+ Ok(Some(frame)) => {
+ if tx.send(Ok(frame)).is_err() {
+ return;
+ }
+ }
+ Ok(None) => {
+ let _ = tx.send(Err(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "the box closed the connection",
+ )));
+ return;
+ }
+ Err(e) => {
+ let _ = tx.send(Err(e));
+ return;
+ }
+ }
+ }
+ })
+ .expect("the reader thread starts");
+ let now = Instant::now();
+ let mut conn = Conn {
+ child,
+ stdin: BufWriter::with_capacity(1 << 20, stdin),
+ frames,
+ sent: BTreeMap::new(),
+ acked: BTreeMap::new(),
+ journal_sent: BTreeMap::new(),
+ journal_names: BTreeSet::new(),
+ sent_total: 0,
+ ticks: VecDeque::new(),
+ caught_up_at: now,
+ last_status: None,
+ last_frame_sent: now,
+ };
+ let hello = json!({
+ "t": "hello",
+ "protocol": remote::PROTOCOL,
+ "runId": self.config.run_id,
+ "release": self.config.release,
+ "binaries": self.config.binaries,
+ "env": self.config.env,
+ });
+ if let Err(e) = conn.send(hello, b"") {
+ conn.close();
+ return Err((format!("sending hello: {e}"), retry));
+ }
+ let state = match conn.frames.recv_timeout(self.config.handshake) {
+ Ok(Ok(frame)) if frame.kind() == "state" => frame,
+ Ok(Ok(frame)) if frame.kind() == "error" => {
+ let message = frame.header["message"].as_str().unwrap_or("").to_owned();
+ conn.close();
+ // A refusal (another release, another protocol) will not fix itself soon.
+ return Err((
+ format!("the box refused: {message}"),
+ retry.max(Duration::from_secs(60)),
+ ));
+ }
+ Ok(Ok(frame)) => {
+ let kind = frame.kind().to_owned();
+ conn.close();
+ return Err((format!("expected state, got {kind:?}"), retry));
+ }
+ Ok(Err(e)) => {
+ conn.close();
+ return Err((format!("the handshake: {e}"), retry));
+ }
+ Err(_) => {
+ conn.close();
+ return Err(("no answer to hello".to_owned(), retry));
+ }
+ };
+ let h = &state.header;
+ if h["runId"].as_str() != Some(self.config.run_id.as_str()) {
+ conn.close();
+ return Err((format!("the box answered for the run {}", h["runId"]), retry));
+ }
+ for (name, size) in h["traces"].as_object().into_iter().flatten() {
+ if let Some(size) = size.as_u64() {
+ conn.sent.insert(name.clone(), size);
+ conn.acked.insert(name.clone(), size);
+ }
+ }
+ self.absorb_done(&h["done"]);
+ let held: BTreeSet = h["gens"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_u64)
+ .collect();
+ self.sent_gens.extend(held);
+ Ok(conn)
+ }
+
+ /// Trace files the box has finished: delete them here, never send them again.
+ fn absorb_done(&mut self, done: &Value) {
+ for name in done.as_array().into_iter().flatten().filter_map(Value::as_str) {
+ if !remote::is_trace_name(name) {
+ continue;
+ }
+ if self.done.insert(name.to_owned()) {
+ let path = self.config.trace_dir.join(name);
+ if path.is_file() && std::fs::remove_file(&path).is_ok() {
+ log(format!("{name} is finished on the box; removed here"));
+ }
+ }
+ }
+ }
+
+ /// One connection's life. `Ok(Some(end))` ends the relay; `Ok(None)` or `Err` reconnects.
+ fn session(&mut self, mut conn: Conn) -> Result