diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md
index 0660719..b303e63 100644
--- a/docs/design/session-framework/implementation.md
+++ b/docs/design/session-framework/implementation.md
@@ -683,6 +683,70 @@ a timing, load or segment-handling bug.
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
+### SHADOW-02 — The shadow on a build box (port slice)
+
+**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
+live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
+the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
+
+**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
+seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
+further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
+back to 0.999-1.0 the moment the shadow was stopped.
+
+- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
+ guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
+ pins; no path, no secret).
+- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
+ per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
+ the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
+ blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
+ disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
+ while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
+ byte that was on disk a minute ago). The box's verdict is written back only when it is this
+ run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
+- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
+ box): the release directory and binary hashes must equal its own; a new run id resets the mirror
+ and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
+ finished is never written again (`done`, and the relay then deletes the container's copy);
+ reports liveness (heartbeat fresh, verdict this run's and running or passed).
+- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
+ stop while following is a `coverage` divergence; coverage reads the journal before listing the
+ traces. `shadow::release` holds the release hashing the binary and `check` share.
+- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
+ refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
+ and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
+ `flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
+ `Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
+ on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
+ `flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
+ `02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
+ section has the set-up.
+
+**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
+the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
+a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
+the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
+follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
+its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
+it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
+and `resync`, the run reset, the env allowlist.
+
+**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
+build box standing in for the release container, the remote shadow on another behind a real sshd
+with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
+(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
+11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
+3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
+the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
+
+**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
+sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
+the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
+thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
+the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
+the trace is on, so the trace's cost counts against it.
+
### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md
index 2cd8c2d..9a6d8e5 100644
--- a/docs/design/session-framework/legacy-gameboy-v1.md
+++ b/docs/design/session-framework/legacy-gameboy-v1.md
@@ -800,7 +800,6 @@ several processes.
- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it,
because the shadow started late or its spool evicted the file;
- `operator-reward-pulse`;
-- `trace-cap`: the live trace stopped at its byte cap, or with no consumer;
- `no-transition`: a process that ran none.
A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which
@@ -878,3 +877,54 @@ 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. A writer thread owns the link, so a stall never blocks the relay:
+ new saves are read as they appear and held in memory (256 MiB, about 8 minutes; a hot save lives
+ about ten seconds), trace bytes wait on disk, and a newer file and the journal wait until every
+ older file is complete on its way.
+- *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, and the byte cap, end the verdict's window instead (`window.ends`): what was compared
+ before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). 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..4635e39 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,21 @@
# 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, 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--.jsonl flysim's per-process trace (4 GiB each, 8 in all)
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
@@ -59,11 +76,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 +259,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 +310,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 +449,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,26 +495,79 @@ 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; 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:
+ 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:
+ 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:
+ 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 v.get("window") is None:
+ refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
+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"):
+ 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
[ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string.
set -a
- # shellcheck disable=SC1091
- . /etc/fly/fly.env
+ # shellcheck disable=SC1090,SC1091
+ . "${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 "$@"
}
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..7ba795d
--- /dev/null
+++ b/infra/box/fly-shadow-remote-setup
@@ -0,0 +1,145 @@
+#!/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] [--threads N]
+#
+# 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 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, 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="..." . 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).
+# 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]"
+tarball="$1"; rom="$2"; pubkey="$3"; shift 3
+from=""; cpus=""; threads=4
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --from) from="$2"; shift 2 ;;
+ --cpus) cpus="$2"; shift 2 ;;
+ --threads) threads="$2"; shift 2 ;;
+ *) die "unknown option $1" ;;
+ esac
+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"
+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"
+[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
+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, 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.
+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/10-cores.conf
+log "${threads} threads${cpus:+ on CPUs $cpus}"
+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..7229634
--- /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/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
+# 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..2f274de 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,9 +581,19 @@ 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);
+ - 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.
@@ -586,18 +608,110 @@ 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 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 ends its window at that
+ stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
+ gap, never a skip. The shadow discards the brain time and saves compared before it
+ (`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
+ last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
+ the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
+ `coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
+ a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
+ The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
+ does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
+ the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
+ new window has compared the required time.
+ **After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
+ would have to restart while the stopped trace is still the newest file and reach its stop before
+ any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
+ (`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
+ container, `pct exec --` in front): `/opt/fly/bin/fly-shadow-run stop
+ --restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
+ one.
+ **Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
+ restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
+ and the run is lost (safe: start a new run as above); do not rely on the fast case.
+ `coverageLost` is synced to disk before the chunk with the stop is forwarded.
+- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
+ Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
+ container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
+ the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
+ flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
+ threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
+ counts against it; if the guard trips on a remote run, the trace alone is too much for the live
+ fly's headroom. `--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 --threads `.
+ It installs the release at the same `/opt/fly/releases/` path (MANIFEST-verified,
+ 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="…" `,
+ `/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. **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.
+
+Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
+SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
+1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
+catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
+host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
+6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
+with `--cpus` and `--threads`; keep other heavy work (bx) off that box
+for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
## Cutover to the session runtime (CUT-01)
@@ -609,7 +723,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..cc2a776 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,119 @@ 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), 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"
+ 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), 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\",\"window\":{\"lastStopTrace\":null\}\}}" > "$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="$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" ;;
+ *) 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)"
+ 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\",\"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}"
+ # B2: a verdict that does not carry its window (an older shadow) may count time before a gap.
+ rc_check "a verdict without a window (B2)" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}"
+ rc_check "a verdict with a window, after a stop (B2)" passes-gates "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\",\"window\":{\"lastStopTrace\":\"trace-1790000005000-4242.jsonl\"}}"
+ 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
+# 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
+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\""
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..354e135
--- /dev/null
+++ b/services/flysim/crates/fly-legacy-session/src/shadow/ingest.rs
@@ -0,0 +1,649 @@
+//! `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, 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 = 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);
+ }
+ (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(
+ 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;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A writer the test can read back.
+ #[derive(Clone, Default)]
+ struct Shared(Arc>>);
+
+ impl Write for Shared {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ fn frames(out: &Shared) -> Vec {
+ let bytes = out.0.lock().unwrap().clone();
+ let mut input = std::io::Cursor::new(bytes);
+ std::iter::from_fn(|| remote::read_frame(&mut input).unwrap()).collect()
+ }
+
+ fn config(root: &Path) -> IngestConfig {
+ let mut c = IngestConfig::new(
+ root.to_owned(),
+ "/opt/fly/releases/v1".to_owned(),
+ [("fly-shadow".to_owned(), "a".repeat(64))].into(),
+ );
+ c.status_every = Duration::from_secs(3600);
+ c
+ }
+
+ fn wire(frames: &[(Value, &[u8])]) -> std::io::Cursor> {
+ let mut bytes = Vec::new();
+ for (header, body) in frames {
+ remote::write_frame(&mut bytes, header.clone(), body).unwrap();
+ }
+ std::io::Cursor::new(bytes)
+ }
+
+ fn hello(release: &str) -> Value {
+ json!({"t": "hello", "protocol": remote::PROTOCOL, "runId": "1790000000000",
+ "release": release, "binaries": {"fly-shadow": "a".repeat(64)},
+ "env": {"FLY_MACRO_MODE": "macros", "FLY_ROM": "/elsewhere", "FLY_GAME": "a b"}})
+ }
+
+ #[test]
+ fn another_release_is_refused_before_anything_is_written() {
+ let root = tempfile::tempdir().unwrap();
+ let out = Shared::default();
+ let input = wire(&[(hello("/opt/fly/releases/v2"), b"")]);
+ let err = serve(input, Box::new(out.clone()), config(root.path())).unwrap_err();
+ assert!(err.contains("same path"), "{err}");
+ let got = frames(&out);
+ assert_eq!(got.len(), 1);
+ assert_eq!(got[0].kind(), "error");
+ assert!(!root.path().join("run-id").exists());
+ }
+
+ #[test]
+ fn a_run_is_mirrored_by_name_and_offset_only() {
+ let root = tempfile::tempdir().unwrap();
+ let layout = Layout::of(root.path());
+ std::fs::create_dir_all(&layout.hot).unwrap();
+ // The previous run's leftovers go when a new run says hello.
+ std::fs::write(layout.hot.join("7.checkpoint"), b"old").unwrap();
+ let name = "trace-1790000000001-42.jsonl";
+ let out = Shared::default();
+ let input = wire(&[
+ (hello("/opt/fly/releases/v1"), b""),
+ (json!({"t": "trace", "name": name, "offset": 0}), b""),
+ (json!({"t": "trace", "name": name, "offset": 0}), b"{\"a\":1}\n"),
+ // A chunk at the wrong offset is not appended: the relay is asked to resend.
+ (json!({"t": "trace", "name": name, "offset": 99}), b"x"),
+ (json!({"t": "ckpt", "store": "hot", "gen": 12}), b"FLYSIM01"),
+ (json!({"t": "journal", "name": "sugar-journal.jsonl"}), b"{}\n"),
+ (json!({"t": "bye"}), b""),
+ ]);
+ serve(input, Box::new(out.clone()), config(root.path())).unwrap();
+ assert_eq!(std::fs::read(layout.trace.join(name)).unwrap(), b"{\"a\":1}\n");
+ assert_eq!(std::fs::read(layout.hot.join("12.checkpoint")).unwrap(), b"FLYSIM01");
+ assert!(!layout.hot.join("7.checkpoint").exists());
+ assert_eq!(
+ std::fs::read_to_string(&layout.run_id).unwrap(),
+ "1790000000000\n"
+ );
+ // Only the forwarded, plain settings reach the box's env file.
+ assert_eq!(
+ std::fs::read_to_string(&layout.live_env).unwrap(),
+ "FLY_MACRO_MODE=macros\n"
+ );
+ let got = frames(&out);
+ assert_eq!(got[0].kind(), "state");
+ assert!(got.iter().any(|f| f.kind() == "resync" && f.header["size"] == 8));
+ // A path in a name is refused outright.
+ let input = wire(&[
+ (hello("/opt/fly/releases/v1"), b""),
+ (json!({"t": "trace", "name": "../x.jsonl", "offset": 0}), b"x"),
+ ]);
+ assert!(serve(input, Box::new(Shared::default()), config(root.path())).is_err());
+ assert!(!root.path().join("x.jsonl").exists());
+ // The same run reconnecting keeps the mirror.
+ let input = wire(&[(hello("/opt/fly/releases/v1"), b"")]);
+ let out = Shared::default();
+ serve(input, Box::new(out.clone()), config(root.path())).unwrap();
+ assert_eq!(frames(&out)[0].header["traces"][name], 8);
+ }
+}
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..a794fc2 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()],
@@ -507,6 +525,8 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
checkpoints: Checkpoints::default(),
segments_compared: 0,
skipped: Vec::new(),
+ window_ends: Vec::new(),
+ last_stop_trace: None,
divergence: None,
started_at: verdict::now_iso(),
passed_at: None,
@@ -515,7 +535,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 +571,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 +606,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 +662,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 +744,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) => {}
@@ -710,6 +776,18 @@ impl Shadow {
let _ = std::fs::remove_file(&next);
}
}
+ SegmentEnd::Skipped("trace-cap", reason) => {
+ // A stopped trace is a coverage gap: what was compared before it stops
+ // counting (SHADOW-02 B2).
+ eprintln!(
+ "fly-shadow: {name} stopped after {compared} transitions: {reason}; the \
+ window restarts after it"
+ );
+ self.verdict.end_window(&name, reason);
+ if !self.config.keep_traces {
+ let _ = std::fs::remove_file(&next);
+ }
+ }
SegmentEnd::Skipped(kind, reason) => {
eprintln!(
"fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}"
@@ -751,6 +829,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.
@@ -983,6 +1064,11 @@ impl Shadow {
let mut rank_since_ms = rank_since_ms;
let mut context: VecDeque<(Value, Value)> = VecDeque::new();
let mut captures_taken: u64 = 0;
+ // After a declared reward pulse the rest of the trace cannot be compared, but it is still
+ // read for its stop line: a stop later in the same trace is a coverage gap and must end
+ // the window (SHADOW-02 r3 N5).
+ let mut reward_skipped = false;
+ let compared_before = self.verdict.agreement.transitions;
loop {
let line = match self.next_line(follower).await {
Ok(Some(line)) => line,
@@ -996,11 +1082,35 @@ 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"]),
);
}
+ if reward_skipped {
+ continue;
+ }
let Some(behaviour) = live.get("behaviour").cloned() else {
continue;
};
@@ -1018,13 +1128,22 @@ impl Shadow {
admission.replay_sugar(duration);
}
Some("reward") => {
- return SegmentEnd::Skipped(
- "operator-reward-pulse",
- format!(
+ let compared = self.verdict.agreement.transitions - compared_before;
+ eprintln!(
+ "fly-shadow: {name} skipped (operator-reward-pulse) after {compared} \
+ transitions; reading on for a stop"
+ );
+ self.verdict.skipped.push(Skipped {
+ trace: name.to_owned(),
+ transitions_compared: compared,
+ kind: "operator-reward-pulse".to_owned(),
+ reason: format!(
"an operator reward pulse at step {step:?} (declared \
operator-reward-pulse: not available on the session runtime)"
),
- );
+ });
+ reward_skipped = true;
+ break;
}
other => {
return SegmentEnd::Skipped(
@@ -1034,6 +1153,9 @@ impl Shadow {
}
}
}
+ if reward_skipped {
+ continue;
+ }
// Back off while the live fly is losing real time ([`LagGuard`]).
if let Some(lag) = self.lag.clone() {
let throttle = Instant::now();
@@ -1295,6 +1417,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..d18c8f2
--- /dev/null
+++ b/services/flysim/crates/fly-legacy-session/src/shadow/relay.rs
@@ -0,0 +1,1175 @@
+//! `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.
+//!
+//! **A stalled link.** A writer thread owns the ssh pipe, so the relay never blocks on it: it keeps
+//! ticking, reports itself unhealthy and stops the heartbeat. New saves are still read the moment
+//! they appear and held in memory ([`QUEUE_SAVES`], about 8 minutes of hot saves), because the
+//! container keeps a hot save only about ten seconds; trace bytes wait on disk ([`QUEUE_TRACE`]),
+//! and a newer trace file and the journal are held back until every older file is complete on its
+//! way to the box (the box ends a segment when a newer file appears, and checks each boot header
+//! against the files it has).
+//!
+//! **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.
+//! 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 (`"reason":"no-consumer"`, after ten minutes without a
+//! heartbeat, or `"reason":"byte-cap"`) leaves the live fly running untraced, and the box's
+//! catch-up bound counts trace *lines*, so a box that has not yet reached that line looks caught up
+//! once the link is back. The relay therefore scans the trace bytes it forwards for that marker;
+//! on finding it, it sets `coverageLost` in `relay.json` (sticky, also across a relay restart of the
+//! same run) and reports itself unhealthy, which stops the heartbeat and makes `check` refuse. It
+//! clears only when the box's verdict says its window starts after that stop (`window.lastStopTrace`
+//! is the lost trace or a later one: the shadow ended its window at the stop, so its compared
+//! brain time counts only from after the gap), never by the shadow catching up or restarting. A
+//! relay that restarts mid-run ends the run's coverage (flysim stops tracing without a heartbeat)
+//! and the loss is safe. `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};
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, 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,
+}
+
+/// 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;
+
+/// One connection to the box.
+struct Conn {
+ child: Child,
+ /// Frames for the writer thread, which owns the pipe; body bytes not yet written; the
+ /// writer's error, once it has one.
+ tx: Option>)>>,
+ queued: Arc,
+ write_error: Arc>>,
+ 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 {
+ /// Queues a frame for the writer; never blocks. An error is the writer's (a broken link).
+ fn send(&mut self, header: Value, body: Vec) -> std::io::Result<()> {
+ self.send_shared(header, Arc::new(body))
+ }
+
+ /// [`Conn::send`] of a body the relay also keeps (a save not yet confirmed).
+ fn send_shared(&mut self, header: Value, body: Arc>) -> std::io::Result<()> {
+ if let Some(e) = self.write_error.lock().unwrap_or_else(|p| p.into_inner()).clone() {
+ return Err(std::io::Error::other(e));
+ }
+ let len = body.len() as u64;
+ self.queued.fetch_add(len, Ordering::Relaxed);
+ self.tx
+ .as_ref()
+ .ok_or_else(|| std::io::Error::other("closed"))?
+ .send((header, body))
+ .map_err(|_| std::io::Error::other("the writer stopped"))?;
+ self.sent_total += len;
+ self.last_frame_sent = Instant::now();
+ Ok(())
+ }
+
+ /// Body bytes queued and not yet written to the link.
+ fn queued(&self) -> u64 {
+ self.queued.load(Ordering::Relaxed)
+ }
+
+ fn close(mut self) {
+ if let Some(tx) = self.tx.take() {
+ let _ = tx.send((json!({"t": "bye"}), Arc::new(Vec::new())));
+ }
+ 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();
+ }
+}
+
+/// A save read from a live store and not yet confirmed by the box.
+struct PendingSave {
+ store: &'static str,
+ generation: u64,
+ bytes: Arc>,
+ /// On the current connection: queued, with the connection's byte total after it (the box has
+ /// it once `received` reaches that).
+ queued_at: Option,
+}
+
+/// 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 read (or held by the box, or older than the run).
+ sent_gens: BTreeSet,
+ /// Saves read and not yet confirmed by the box, oldest first, and their bytes: they survive a
+ /// broken connection and are sent again on the next ([`QUEUE_SAVES`] bounds them).
+ pending: VecDeque,
+ pending_bytes: u64,
+ /// 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,
+ /// 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,
+ /// The `startedAt` of the latest relayed verdict: the box shadow's window.
+ window: Option,
+ /// 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)>,
+}
+
+/// Coverage of the live fly was lost: flysim stopped its trace (no consumer, or the byte cap).
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct CoverageLost {
+ trace: String,
+ /// The box shadow's window when it was seen; `None` when no verdict had arrived (never clears).
+ window: Option,
+ at: String,
+}
+
+/// Whether trace file `a` started at or after `b` (by the start in its name; else by name).
+fn trace_not_before(a: &str, b: &str) -> bool {
+ match (
+ super::trace_start_ms(Path::new(a)),
+ super::trace_start_ms(Path::new(b)),
+ ) {
+ (Some(x), Some(y)) => x >= y,
+ _ => a >= b,
+ }
+}
+
+/// The reasons for which flysim stops a trace, as written in its `{"truncated":true,"reason":..}`
+/// line: no consumer (a stale heartbeat) and the byte cap. Both leave the live fly running
+/// untraced, so the relay treats them alike (SHADOW-02 r3 N4).
+const STOP_MARKERS: [&[u8]; 2] = [b"\"reason\":\"no-consumer\"", b"\"reason\":\"byte-cap\""];
+
+/// Whether `bytes` hold a whole `{"truncated":true,"reason":"no-consumer"|"byte-cap"}` line.
+fn has_stop_marker(bytes: &[u8]) -> bool {
+ STOP_MARKERS.iter().any(|marker| {
+ let mut from = 0;
+ while let Some(i) = bytes[from..].windows(marker.len()).position(|w| w == *marker) {
+ let at = from + i;
+ let start = bytes[..at].iter().rposition(|b| *b == b'\n').map_or(0, |n| n + 1);
+ let end = bytes[at..].iter().position(|b| *b == b'\n').map_or(bytes.len(), |n| at + n);
+ 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,
+}
+
+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) {
+ 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(),
+ pending: VecDeque::new(),
+ pending_bytes: 0,
+ 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,
+ 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);
+ 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 (out_tx, outgoing) = mpsc::channel::<(Value, Arc>)>();
+ let queued = Arc::new(AtomicU64::new(0));
+ let write_error: Arc>> = Arc::new(Mutex::new(None));
+ {
+ let (queued, write_error) = (Arc::clone(&queued), Arc::clone(&write_error));
+ std::thread::Builder::new()
+ .name("fly-shadow-relay-write".to_owned())
+ .spawn(move || {
+ let mut out = BufWriter::with_capacity(1 << 20, stdin);
+ for (header, body) in outgoing {
+ if let Err(e) = remote::write_frame(&mut out, header, &body) {
+ *write_error.lock().unwrap_or_else(|p| p.into_inner()) =
+ Some(e.to_string());
+ return;
+ }
+ queued.fetch_sub(body.len() as u64, Ordering::Relaxed);
+ }
+ })
+ .expect("the writer thread starts");
+ }
+ 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,
+ tx: Some(out_tx),
+ queued,
+ write_error,
+ 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, Vec::new()) {
+ 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"]);
+ // What the box holds, and what this relay still has pending (sent again on this
+ // connection unless the box has it): a save queued on a connection that broke is not lost.
+ let held: BTreeSet = h["gens"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_u64)
+ .collect();
+ self.pending.retain(|p| !held.contains(&p.generation));
+ for p in self.pending.iter_mut() {
+ p.queued_at = None;
+ }
+ self.pending_bytes = self.pending.iter().map(|p| p.bytes.len() as u64).sum();
+ self.sent_gens = held;
+ self.sent_gens
+ .extend(self.pending.iter().map(|p| p.generation));
+ 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