Compare commits

..

No commits in common. "519503a523bd0f65f932e925fbefa6b7bd457001" and "ce6dcfeb65972faa85573b656bb7fd937fa3be90" have entirely different histories.

20 changed files with 66 additions and 4037 deletions

View file

@ -683,70 +683,6 @@ a timing, load or segment-handling bug.
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
stops flysim from starting. The test adds such a process, untraced, and the shadow fails. stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
### SHADOW-02 — The shadow on a build box (port slice)
**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
back to 0.999-1.0 the moment the shadow was stopped.
- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
pins; no path, no secret).
- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
byte that was on disk a minute ago). The box's verdict is written back only when it is this
run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
box): the release directory and binary hashes must equal its own; a new run id resets the mirror
and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
finished is never written again (`done`, and the relay then deletes the container's copy);
reports liveness (heartbeat fresh, verdict this run's and running or passed).
- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
stop while following is a `coverage` divergence; coverage reads the journal before listing the
traces. `shadow::release` holds the release hashing the binary and `check` share.
- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
`flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
`Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
`flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
`02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
section has the set-up.
**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
and `resync`, the run reset, the env allowlist.
**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
build box standing in for the release container, the remote shadow on another behind a real sshd
with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
the trace is on, so the trace's cost counts against it.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.

View file

@ -800,6 +800,7 @@ several processes.
- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it, - `startup-save-gone`: a process whose startup save was already gone when the shadow reached it,
because the shadow started late or its spool evicted the file; because the shadow started late or its spool evicted the file;
- `operator-reward-pulse`; - `operator-reward-pulse`;
- `trace-cap`: the live trace stopped at its byte cap, or with no consumer;
- `no-transition`: a process that ran none. - `no-transition`: a process that ran none.
A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which
@ -877,54 +878,3 @@ over:
`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when `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 it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is
CUT-01's. CUT-01's.
**Amendment, 2026-09-30 (SHADOW-02): the shadow runs on a build box.** On the release container
the shadow cost the live fly real time: SCHED_IDLE on the page and encoder CPUs, sharing them with
the encoder and the browser and the memory bandwidth of flysim's NUMA node, it took about 27 ms a
frame, fell further behind every hour (so it could never meet the catch-up bound), and the live
realtime factor fell from 0.9998 to 0.93-0.98. It recovered to 0.999-1.0 the moment the shadow
stopped. The comparison itself is unchanged: the shadow is the same binary of the same release,
following the same trace. What moves is where it runs, and so how its inputs reach it and its
verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
- *The relay* (`fly-shadow relay`, the container's `flyshadow.service` with the drop-in
`fly-shadow-run start` writes) opens one ssh connection to the box and streams, every quarter
second: the new live saves of both stores, then the new bytes of every trace file of this run
(oldest first; a file's size read after the directory listing, so an older file is complete
when a newer one reaches the box), then the sugar journal as read before the listing. Trace files
that started before the run (`FLY_SHADOW_RUN_ID`, the start's Unix ms) and saves older than a
minute before it are not sent. A writer thread owns the link, so a stall never blocks the relay:
new saves are read as they appear and held in memory (256 MiB, about 8 minutes; a hot save lives
about ten seconds), trace bytes wait on disk, and a newer file and the journal wait until every
older file is complete on its way.
- *The ingest* (`fly-shadow ingest --root <dir>`) 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 `<trace dir>/consumer` on the container is now the relay's. The relay
touches it only while it is healthy: connected; the box reported within 30 s that the shadow of
this run is alive (its own heartbeat fresh and its verdict this run's, running or passed); and
the box has acknowledged every byte that was on the container's disk a minute earlier. A dead box,
shadow or link, and a stalled sync, therefore stop the live trace exactly as a dead local shadow
does. The relay removes the file when it stops.
- *The verdict* on the container is the box's `verdict.json`, written back only when its new
`runId` member is this run's, with two changes: `lagTransitions` is the box's plus the live
trace not yet acknowledged by the box, so the catch-up bound covers the sync; and a `relay`
member (`relayedAt`, `remoteLagTransitions`, `unsyncedBytes`, `unsyncedTransitions`). A diverged
verdict brings `divergence.json` and the checkpoint files back, and the relay exits with status 3.
- *Coverage, tightened for both placements.* A trace that stops for want of a consumer
(`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage`
divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with
a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow
started, and the byte cap, end the verdict's window instead (`window.ends`): what was compared
before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). The coverage
check reads the sugar journal before it lists the trace directory (a process creates its trace
file before it writes its boot header, so a boot between the two reads could look untraced
the other way round).
- *`fly-shadow-run check`*, remote: in addition to everything above, `/srv/fly/shadow/relay.json`
must be less than a minute old and say `healthy`. `fly-shadow check` (the Rust rule) is
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
cost, which is a few file reads and one ssh stream.

View file

@ -985,12 +985,3 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at 3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at
most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK, most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK,
r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES. r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES.
- 2026-10-01 (v0.7.3, port slice SHADOW-02): the shadow moves off the release container. On the
container a light relay forwards the live trace, new saves and the sugar journal over one outbound
ssh link whose key can only run the receiver; a build box mirrors them and runs the unchanged
shadow on its own cores; the verdict comes back. Release binding by binary hashes; the relay's
heartbeat is fresh only while the link, the box's shadow and the sync are; any trace stop (no
consumer, byte cap, outage) ends the verdict window, so a pass needs 3 h of compared brain time
after the last loss. The guard and `check` stay on the container. The on-box shadow (v0.7.0)
slowed the live fly; the relay costs about 0.5% of a core. Reviews: BLOCK, BLOCK,
APPROVE-WITH-NOTES, APPROVE.

View file

@ -18,10 +18,7 @@ need pct
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \ 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 \ 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 # Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl` # needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three # (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three

View file

@ -5,9 +5,7 @@
# agent at a time). # agent at a time).
# #
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service # 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. The shadow runs on a # and the live-impact guard, restart flysim once
# 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 # 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 # restart; --restart-flysim restarts it now), remove trace and spool
# fly-shadow-run status the verdict in one screen # fly-shadow-run status the verdict in one screen
@ -53,21 +51,6 @@
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart # 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. # 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=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
#
# Files (all owned by fly): # Files (all owned by fly):
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all) # /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
# /srv/fly/shadow/trace/consumer the shadow's heartbeat # /srv/fly/shadow/trace/consumer the shadow's heartbeat
@ -76,18 +59,11 @@
# /srv/fly/shadow/divergence.json the first divergence with its context # /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/baseline.json the guard's baseline (and baseline-samples.jsonl)
# /srv/fly/shadow/guard-state.json the guard's recent samples # /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 set -euo pipefail
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}" SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
DROPIN_DIR=/etc/systemd/system/flysim.service.d DROPIN_DIR=/etc/systemd/system/flysim.service.d
DROPIN="$DROPIN_DIR/shadow-trace.conf" 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}" BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}" METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}" CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
@ -259,35 +235,10 @@ if both:
esac 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() { start() {
need_root 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" [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running" 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 check_cpuset
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace" 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. # A previous run's verdict is kept beside, never read as this run's.
@ -310,30 +261,7 @@ start() {
printf '{}\n' > "$SHADOW_DIR/guard-state.json" printf '{}\n' > "$SHADOW_DIR/guard-state.json"
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json" chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
log "baseline: $base" log "baseline: $base"
mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR" mkdir -p "$DROPIN_DIR"
if [ "$mode" = remote ]; then
local run_id
run_id="$(date +%s%3N)"
[ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
cat > "$REMOTE_DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
[Service]
EnvironmentFile=$REMOTE_ENV
Environment=FLY_SHADOW_RUN_ID=$run_id
ExecStart=
ExecStart=$BIN relay
CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=1G
EOF
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
else
rm -f "$REMOTE_DROPIN"
log "LOCAL shadow on this container (--local)"
fi
cat > "$DROPIN" <<EOF cat > "$DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard. # written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service] [Service]
@ -341,15 +269,13 @@ Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
EOF EOF
systemctl daemon-reload systemctl daemon-reload
rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
systemctl start flyshadow.service systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the # flysim starts no trace without a live consumer: wait for the shadow's heartbeat.
# relay writes it once the box's shadow of this run is alive and the sync is caught up). for _ in $(seq 1 60); do
for _ in $(seq 1 "$HEARTBEAT_WAIT"); do
[ -f "$SHADOW_DIR/trace/consumer" ] && break [ -f "$SHADOW_DIR/trace/consumer" ] && break
sleep 1 sleep 1
done done
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; } [ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up"; }
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start" log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
systemctl restart flysim.service systemctl restart flysim.service
systemctl start flyshadow-guard.timer systemctl start flyshadow-guard.timer
@ -360,7 +286,7 @@ EOF
stop_all() { stop_all() {
systemctl stop flyshadow-guard.timer 2>/dev/null || true systemctl stop flyshadow-guard.timer 2>/dev/null || true
systemctl stop flyshadow.service 2>/dev/null || true systemctl stop flyshadow.service 2>/dev/null || true
rm -f "$DROPIN" "$REMOTE_DROPIN" rm -f "$DROPIN"
systemctl daemon-reload systemctl daemon-reload
log "stopped the shadow: $1" log "stopped the shadow: $1"
} }
@ -449,15 +375,6 @@ status() {
systemctl is-active flyshadow.service || true systemctl is-active flyshadow.service || true
systemctl is-active flyshadow-guard.timer || true systemctl is-active flyshadow-guard.timer || true
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")" [ -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; } [ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
python3 - "$SHADOW_DIR/verdict.json" <<'PY' python3 - "$SHADOW_DIR/verdict.json" <<'PY'
import json, sys import json, sys
@ -495,79 +412,26 @@ check() {
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)" echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
exit 1 exit 1
fi fi
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
local why rc=0 run_id=""
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
import datetime, json, sys
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
def refuse(msg):
print(msg); sys.exit(1)
try:
v = json.load(open(verdict_path))
except Exception:
v = {}
if mode == "local":
if v.get("runId") is not None:
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
sys.exit(0)
if not run_id:
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
try:
r = json.load(open(relay_path))
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
refuse("no readable relay.json (%s)" % e)
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
refuse("relay.json is %.0f s old" % age)
if r.get("runId") != run_id:
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
if v.get("runId") != run_id:
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
if v.get("window") is None:
refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
if r.get("coverageLost"):
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
if not r.get("healthy"):
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
ta = r.get("traceAgeSeconds")
if ta is None:
refuse("no live trace file of this run")
if ta > 90:
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
PY
)" || rc=$?
if [ "$rc" != 0 ]; then
echo "cutover refused: remote shadow: $why"
exit 1
fi
[ -x "$BIN" ] || die "$BIN is missing" [ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string. # The live service's configuration, for its compatibility string.
set -a set -a
# shellcheck disable=SC1090,SC1091 # shellcheck disable=SC1091
. "${FLY_ENV_FILE:-/etc/fly/fly.env}" . /etc/fly/fly.env
set +a set +a
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there. # The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current "${FLY_CURRENT_DIR:-/opt/fly/current}" \ "$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \
--binary flysim-session "$@" --binary flysim-session "$@"
} }
cmd="${1:-}" cmd="${1:-}"
[ $# -gt 0 ] && shift [ $# -gt 0 ] && shift
case "$cmd" in case "$cmd" in
start) start "$@" ;; start) start ;;
stop) stop "$@" ;; stop) stop "$@" ;;
status) status ;; status) status ;;
check) check "$@" ;; check) check "$@" ;;
guard) guard ;; guard) guard ;;
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;; 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" ;; simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$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 ;; *) 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 ;;
esac esac

