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, String> { + let result = loop { + if self.stop.requested() { + break Ok(Some(RelayEnd::Stopped)); + } + let tick = Instant::now(); + if let Err(e) = self.push(&mut conn) { + break Err(format!("sending: {e}")); + } + conn.ticks.push_back((tick, conn.sent_total)); + // Incoming frames. + let mut ended = None; + loop { + match conn.frames.try_recv() { + Ok(Ok(frame)) => { + if let Err(e) = self.receive(&mut conn, frame) { + ended = Some(Err(e)); + break; + } + } + Ok(Err(e)) => { + ended = Some(Err(e.to_string())); + break; + } + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) => { + ended = Some(Err("the reader stopped".to_owned())); + break; + } + } + } + if let Some(ended) = ended { + break ended; + } + let healthy = self.healthy(&conn); + if healthy + && self + .last_beat + .is_none_or(|t| t.elapsed() >= self.config.beat_every) + { + let path = self.config.trace_dir.join(flysim::trace::CONSUMER_FILE); + if let Err(e) = std::fs::write(&path, verdict::now_iso()) { + log(format!("could not write {}: {e}", path.display())); + } + self.last_beat = Some(Instant::now()); + } + if self.last_relay_json.elapsed() >= Duration::from_secs(5) { + self.write_relay_json(Some(&conn), healthy); + } + if let Some(at) = self.diverged_at + && (self.have_divergence || at.elapsed() >= Duration::from_secs(60)) + { + log("the remote shadow diverged: its verdict and divergence are in place"); + break Ok(Some(RelayEnd::Diverged)); + } + if conn.last_frame_sent.elapsed() >= Duration::from_secs(5) + && conn.queued() == 0 + && let Err(e) = conn.send(json!({"t": "ping"}), Vec::new()) + { + break Err(format!("sending: {e}")); + } + let spent = tick.elapsed(); + if spent < self.config.tick { + std::thread::sleep(self.config.tick - spent); + } + }; + conn.close(); + result + } + + /// Healthy: connected, the box's shadow for this run alive lately, the sync caught up. + fn healthy(&self, conn: &Conn) -> bool { + let alive = conn.last_status.as_ref().is_some_and(|(at, alive, _)| { + *alive && at.elapsed() <= self.config.alive_within + }); + alive + && conn.caught_up_at.elapsed() <= self.config.stall + && self.diverged_at.is_none() + && self.coverage_lost.is_none() + } + + /// A previous relay of this run may have seen the stop: keep it (sticky). + fn load_coverage_lost(&mut self) { + let Ok(bytes) = std::fs::read(self.config.out_dir.join("relay.json")) else { + return; + }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + return; + }; + if v["runId"].as_str() != Some(self.config.run_id.as_str()) { + return; + } + let lost = &v["coverageLost"]; + if let Some(trace) = lost["trace"].as_str() { + self.coverage_lost = Some(CoverageLost { + trace: trace.to_owned(), + window: lost["window"].as_str().map(str::to_owned), + at: lost["at"].as_str().unwrap_or("").to_owned(), + }); + self.window = lost["window"].as_str().map(str::to_owned); + } + } + + /// Writes `coverageLost` into `relay.json` and syncs it (file and directory). + fn persist_coverage_lost(&self) { + let path = self.config.out_dir.join("relay.json"); + let mut value = std::fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .filter(|v| v["runId"].as_str() == Some(self.config.run_id.as_str())) + .unwrap_or_else(|| { + json!({"format": "fly-shadow-relay-v1", "runId": self.config.run_id, "healthy": false}) + }); + value["healthy"] = json!(false); + value["coverageLost"] = self.coverage_lost.as_ref().map_or( + Value::Null, + |c| json!({"trace": c.trace, "window": c.window, "at": c.at}), + ); + if let Err(e) = verdict::write_json_durable(&path, &value) { + log(format!("could not write {}: {e}", path.display())); + } + } + + /// Looks for flysim's stop (no consumer, byte cap) in trace bytes about to be sent. + fn scan_trace(&mut self, name: &str, offset: u64, chunk: &[u8]) { + let mut buf = match self.scan_tail.remove(name) { + Some((end, tail)) if end == offset => tail, + _ => Vec::new(), + }; + buf.extend_from_slice(chunk); + if self.coverage_lost.is_none() && has_stop_marker(&buf) { + log(format!( + "{name}: flysim stopped its trace (no consumer or byte cap); coverage of the live fly \ + is lost for this window" + )); + self.coverage_lost = Some(CoverageLost { + trace: name.to_owned(), + window: self.window.clone(), + at: verdict::now_iso(), + }); + // Durable before the chunk that holds the stop is sent: a relay that dies after + // sending and before its next tick would otherwise resume past the stop unaware. + self.persist_coverage_lost(); + self.last_relay_json = Instant::now() - Duration::from_secs(60); + } + let keep = buf.len().saturating_sub(256); + self.scan_tail + .insert(name.to_owned(), (offset + chunk.len() as u64, buf.split_off(keep))); + } + + /// One tick's sends: saves, then trace bytes, then the journal read first. + fn push(&mut self, conn: &mut Conn) -> std::io::Result<()> { + // The journal, read before the trace directory is listed (coverage). + let mut journal: Vec<(String, Vec, (u64, u64))> = Vec::new(); + let mut journal_names = BTreeSet::new(); + for entry in std::fs::read_dir(&self.config.hot_dir) + .into_iter() + .flatten() + .flatten() + { + let name = entry.file_name().to_string_lossy().into_owned(); + if !remote::is_journal_name(&name) { + continue; + } + journal_names.insert(name.clone()); + let Ok(meta) = entry.metadata() else { continue }; + let signature = (meta.len(), remote::mtime_ms(&meta).unwrap_or(0)); + if conn.journal_sent.get(&name) == Some(&signature) { + continue; + } + if let Ok(bytes) = std::fs::read(entry.path()) { + journal.push((name, bytes, signature)); + } + } + // New saves. + let floor_ms = self.run_start_ms.map(|ms| ms.saturating_sub(60_000)); + for (store, dir) in [ + ("hot", self.config.hot_dir.clone()), + ("durable", self.config.durable_dir.clone()), + ] { + let mut found: Vec<(u64, PathBuf, Option)> = std::fs::read_dir(&dir) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let generation = generation_of(e.file_name().to_str()?)?; + let modified = e.metadata().ok().and_then(|m| remote::mtime_ms(&m)); + Some((generation, e.path(), modified)) + }) + .collect(); + found.sort(); + for (generation, path, modified) in found { + if self.sent_gens.contains(&generation) { + continue; + } + if self.pending_bytes >= QUEUE_SAVES { + break; + } + if let (Some(floor), Some(modified)) = (floor_ms, modified) + && modified < floor + { + self.sent_gens.insert(generation); + continue; + } + // Rotated away since the listing: gone for good. + let Ok(bytes) = std::fs::read(&path) else { + continue; + }; + self.pending_bytes += bytes.len() as u64; + self.pending.push_back(PendingSave { + store, + generation, + bytes: Arc::new(bytes), + queued_at: None, + }); + self.sent_gens.insert(generation); + } + } + // Every save not yet queued on this connection, in generation order, before any trace. + let mut order: Vec = (0..self.pending.len()) + .filter(|i| self.pending[*i].queued_at.is_none()) + .collect(); + order.sort_by_key(|i| self.pending[*i].generation); + for i in order { + let p = &self.pending[i]; + let header = json!({"t": "ckpt", "store": p.store, "gen": p.generation}); + conn.send_shared(header, Arc::clone(&p.bytes))?; + self.pending[i].queued_at = Some(conn.sent_total); + } + // Trace bytes: list, then read each size. A file that cannot be brought up to date now holds + // back every newer file and the journal. + let files = follow::trace_files(&self.config.trace_dir).unwrap_or_default(); + let mut complete = true; + for path in files { + if !complete { + break; + } + let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned()) else { + continue; + }; + if self.done.contains(&name) || !remote::is_trace_name(&name) { + continue; + } + if let (Some(start), Some(run)) = (super::trace_start_ms(&path), self.run_start_ms) + && start < run + { + continue; + } + let Ok(size) = std::fs::metadata(&path).map(|m| m.len()) else { + continue; + }; + // A new file exists on the box at once, even while flysim's buffer still holds its + // first bytes: its boot header may reach the box in this very tick (coverage). + if !conn.sent.contains_key(&name) { + conn.send(json!({"t": "trace", "name": name, "offset": 0}), Vec::new())?; + conn.sent.insert(name.clone(), 0); + } + let mut offset = conn.sent.get(&name).copied().unwrap_or(0); + if size <= offset { + continue; + } + let Ok(mut file) = std::fs::File::open(&path) else { + continue; + }; + file.seek(SeekFrom::Start(offset))?; + while offset < size { + if conn.queued() >= QUEUE_TRACE { + complete = false; + break; + } + let want = (size - offset).min(remote::TRACE_CHUNK) as usize; + let mut chunk = vec![0u8; want]; + file.read_exact(&mut chunk)?; + self.trace_bytes += chunk.len() as u64; + self.trace_lines += chunk.iter().filter(|b| **b == b'\n').count() as u64; + self.scan_trace(&name, offset, &chunk); + conn.send(json!({"t": "trace", "name": name, "offset": offset}), chunk)?; + offset += want as u64; + conn.sent.insert(name.clone(), offset); + } + } + // The journal as read above, once every trace file it can name is on its way. + if complete { + for (name, bytes, signature) in journal { + conn.send(json!({"t": "journal", "name": name}), bytes)?; + conn.journal_sent.insert(name, signature); + } + if journal_names != conn.journal_names { + conn.send( + json!({"t": "journal-set", "names": journal_names}), + Vec::new(), + )?; + conn.journal_names = journal_names; + } + } + // Keep the set of sent generations bounded (the newest 2048, about 3 h of hot saves). An + // older one still on disk is skipped again by its age, or at worst sent again (harmless: + // the ingest rewrites the same file). + if self.sent_gens.len() > 4096 + && let Some(&oldest) = self.sent_gens.iter().nth(self.sent_gens.len() - 2048) + { + self.sent_gens = self.sent_gens.split_off(&oldest); + } + Ok(()) + } + + fn receive(&mut self, conn: &mut Conn, frame: Frame) -> Result<(), String> { + let h = &frame.header; + match frame.kind() { + "status" => { + let received = h["received"].as_u64().unwrap_or(0); + while conn + .ticks + .front() + .is_some_and(|(_, total)| *total <= received) + { + let (at, _) = conn.ticks.pop_front().expect("a tick"); + conn.caught_up_at = at; + } + // Saves the box now has. + let before = self.pending.len(); + self.pending + .retain(|p| p.queued_at.is_none_or(|t| t > received)); + if self.pending.len() != before { + self.pending_bytes = self.pending.iter().map(|p| p.bytes.len() as u64).sum(); + } + conn.acked.clear(); + for (name, size) in h["traces"].as_object().into_iter().flatten() { + if let Some(size) = size.as_u64() { + conn.acked.insert(name.clone(), size); + } + } + self.absorb_done(&h["done"]); + let alive = h["alive"].as_bool().unwrap_or(false); + let why = h["why"].as_str().unwrap_or("").to_owned(); + if !alive + && conn + .last_status + .as_ref() + .is_none_or(|(_, was, old)| *was || *old != why) + { + log(format!("the remote shadow is not alive: {why}")); + } + conn.last_status = Some((Instant::now(), alive, why)); + } + "resync" => { + let name = h["name"].as_str().unwrap_or(""); + if remote::is_trace_name(name) { + let size = h["size"].as_u64().unwrap_or(0); + log(format!("the box has {size} bytes of {name}; resending from there")); + conn.sent.insert(name.to_owned(), size); + } + } + "verdict" => self.relay_verdict(conn, &frame.body), + "file" => { + let name = h["name"].as_str().unwrap_or(""); + if !self + .files + .admit(name, frame.body.len(), self.diverged_at.is_some()) + { + log(format!( + "refused a file {name:?} ({} bytes) from the box", + frame.body.len() + )); + } else { + let path = self.config.out_dir.join(name); + remote::atomic_write(&path, &frame.body) + .map_err(|e| format!("{}: {e}", path.display()))?; + if name == "divergence.json" { + self.have_divergence = true; + } + } + } + "error" => return Err(format!("the box: {}", h["message"])), + other => return Err(format!("an unknown frame {other:?}")), + } + Ok(()) + } + + /// Live trace bytes not yet on the box, and about how many transitions that is. + fn unsynced(&self, conn: Option<&Conn>) -> (u64, u64) { + let bytes: u64 = follow::trace_files(&self.config.trace_dir) + .unwrap_or_default() + .iter() + .filter_map(|path| { + let name = path.file_name()?.to_string_lossy().into_owned(); + if self.done.contains(&name) { + return None; + } + if let (Some(start), Some(run)) = (super::trace_start_ms(path), self.run_start_ms) + && start < run + { + return None; + } + let size = std::fs::metadata(path).ok()?.len(); + let acked = conn.and_then(|c| c.acked.get(&name).copied()).unwrap_or(0); + Some(size.saturating_sub(acked)) + }) + .sum(); + let mean = if self.trace_lines > 0 { + (self.trace_bytes / self.trace_lines).max(1) + } else { + 750 + }; + (bytes, bytes.div_ceil(mean)) + } + + /// Seconds since the newest trace file of this run was written (`None`: there is none). + fn trace_age_seconds(&self) -> Option { + follow::trace_files(&self.config.trace_dir) + .unwrap_or_default() + .iter() + .filter(|path| { + !matches!((super::trace_start_ms(path), self.run_start_ms), + (Some(start), Some(run)) if start < run) + }) + .filter_map(|path| std::fs::metadata(path).ok()?.modified().ok()) + .max() + .map(|t| { + std::time::SystemTime::now() + .duration_since(t) + .unwrap_or_default() + .as_secs() + }) + } + + /// Writes the box's verdict here, when it is this run's, with the sync's backlog added. + fn relay_verdict(&mut self, conn: &Conn, bytes: &[u8]) { + let Ok(mut v) = serde_json::from_slice::(bytes) else { + log("the box sent a verdict that does not parse"); + return; + }; + if v["runId"].as_str() != Some(self.config.run_id.as_str()) { + return; + } + let (unsynced_bytes, unsynced) = self.unsynced(Some(conn)); + let remote_lag = v["lagTransitions"].as_u64().unwrap_or(u64::MAX / 2); + self.remote_lag = remote_lag; + v["lagTransitions"] = json!(remote_lag.saturating_add(unsynced)); + v["relay"] = json!({ + "relayedAt": verdict::now_iso(), + "remoteLagTransitions": remote_lag, + "unsyncedBytes": unsynced_bytes, + "unsyncedTransitions": unsynced, + }); + // The loss clears only once the box's verdict counts from after it: its window's last + // trace stop is the lost trace or a later one (SHADOW-02 B2). A verdict that has not + // reached the stop, or a restarted shadow's that replays the stopped trace before its + // stop line, still counts the time before the gap, so the loss stays. + if let Some(lost) = &self.coverage_lost + && let Some(stop) = v["window"]["lastStopTrace"].as_str() + && trace_not_before(stop, &lost.trace) + { + log("the box's verdict counts from after the trace stop: the coverage loss is closed"); + self.coverage_lost = None; + self.last_relay_json = Instant::now() - Duration::from_secs(60); + } + self.window = v["startedAt"].as_str().map(str::to_owned); + if v["status"] == "diverged" && self.diverged_at.is_none() { + self.diverged_at = Some(Instant::now()); + } + let path = self.config.out_dir.join("verdict.json"); + if let Err(e) = verdict::write_json(&path, &v) { + log(format!("could not write {}: {e}", path.display())); + } + } + + fn write_relay_json(&mut self, conn: Option<&Conn>, healthy: bool) { + self.last_relay_json = Instant::now(); + let (unsynced_bytes, unsynced) = self.unsynced(conn); + let coverage_lost = self.coverage_lost.as_ref().map(|c| { + json!({"trace": c.trace, "window": c.window, "at": c.at}) + }); + let value = json!({ + "format": "fly-shadow-relay-v1", + "updatedAt": verdict::now_iso(), + "runId": self.config.run_id, + "connected": conn.is_some(), + "healthy": healthy, + "coverageLost": coverage_lost, + "traceAgeSeconds": self.trace_age_seconds(), + "remoteAlive": conn.and_then(|c| c.last_status.as_ref()).map(|(_, alive, _)| *alive), + "remoteWhy": conn.and_then(|c| c.last_status.as_ref()).map(|(_, _, why)| why.clone()), + "caughtUpSecondsAgo": conn.map(|c| c.caught_up_at.elapsed().as_secs()), + "sentBytes": conn.map(|c| c.sent_total), + "queuedBytes": conn.map(|c| c.queued()), + "pendingSaves": self.pending.len(), + "unsyncedBytes": unsynced_bytes, + "unsyncedTransitions": unsynced, + "remoteLagTransitions": self.remote_lag, + "lastBeatSecondsAgo": self.last_beat.map(|t| t.elapsed().as_secs()), + }); + let path = self.config.out_dir.join("relay.json"); + if let Err(e) = verdict::write_json(&path, &value) { + log(format!("could not write {}: {e}", path.display())); + } + } +} + +/// The ssh command that reaches the box's ingest, with nothing from the user's ssh configuration: +/// this key, these known hosts, batch mode, keep-alives that end a dead connection in 30 s. +pub fn ssh_command( + target: &str, + key: &Path, + known_hosts: &Path, + port: Option, +) -> Vec { + let mut argv: Vec = [ + "ssh", + "-F", + "/dev/null", + "-T", + "-o", + "BatchMode=yes", + "-o", + "IdentitiesOnly=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ServerAliveInterval=10", + "-o", + "ServerAliveCountMax=3", + "-o", + "ConnectTimeout=15", + "-o", + "ClearAllForwardings=yes", + ] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + argv.push("-o".to_owned()); + argv.push(format!("UserKnownHostsFile={}", known_hosts.display())); + argv.push("-i".to_owned()); + argv.push(key.display().to_string()); + if let Some(port) = port { + argv.push("-p".to_owned()); + argv.push(port.to_string()); + } + argv.push(target.to_owned()); + // Ignored by the box: its authorized_keys forces `fly-shadow ingest`. + argv.push("fly-shadow-ingest".to_owned()); + argv +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_no_consumer_stop_is_found_and_nothing_else_is() { + assert!(has_stop_marker( + b"{\"a\":1}\n{\"reason\":\"no-consumer\",\"truncated\":true}\n" + )); + assert!(has_stop_marker( + b"{\"truncated\":true,\"reason\":\"no-consumer\"}" + )); + // The byte cap is a stop like any other (N4). + assert!(has_stop_marker( + b"{\"reason\":\"byte-cap\",\"truncated\":true}\n" + )); + assert!(!has_stop_marker(b"{\"reason\":\"other\",\"truncated\":true}\n")); + assert!(!has_stop_marker(b"{\"reason\":\"byte-cap\"}\n")); + // Not a marker line. + assert!(!has_stop_marker(b"{\"note\":{\"reason\":\"no-consumer\"}}\n")); + assert!(!has_stop_marker(b"")); + } + + #[test] + fn divergence_files_come_only_after_a_diverged_verdict_and_are_bounded() { + let mut files = DivergenceFiles::default(); + assert!(!files.admit("divergence.json", 10, false), "not diverged yet"); + assert!(!files.admit("../evil", 10, true)); + assert!(!files.admit("divergence.json", DivergenceFiles::MAX_JSON + 1, true)); + assert!(files.admit("divergence.json", 10, true)); + assert!(files.admit("divergence.json", 10, true), "the same file again"); + assert!(files.admit("divergence-live-g1.checkpoint", 1 << 20, true)); + assert!(!files.admit( + "divergence-shadow-g1.checkpoint", + DivergenceFiles::MAX_CHECKPOINT + 1, + true + )); + assert!(files.admit("divergence-shadow-g1.checkpoint", 1 << 20, true)); + assert!( + !files.admit("divergence-shadow-g2.checkpoint", 1, true), + "a fourth file" + ); + } + + #[test] + fn the_saves_queue_holds_the_whole_stale_window() { + // Review N5: a stall of up to the trace's ten-minute stale window must not lose the saves + // the shadow needs (with a margin of a fifth). + const { assert!(QUEUE_SAVES >= STALE_WINDOW_SECONDS * SAVE_BYTES_PER_SECOND * 6 / 5) }; + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/release.rs b/services/flysim/crates/fly-legacy-session/src/shadow/release.rs new file mode 100644 index 0000000..abae299 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/release.rs @@ -0,0 +1,50 @@ +//! The release a verdict vouches for: the resolved directory of the running binary and the +//! SHA-256 of the release binaries in it, by name. `fly-shadow run` writes them into the verdict's +//! `candidate`; `fly-shadow check` recomputes them for what `/opt/fly/current` resolves to; the +//! remote shadow's relay and ingest (SHADOW-02) compare them at the handshake, so a box can only +//! shadow the exact release the container runs, installed at the same path. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// 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. +pub const RELEASE_BINARIES: [&str; 5] = [ + "flysim-session", + "fly-session", + "fly-shadow", + "flysim", + "fly-edge", +]; + +/// SHA-256 of a file, lowercase hex. +pub fn file_sha256(path: &Path) -> std::io::Result { + Ok(super::sha256_hex(&std::fs::read(path)?)) +} + +/// SHA-256 of the release binaries in `dir`, by name (the ones present). +pub fn binaries_in(dir: &Path) -> std::io::Result> { + let mut out = BTreeMap::new(); + for name in RELEASE_BINARIES { + let path = dir.join(name); + if path.is_file() { + out.insert(name.to_owned(), file_sha256(&path)?); + } + } + Ok(out) +} + +/// The resolved directory of the running binary: the release it runs from. +pub fn this_release() -> PathBuf { + std::env::current_exe() + .map(|exe| this_release_of(&exe)) + .unwrap_or_default() +} + +/// The resolved directory of the binary at `exe`. +pub fn this_release_of(exe: &Path) -> PathBuf { + exe.canonicalize() + .ok() + .and_then(|exe| exe.parent().map(Path::to_owned)) + .unwrap_or_default() +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/remote.rs b/services/flysim/crates/fly-legacy-session/src/shadow/remote.rs new file mode 100644 index 0000000..e44f84a --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/remote.rs @@ -0,0 +1,248 @@ +//! SHADOW-02: the shadow run on a build box instead of the release container. This module is the +//! wire protocol between the two halves; [`super::relay`] is the container's half and +//! [`super::ingest`] the box's. +//! +//! ```text +//! release container build box +//! flysim --FLY_TRACE_DIR--> trace/ <-- consumer --+ flyshadow-remote.service: fly-shadow run +//! stores (hot, durable), sugar journal | follows /trace, reads /hot, +//! flyshadow.service = fly-shadow relay ---- ssh ---+--> fly-shadow ingest --root +//! pushes trace bytes, new saves, the journal | (the forced command of a key that +//! writes back verdict.json, divergence.*, | can do nothing else) writes the mirror +//! touches trace/consumer while the box is alive | and sends back acks, the shadow's +//! and the sync is caught up | liveness, verdict and divergence +//! ``` +//! +//! The container opens the one connection (`ssh -T ...`, the box's `authorized_keys` +//! forces `fly-shadow ingest`), so the build box holds no credential for the release container. +//! Both directions carry *frames*: one JSON header line with a `t` (kind) and a `len`, followed by +//! `len` bytes of body. +//! +//! | `t` | direction | header | body | +//! | --- | --- | --- | --- | +//! | `hello` | relay to ingest | `protocol`, `runId`, `release`, `binaries`, `env` | | +//! | `state` | ingest to relay | `runId`, `traces` (name to size), `done`, `gens` | | +//! | `trace` | relay to ingest | `name`, `offset` | bytes to append at `offset` | +//! | `ckpt` | relay to ingest | `store` (`hot`, `durable`), `gen` | the whole `.checkpoint` | +//! | `journal` | relay to ingest | `name` | the whole journal file | +//! | `journal-set` | relay to ingest | `names` (every journal file there is) | | +//! | `ping`, `bye` | relay to ingest | | | +//! | `status` | ingest to relay | `received`, `traces`, `done`, `alive`, `why`, `verdictStatus` | | +//! | `resync` | ingest to relay | `name`, `size` | | +//! | `verdict` | ingest to relay | | the shadow's `verdict.json` | +//! | `file` | ingest to relay | `name` (`divergence.json`, `divergence-*.checkpoint`) | the file | +//! | `error` | ingest to relay | `message` | | +//! +//! `received` is the count of body bytes the ingest has applied on this connection; the relay +//! compares it with what it had sent, which is how it knows the box has everything that was on +//! the container's disk a given time ago ([`super::relay`]). + +use std::io::{BufRead, Read, Write}; +use std::path::Path; + +use serde_json::{Value, json}; + +/// The protocol name in `hello`. +pub const PROTOCOL: &str = "fly-shadow-relay-v1"; + +/// The longest header line accepted. +pub const MAX_HEADER: usize = 64 << 10; + +/// The largest body accepted (a checkpoint is about 2.7 MB; trace chunks are 4 MiB at most). +pub const MAX_BODY: u64 = 64 << 20; + +/// The biggest trace chunk the relay sends in one frame. +pub const TRACE_CHUNK: u64 = 4 << 20; + +/// The live configuration the relay forwards to the box, so the remote shadow runs the live +/// service's composition (game, macro mode, accepted adapters, pins): exactly these names, and +/// nothing that is a path or a secret. The box's own env file supplies the paths. +pub const FORWARDED_ENV: [&str; 14] = [ + "FLY_GAME", + "FLYSIM_LOOP_GAME", + "FLY_MACRO_MODE", + "FLYSIM_MACROS_MODE", + "FLY_ACCEPT_ADAPTERS", + "FLY_MACRO_BLOCKED_MINUTES", + "FLY_ROM_SHA256", + "FLY_ROM_PLATFORMER_SHA256", + "FLYSIM_GAME_PLATFORMER_ROM_SHA256", + "FLY_REWARD_ADAPTER", + "FLY_DECODER_PRESET", + "FLYSIM_LOOP_SPEED", + "FLYSIM_LOOP_WARMUP_MS", + "FLYSIM_FEED_AUDIO_HZ", +]; + +/// A forwarded value is short and plain: no quotes, spaces or newlines reach the box's env file. +pub fn env_value_ok(value: &str) -> bool { + value.len() <= 1024 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._,:+-/@".contains(&b)) +} + +/// One frame. +#[derive(Debug)] +pub struct Frame { + pub header: Value, + pub body: Vec, +} + +impl Frame { + pub fn kind(&self) -> &str { + self.header["t"].as_str().unwrap_or("") + } +} + +fn invalid(message: impl Into) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, message.into()) +} + +/// Writes one frame and flushes. +pub fn write_frame( + out: &mut W, + mut header: Value, + body: &[u8], +) -> std::io::Result<()> { + header["len"] = json!(body.len()); + let mut line = serde_json::to_vec(&header).map_err(|e| invalid(e.to_string()))?; + line.push(b'\n'); + out.write_all(&line)?; + out.write_all(body)?; + out.flush() +} + +/// Reads one frame; `None` at a clean end of the stream. +pub fn read_frame(input: &mut R) -> std::io::Result> { + let mut line = Vec::new(); + let n = input + .by_ref() + .take(MAX_HEADER as u64 + 1) + .read_until(b'\n', &mut line)?; + if n == 0 { + return Ok(None); + } + if line.last() != Some(&b'\n') { + return Err(invalid("a frame header that is cut or too long")); + } + let header: Value = serde_json::from_slice(&line).map_err(|e| invalid(e.to_string()))?; + if !header.is_object() { + return Err(invalid("a frame header that is not an object")); + } + let len = header["len"].as_u64().unwrap_or(0); + if len > MAX_BODY { + return Err(invalid(format!("a {len}-byte frame body"))); + } + let mut body = vec![0u8; len as usize]; + input.read_exact(&mut body)?; + Ok(Some(Frame { header, body })) +} + +/// `trace-<13 digits>-.jsonl`, flysim's per-process trace file name. +pub fn is_trace_name(name: &str) -> bool { + let Some(rest) = name + .strip_prefix("trace-") + .and_then(|r| r.strip_suffix(".jsonl")) + else { + return false; + }; + let Some((ms, pid)) = rest.split_once('-') else { + return false; + }; + ms.len() == 13 + && ms.bytes().all(|b| b.is_ascii_digit()) + && !pid.is_empty() + && pid.len() <= 10 + && pid.bytes().all(|b| b.is_ascii_digit()) +} + +/// `sugar-journal.jsonl` or a rotation `sugar-journal-.jsonl`. +pub fn is_journal_name(name: &str) -> bool { + name == flysim::journal::FILE_NAME + || name + .strip_prefix("sugar-journal-") + .and_then(|r| r.strip_suffix(".jsonl")) + .is_some_and(|n| !n.is_empty() && n.len() <= 4 && n.bytes().all(|b| b.is_ascii_digit())) +} + +/// What a diverged shadow leaves for the review: `divergence.json` and the two checkpoint files. +pub fn is_divergence_file(name: &str) -> bool { + name == "divergence.json" + || ["divergence-live-g", "divergence-shadow-g"] + .iter() + .filter_map(|p| name.strip_prefix(p)) + .filter_map(|r| r.strip_suffix(".checkpoint")) + .any(|g| !g.is_empty() && g.len() <= 20 && g.bytes().all(|b| b.is_ascii_digit())) +} + +/// Writes `bytes` to `path` through a temporary file and a rename. +pub fn atomic_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = path.with_file_name(format!(".{name}.tmp")); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Unix milliseconds of a file's modification time. +pub fn mtime_ms(meta: &std::fs::Metadata) -> Option { + meta.modified() + .ok()? + .duration_since(std::time::UNIX_EPOCH) + .ok() + .map(|d| d.as_millis() as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_round_trip_and_bad_ones_are_refused() { + let mut wire = Vec::new(); + write_frame(&mut wire, json!({"t": "trace", "name": "x", "offset": 3}), b"abc\n").unwrap(); + write_frame(&mut wire, json!({"t": "ping"}), b"").unwrap(); + let mut input = std::io::Cursor::new(wire); + let a = read_frame(&mut input).unwrap().unwrap(); + assert_eq!((a.kind(), a.body.as_slice()), ("trace", b"abc\n".as_slice())); + assert_eq!(a.header["offset"], 3); + assert_eq!(read_frame(&mut input).unwrap().unwrap().kind(), "ping"); + assert!(read_frame(&mut input).unwrap().is_none()); + // A body shorter than its len, an oversized body, a non-object header. + let mut cut = std::io::Cursor::new(b"{\"t\":\"x\",\"len\":10}\nabc".to_vec()); + assert!(read_frame(&mut cut).is_err()); + let mut huge = std::io::Cursor::new(format!("{{\"len\":{}}}\n", MAX_BODY + 1).into_bytes()); + assert!(read_frame(&mut huge).is_err()); + let mut list = std::io::Cursor::new(b"[1]\n".to_vec()); + assert!(read_frame(&mut list).is_err()); + } + + #[test] + fn names_are_checked_before_they_become_paths() { + assert!(is_trace_name("trace-1790741297310-444741.jsonl")); + for bad in [ + "trace-179074129731-4.jsonl", + "trace-1790741297310-.jsonl", + "trace-1790741297310-4/../x.jsonl", + "../trace-1790741297310-4.jsonl", + "consumer", + ] { + assert!(!is_trace_name(bad), "{bad}"); + } + assert!(is_journal_name("sugar-journal.jsonl")); + assert!(is_journal_name("sugar-journal-2.jsonl")); + assert!(!is_journal_name("sugar-journal-.jsonl")); + assert!(!is_journal_name("sugar-journal-../x.jsonl")); + assert!(is_divergence_file("divergence.json")); + assert!(is_divergence_file("divergence-live-g42.checkpoint")); + assert!(!is_divergence_file("divergence-live-g.checkpoint")); + assert!(!is_divergence_file("verdict.json")); + assert!(env_value_ok("pokered-unique8-v7,pokered-unique8-v6")); + assert!(!env_value_ok("a b")); + assert!(!env_value_ok("x\ny")); + assert!(!env_value_ok("$(x)")); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs index a1923d7..c2df4da 100644 --- a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs +++ b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs @@ -13,6 +13,8 @@ //! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence | //! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) | //! | `declaredDifferences` | the named exclusions the comparison applied | +//! | `runId` | SHADOW-02, a remote shadow: the relay's run (`null` for a shadow on the container) | +//! | `relay` | SHADOW-02, added by the relay on the container: `lagTransitions` there includes the live trace not yet on the box | //! //! `pass` is sticky only while nothing diverges: a shadow that keeps running after it passed and //! then finds a difference turns the verdict to `diverged`. `stopped` is a shadow that exited @@ -48,12 +50,13 @@ use crate::trace::{Agreement, Difference}; pub const FORMAT: &str = "fly-shadow-verdict-v1"; /// Skips that are the live side's own events, not the session runtime's failures: the operator -/// reward pulse (declared), a startup save rotated away before the shadow reached it, a trace -/// stopped at its byte cap or for want of a consumer, and a process that ran no transition. -pub const SKIP_KINDS: [&str; 4] = [ +/// reward pulse (declared), a startup save rotated away before the shadow reached it, and a +/// process that ran no transition. A trace that stopped (byte cap, or no consumer before this +/// shadow started) is a coverage gap, never a skip: it ends the window, see [`Verdict::end_window`] +/// (SHADOW-02 B2). +pub const SKIP_KINDS: [&str; 3] = [ "operator-reward-pulse", "startup-save-gone", - "trace-cap", "no-transition", ]; @@ -138,6 +141,14 @@ pub struct Skipped { pub reason: String, } +/// A coverage gap: the live trace stopped, so everything compared before it no longer counts. +#[derive(Clone, Debug)] +pub struct WindowEnd { + pub trace: String, + pub reason: String, + pub discarded_brain_seconds: f64, +} + /// The first divergence and its context. #[derive(Clone, Debug)] pub struct Divergence { @@ -226,6 +237,10 @@ pub struct Verdict { pub checkpoints: Checkpoints, pub segments_compared: u64, pub skipped: Vec, + /// Trace stops (coverage gaps) that ended a window: what they discarded. + pub window_ends: Vec, + /// The trace whose stop last ended the window (`None`: none yet). `compared` counts only after. + pub last_stop_trace: Option, pub divergence: Option, pub started_at: String, pub passed_at: Option, @@ -235,6 +250,8 @@ pub struct Verdict { pub live_lag_seconds: Option, pub spool_evicted: u64, pub cost: Cost, + /// SHADOW-02: the relay's run id, for a remote shadow (`null` on the release container). + pub run_id: Option, } pub fn now_iso() -> String { @@ -269,6 +286,27 @@ pub fn iso(ms: i64) -> String { } impl Verdict { + /// A coverage gap (a trace stopped, whatever the reason): the live fly may run untraced from + /// here, so the brain time and saves compared so far stop counting. A pass needs the whole + /// window after the last gap (SHADOW-02 B2). + pub fn end_window(&mut self, trace: &str, reason: String) { + self.window_ends.push(WindowEnd { + trace: trace.to_owned(), + reason, + discarded_brain_seconds: self.brain_ms / 1000.0, + }); + self.last_stop_trace = Some(trace.to_owned()); + self.brain_ms = 0.0; + self.checkpoints = Checkpoints::default(); + // A pass belongs to the window it was reached in: the new one has not qualified yet + // (r3 N3). A diverged or errored verdict stays what it is. + if self.status == Status::Pass { + self.status = Status::Running; + self.passed_at = None; + self.reason = String::new(); + } + } + pub fn brain_seconds(&self) -> f64 { self.brain_ms / 1000.0 } @@ -311,6 +349,12 @@ impl Verdict { "skipped": self.skipped.iter().map(|s| json!({ "trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason, })).collect::>(), + "window": { + "lastStopTrace": self.last_stop_trace, + "ends": self.window_ends.iter().map(|w| json!({ + "trace": w.trace, "reason": w.reason, "discardedBrainSeconds": (w.discarded_brain_seconds * 1000.0).round() / 1000.0, + })).collect::>(), + }, "declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::>(), "firstDivergence": self.divergence.as_ref().map(|d| { let mut v = d.to_json(); @@ -325,6 +369,7 @@ impl Verdict { "liveLagSeconds": self.live_lag_seconds, "spoolEvicted": self.spool_evicted, "cost": self.cost.to_json(), + "runId": self.run_id, }) } } @@ -338,6 +383,22 @@ pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> { std::fs::rename(&tmp, path) } +/// [`write_json`], synced to disk (file and directory) before it returns. +pub fn write_json_durable(path: &Path, value: &Value) -> std::io::Result<()> { + use std::io::Write; + let tmp = path.with_extension("json.tmp"); + let mut text = serde_json::to_string_pretty(value).expect("JSON serializes"); + text.push('\n'); + let mut f = std::fs::File::create(&tmp)?; + f.write_all(text.as_bytes())?; + f.sync_all()?; + std::fs::rename(&tmp, path)?; + if let Some(dir) = path.parent() { + std::fs::File::open(dir)?.sync_all()?; + } + Ok(()) +} + /// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`], /// [`MAX_UNAVAILABLE_FRACTION`]). pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> { @@ -411,6 +472,12 @@ pub fn allows_cutover( if candidate["compatibility"] != compatibility { return Err("the verdict is for another compatibility string".to_owned()); } + // Only a build that ends the window at a coverage gap counts brain time after it. + if verdict["window"].is_null() { + return Err( + "the verdict does not say where its window starts (an older shadow)".to_owned(), + ); + } let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0); // The operator's window is a floor the verdict cannot lower: a shadow run with a shorter // `--required-brain-seconds` (a rehearsal, a test) never arms the cutover. @@ -516,6 +583,8 @@ mod tests { }, segments_compared: 1, skipped: Vec::new(), + window_ends: Vec::new(), + last_stop_trace: None, divergence: None, started_at: now_iso(), passed_at: None, @@ -524,10 +593,94 @@ mod tests { live_lag_seconds: None, spool_evicted: 0, cost: Cost::default(), + run_id: None, } .to_json() } + fn verdict_struct(status: Status) -> Verdict { + Verdict { + status, + reason: String::new(), + binary_sha256: String::new(), + binaries: Default::default(), + release: String::new(), + compatibility: String::new(), + execution_mode: String::new(), + agent_threads: 1, + required_brain_seconds: 10_800.0, + agreement: Agreement::default(), + brain_ms: 1_819_000.0, + ledger_checks: 0, + checkpoints: Checkpoints { + identical: 400, + declared: 0, + unavailable: 0, + }, + segments_compared: 1, + skipped: Vec::new(), + window_ends: Vec::new(), + last_stop_trace: None, + divergence: None, + started_at: now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + run_id: None, + } + } + + #[test] + fn a_stop_ends_the_window() { + // B2: brain time compared before a coverage gap never counts toward a pass. + let mut v = verdict_struct(Status::Running); + v.brain_ms = 1_819_000.0; + v.checkpoints = Checkpoints { + identical: 400, + declared: 0, + unavailable: 0, + }; + v.end_window("trace-1.jsonl", "no-consumer".to_owned()); + assert_eq!(v.brain_seconds(), 0.0); + v.brain_ms += 170_000.0; + let j = v.to_json(); + assert_eq!(j["compared"]["brainSeconds"], 170.0); + assert_eq!(j["compared"]["checkpoints"]["identical"], 0); + assert_eq!(j["window"]["lastStopTrace"], "trace-1.jsonl"); + assert_eq!(j["window"]["ends"][0]["discardedBrainSeconds"], 1819.0); + // A gap is not an allowed skip. + assert!(!SKIP_KINDS.contains(&"trace-cap")); + } + + #[test] + fn a_window_end_takes_back_a_pass_and_nothing_else() { + let mut v = verdict_struct(Status::Pass); + v.passed_at = Some(now_iso()); + v.reason = "10800 s compared".to_owned(); + v.brain_ms = 10_800_000.0; + v.end_window("trace-2.jsonl", "byte-cap".to_owned()); + let j = v.to_json(); + assert_eq!(j["status"], "running"); + assert!(j["passedAt"].is_null()); + assert_eq!(j["compared"]["brainSeconds"], 0.0); + assert_eq!(j["window"]["lastStopTrace"], "trace-2.jsonl"); + // The cutover rule refuses it on any count. + let now = parse_iso(&now_iso()).unwrap(); + let binaries: std::collections::BTreeMap = Default::default(); + let release = Release { dir: "/opt/fly/releases/test", binaries: &binaries }; + assert!(allows_cutover(&j, "flysim-session", &release, "c", now, 300).is_err()); + let mut forced = j.clone(); + forced["status"] = json!("pass"); + assert!(allows_cutover(&forced, "flysim-session", &release, "c", now, 300).is_err()); + // Diverged stays diverged. + let mut d = verdict_struct(Status::Diverged); + d.end_window("trace-3.jsonl", "no-consumer".to_owned()); + assert_eq!(d.status, Status::Diverged); + } + #[test] fn the_cutover_rule() { let now = parse_iso(&now_iso()).unwrap(); @@ -540,6 +693,10 @@ mod tests { let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300); let pass = verdict(Status::Pass, 10_800_000.0); assert_eq!(ok(&pass), Ok(())); + // A verdict that does not say where its window starts is an older shadow's (B2). + let mut undated = pass.clone(); + undated.as_object_mut().unwrap().remove("window"); + assert!(ok(&undated).is_err()); // Another binary, another release, a changed file in it. assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err()); let moved = Release { diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow.rs b/services/flysim/crates/fly-legacy-session/tests/shadow.rs index 291b2b4..ab45f4e 100644 --- a/services/flysim/crates/fly-legacy-session/tests/shadow.rs +++ b/services/flysim/crates/fly-legacy-session/tests/shadow.rs @@ -217,6 +217,7 @@ fn config( binary_sha256: "test".to_owned(), binaries: Default::default(), release: String::new(), + run_id_file: None, } } @@ -568,4 +569,57 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() { assert_eq!(d.kind, "boot", "{}", d.detail); assert!(d.detail.contains("restore gate"), "{}", d.detail); assert!(got.skipped.is_empty()); + + // r3 N5: a declared reward pulse ends the comparison of its trace, but a stop later in the + // same trace (here the byte cap) must still end the window: what was compared before the + // pulse, and the untraced time after the stop, must not count toward a pass. + let full_brain_seconds = verdict.brain_seconds(); + let at = tampered(&dirs.trace, &neg.join("reward/trace"), |n, v| { + (n == 100) + .then(|| v["behaviour"]["admissions"] = serde_json::json!([{"kind": "reward"}])) + .is_some() + }); + let files = transitions(&neg.join("reward/trace")); + let (first_name, second_n) = ( + files[0].0.file_name().unwrap().to_string_lossy().into_owned(), + files[1].1, + ); + { + use std::io::Write; + let mut f = std::fs::OpenOptions::new().append(true).open(&files[0].0).unwrap(); + writeln!(f, "{{\"truncated\":true,\"reason\":\"byte-cap\"}}").unwrap(); + } + let _ = std::fs::remove_dir_all(neg.join("reward").join("out")); + let reward_config = self::config(&rom, &neg.join("reward"), &neg.join("reward/trace"), (&empty, &empty), &spool); + let out = reward_config.out_dir.clone(); + let stop = StopFlag::default(); + let handle = spawn_shadow(reward_config, stop.clone()); + let deadline = Instant::now() + Duration::from_secs(600); + loop { + let v = verdict_of(&out); + let ended = !v["window"]["ends"].as_array().is_none_or(|e| e.is_empty()); + if (ended && v["compared"]["transitions"].as_u64() >= Some(101 + second_n as u64)) + || handle.is_finished() + || Instant::now() > deadline + { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + stop.request(); + let (ended, verdict) = handle.join().unwrap().expect("the shadow ran"); + assert_ne!(ended, Ended::Diverged, "{:?}", verdict.reason); + let j = verdict.to_json(); + eprintln!("reward then stop (reward at step {at}): {j}"); + assert_eq!(j["skipped"][0]["kind"], "operator-reward-pulse", "{j}"); + assert_eq!(j["window"]["lastStopTrace"], first_name.as_str(), "{j}"); + assert_eq!(j["window"]["ends"][0]["trace"], first_name.as_str(), "{j}"); + assert!(j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap() > 0.0, "{j}"); + // Only the second process counts, after the window ended: what the first one compared before + // the pulse is dropped and its uncompared remainder never was added, so less than the whole. + let whole = full_brain_seconds; + let after = j["compared"]["brainSeconds"].as_f64().unwrap(); + let dropped = j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap(); + assert!(after + dropped < whole - 1.0, "{after} + {dropped} against {whole}: {j}"); + assert_ne!(j["status"], "pass", "{j}"); } diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs b/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs new file mode 100644 index 0000000..5fb1f41 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/shadow_relay_coverage.rs @@ -0,0 +1,258 @@ +//! SHADOW-02 review B1, without a ROM: the real relay and the real `fly-shadow ingest` (over +//! pipes where production has ssh), with the box's shadow stood in for by a thread that keeps its +//! heartbeat and verdict fresh, as a healthy shadow does. +//! +//! After a long outage flysim stops its trace (`"reason":"no-consumer"`) and the live fly runs +//! untraced. When the link heals the box is alive and, counted in trace lines, caught up long +//! before its shadow reaches that stop. The relay must not call that healthy: it sets a sticky +//! `coverageLost`, stops the heartbeat, and clears it only when the verdict's window starts after the stop (a restart alone does not). + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use fly_legacy_session::shadow::{ + StopFlag, + relay::{self, RelayConfig}, + release, +}; + +const RUN_ID: &str = "1790000000000"; +const TRACE: &str = "trace-1790000005000-4242.jsonl"; + +fn json_of(path: &Path) -> Value { + std::fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or(Value::Null) +} + +fn wait_for(what: &str, secs: u64, mut ok: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(secs); + while !ok() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn append(path: &Path, bytes: &[u8]) { + use std::io::Write; + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .unwrap() + .write_all(bytes) + .unwrap(); +} + +struct Setup { + container: PathBuf, + mirror: PathBuf, + relay_stop: StopFlag, + relay: Option>>, + shadow_alive: Arc, + window: Arc, + fake_shadow: Option>, +} + +impl Setup { + fn start(root: &Path) -> Setup { + let container = root.join("container"); + let mirror = root.join("box"); + for d in ["trace", "hot", "durable", "shadow"] { + std::fs::create_dir_all(container.join(d)).unwrap(); + } + let fly_shadow = PathBuf::from(env!("CARGO_BIN_EXE_fly-shadow")); + let script = format!("exec {} ingest --root {}", fly_shadow.display(), mirror.display()); + let release_dir = release::this_release_of(&fly_shadow); + let mut config = RelayConfig::with_defaults( + container.join("trace"), + container.join("hot"), + container.join("durable"), + container.join("shadow"), + vec!["sh".to_owned(), "-c".to_owned(), script], + RUN_ID.to_owned(), + ); + config.release = release_dir.display().to_string(); + config.binaries = release::binaries_in(&release_dir).unwrap(); + config.tick = Duration::from_millis(50); + config.beat_every = Duration::from_millis(300); + config.alive_within = Duration::from_secs(5); + config.stall = Duration::from_secs(5); + config.reconnect_after = Duration::from_secs(1); + let relay_stop = StopFlag::default(); + let relay = { + let (config, stop) = (config, relay_stop.clone()); + std::thread::spawn(move || relay::run(config, stop)) + }; + let shadow_alive = Arc::new(AtomicBool::new(true)); + let window = Arc::new(AtomicU64::new(1)); + let fake_shadow = { + let (mirror, alive, window) = (mirror.clone(), shadow_alive.clone(), window.clone()); + std::thread::spawn(move || { + // Wait for the run the ingest announces, then behave as a healthy shadow does. + while fly_legacy_session::shadow::read_run_id(&mirror.join("run-id")).as_deref() + != Some(RUN_ID) + { + std::thread::sleep(Duration::from_millis(50)); + } + while alive.load(Ordering::Relaxed) { + let _ = std::fs::write(mirror.join("trace/consumer"), "beat"); + // 1: a window that has not ended at the stop; 2: a new window (a restart) + // that replays the stopped trace and has not reached its stop; 3: one whose + // verdict counts from after the stop. + let w = window.load(Ordering::Relaxed); + let verdict = json!({ + "runId": RUN_ID, "status": "running", "lagTransitions": 0, + "startedAt": format!("window-{}", w.min(2)), + "window": {"lastStopTrace": if w >= 3 { json!(TRACE) } else { Value::Null }}, + }); + let _ = std::fs::write( + mirror.join("out/verdict.json"), + serde_json::to_vec(&verdict).unwrap(), + ); + std::thread::sleep(Duration::from_millis(250)); + } + }) + }; + Setup { + container, + mirror, + relay_stop, + relay: Some(relay), + shadow_alive, + window, + fake_shadow: Some(fake_shadow), + } + } + + fn relay_json(&self) -> Value { + json_of(&self.container.join("shadow/relay.json")) + } + + fn heartbeat_age(&self) -> Option { + std::fs::metadata(self.container.join("trace/consumer")) + .ok()? + .modified() + .ok()? + .elapsed() + .ok() + } +} + +impl Drop for Setup { + fn drop(&mut self) { + self.relay_stop.request(); + self.shadow_alive.store(false, Ordering::Relaxed); + if let Some(h) = self.relay.take() { + let _ = h.join(); + } + if let Some(h) = self.fake_shadow.take() { + let _ = h.join(); + } + } +} + +/// Reproduces review B1: the box is alive and caught up, yet the live trace ended in a +/// no-consumer stop that its shadow has not reached. +#[test] +fn a_no_consumer_stop_in_the_forwarded_trace_makes_the_relay_unhealthy_until_a_new_window() { + let tmp = tempfile::tempdir().unwrap(); + let s = Setup::start(tmp.path()); + let trace = s.container.join("trace").join(TRACE); + append(&trace, b"{\"boot\":true}\n{\"behaviour\":{\"step\":\"1\"}}\n"); + wait_for("a healthy relay that follows the trace", 60, || { + let r = s.relay_json(); + r["healthy"] == true + }); + assert!(s.heartbeat_age().is_some(), "a healthy relay beats"); + + // The outage: flysim wrote its stop (here in two pieces, as a chunk boundary may cut it). + append(&trace, b"{\"reason\":\"no-con"); + std::thread::sleep(Duration::from_millis(400)); + append(&trace, b"sumer\",\"truncated\":true}\n"); + std::thread::sleep(Duration::from_secs(3)); + let r = s.relay_json(); + assert_eq!( + r["healthy"], false, + "B1: the box is alive and caught up, but the live fly now runs untraced: {r}" + ); + assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}"); + assert!(r["traceAgeSeconds"].is_u64(), "{r}"); + + // The link is fine and the box is alive and caught up, for as long as we care to look: still + // not healthy, and no heartbeat (flysim would stop any later trace for want of one). + std::thread::sleep(Duration::from_secs(3)); + let r = s.relay_json(); + assert_eq!(r["remoteAlive"], true, "{r}"); + assert_eq!(r["connected"], true, "{r}"); + assert_eq!(r["healthy"], false, "caught up must not clear a lost coverage: {r}"); + assert!(!r["coverageLost"].is_null(), "sticky: {r}"); + assert!( + s.heartbeat_age().is_none_or(|age| age >= Duration::from_secs(2)), + "an unhealthy relay does not beat" + ); + // Still in the same window after the shadow's own reports: sticky. + std::thread::sleep(Duration::from_secs(1)); + assert!(!s.relay_json()["coverageLost"].is_null()); + + // B2: a restarted shadow (a new window) that has not ended its window at the stop still + // counts the time before the gap: the loss stays. + s.window.store(2, Ordering::Relaxed); + std::thread::sleep(Duration::from_secs(2)); + assert!(!s.relay_json()["coverageLost"].is_null()); + assert_eq!(s.relay_json()["healthy"], false); + // Its verdict counts from after the stop: closed. + s.window.store(3, Ordering::Relaxed); + wait_for("the new window to clear the stop", 60, || { + let r = s.relay_json(); + r["coverageLost"].is_null() && r["healthy"] == true + }); + let _ = &s.mirror; +} + +/// N4: the byte cap stops the trace like a missing consumer: the live fly runs untraced from +/// there, so the relay flags it the same way (sticky, durable, unhealthy). +#[test] +fn a_byte_cap_stop_is_a_lost_coverage_like_a_no_consumer_stop() { + let tmp = tempfile::tempdir().unwrap(); + let s = Setup::start(tmp.path()); + let trace = s.container.join("trace").join(TRACE); + append(&trace, b"{\"boot\":true}\n{\"reason\":\"byte-cap\",\"truncated\":true}\n"); + wait_for("the byte-cap stop to be flagged", 60, || { + !s.relay_json()["coverageLost"].is_null() + }); + let r = s.relay_json(); + assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}"); + assert_eq!(r["healthy"], false, "{r}"); + // Durable: relay.json on disk says so (the same file a restarted relay reads). + std::thread::sleep(Duration::from_secs(2)); + assert!(!s.relay_json()["coverageLost"].is_null(), "sticky: {}", s.relay_json()); +} + +/// A relay restart within the run keeps what the first relay saw. +#[test] +fn a_lost_coverage_survives_a_relay_restart_of_the_same_run() { + let tmp = tempfile::tempdir().unwrap(); + let s = Setup::start(tmp.path()); + let trace = s.container.join("trace").join(TRACE); + append( + &trace, + b"{\"boot\":true}\n{\"reason\":\"no-consumer\",\"truncated\":true}\n", + ); + wait_for("the relay to see the stop", 60, || !s.relay_json()["coverageLost"].is_null()); + drop(s); + // The stopped relay wrote relay.json last; a new relay of the same run (the unit's restart) + // starts from it, reconnects to the same mirror, and is alive and caught up, but not healthy. + let s = Setup::start(tmp.path()); + wait_for("the box reported alive", 60, || s.relay_json()["remoteAlive"] == true); + std::thread::sleep(Duration::from_secs(2)); + let r = s.relay_json(); + assert_eq!(r["coverageLost"]["trace"], TRACE, "{r}"); + assert_eq!(r["remoteAlive"], true, "{r}"); + assert_eq!(r["healthy"], false, "{r}"); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs b/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs new file mode 100644 index 0000000..41fac76 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/shadow_remote.rs @@ -0,0 +1,438 @@ +//! SHADOW-02 end to end on one machine, on the committed toy connectome in raw mode (an explicit +//! ROM job: `FLY_ROM`). +//! +//! The *real* `flysim` service writes its trace into a "container" directory; the relay +//! (`fly_legacy_session::shadow::relay`) streams it and the live saves through the *real* +//! `fly-shadow ingest` binary (over pipes where production has ssh) into a "box" mirror; the +//! remote shadow (`shadow::run` with a run id file) follows the mirror; the relay writes the +//! verdict back and keeps flysim's consumer heartbeat fresh only while all of that is healthy. +//! +//! 1. A fresh fly and a restart, with sugar: the box's `pass` arrives on the container side with +//! this run's id, and finished trace files are removed on the container too. +//! 2. The remote shadow dies: the relay stops the heartbeat and flysim stops its trace; a new +//! shadow starts a new window, ends its window at that stop (which predates it; B2), +//! and follows the next process. +//! 3. The sync stalls (the ingest is stopped): the heartbeat goes stale, flysim stops its trace +//! (`no-consumer`); once the sync is back the box sees the gap and fails the verdict as a +//! `coverage` divergence, the relay brings it and `divergence.json` back and exits. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use fly_legacy_session::shadow::{ + self, Ended, ShadowConfig, StopFlag, + relay::{self, RelayConfig, RelayEnd}, + release, +}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use flysim::snapshot::MacroMode; + +/// The `flysim` binary built from this tree (see `tests/shadow.rs`). +fn flysim_binary() -> Option { + let exe = std::env::current_exe().ok()?; + let profile_dir = exe.parent()?.parent()?; + let target = profile_dir.parent()?; + let release = profile_dir.file_name()? == "release"; + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + let mut build = Command::new(cargo); + build + .args(["build", "-p", "flysim", "--bin", "flysim"]) + .env("CARGO_TARGET_DIR", target) + .current_dir(env!("CARGO_MANIFEST_DIR")); + if release { + build.arg("--release"); + } + match build.status() { + Ok(status) => assert!(status.success(), "building flysim failed"), + Err(e) => { + eprintln!("skipping: cargo is not reachable to build flysim ({e})"); + return None; + } + } + Some(profile_dir.join("flysim")) +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() +} + +fn http(port: u16, method: &str, path: &str, body: Option<&str>) -> Option<(u16, String)> { + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?; + let body = body.unwrap_or(""); + write!( + stream, + "{method} {path} HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .ok()?; + let mut text = String::new(); + stream.read_to_string(&mut text).ok()?; + let status = text.split_whitespace().nth(1)?.parse().ok()?; + Some(( + status, + text.split_once("\r\n\r\n").map_or("", |(_, b)| b).to_owned(), + )) +} + +struct Live { + child: Child, + control: u16, +} + +impl Live { + fn start(binary: &Path, rom: &Path, container: &Path, log: &Path) -> Live { + let control = free_port(); + let child = Command::new(binary) + .env("FLY_ROM", rom) + .env("FLY_DATASET", legacy_parity::toy::dir()) + .env("FLY_STATE", container.join("durable")) + .env("FLY_STATE_HOT", container.join("hot")) + .env("FLY_FEED_BIND", format!("127.0.0.1:{}", free_port())) + .env("FLY_CONTROL_BIND", format!("127.0.0.1:{control}")) + .env("FLY_METRICS_ADDR", format!("127.0.0.1:{}", free_port())) + .env("FLY_MACRO_MODE", "raw") + .env("FLY_CHAT_ENABLED", "false") + .env("FLYSIM_LOOP_GAME", "pokemon-red") + // Real time: a live fly left running while the test waits must not outrun the shadow. + .env("FLYSIM_LOOP_SPEED", "1") + .env("FLYSIM_LOOP_HOT_SECONDS", "1") + .env("FLYSIM_LOOP_CHECKPOINT_SECONDS", "4") + .env("RAYON_NUM_THREADS", "1") + .env("FLY_TRACE_DIR", container.join("trace")) + .env("FLY_TRACE_LEDGERS", "1") + // A stale heartbeat stops the trace after 4 s here (10 minutes on the stream). + .env("FLY_TRACE_CONSUMER_STALE_SECONDS", "4") + .env_remove("FLY_TRACE") + .env_remove("NOTIFY_SOCKET") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(std::fs::File::create(log).unwrap()) + .spawn() + .expect("flysim starts"); + let live = Live { child, control }; + let deadline = Instant::now() + Duration::from_secs(240); + while live.brain_ms().is_none() { + assert!(Instant::now() < deadline, "flysim never ran"); + std::thread::sleep(Duration::from_millis(200)); + } + live + } + + fn brain_ms(&self) -> Option { + let (status, body) = http(self.control, "GET", "/status", None)?; + let v: Value = serde_json::from_str(&body).ok()?; + (status == 200 && v["status"] == "running").then(|| v["brainMs"].as_f64())? + } + + fn sugar(&self, ms: u32) { + let body = format!(r#"{{"durationMs":{ms},"by":"shadow-test","source":"operator"}}"#); + let (status, text) = http(self.control, "POST", "/stimulate", Some(&body)).unwrap(); + assert!((200..300).contains(&status), "sugar refused: {status} {text}"); + } + + fn run_for(&self, brain_ms: f64) { + let start = self.brain_ms().expect("running"); + while self.brain_ms().unwrap_or(start) < start + brain_ms { + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn stop(mut self) { + let _ = Command::new("kill") + .args(["-TERM", &self.child.id().to_string()]) + .status(); + let _ = self.child.wait(); + } +} + +impl Drop for Live { + /// A failed assertion must not leave a live service writing into the next run's directories. + fn drop(&mut self) { + if let Ok(None) = self.child.try_wait() { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } +} + +/// The remote shadow on the mirror, as `flyshadow-remote.service` runs it. +fn box_shadow(rom: &Path, root: &Path) -> ShadowConfig { + ShadowConfig { + trace_dir: root.join("trace"), + hot_dir: root.join("hot"), + durable_dir: root.join("durable"), + out_dir: root.join("out"), + spool_dir: root.join("out/spool"), + work_dir: root.join("work"), + rom_path: rom.to_owned(), + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + // The live service's loop.speed (real time), which its saves record. + speed: 1.0, + mode: ExecutionMode::InProcess, + agent_threads: 1, + required_brain_seconds: 20.0, + all_files: false, + keep_traces: false, + keep_spool: false, + exit_on_pass: false, + max_transitions: None, + spool_max_bytes: 1 << 30, + context_lines: 5, + poll: Duration::from_millis(20), + lag_guard: None, + binary_sha256: "test".to_owned(), + binaries: Default::default(), + release: String::new(), + run_id_file: Some(root.join("run-id")), + } +} + +fn spawn_shadow( + config: ShadowConfig, + stop: StopFlag, +) -> std::thread::JoinHandle> { + std::thread::spawn(move || { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap() + .block_on(shadow::run(config, stop)) + }) +} + +fn json_of(path: &Path) -> Value { + std::fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or(Value::Null) +} + +fn wait_for(what: &str, secs: u64, mut ok: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(secs); + while !ok() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(100)); + } +} + +fn mtime(path: &Path) -> Option { + std::fs::metadata(path).ok()?.modified().ok() +} + +#[test] +fn the_remote_shadow_follows_through_the_relay_and_fails_closed() { + let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return; + }; + let Some(flysim) = flysim_binary() else { + return; + }; + let tmp = tempfile::tempdir().unwrap(); + let kept = std::env::var_os("FLY_SHADOW_TEST_DIR").map(PathBuf::from); + if let Some(dir) = &kept { + let _ = std::fs::remove_dir_all(dir); + std::fs::create_dir_all(dir).unwrap(); + } + let root = kept.unwrap_or_else(|| tmp.path().to_owned()); + let container = root.join("container"); + let mirror = root.join("box"); + for d in ["trace", "hot", "durable", "shadow"] { + std::fs::create_dir_all(container.join(d)).unwrap(); + } + let consumer = container.join("trace").join(flysim::trace::CONSUMER_FILE); + let verdict_path = container.join("shadow/verdict.json"); + + // The ingest is the real binary; production reaches it through ssh, this test through pipes. + let fly_shadow = PathBuf::from(env!("CARGO_BIN_EXE_fly-shadow")); + let pid_file = root.join("ingest.pid"); + let script = format!( + "echo $$ > {}; exec {} ingest --root {}", + pid_file.display(), + fly_shadow.display(), + mirror.display() + ); + let release_dir = release::this_release_of(&fly_shadow); + let run_id = "1790000000000".to_owned(); + let mut config = RelayConfig::with_defaults( + container.join("trace"), + container.join("hot"), + container.join("durable"), + container.join("shadow"), + vec!["sh".to_owned(), "-c".to_owned(), script], + run_id.clone(), + ); + config.release = release_dir.display().to_string(); + config.binaries = release::binaries_in(&release_dir).unwrap(); + config.env = [("FLY_MACRO_MODE".to_owned(), "raw".to_owned())].into(); + config.tick = Duration::from_millis(50); + config.beat_every = Duration::from_secs(1); + config.alive_within = Duration::from_secs(5); + config.stall = Duration::from_secs(5); + config.reconnect_after = Duration::from_secs(1); + // The run id is the start's Unix ms: everything of this test is newer. + config.run_id = run_id.clone(); + let relay_stop = StopFlag::default(); + let relay = { + let (config, stop) = (config.clone(), relay_stop.clone()); + std::thread::spawn(move || relay::run(config, stop)) + }; + wait_for("the ingest to write the run id", 120, || { + shadow::read_run_id(&mirror.join("run-id")).as_deref() == Some(run_id.as_str()) + }); + assert_eq!( + std::fs::read_to_string(mirror.join("live.env")).unwrap(), + "FLY_MACRO_MODE=raw\n", + "only the forwarded composition settings reach the box" + ); + let shadow_stop = StopFlag::default(); + let shadow = spawn_shadow(box_shadow(&rom, &mirror), shadow_stop.clone()); + wait_for("the relay's heartbeat (box shadow alive)", 60, || { + consumer.is_file() + }); + + // 1. A fresh fly with sugar, and a restart. + let live = Live::start(&flysim, &rom, &container, &root.join("flysim-1.log")); + live.sugar(300); + live.run_for(8_000.0); + live.sugar(600); + live.run_for(8_000.0); + live.stop(); + let first_file = shadow::follow::trace_files(&container.join("trace")).unwrap()[0].clone(); + let live = Live::start(&flysim, &rom, &container, &root.join("flysim-2.log")); + live.sugar(450); + live.run_for(12_000.0); + live.stop(); + wait_for("the box's pass, over both processes and all sugar", 300, || { + let v = json_of(&verdict_path); + assert_ne!(v["status"], "diverged", "{v}"); + v["status"] == "pass" + && v["compared"]["segments"].as_u64() >= Some(2) + && v["compared"]["sugar"].as_u64() >= Some(3) + }); + let v = json_of(&verdict_path); + eprintln!("relayed verdict: {}", serde_json::to_string_pretty(&v).unwrap()); + assert_eq!(v["runId"], run_id.as_str()); + assert!(v["firstDivergence"].is_null()); + assert!(v["relay"]["unsyncedBytes"].is_u64(), "{v}"); + assert!(v["compared"]["segments"].as_u64().unwrap() >= 2); + assert!(v["compared"]["sugar"].as_u64().unwrap() >= 3); + assert!(v["compared"]["checkpoints"]["identical"].as_u64().unwrap() >= 3); + wait_for("the finished first file removed on the container", 60, || { + !first_file.exists() + }); + let relay_json = json_of(&container.join("shadow/relay.json")); + assert_eq!(relay_json["healthy"], true, "{relay_json}"); + + // 2. The remote shadow dies: no more heartbeat on the container, so flysim stops its trace. + let live = Live::start(&flysim, &rom, &container, &root.join("flysim-3.log")); + live.run_for(3_000.0); + shadow_stop.request(); + let (ended, _) = shadow.join().unwrap().expect("the shadow ran"); + assert_eq!(ended, Ended::Stopped); + std::thread::sleep(Duration::from_secs(7)); + let beat = mtime(&consumer); + std::thread::sleep(Duration::from_secs(4)); + assert_eq!( + mtime(&consumer), + beat, + "the relay must not beat for a dead remote shadow" + ); + let second_file = shadow::follow::trace_files(&container.join("trace")) + .unwrap() + .pop() + .unwrap(); + let mirrored = mirror.join("trace").join(second_file.file_name().unwrap()); + wait_for("the trace stopped (no consumer) and mirrored", 120, || { + std::fs::read_to_string(&mirrored).is_ok_and(|t| t.contains("\"no-consumer\"")) + }); + // A new shadow (its unit's restart) starts a new window on the same run. + let started_before = json_of(&verdict_path)["startedAt"].clone(); + let shadow_stop = StopFlag::default(); + let shadow = spawn_shadow(box_shadow(&rom, &mirror), shadow_stop.clone()); + wait_for("the heartbeat again", 60, || mtime(&consumer) != beat); + wait_for("the new window relayed", 60, || { + json_of(&verdict_path)["startedAt"] != started_before + }); + live.stop(); + // The stop happened before this shadow: it ends the window (nothing before it counts), it is + // not a skip. + wait_for("the stopped file to end the window", 120, || { + json_of(&verdict_path)["window"]["ends"] + .as_array() + .is_some_and(|e| !e.is_empty()) + }); + assert!( + json_of(&verdict_path)["skipped"] + .as_array() + .is_some_and(|s| s.iter().all(|k| k["kind"] != "trace-cap")) + ); + let live = Live::start(&flysim, &rom, &container, &root.join("flysim-4.log")); + live.run_for(3_000.0); + wait_for("the new window comparing the next process", 120, || { + json_of(&verdict_path)["compared"]["transitions"].as_u64() > Some(0) + }); + assert!(json_of(&verdict_path)["firstDivergence"].is_null()); + // B2: the replayed stopped trace's brain time was discarded at its stop; the verdict counts + // only the process after the gap. + { + let v = json_of(&verdict_path); + let discarded = v["window"]["ends"][0]["discardedBrainSeconds"] + .as_f64() + .unwrap(); + let compared = v["compared"]["brainSeconds"].as_f64().unwrap(); + assert!( + discarded > 0.0, + "the stopped trace had brain time before the gap: {v}" + ); + assert!( + compared < discarded, + "{compared} s counted after the gap, {discarded} s before it must not count: {v}" + ); + } + + // 3. The sync stalls: the ingest stops reading. + let pid = std::fs::read_to_string(&pid_file).unwrap().trim().to_owned(); + Command::new("kill").args(["-STOP", &pid]).status().unwrap(); + let live_file = shadow::follow::trace_files(&container.join("trace")) + .unwrap() + .pop() + .unwrap(); + wait_for("flysim to stop its trace for want of a consumer", 180, || { + std::fs::read_to_string(&live_file).is_ok_and(|t| t.contains("\"no-consumer\"")) + }); + // The relay never blocks on the stalled link: it keeps reporting, and says it is not healthy. + wait_for("relay.json to say the stalled relay is not healthy", 60, || { + json_of(&container.join("shadow/relay.json"))["healthy"] == false + }); + // The sync comes back (a new connection): the box sees the gap. + Command::new("kill").args(["-KILL", &pid]).status().unwrap(); + let end = relay.join().unwrap().expect("the relay ran"); + assert_eq!(end, RelayEnd::Diverged, "the relay exits on the remote divergence"); + let v = json_of(&verdict_path); + assert_eq!(v["status"], "diverged", "{v}"); + assert_eq!(v["firstDivergence"]["kind"], "coverage", "{v}"); + assert!( + container.join("shadow/divergence.json").is_file(), + "divergence.json comes back" + ); + assert!(!consumer.exists(), "a stopped relay leaves no heartbeat"); + let (ended, verdict) = shadow.join().unwrap().expect("the shadow ran"); + assert_eq!(ended, Ended::Diverged, "{}", verdict.reason); + live.stop(); + drop(relay_stop); +}