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