View file

@ -1,145 +0,0 @@
#!/usr/bin/env bash
# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
# Idempotent: re-run it for every release the container runs.
#
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
#
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
# root-owned, and /opt/fly/current points to it: the shadow's verdict names
# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
# refuses a relay whose release differs.
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
# live fly's NUMA node.
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
# clearly faster than real time: see the runbook's "Which box".
#
# What it sets up:
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# ignores what the client asks for; the ingest writes nothing outside the mirror;
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
# run id the relay brings).
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
set -euo pipefail
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
log() { echo "fly-shadow-remote-setup: $*"; }
[ "$(id -u)" = 0 ] || die "run as root on the build box"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
from=""; cpus=""; threads=4
while [ $# -gt 0 ]; do
case "$1" in
--from) from="$2"; shift 2 ;;
--cpus) cpus="$2"; shift 2 ;;
--threads) threads="$2"; shift 2 ;;
*) die "unknown option $1" ;;
esac
done
here="$(cd "$(dirname "$0")" && pwd)"
ROOT=/srv/fly-shadow-remote
HOME_DIR=/srv/fly-shadow-remote-home
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
[ -f "$tarball" ] || die "no tarball $tarball"
[ -f "$rom" ] || die "no ROM $rom"
[ -f "$pubkey" ] || die "no public key $pubkey"
base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
key="$(head -n 1 "$pubkey")"
[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
# The release, exactly as 05-deploy installs it on the container (but root-owned here).
release="/opt/fly/releases/${version}"
if [ -f "$release/MANIFEST" ]; then
log "release $version already at $release"
else
install -d -m 0755 "$release"
tar -xzf "$tarball" -C "$release"
chown -R root:root "$release"
fi
(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
"$release/fly-shadow" ingest 2>&1 | grep -q 'needs --root' \
|| die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
log "/opt/fly/current -> $release"
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
if id flyshadow >/dev/null 2>&1; then
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
else
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
fi
if [ -e "$ROOT" ]; then
[ -d "$ROOT" ] || die "$ROOT is not a directory"
else
mkdir -m 0750 "$ROOT"
chown -h flyshadow:flyshadow "$ROOT"
fi
for d in trace hot durable out; do
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
if [ -e "$ROOT/$d" ]; then
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
else
mkdir -m 0750 "$ROOT/$d"
chown -h flyshadow:flyshadow "$ROOT/$d"
fi
done
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
install -d -o root -g root -m 0755 "$HOME_DIR"
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
log "authorized_keys: the relay key may run only the ingest"
# The cartridge and this box's paths.
rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
install -d -m 0755 /srv/fly/rom
install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
install -d -m 0755 /etc/fly
cat > /etc/fly/fly-shadow-remote.env <<ENV
# written by infra/box/fly-shadow-remote-setup (SHADOW-02): this box's paths for the remote shadow.
FLY_ROM=/srv/fly/rom/${rom_sha}.gb
FLY_DATASET=/opt/fly/current/data/fafb-v783
ENV
log "ROM sha256 $rom_sha (must equal the container's ROM_SHA256)"
# The units.
install -m 0644 "$here/flyshadow-remote.service" /etc/systemd/system/flyshadow-remote.service
install -m 0644 "$here/flyshadow-remote.path" /etc/systemd/system/flyshadow-remote.path
install -d -m 0755 /etc/systemd/system/flyshadow-remote.service.d
{
printf '# written by fly-shadow-remote-setup\n[Service]\nEnvironment=FLY_SHADOW_THREADS=%s\n' "$threads"
[ -n "$cpus" ] && printf 'AllowedCPUs=%s\n' "$cpus"
} > /etc/systemd/system/flyshadow-remote.service.d/10-cores.conf
log "${threads} threads${cpus:+ on CPUs $cpus}"
systemctl daemon-reload
systemctl enable --now flyshadow-remote.path
systemctl enable flyshadow-remote.service
# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
systemctl try-restart flyshadow-remote.service || true
log "ready: the container's fly-shadow-run start brings the first run id"

View file

@ -1,13 +0,0 @@
# 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

View file

@ -1,55 +0,0 @@
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
#
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the
# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
# the SAME release (installed from the same tarball at the same /opt/fly/releases/<version> 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 <root>/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
# <root>/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

View file

@ -527,30 +527,18 @@ 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. the release container in the host log first, as for any host work.
``` ```
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, remote shadow + guard, one flysim restart pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, shadow + guard, one flysim restart
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (and a guard trip) in one screen pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict (and a guard trip) in one screen
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off pct exec <ctid> -- /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 - **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 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: 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`, 1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
`FLY_TRACE_LEDGERS=60`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this `FLY_TRACE_LEDGERS=60`);
run's id: the start's Unix ms); 2. starts `flyshadow.service` and waits for its heartbeat;
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; 3. restarts `flysim.service` once;
4. starts `flyshadow-guard.timer`. 4. starts `flyshadow-guard.timer`.
@ -581,19 +569,9 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow,
- at least 10,800 brain seconds, whatever window the shadow was started with; - 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 - 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); `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 - the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
other shadowed binary unchanged; other shadowed binary unchanged;
- the shadow is caught up (at most about a minute behind); - the shadow is caught up (at most about a minute behind);
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
a trace that is not being written while the shadow claims to follow refuses the check (a paused
flysim refuses too, until it runs);
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
refuse (safe, not silent). Run NTP on both;
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future - the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
(a clock stepped back must not keep an old pass fresh); (a clock stepped back must not keep an old pass fresh);
- no segment was skipped for a reason other than the live side's own. - no segment was skipped for a reason other than the live side's own.
@ -608,110 +586,18 @@ pct exec <ctid> -- /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 (`/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 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 stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
deletes every file it has compared (remote: the box deletes its copy, and the relay then deletes deletes every file it has compared.
the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is - **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while `cpuset.conf`). It pauses for a minute while flysim's lag grows faster than its baseline rate, and
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A it stops pausing when a pause does not help. Disk: about
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where 160 MB of trace per live hour, and a spool of at most 512 MiB.
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that
stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
gap, never a skip. The shadow discards the brain time and saves compared before it
(`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
`coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
new window has compared the required time.
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
would have to restart while the stopped trace is still the newest file and reach its stop before
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
one.
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
and the run is lost (safe: start a new run as above); do not rely on the fast case.
`coverageLost` is synced to disk before the chunk with the stop is forwarded.
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
counts against it; if the guard trips on a remote run, the trace alone is too much for the live
fly's headroom. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the - **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 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). cpuset drop-in when the CT conf and CPUSET disagree).
- **Stop** stops the unit and the guard, removes the drop-ins, and deletes the trace and the spool - **Stop** stops the unit and the guard, removes the drop-in, and deletes the trace and the spool
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace (`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
within a minute, because its consumer is gone. Remote, the box's shadow keeps running idle until within a minute, because its consumer is gone.
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-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
`/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@<box address>`,
`FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
it and runs in remote mode.
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
after an hour. The ingest refuses a relay whose release directory or binaries
differ from the box's (another release on the container: re-run step 2 with its tarball);
`journalctl -u flyshadow` on the container shows it.
Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
with `--cpus` and `--threads`; keep other heavy work (bx) off that box
for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
## Cutover to the session runtime (CUT-01) ## Cutover to the session runtime (CUT-01)
@ -723,8 +609,7 @@ 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. # 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) # 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; on a build box # 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact:
# (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 start
pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass 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: # 3. Cutover: the shadow's gate, then the switch. One command line:

View file

@ -683,8 +683,7 @@ 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" \ 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_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_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_BASELINE_SECONDS=1 \
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 2>&1)" || rc=$?
FLY_METRICS_URL=http://127.0.0.1:1 "$INFRA_DIR/bin/fly-shadow-run" start --local 2>&1)" || rc=$?
case "$2" in case "$2" in
refuse) refuse)
if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \ if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \
@ -711,119 +710,7 @@ if command -v python3 >/dev/null 2>&1; then
else else
fail "python3 is needed to test fly-shadow-run's cpuset check" fail "python3 is needed to test fly-shadow-run's cpuset check"
fi 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" rm -rf "$cs_tmp"
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute
# old), of this run (the drop-in's id, the verdict's too), without coverageLost (review B1: flysim
# stopped its trace for want of a consumer) and with a live trace written in the last 90 s.
if command -v python3 >/dev/null 2>&1; then
rc_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-relay.XXXXXX")"
mkdir -p "$rc_tmp/bin" "$rc_tmp/shadow" "$rc_tmp/flyshadow.d"
printf '#!/bin/sh\ncase "$1" in is-active) exit 0 ;; esac\nexit 0\n' > "$rc_tmp/bin/systemctl"
chmod +x "$rc_tmp/bin/systemctl"
printf '[Service]\nEnvironment=FLY_SHADOW_RUN_ID=1790000000000\n' > "$rc_tmp/flyshadow.d/remote.conf"
printf '{"rtfMean":1,"rtfSd":0,"lagRate":0,"samples":60,"margin":0.05}\n' > "$rc_tmp/shadow/baseline.json"
rc_check() { # name, expect (refused|passes-gates), relay.json (or none), verdict.json (default: this run's), [local]
local rc=0 out dropin_dir="$rc_tmp/flyshadow.d"
rm -f "$rc_tmp/shadow/relay.json"
[ "$3" = none ] || printf '%s\n' "$3" > "$rc_tmp/shadow/relay.json"
printf '%s\n' "${4:-{\"runId\":\"1790000000000\",\"status\":\"running\",\"window\":{\"lastStopTrace\":null\}\}}" > "$rc_tmp/shadow/verdict.json"
[ "${5:-}" = local ] && dropin_dir="$rc_tmp/none.d"
out="$(PATH="$rc_tmp/bin:$PATH" FLY_SHADOW_DIR="$rc_tmp/shadow" FLY_SHADOW_BIN="$rc_tmp/none" \
FLY_SHADOW_REMOTE_DROPIN_DIR="$dropin_dir" "$INFRA_DIR/bin/fly-shadow-run" check 2>&1)" || rc=$?
case "$2:$rc" in
refused:1) pass "fly-shadow-run check (remote), $1: ${out#cutover refused: }" ;;
passes-gates:2) pass "fly-shadow-run check (remote), $1: past the relay precondition" ;;
*) fail "fly-shadow-run check (remote), $1: expected $2, got exit $rc: $out" ;;
esac
}
now="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
old="$(date -u -d '-5 min' +%Y-%m-%dT%H:%M:%S.000Z)"
good="\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":12"
rc_check "no relay.json" refused none
rc_check "relay not healthy" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":false,\"connected\":true,\"remoteAlive\":false,\"remoteWhy\":\"the shadow has no heartbeat\"}"
rc_check "relay.json 5 minutes old" refused "{\"updatedAt\":\"$old\",\"runId\":\"1790000000000\",\"healthy\":true,\"traceAgeSeconds\":1}"
rc_check "relay healthy, run, trace current" passes-gates "{$good}"
# B1: healthy and caught up, but the live trace ended in a no-consumer stop the shadow has not reached.
rc_check "coverage lost while the relay reports healthy (B1)" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":{\"trace\":\"trace-1790000005000-4242.jsonl\",\"window\":\"w1\"},\"traceAgeSeconds\":12}"
rc_check "live trace not written for 5 minutes" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":300}"
rc_check "no live trace file" refused "{\"updatedAt\":\"$now\",\"runId\":\"1790000000000\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":null}"
rc_check "relay.json of another run" refused "{\"updatedAt\":\"$now\",\"runId\":\"1789999999999\",\"healthy\":true,\"coverageLost\":null,\"traceAgeSeconds\":12}"
# B2: a verdict that does not carry its window (an older shadow) may count time before a gap.
rc_check "a verdict without a window (B2)" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}"
rc_check "a verdict with a window, after a stop (B2)" passes-gates "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\",\"window\":{\"lastStopTrace\":\"trace-1790000005000-4242.jsonl\"}}"
rc_check "verdict of another run" refused "{$good}" "{\"runId\":\"1789999999999\",\"status\":\"pass\"}"
rc_check "a local run's verdict (no run id) in remote mode" refused "{$good}" "{\"runId\":null,\"status\":\"pass\"}"
rc_check "a remote verdict without a remote drop-in" refused "{$good}" "{\"runId\":\"1790000000000\",\"status\":\"pass\"}" local
rc_check "a local verdict and no drop-in" passes-gates none "{\"runId\":null,\"status\":\"pass\"}" local
rm -rf "$rc_tmp"
fi
# SHADOW-02: the build box's units live outside infra/units (05-deploy converges every unit there
# onto the release container) and keep the remote shadow's semantics.
BOX_UNIT="$INFRA_DIR/box/flyshadow-remote.service"
if ls "$INFRA_DIR"/units/flyshadow-remote* >/dev/null 2>&1; then
fail "the build box's flyshadow-remote units must not be in infra/units (05-deploy would install them on the release container)"
elif [ ! -f "$BOX_UNIT" ] || [ ! -f "$INFRA_DIR/box/flyshadow-remote.path" ]; then
fail "infra/box/flyshadow-remote.service and .path are missing"
else
grep -qE '^ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0( |$)' "$BOX_UNIT" \
&& pass "flyshadow-remote.service runs the release's fly-shadow on the mirror, for the relay's run" \
|| fail "flyshadow-remote.service must run /opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0"
{ grep -qE '^Restart=always$' "$BOX_UNIT" && grep -qE '^RestartPreventExitStatus=3$' "$BOX_UNIT"; } \
&& pass "flyshadow-remote.service restarts for a new run (exit 4) and stays stopped after a divergence (exit 3)" \
|| fail "flyshadow-remote.service needs Restart=always and RestartPreventExitStatus=3"
grep -qE '^CPUSchedulingPolicy=idle' "$BOX_UNIT" \
&& fail "flyshadow-remote.service must not be idle-scheduled: it has its own cores" \
|| pass "flyshadow-remote.service runs at normal priority on its own cores"
grep -qE '^PathChanged=/srv/fly-shadow-remote/run-id$' "$INFRA_DIR/box/flyshadow-remote.path" \
&& pass "flyshadow-remote.path starts the shadow on a new run id" \
|| fail "flyshadow-remote.path must watch /srv/fly-shadow-remote/run-id"
fi
SETUP="$INFRA_DIR/box/fly-shadow-remote-setup"
bash -n "$SETUP" && pass "fly-shadow-remote-setup parses" || fail "fly-shadow-remote-setup does not parse"
# Review N3: the key file is outside anything flyshadow owns; no symlink is followed as root; --from is required.
grep -qE '^HOME_DIR=/srv/fly-shadow-remote-home$' "$SETUP" \
&& grep -qF 'install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"' "$SETUP" \
&& grep -qF 'authorized_keys.new' "$SETUP" && ! grep -qF '"$ROOT/.ssh/authorized_keys' "$SETUP" \
&& pass "fly-shadow-remote-setup keeps authorized_keys in a root-owned home, not in the flyshadow-owned mirror" \
|| fail "fly-shadow-remote-setup must put .ssh in a root-owned home (HOME_DIR), not in the mirror"
if grep -nE '^[[:space:]]*(install -d|chown|chmod)[^#]*"\$ROOT' "$SETUP" | grep -v -- 'chown -h' | grep -q .; then
fail "fly-shadow-remote-setup must not install -d / chown / chmod under the flyshadow-owned mirror (it follows symlinks as root)"
else
pass "fly-shadow-remote-setup never chowns or chmods under the mirror without -h, nor installs into it"
fi
grep -qF '[ -L "$ROOT/$d" ] && die' "$SETUP" \
&& pass "fly-shadow-remote-setup refuses a symlink in the mirror on a re-run" \
|| fail "fly-shadow-remote-setup must refuse a symlink under the mirror"
grep -qF '[ -n "$from" ] || die "--from is required' "$SETUP" \
&& pass "fly-shadow-remote-setup requires --from" \
|| fail "fly-shadow-remote-setup must require --from"
grep -qF 'restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\"' "$INFRA_DIR/box/fly-shadow-remote-setup" \
&& pass "fly-shadow-remote-setup limits the relay key to the ingest (restrict, forced command)" \
|| fail "fly-shadow-remote-setup must write restrict,command=\"/opt/fly/current/fly-shadow ingest --root \$ROOT\""
if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then 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" pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs"
else else

View file

@ -3,9 +3,6 @@
//! ```text //! ```text
//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit) //! 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 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 //! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through
@ -30,20 +27,8 @@
//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) | //! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) |
//! | `--exit-on-pass` | exit once the verdict is `pass` | //! | `--exit-on-pass` | exit once the verdict is `pass` |
//! | `--max-transitions N` | stop after N compared transitions | //! | `--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, 4 a new run, 2 the shadow's own error. //! Exit status: 0 passed or stopped, 3 diverged, 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] //! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current` //! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
@ -55,9 +40,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use fly_legacy_session::shadow::{ use fly_legacy_session::shadow::{self, LagGuard, ShadowConfig, StopFlag, verdict};
self, LagGuard, ShadowConfig, StopFlag, ingest, relay, release, remote, verdict,
};
use fly_session::ExecutionMode; use fly_session::ExecutionMode;
fn usage() -> ! { fn usage() -> ! {
@ -114,20 +97,42 @@ fn env_path(name: &str) -> Option<PathBuf> {
} }
fn file_sha256(path: &std::path::Path) -> String { fn file_sha256(path: &std::path::Path) -> String {
release::file_sha256(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display()))) let bytes = std::fs::read(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display())));
shadow::sha256_hex(&bytes)
} }
fn this_binary() -> PathBuf { fn this_binary() -> PathBuf {
std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}"))) 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. /// SHA-256 of the release binaries in `dir`, by name.
fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> { fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> {
release::binaries_in(dir).unwrap_or_else(|e| die(format!("{}: {e}", dir.display()))) RELEASE_BINARIES
.iter()
.filter_map(|name| {
let path = dir.join(name);
path.is_file()
.then(|| ((*name).to_owned(), file_sha256(&path)))
})
.collect()
} }
/// The resolved directory of this binary: the release it runs from.
fn this_release() -> PathBuf { fn this_release() -> PathBuf {
release::this_release() this_binary()
.parent()
.and_then(|d| d.canonicalize().ok())
.unwrap_or_default()
} }
fn main() { fn main() {
@ -139,11 +144,6 @@ fn main() {
let mut args = Args(argv); let mut args = Args(argv);
match command.as_str() { match command.as_str() {
"run" => run(args), "run" => run(args),
"relay" => {
args.done();
relay_main()
}
"ingest" => ingest_main(args),
"check" => { "check" => {
let verdict_path: PathBuf = args let verdict_path: PathBuf = args
.value("--verdict") .value("--verdict")
@ -244,7 +244,6 @@ fn run(mut args: Args) {
let keep_spool = args.flag("--keep-spool"); let keep_spool = args.flag("--keep-spool");
let exit_on_pass = args.flag("--exit-on-pass"); let exit_on_pass = args.flag("--exit-on-pass");
let max_transitions: Option<u64> = args.parsed("--max-transitions"); let max_transitions: Option<u64> = args.parsed("--max-transitions");
let run_id_file = args.value("--run-id-file").map(PathBuf::from);
// Undocumented: the toy connectome, for tests only. // Undocumented: the toy connectome, for tests only.
let profile = match args.value("--profile") { let profile = match args.value("--profile") {
None => fly_session::legacy_agent::LegacyProfileKind::Production, None => fly_session::legacy_agent::LegacyProfileKind::Production,
@ -306,7 +305,6 @@ fn run(mut args: Args) {
binary_sha256: file_sha256(&this_binary()), binary_sha256: file_sha256(&this_binary()),
binaries: binaries_in(&this_release()), binaries: binaries_in(&this_release()),
release: this_release().display().to_string(), release: this_release().display().to_string(),
run_id_file,
}; };
eprintln!( eprintln!(
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)", "fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
@ -339,10 +337,6 @@ fn run(mut args: Args) {
}); });
match ended { match ended {
Ok((shadow::Ended::Diverged, _)) => std::process::exit(3), 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)) => { Ok((ended, verdict)) => {
eprintln!( eprintln!(
"fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}", "fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}",
@ -354,111 +348,3 @@ fn run(mut args: Args) {
Err(e) => die(e), 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<String> = 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::<u16>()
.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);
}
}

View file

@ -1,649 +0,0 @@
//! `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 |
//! | --- | --- |
//! | `<root>/trace/` | the live trace files, appended as they grow; the shadow's heartbeat `consumer` |
//! | `<root>/hot/`, `<root>/durable/` | the live saves (`<gen>.checkpoint`), bounded; the sugar journal in `hot/` |
//! | `<root>/out/` | the shadow's verdict, divergence and spool |
//! | `<root>/run-id` | the relay's run: a new one resets the mirror and restarts the shadow |
//! | `<root>/live.env` | the live composition's settings ([`super::remote::FORWARDED_ENV`]) |
//! | `<root>/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<String, String>,
/// 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<String, String>) -> 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<String>,
done: BTreeSet<String>,
}
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<String> {
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<Mutex<Box<dyn Write + Send>>>;
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<String, u64> {
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 `<gen>.checkpoint` files in `dir`, with their sizes.
fn gens_in(dir: &Path) -> BTreeMap<u64, u64> {
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<Vec<u8>>, 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<R: BufRead>(
mut input: R,
output: Box<dyn Write + Send>,
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<String, String> =
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<u64> = 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<Ledger>, stop: &AtomicBool, config: &IngestConfig) {
let layout = Layout::of(&config.root);
let mut sent_verdict: Option<Vec<u8>> = None;
let mut sent_files: BTreeSet<String> = BTreeSet::new();
let mut last = Instant::now() - config.status_every;
while !stop.load(Ordering::Relaxed) {
if last.elapsed() < config.status_every {
std::thread::sleep(Duration::from_millis(50));
continue;
}
last = Instant::now();
let (traces, received, done, run_id) = {
let mut l = ledger.lock().unwrap_or_else(|p| p.into_inner());
// Listed under the lock: a file `apply_trace` creates (under the same lock) between a
// listing and this point would otherwise look removed, and be marked finished.
let traces = trace_sizes(&layout.trace);
let gone: Vec<String> = l
.created
.iter()
.filter(|n| !traces.contains_key(*n))
.cloned()
.collect();
if !gone.is_empty() {
for name in gone {
l.created.remove(&name);
l.done.insert(name);
}
l.save(&layout.ledger);
}
(traces, l.received, l.done.clone(), l.run_id.clone())
};
let (alive, why, verdict, status) = shadow_state(&layout, &run_id, config.alive_within);
let mut result = send(
out,
json!({"t": "status", "received": received, "traces": traces, "done": done,
"alive": alive, "why": why, "verdictStatus": status}),
b"",
);
if result.is_ok()
&& let Some(bytes) = verdict
&& sent_verdict.as_ref() != Some(&bytes)
{
result = send(out, json!({"t": "verdict"}), &bytes);
sent_verdict = Some(bytes);
}
if result.is_ok() && status == "diverged" {
for entry in std::fs::read_dir(&layout.out).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if remote::is_divergence_file(&name)
&& !sent_files.contains(&name)
&& let Ok(bytes) = std::fs::read(entry.path())
{
result = send(out, json!({"t": "file", "name": name}), &bytes);
sent_files.insert(name);
}
}
}
if result.is_err() {
stop.store(true, Ordering::Relaxed);
}
}
}
fn apply_loop<R: BufRead>(
input: &mut R,
out: &Output,
ledger: &Mutex<Ledger>,
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<Ledger>,
layout: &Layout,
) -> Result<(), String> {
let name = frame.header["name"].as_str().unwrap_or("");
if !remote::is_trace_name(name) {
return Err(format!("a trace named {name:?}"));
}
let offset = frame.header["offset"]
.as_u64()
.ok_or("a trace chunk with no offset")?;
let path = layout.trace.join(name);
let size = std::fs::metadata(&path).ok().map(|m| m.len());
{
let mut l = ledger.lock().unwrap_or_else(|p| p.into_inner());
// Finished by the shadow (or created here and removed since): never written again.
if l.done.contains(name) || (size.is_none() && l.created.contains(name)) {
return Ok(());
}
if size.is_none() && offset == 0 {
std::fs::File::create(&path).map_err(|e| format!("{}: {e}", path.display()))?;
l.created.insert(name.to_owned());
l.save(&layout.ledger);
}
}
let size = size.unwrap_or(0);
if size != offset {
return send(
out,
json!({"t": "resync", "name": name, "size": size}),
b"",
)
.map_err(|e| format!("writing resync: {e}"));
}
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(&path)
.map_err(|e| format!("{}: {e}", path.display()))?;
file.write_all(&frame.body)
.map_err(|e| format!("{}: {e}", path.display()))
}
/// Keeps the mirrored saves under `keep` bytes, dropping the oldest generations first.
pub fn prune_saves(layout: &Layout, keep: u64) {
let mut all: Vec<(u64, PathBuf, u64)> = Vec::new();
for dir in [&layout.hot, &layout.durable] {
for (generation, len) in gens_in(dir) {
all.push((generation, dir.join(format!("{generation}.checkpoint")), len));
}
}
all.sort();
let mut total: u64 = all.iter().map(|(_, _, len)| len).sum();
for (_, path, len) in all {
if total <= keep {
break;
}
if std::fs::remove_file(&path).is_ok() {
total -= len;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A writer the test can read back.
#[derive(Clone, Default)]
struct Shared(Arc<Mutex<Vec<u8>>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn frames(out: &Shared) -> Vec<Frame> {
let bytes = out.0.lock().unwrap().clone();
let mut input = std::io::Cursor::new(bytes);
std::iter::from_fn(|| remote::read_frame(&mut input).unwrap()).collect()
}
fn config(root: &Path) -> IngestConfig {
let mut c = IngestConfig::new(
root.to_owned(),
"/opt/fly/releases/v1".to_owned(),
[("fly-shadow".to_owned(), "a".repeat(64))].into(),
);
c.status_every = Duration::from_secs(3600);
c
}
fn wire(frames: &[(Value, &[u8])]) -> std::io::Cursor<Vec<u8>> {
let mut bytes = Vec::new();
for (header, body) in frames {
remote::write_frame(&mut bytes, header.clone(), body).unwrap();
}
std::io::Cursor::new(bytes)
}
fn hello(release: &str) -> Value {
json!({"t": "hello", "protocol": remote::PROTOCOL, "runId": "1790000000000",
"release": release, "binaries": {"fly-shadow": "a".repeat(64)},
"env": {"FLY_MACRO_MODE": "macros", "FLY_ROM": "/elsewhere", "FLY_GAME": "a b"}})
}
#[test]
fn another_release_is_refused_before_anything_is_written() {
let root = tempfile::tempdir().unwrap();
let out = Shared::default();
let input = wire(&[(hello("/opt/fly/releases/v2"), b"")]);
let err = serve(input, Box::new(out.clone()), config(root.path())).unwrap_err();
assert!(err.contains("same path"), "{err}");
let got = frames(&out);
assert_eq!(got.len(), 1);
assert_eq!(got[0].kind(), "error");
assert!(!root.path().join("run-id").exists());
}
#[test]
fn a_run_is_mirrored_by_name_and_offset_only() {
let root = tempfile::tempdir().unwrap();
let layout = Layout::of(root.path());
std::fs::create_dir_all(&layout.hot).unwrap();
// The previous run's leftovers go when a new run says hello.
std::fs::write(layout.hot.join("7.checkpoint"), b"old").unwrap();
let name = "trace-1790000000001-42.jsonl";
let out = Shared::default();
let input = wire(&[
(hello("/opt/fly/releases/v1"), b""),
(json!({"t": "trace", "name": name, "offset": 0}), b""),
(json!({"t": "trace", "name": name, "offset": 0}), b"{\"a\":1}\n"),
// A chunk at the wrong offset is not appended: the relay is asked to resend.
(json!({"t": "trace", "name": name, "offset": 99}), b"x"),
(json!({"t": "ckpt", "store": "hot", "gen": 12}), b"FLYSIM01"),
(json!({"t": "journal", "name": "sugar-journal.jsonl"}), b"{}\n"),
(json!({"t": "bye"}), b""),
]);
serve(input, Box::new(out.clone()), config(root.path())).unwrap();
assert_eq!(std::fs::read(layout.trace.join(name)).unwrap(), b"{\"a\":1}\n");
assert_eq!(std::fs::read(layout.hot.join("12.checkpoint")).unwrap(), b"FLYSIM01");
assert!(!layout.hot.join("7.checkpoint").exists());
assert_eq!(
std::fs::read_to_string(&layout.run_id).unwrap(),
"1790000000000\n"
);
// Only the forwarded, plain settings reach the box's env file.
assert_eq!(
std::fs::read_to_string(&layout.live_env).unwrap(),
"FLY_MACRO_MODE=macros\n"
);
let got = frames(&out);
assert_eq!(got[0].kind(), "state");
assert!(got.iter().any(|f| f.kind() == "resync" && f.header["size"] == 8));
// A path in a name is refused outright.
let input = wire(&[
(hello("/opt/fly/releases/v1"), b""),
(json!({"t": "trace", "name": "../x.jsonl", "offset": 0}), b"x"),
]);
assert!(serve(input, Box::new(Shared::default()), config(root.path())).is_err());
assert!(!root.path().join("x.jsonl").exists());
// The same run reconnecting keeps the mirror.
let input = wire(&[(hello("/opt/fly/releases/v1"), b"")]);
let out = Shared::default();
serve(input, Box::new(out.clone()), config(root.path())).unwrap();
assert_eq!(frames(&out)[0].header["traces"][name], 8);
}
}

View file

@ -30,10 +30,6 @@
pub mod checkpoint; pub mod checkpoint;
pub mod follow; pub mod follow;
pub mod ingest;
pub mod relay;
pub mod release;
pub mod remote;
pub mod spool; pub mod spool;
pub mod verdict; pub mod verdict;
@ -109,12 +105,6 @@ pub struct ShadowConfig {
/// The release binaries beside it, by name, and their directory (the verdict's `candidate`). /// The release binaries beside it, by name, and their directory (the verdict's `candidate`).
pub binaries: std::collections::BTreeMap<String, String>, pub binaries: std::collections::BTreeMap<String, String>,
pub release: String, 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<PathBuf>,
} }
/// The back-off that keeps the shadow from costing the live fly real time, judged against the /// The back-off that keeps the shadow from costing the live fly real time, judged against the
@ -288,8 +278,6 @@ pub enum Ended {
Diverged, Diverged,
Stopped, Stopped,
Limit, Limit,
/// The run id changed ([`ShadowConfig::run_id_file`]): a new run was started.
NewRun,
} }
/// Why a segment ended. /// Why a segment ended.
@ -466,12 +454,6 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
record: true, record: true,
}; };
let compatibility = crate::composition::compatibility_of(&session_config); 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( let mut spool = Spool::new(
&config.spool_dir, &config.spool_dir,
vec![config.hot_dir.clone(), config.durable_dir.clone()], vec![config.hot_dir.clone(), config.durable_dir.clone()],
@ -525,8 +507,6 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
checkpoints: Checkpoints::default(), checkpoints: Checkpoints::default(),
segments_compared: 0, segments_compared: 0,
skipped: Vec::new(), skipped: Vec::new(),
window_ends: Vec::new(),
last_stop_trace: None,
divergence: None, divergence: None,
started_at: verdict::now_iso(), started_at: verdict::now_iso(),
passed_at: None, passed_at: None,
@ -535,18 +515,7 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
live_lag_seconds: None, live_lag_seconds: None,
spool_evicted: 0, spool_evicted: 0,
cost: Cost::default(), 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, config,
session_config, session_config,
compatibility, compatibility,
@ -571,12 +540,11 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
match ended { match ended {
Ended::Diverged => {} Ended::Diverged => {}
Ended::Pass => {} Ended::Pass => {}
Ended::Stopped | Ended::Limit | Ended::NewRun => { Ended::Stopped | Ended::Limit => {
if shadow.verdict.status == Status::Running { if shadow.verdict.status == Status::Running {
shadow.verdict.status = Status::Stopped; shadow.verdict.status = Status::Stopped;
shadow.verdict.reason = match ended { shadow.verdict.reason = match ended {
Ended::Limit => "stopped at the transition limit".to_owned(), 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(), _ => "stopped before the window was complete".to_owned(),
}; };
} }
@ -606,36 +574,9 @@ struct Shadow {
traces_seen: std::collections::BTreeSet<u64>, traces_seen: std::collections::BTreeSet<u64>,
boots_checked: std::collections::BTreeSet<u64>, boots_checked: std::collections::BTreeSet<u64>,
last_coverage: Instant, last_coverage: Instant,
/// The run id this shadow started with, and when the file was last looked at.
run_id: Option<String>,
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<String, u64>,
}
/// The run id in `path` (trimmed), if the file exists and is not empty.
pub fn read_run_id(path: &Path) -> Option<String> {
let text = std::fs::read_to_string(path).ok()?;
let id = text.trim();
(!id.is_empty()).then(|| id.to_owned())
} }
impl Shadow { 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) { fn write(&mut self) {
self.verdict.spool_evicted = self.spool.evicted(); self.verdict.spool_evicted = self.spool.evicted();
// Refreshed on every write, backed off or not, so the verdict's catch-up bound is current. // Refreshed on every write, backed off or not, so the verdict's catch-up bound is current.
@ -662,15 +603,11 @@ impl Shadow {
return None; return None;
} }
self.last_coverage = Instant::now(); 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) { if let Ok(files) = follow::trace_files(&self.config.trace_dir) {
self.traces_seen self.traces_seen
.extend(files.iter().filter_map(|f| trace_start_ms(f))); .extend(files.iter().filter_map(|f| trace_start_ms(f)));
} }
let segments = flysim::journal::read_segments(&self.config.hot_dir).ok()?;
let boots: Vec<Value> = segments.into_iter().filter_map(|s| s.boot).collect(); let boots: Vec<Value> = segments.into_iter().filter_map(|s| s.boot).collect();
let untraced = untraced_boots( let untraced = untraced_boots(
&boots, &boots,
@ -744,9 +681,6 @@ impl Shadow {
if self.stop.requested() { if self.stop.requested() {
return Ok(Ended::Stopped); return Ok(Ended::Stopped);
} }
if self.new_run() {
return Ok(Ended::NewRun);
}
match follow::next_file(&dir, current.as_deref()) { match follow::next_file(&dir, current.as_deref()) {
Ok(Some(path)) => break path, Ok(Some(path)) => break path,
Ok(None) => {} Ok(None) => {}
@ -776,18 +710,6 @@ impl Shadow {
let _ = std::fs::remove_file(&next); let _ = std::fs::remove_file(&next);
} }
} }
SegmentEnd::Skipped("trace-cap", reason) => {
// A stopped trace is a coverage gap: what was compared before it stops
// counting (SHADOW-02 B2).
eprintln!(
"fly-shadow: {name} stopped after {compared} transitions: {reason}; the \
window restarts after it"
);
self.verdict.end_window(&name, reason);
if !self.config.keep_traces {
let _ = std::fs::remove_file(&next);
}
}
SegmentEnd::Skipped(kind, reason) => { SegmentEnd::Skipped(kind, reason) => {
eprintln!( eprintln!(
"fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}" "fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}"
@ -829,9 +751,6 @@ impl Shadow {
if self.stop.requested() { if self.stop.requested() {
return Err(SegmentEnd::Stop(Ended::Stopped)); return Err(SegmentEnd::Stop(Ended::Stopped));
} }
if self.new_run() {
return Err(SegmentEnd::Stop(Ended::NewRun));
}
if follow::superseded(follower.path()) { if follow::superseded(follower.path()) {
// The next process exists, so this one has exited and flushed: one more read for // 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. // a final flush racing the directory listing, then the segment is over.
@ -1064,11 +983,6 @@ impl Shadow {
let mut rank_since_ms = rank_since_ms; let mut rank_since_ms = rank_since_ms;
let mut context: VecDeque<(Value, Value)> = VecDeque::new(); let mut context: VecDeque<(Value, Value)> = VecDeque::new();
let mut captures_taken: u64 = 0; let mut captures_taken: u64 = 0;
// After a declared reward pulse the rest of the trace cannot be compared, but it is still
// read for its stop line: a stop later in the same trace is a coverage gap and must end
// the window (SHADOW-02 r3 N5).
let mut reward_skipped = false;
let compared_before = self.verdict.agreement.transitions;
loop { loop {
let line = match self.next_line(follower).await { let line = match self.next_line(follower).await {
Ok(Some(line)) => line, Ok(Some(line)) => line,
@ -1082,35 +996,11 @@ impl Shadow {
} }
}; };
if live.get("truncated").is_some() { 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( return SegmentEnd::Skipped(
"trace-cap", "trace-cap",
format!("the live trace stopped ({})", live["reason"]), format!("the live trace stopped ({})", live["reason"]),
); );
} }
if reward_skipped {
continue;
}
let Some(behaviour) = live.get("behaviour").cloned() else { let Some(behaviour) = live.get("behaviour").cloned() else {
continue; continue;
}; };
@ -1128,22 +1018,13 @@ impl Shadow {
admission.replay_sugar(duration); admission.replay_sugar(duration);
} }
Some("reward") => { Some("reward") => {
let compared = self.verdict.agreement.transitions - compared_before; return SegmentEnd::Skipped(
eprintln!( "operator-reward-pulse",
"fly-shadow: {name} skipped (operator-reward-pulse) after {compared} \ format!(
transitions; reading on for a stop"
);
self.verdict.skipped.push(Skipped {
trace: name.to_owned(),
transitions_compared: compared,
kind: "operator-reward-pulse".to_owned(),
reason: format!(
"an operator reward pulse at step {step:?} (declared \ "an operator reward pulse at step {step:?} (declared \
operator-reward-pulse: not available on the session runtime)" operator-reward-pulse: not available on the session runtime)"
), ),
}); );
reward_skipped = true;
break;
} }
other => { other => {
return SegmentEnd::Skipped( return SegmentEnd::Skipped(
@ -1153,9 +1034,6 @@ impl Shadow {
} }
} }
} }
if reward_skipped {
continue;
}
// Back off while the live fly is losing real time ([`LagGuard`]). // Back off while the live fly is losing real time ([`LagGuard`]).
if let Some(lag) = self.lag.clone() { if let Some(lag) = self.lag.clone() {
let throttle = Instant::now(); let throttle = Instant::now();
@ -1417,9 +1295,6 @@ impl Shadow {
if let Some(divergence) = self.coverage() { if let Some(divergence) = self.coverage() {
return SegmentEnd::Diverged(Box::new(divergence)); return SegmentEnd::Diverged(Box::new(divergence));
} }
if self.new_run() {
return SegmentEnd::Stop(Ended::NewRun);
}
self.write_if_due(); self.write_if_due();
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,50 +0,0 @@
//! 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<String> {
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<BTreeMap<String, String>> {
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()
}

View file

@ -1,248 +0,0 @@
//! 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 <root>/trace, reads <root>/hot,
//! flyshadow.service = fly-shadow relay ---- ssh ---+--> fly-shadow ingest --root <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 <box> ...`, 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 `<gen>.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<u8>,
}
impl Frame {
pub fn kind(&self) -> &str {
self.header["t"].as_str().unwrap_or("")
}
}
fn invalid(message: impl Into<String>) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
}
/// Writes one frame and flushes.
pub fn write_frame<W: Write + ?Sized>(
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<R: BufRead>(input: &mut R) -> std::io::Result<Option<Frame>> {
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>-<pid>.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-<n>.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<u64> {
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)"));
}
}

View file

@ -13,8 +13,6 @@
//! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence | //! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence |
//! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) | //! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) |
//! | `declaredDifferences` | the named exclusions the comparison applied | //! | `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 //! `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 //! then finds a difference turns the verdict to `diverged`. `stopped` is a shadow that exited
@ -50,13 +48,12 @@ use crate::trace::{Agreement, Difference};
pub const FORMAT: &str = "fly-shadow-verdict-v1"; 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 /// 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, and a /// reward pulse (declared), a startup save rotated away before the shadow reached it, a trace
/// process that ran no transition. A trace that stopped (byte cap, or no consumer before this /// stopped at its byte cap or for want of a consumer, and a process that ran no transition.
/// shadow started) is a coverage gap, never a skip: it ends the window, see [`Verdict::end_window`] pub const SKIP_KINDS: [&str; 4] = [
/// (SHADOW-02 B2).
pub const SKIP_KINDS: [&str; 3] = [
"operator-reward-pulse", "operator-reward-pulse",
"startup-save-gone", "startup-save-gone",
"trace-cap",
"no-transition", "no-transition",
]; ];
@ -141,14 +138,6 @@ pub struct Skipped {
pub reason: String, pub reason: String,
} }
/// A coverage gap: the live trace stopped, so everything compared before it no longer counts.
#[derive(Clone, Debug)]
pub struct WindowEnd {
pub trace: String,
pub reason: String,
pub discarded_brain_seconds: f64,
}
/// The first divergence and its context. /// The first divergence and its context.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Divergence { pub struct Divergence {
@ -237,10 +226,6 @@ pub struct Verdict {
pub checkpoints: Checkpoints, pub checkpoints: Checkpoints,
pub segments_compared: u64, pub segments_compared: u64,
pub skipped: Vec<Skipped>, pub skipped: Vec<Skipped>,
/// Trace stops (coverage gaps) that ended a window: what they discarded.
pub window_ends: Vec<WindowEnd>,
/// The trace whose stop last ended the window (`None`: none yet). `compared` counts only after.
pub last_stop_trace: Option<String>,
pub divergence: Option<Divergence>, pub divergence: Option<Divergence>,
pub started_at: String, pub started_at: String,
pub passed_at: Option<String>, pub passed_at: Option<String>,
@ -250,8 +235,6 @@ pub struct Verdict {
pub live_lag_seconds: Option<f64>, pub live_lag_seconds: Option<f64>,
pub spool_evicted: u64, pub spool_evicted: u64,
pub cost: Cost, pub cost: Cost,
/// SHADOW-02: the relay's run id, for a remote shadow (`null` on the release container).
pub run_id: Option<String>,
} }
pub fn now_iso() -> String { pub fn now_iso() -> String {
@ -286,27 +269,6 @@ pub fn iso(ms: i64) -> String {
} }
impl Verdict { impl Verdict {
/// A coverage gap (a trace stopped, whatever the reason): the live fly may run untraced from
/// here, so the brain time and saves compared so far stop counting. A pass needs the whole
/// window after the last gap (SHADOW-02 B2).
pub fn end_window(&mut self, trace: &str, reason: String) {
self.window_ends.push(WindowEnd {
trace: trace.to_owned(),
reason,
discarded_brain_seconds: self.brain_ms / 1000.0,
});
self.last_stop_trace = Some(trace.to_owned());
self.brain_ms = 0.0;
self.checkpoints = Checkpoints::default();
// A pass belongs to the window it was reached in: the new one has not qualified yet
// (r3 N3). A diverged or errored verdict stays what it is.
if self.status == Status::Pass {
self.status = Status::Running;
self.passed_at = None;
self.reason = String::new();
}
}
pub fn brain_seconds(&self) -> f64 { pub fn brain_seconds(&self) -> f64 {
self.brain_ms / 1000.0 self.brain_ms / 1000.0
} }
@ -349,12 +311,6 @@ impl Verdict {
"skipped": self.skipped.iter().map(|s| json!({ "skipped": self.skipped.iter().map(|s| json!({
"trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason, "trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason,
})).collect::<Vec<_>>(), })).collect::<Vec<_>>(),
"window": {
"lastStopTrace": self.last_stop_trace,
"ends": self.window_ends.iter().map(|w| json!({
"trace": w.trace, "reason": w.reason, "discardedBrainSeconds": (w.discarded_brain_seconds * 1000.0).round() / 1000.0,
})).collect::<Vec<_>>(),
},
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(), "declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
"firstDivergence": self.divergence.as_ref().map(|d| { "firstDivergence": self.divergence.as_ref().map(|d| {
let mut v = d.to_json(); let mut v = d.to_json();
@ -369,7 +325,6 @@ impl Verdict {
"liveLagSeconds": self.live_lag_seconds, "liveLagSeconds": self.live_lag_seconds,
"spoolEvicted": self.spool_evicted, "spoolEvicted": self.spool_evicted,
"cost": self.cost.to_json(), "cost": self.cost.to_json(),
"runId": self.run_id,
}) })
} }
} }
@ -383,22 +338,6 @@ pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> {
std::fs::rename(&tmp, path) std::fs::rename(&tmp, path)
} }
/// [`write_json`], synced to disk (file and directory) before it returns.
pub fn write_json_durable(path: &Path, value: &Value) -> std::io::Result<()> {
use std::io::Write;
let tmp = path.with_extension("json.tmp");
let mut text = serde_json::to_string_pretty(value).expect("JSON serializes");
text.push('\n');
let mut f = std::fs::File::create(&tmp)?;
f.write_all(text.as_bytes())?;
f.sync_all()?;
std::fs::rename(&tmp, path)?;
if let Some(dir) = path.parent() {
std::fs::File::open(dir)?.sync_all()?;
}
Ok(())
}
/// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`], /// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`],
/// [`MAX_UNAVAILABLE_FRACTION`]). /// [`MAX_UNAVAILABLE_FRACTION`]).
pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> { pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> {
@ -472,12 +411,6 @@ pub fn allows_cutover(
if candidate["compatibility"] != compatibility { if candidate["compatibility"] != compatibility {
return Err("the verdict is for another compatibility string".to_owned()); return Err("the verdict is for another compatibility string".to_owned());
} }
// Only a build that ends the window at a coverage gap counts brain time after it.
if verdict["window"].is_null() {
return Err(
"the verdict does not say where its window starts (an older shadow)".to_owned(),
);
}
let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0); let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0);
// The operator's window is a floor the verdict cannot lower: a shadow run with a shorter // The operator's window is a floor the verdict cannot lower: a shadow run with a shorter
// `--required-brain-seconds` (a rehearsal, a test) never arms the cutover. // `--required-brain-seconds` (a rehearsal, a test) never arms the cutover.
@ -583,8 +516,6 @@ mod tests {
}, },
segments_compared: 1, segments_compared: 1,
skipped: Vec::new(), skipped: Vec::new(),
window_ends: Vec::new(),
last_stop_trace: None,
divergence: None, divergence: None,
started_at: now_iso(), started_at: now_iso(),
passed_at: None, passed_at: None,
@ -593,94 +524,10 @@ mod tests {
live_lag_seconds: None, live_lag_seconds: None,
spool_evicted: 0, spool_evicted: 0,
cost: Cost::default(), cost: Cost::default(),
run_id: None,
} }
.to_json() .to_json()
} }
fn verdict_struct(status: Status) -> Verdict {
Verdict {
status,
reason: String::new(),
binary_sha256: String::new(),
binaries: Default::default(),
release: String::new(),
compatibility: String::new(),
execution_mode: String::new(),
agent_threads: 1,
required_brain_seconds: 10_800.0,
agreement: Agreement::default(),
brain_ms: 1_819_000.0,
ledger_checks: 0,
checkpoints: Checkpoints {
identical: 400,
declared: 0,
unavailable: 0,
},
segments_compared: 1,
skipped: Vec::new(),
window_ends: Vec::new(),
last_stop_trace: None,
divergence: None,
started_at: now_iso(),
passed_at: None,
current_trace: None,
lag_transitions: 0,
live_lag_seconds: None,
spool_evicted: 0,
cost: Cost::default(),
run_id: None,
}
}
#[test]
fn a_stop_ends_the_window() {
// B2: brain time compared before a coverage gap never counts toward a pass.
let mut v = verdict_struct(Status::Running);
v.brain_ms = 1_819_000.0;
v.checkpoints = Checkpoints {
identical: 400,
declared: 0,
unavailable: 0,
};
v.end_window("trace-1.jsonl", "no-consumer".to_owned());
assert_eq!(v.brain_seconds(), 0.0);
v.brain_ms += 170_000.0;
let j = v.to_json();
assert_eq!(j["compared"]["brainSeconds"], 170.0);
assert_eq!(j["compared"]["checkpoints"]["identical"], 0);
assert_eq!(j["window"]["lastStopTrace"], "trace-1.jsonl");
assert_eq!(j["window"]["ends"][0]["discardedBrainSeconds"], 1819.0);
// A gap is not an allowed skip.
assert!(!SKIP_KINDS.contains(&"trace-cap"));
}
#[test]
fn a_window_end_takes_back_a_pass_and_nothing_else() {
let mut v = verdict_struct(Status::Pass);
v.passed_at = Some(now_iso());
v.reason = "10800 s compared".to_owned();
v.brain_ms = 10_800_000.0;
v.end_window("trace-2.jsonl", "byte-cap".to_owned());
let j = v.to_json();
assert_eq!(j["status"], "running");
assert!(j["passedAt"].is_null());
assert_eq!(j["compared"]["brainSeconds"], 0.0);
assert_eq!(j["window"]["lastStopTrace"], "trace-2.jsonl");
// The cutover rule refuses it on any count.
let now = parse_iso(&now_iso()).unwrap();
let binaries: std::collections::BTreeMap<String, String> = Default::default();
let release = Release { dir: "/opt/fly/releases/test", binaries: &binaries };
assert!(allows_cutover(&j, "flysim-session", &release, "c", now, 300).is_err());
let mut forced = j.clone();
forced["status"] = json!("pass");
assert!(allows_cutover(&forced, "flysim-session", &release, "c", now, 300).is_err());
// Diverged stays diverged.
let mut d = verdict_struct(Status::Diverged);
d.end_window("trace-3.jsonl", "no-consumer".to_owned());
assert_eq!(d.status, Status::Diverged);
}
#[test] #[test]
fn the_cutover_rule() { fn the_cutover_rule() {
let now = parse_iso(&now_iso()).unwrap(); let now = parse_iso(&now_iso()).unwrap();
@ -693,10 +540,6 @@ mod tests {
let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300); let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300);
let pass = verdict(Status::Pass, 10_800_000.0); let pass = verdict(Status::Pass, 10_800_000.0);
assert_eq!(ok(&pass), Ok(())); assert_eq!(ok(&pass), Ok(()));
// A verdict that does not say where its window starts is an older shadow's (B2).
let mut undated = pass.clone();
undated.as_object_mut().unwrap().remove("window");
assert!(ok(&undated).is_err());
// Another binary, another release, a changed file in it. // Another binary, another release, a changed file in it.
assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err()); assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err());
let moved = Release { let moved = Release {

View file

@ -217,7 +217,6 @@ fn config(
binary_sha256: "test".to_owned(), binary_sha256: "test".to_owned(),
binaries: Default::default(), binaries: Default::default(),
release: String::new(), release: String::new(),
run_id_file: None,
} }
} }
@ -569,57 +568,4 @@ fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() {
assert_eq!(d.kind, "boot", "{}", d.detail); assert_eq!(d.kind, "boot", "{}", d.detail);
assert!(d.detail.contains("restore gate"), "{}", d.detail); assert!(d.detail.contains("restore gate"), "{}", d.detail);
assert!(got.skipped.is_empty()); assert!(got.skipped.is_empty());
// r3 N5: a declared reward pulse ends the comparison of its trace, but a stop later in the
// same trace (here the byte cap) must still end the window: what was compared before the
// pulse, and the untraced time after the stop, must not count toward a pass.
let full_brain_seconds = verdict.brain_seconds();
let at = tampered(&dirs.trace, &neg.join("reward/trace"), |n, v| {
(n == 100)
.then(|| v["behaviour"]["admissions"] = serde_json::json!([{"kind": "reward"}]))
.is_some()
});
let files = transitions(&neg.join("reward/trace"));
let (first_name, second_n) = (
files[0].0.file_name().unwrap().to_string_lossy().into_owned(),
files[1].1,
);
{
use std::io::Write;
let mut f = std::fs::OpenOptions::new().append(true).open(&files[0].0).unwrap();
writeln!(f, "{{\"truncated\":true,\"reason\":\"byte-cap\"}}").unwrap();
}
let _ = std::fs::remove_dir_all(neg.join("reward").join("out"));
let reward_config = self::config(&rom, &neg.join("reward"), &neg.join("reward/trace"), (&empty, &empty), &spool);
let out = reward_config.out_dir.clone();
let stop = StopFlag::default();
let handle = spawn_shadow(reward_config, stop.clone());
let deadline = Instant::now() + Duration::from_secs(600);
loop {
let v = verdict_of(&out);
let ended = !v["window"]["ends"].as_array().is_none_or(|e| e.is_empty());
if (ended && v["compared"]["transitions"].as_u64() >= Some(101 + second_n as u64))
|| handle.is_finished()
|| Instant::now() > deadline
{
break;
}
std::thread::sleep(Duration::from_millis(100));
}
stop.request();
let (ended, verdict) = handle.join().unwrap().expect("the shadow ran");
assert_ne!(ended, Ended::Diverged, "{:?}", verdict.reason);
let j = verdict.to_json();
eprintln!("reward then stop (reward at step {at}): {j}");
assert_eq!(j["skipped"][0]["kind"], "operator-reward-pulse", "{j}");
assert_eq!(j["window"]["lastStopTrace"], first_name.as_str(), "{j}");
assert_eq!(j["window"]["ends"][0]["trace"], first_name.as_str(), "{j}");
assert!(j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap() > 0.0, "{j}");
// Only the second process counts, after the window ended: what the first one compared before
// the pulse is dropped and its uncompared remainder never was added, so less than the whole.
let whole = full_brain_seconds;
let after = j["compared"]["brainSeconds"].as_f64().unwrap();
let dropped = j["window"]["ends"][0]["discardedBrainSeconds"].as_f64().unwrap();
assert!(after + dropped < whole - 1.0, "{after} + {dropped} against {whole}: {j}");
assert_ne!(j["status"], "pass", "{j}");
} }

View file

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

View file

@ -1,438 +0,0 @@
//! SHADOW-02 end to end on one machine, on the committed toy connectome in raw mode (an explicit
//! ROM job: `FLY_ROM`).
//!
//! The *real* `flysim` service writes its trace into a "container" directory; the relay
//! (`fly_legacy_session::shadow::relay`) streams it and the live saves through the *real*
//! `fly-shadow ingest` binary (over pipes where production has ssh) into a "box" mirror; the
//! remote shadow (`shadow::run` with a run id file) follows the mirror; the relay writes the
//! verdict back and keeps flysim's consumer heartbeat fresh only while all of that is healthy.
//!
//! 1. A fresh fly and a restart, with sugar: the box's `pass` arrives on the container side with
//! this run's id, and finished trace files are removed on the container too.
//! 2. The remote shadow dies: the relay stops the heartbeat and flysim stops its trace; a new
//! shadow starts a new window, ends its window at that stop (which predates it; B2),
//! and follows the next process.
//! 3. The sync stalls (the ingest is stopped): the heartbeat goes stale, flysim stops its trace
//! (`no-consumer`); once the sync is back the box sees the gap and fails the verdict as a
//! `coverage` divergence, the relay brings it and `divergence.json` back and exits.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use serde_json::Value;
use fly_legacy_session::shadow::{
self, Ended, ShadowConfig, StopFlag,
relay::{self, RelayConfig, RelayEnd},
release,
};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use flysim::snapshot::MacroMode;
/// The `flysim` binary built from this tree (see `tests/shadow.rs`).
fn flysim_binary() -> Option<PathBuf> {
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<f64> {
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<Result<(Ended, shadow::verdict::Verdict), String>> {
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::time::SystemTime> {
std::fs::metadata(path).ok()?.modified().ok()
}
#[test]
fn the_remote_shadow_follows_through_the_relay_and_fails_closed() {
let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
return;
};
let Some(flysim) = flysim_binary() else {
return;
};
let tmp = tempfile::tempdir().unwrap();
let kept = std::env::var_os("FLY_SHADOW_TEST_DIR").map(PathBuf::from);
if let Some(dir) = &kept {
let _ = std::fs::remove_dir_all(dir);
std::fs::create_dir_all(dir).unwrap();
}
let root = kept.unwrap_or_else(|| tmp.path().to_owned());
let container = root.join("container");
let mirror = root.join("box");
for d in ["trace", "hot", "durable", "shadow"] {
std::fs::create_dir_all(container.join(d)).unwrap();
}
let consumer = container.join("trace").join(flysim::trace::CONSUMER_FILE);
let verdict_path = container.join("shadow/verdict.json");
// The ingest is the real binary; production reaches it through ssh, this test through pipes.
let fly_shadow = PathBuf::from(env!("CARGO_BIN_EXE_fly-shadow"));
let pid_file = root.join("ingest.pid");
let script = format!(
"echo $$ > {}; exec {} ingest --root {}",
pid_file.display(),
fly_shadow.display(),
mirror.display()
);
let release_dir = release::this_release_of(&fly_shadow);
let run_id = "1790000000000".to_owned();
let mut config = RelayConfig::with_defaults(
container.join("trace"),
container.join("hot"),
container.join("durable"),
container.join("shadow"),
vec!["sh".to_owned(), "-c".to_owned(), script],
run_id.clone(),
);
config.release = release_dir.display().to_string();
config.binaries = release::binaries_in(&release_dir).unwrap();
config.env = [("FLY_MACRO_MODE".to_owned(), "raw".to_owned())].into();
config.tick = Duration::from_millis(50);
config.beat_every = Duration::from_secs(1);
config.alive_within = Duration::from_secs(5);
config.stall = Duration::from_secs(5);
config.reconnect_after = Duration::from_secs(1);
// The run id is the start's Unix ms: everything of this test is newer.
config.run_id = run_id.clone();
let relay_stop = StopFlag::default();
let relay = {
let (config, stop) = (config.clone(), relay_stop.clone());
std::thread::spawn(move || relay::run(config, stop))
};
wait_for("the ingest to write the run id", 120, || {
shadow::read_run_id(&mirror.join("run-id")).as_deref() == Some(run_id.as_str())
});
assert_eq!(
std::fs::read_to_string(mirror.join("live.env")).unwrap(),
"FLY_MACRO_MODE=raw\n",
"only the forwarded composition settings reach the box"
);
let shadow_stop = StopFlag::default();
let shadow = spawn_shadow(box_shadow(&rom, &mirror), shadow_stop.clone());
wait_for("the relay's heartbeat (box shadow alive)", 60, || {
consumer.is_file()
});
// 1. A fresh fly with sugar, and a restart.
let live = Live::start(&flysim, &rom, &container, &root.join("flysim-1.log"));
live.sugar(300);
live.run_for(8_000.0);
live.sugar(600);
live.run_for(8_000.0);
live.stop();
let first_file = shadow::follow::trace_files(&container.join("trace")).unwrap()[0].clone();
let live = Live::start(&flysim, &rom, &container, &root.join("flysim-2.log"));
live.sugar(450);
live.run_for(12_000.0);
live.stop();
wait_for("the box's pass, over both processes and all sugar", 300, || {
let v = json_of(&verdict_path);
assert_ne!(v["status"], "diverged", "{v}");
v["status"] == "pass"
&& v["compared"]["segments"].as_u64() >= Some(2)
&& v["compared"]["sugar"].as_u64() >= Some(3)
});
let v = json_of(&verdict_path);
eprintln!("relayed verdict: {}", serde_json::to_string_pretty(&v).unwrap());
assert_eq!(v["runId"], run_id.as_str());
assert!(v["firstDivergence"].is_null());
assert!(v["relay"]["unsyncedBytes"].is_u64(), "{v}");
assert!(v["compared"]["segments"].as_u64().unwrap() >= 2);
assert!(v["compared"]["sugar"].as_u64().unwrap() >= 3);
assert!(v["compared"]["checkpoints"]["identical"].as_u64().unwrap() >= 3);
wait_for("the finished first file removed on the container", 60, || {
!first_file.exists()
});
let relay_json = json_of(&container.join("shadow/relay.json"));
assert_eq!(relay_json["healthy"], true, "{relay_json}");
// 2. The remote shadow dies: no more heartbeat on the container, so flysim stops its trace.
let live = Live::start(&flysim, &rom, &container, &root.join("flysim-3.log"));
live.run_for(3_000.0);
shadow_stop.request();
let (ended, _) = shadow.join().unwrap().expect("the shadow ran");
assert_eq!(ended, Ended::Stopped);
std::thread::sleep(Duration::from_secs(7));
let beat = mtime(&consumer);
std::thread::sleep(Duration::from_secs(4));
assert_eq!(
mtime(&consumer),
beat,
"the relay must not beat for a dead remote shadow"
);
let second_file = shadow::follow::trace_files(&container.join("trace"))
.unwrap()
.pop()
.unwrap();
let mirrored = mirror.join("trace").join(second_file.file_name().unwrap());
wait_for("the trace stopped (no consumer) and mirrored", 120, || {
std::fs::read_to_string(&mirrored).is_ok_and(|t| t.contains("\"no-consumer\""))
});
// A new shadow (its unit's restart) starts a new window on the same run.
let started_before = json_of(&verdict_path)["startedAt"].clone();
let shadow_stop = StopFlag::default();
let shadow = spawn_shadow(box_shadow(&rom, &mirror), shadow_stop.clone());
wait_for("the heartbeat again", 60, || mtime(&consumer) != beat);
wait_for("the new window relayed", 60, || {
json_of(&verdict_path)["startedAt"] != started_before
});
live.stop();
// The stop happened before this shadow: it ends the window (nothing before it counts), it is
// not a skip.
wait_for("the stopped file to end the window", 120, || {
json_of(&verdict_path)["window"]["ends"]
.as_array()
.is_some_and(|e| !e.is_empty())
});
assert!(
json_of(&verdict_path)["skipped"]
.as_array()
.is_some_and(|s| s.iter().all(|k| k["kind"] != "trace-cap"))
);
let live = Live::start(&flysim, &rom, &container, &root.join("flysim-4.log"));
live.run_for(3_000.0);
wait_for("the new window comparing the next process", 120, || {
json_of(&verdict_path)["compared"]["transitions"].as_u64() > Some(0)
});
assert!(json_of(&verdict_path)["firstDivergence"].is_null());
// B2: the replayed stopped trace's brain time was discarded at its stop; the verdict counts
// only the process after the gap.
{
let v = json_of(&verdict_path);
let discarded = v["window"]["ends"][0]["discardedBrainSeconds"]
.as_f64()
.unwrap();
let compared = v["compared"]["brainSeconds"].as_f64().unwrap();
assert!(
discarded > 0.0,
"the stopped trace had brain time before the gap: {v}"
);
assert!(
compared < discarded,
"{compared} s counted after the gap, {discarded} s before it must not count: {v}"
);
}
// 3. The sync stalls: the ingest stops reading.
let pid = std::fs::read_to_string(&pid_file).unwrap().trim().to_owned();
Command::new("kill").args(["-STOP", &pid]).status().unwrap();
let live_file = shadow::follow::trace_files(&container.join("trace"))
.unwrap()
.pop()
.unwrap();
wait_for("flysim to stop its trace for want of a consumer", 180, || {
std::fs::read_to_string(&live_file).is_ok_and(|t| t.contains("\"no-consumer\""))
});
// The relay never blocks on the stalled link: it keeps reporting, and says it is not healthy.
wait_for("relay.json to say the stalled relay is not healthy", 60, || {
json_of(&container.join("shadow/relay.json"))["healthy"] == false
});
// The sync comes back (a new connection): the box sees the gap.
Command::new("kill").args(["-KILL", &pid]).status().unwrap();
let end = relay.join().unwrap().expect("the relay ran");
assert_eq!(end, RelayEnd::Diverged, "the relay exits on the remote divergence");
let v = json_of(&verdict_path);
assert_eq!(v["status"], "diverged", "{v}");
assert_eq!(v["firstDivergence"]["kind"], "coverage", "{v}");
assert!(
container.join("shadow/divergence.json").is_file(),
"divergence.json comes back"
);
assert!(!consumer.exists(), "a stopped relay leaves no heartbeat");
let (ended, verdict) = shadow.join().unwrap().expect("the shadow ran");
assert_eq!(ended, Ended::Diverged, "{}", verdict.reason);
live.stop();
drop(relay_stop);
}