infra: the shadow's live-impact guard (SHADOW-01 review N2, N1)

fly-shadow-run start records the live fly's baseline (fly_realtime_factor
over 10 s, fly_lag_seconds, uptime), waits for the shadow's heartbeat and
starts flyshadow-guard.timer. fly-shadow-run guard (every 60 s, root)
stops the shadow and the guard, removes the trace drop-in and restarts
flysim without the trace when fly_lag_seconds grew 1 s in the same
process or the mean realtime factor fell below min(0.97, baseline-0.03);
a paused fly is not judged, a restarted one rebaselines. check passes
--current /opt/fly/current --binary flysim-session. lint drives the
guard's rule on six cases. Runbook rewritten: the trace cannot outlive
the shadow (heartbeat, 8 GiB directory cap), not the old claim.
This commit is contained in:
acamilo 2026-09-29 22:15:38 +00:00
parent e085876d79
commit 2d8b529f42
6 changed files with 270 additions and 51 deletions

View file

@ -1,39 +1,120 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# infra/bin/fly-shadow-run — start, stop and read SHADOW-01's shadow run on the release container. # infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
# Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the container, by the # container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
# coordinator, with the container claimed in the host's agent claim log (one agent at a time). # container, by the coordinator, with the container claimed in the host's agent claim log (one
# agent at a time).
# #
# fly-shadow-run start turn flysim's trace on, start flyshadow.service, restart flysim once # fly-shadow-run start baseline the live fly, turn flysim's trace on, start flyshadow.service
# fly-shadow-run stop stop flyshadow.service, turn the trace off (at flysim's next restart; # and the live-impact guard, restart flysim once
# --restart-flysim restarts it now), remove the trace and the spool # fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
# restart; --restart-flysim restarts it now), remove trace and spool
# fly-shadow-run status the verdict in one screen # fly-shadow-run status the verdict in one screen
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover # fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
# into the release /opt/fly/current points to, onto flysim-session
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
# without the trace if the live fly pays for the shadow
# fly-shadow-run decide BASELINE SAMPLE the guard's rule on two JSON files (lint tests it)
# #
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once, # The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the # the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can # ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
# only follow a process from that process's own startup save. # only follow a process from that process's own startup save.
# #
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
# it has compared.
#
# The guard (N2 of the SHADOW-01 review). `start` records the live fly's baseline first: the mean
# fly_realtime_factor over 10 s, fly_lag_seconds and fly_uptime_seconds. Every minute the guard
# samples again and TRIPS when, while flysim is running (not paused, booting or recovering):
# - fly_lag_seconds grew by at least GUARD_LAG_SECONDS (1 s) in the same flysim process -- the
# loop fell more than a second behind real time; a new process restarts the count from 0; or
# - the 10-s mean fly_realtime_factor is below min(0.97, baseline - 0.03).
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json.
#
# Files (all owned by fly): # Files (all owned by fly):
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (capped at 4 GiB each) # /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/spool/ copies of the live saves, bounded (512 MiB) # /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB)
# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract) # /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract)
# /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
set -euo pipefail set -euo pipefail
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"
BIN=/opt/fly/current/fly-shadow BIN=/opt/fly/current/fly-shadow
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
# The ledger digest period in transitions: about one a second. Every boundary is proved in the # The ledger digest period in transitions: about one a second. Every boundary is proved in the
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work. # offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}" LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
GUARD_LAG_SECONDS="${FLY_SHADOW_GUARD_LAG_SECONDS:-1}"
die() { echo "fly-shadow-run: $*" >&2; exit 2; } die() { echo "fly-shadow-run: $*" >&2; exit 2; }
log() { echo "fly-shadow-run: $*"; } log() { echo "fly-shadow-run: $*"; }
need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; } need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }
# One JSON sample of the live fly: {status, rtMean, lag, uptime}, the realtime factor averaged
# over 10 one-second reads.
sample() {
python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url = sys.argv[1], sys.argv[2]
def metrics():
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
out = {}
for line in text.splitlines():
if line.startswith("#"):
continue
parts = line.split()
if len(parts) == 2:
try:
out[parts[0]] = float(parts[1])
except ValueError:
pass
return out
factors = []
for _ in range(10):
factors.append(metrics().get("fly_realtime_factor", 0.0))
time.sleep(1)
m = metrics()
try:
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
status = None
print(json.dumps({"status": status, "rtMean": sum(factors) / len(factors),
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}
# The guard's rule: BASELINE and SAMPLE are JSON files. Prints "ok", "rebaseline <json>" (a new
# flysim process: the lag count restarts) or "trip <reason>"; exit 0, 0 or 1.
decide() {
python3 - "$1" "$2" "$GUARD_LAG_SECONDS" <<'PY'
import json, sys
base = json.load(open(sys.argv[1])); now = json.load(open(sys.argv[2])); lag_bound = float(sys.argv[3])
if now.get("status") != "running" or now.get("lag") is None or now.get("uptime") is None:
print("ok (flysim is %s: not judged)" % now.get("status")); sys.exit(0)
if now["uptime"] < base["uptime"]:
# A new process (a restart the shadow follows): its lag starts at zero.
base = dict(base, lag=0.0, uptime=now["uptime"])
rebased = True
else:
rebased = False
if now["lag"] - base["lag"] >= lag_bound:
print("trip fly_lag_seconds grew %.1f s since the baseline" % (now["lag"] - base["lag"])); sys.exit(1)
floor = min(0.97, base["rtMean"] - 0.03)
if now["rtMean"] < floor:
print("trip fly_realtime_factor %.3f below %.3f (baseline %.3f)" % (now["rtMean"], floor, base["rtMean"])); sys.exit(1)
print(("rebaseline " + json.dumps(base)) if rebased else "ok"); sys.exit(0)
PY
}
start() { start() {
need_root need_root
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01" [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
@ -43,19 +124,43 @@ start() {
if [ -f "$SHADOW_DIR/verdict.json" ]; then if [ -f "$SHADOW_DIR/verdict.json" ]; then
mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json" mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
fi fi
rm -f "$SHADOW_DIR/divergence.json" rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
log "recording the live fly's baseline (10 s)"
local base
base="$(sample)" || die "could not read flysim's metrics for the baseline"
python3 -c 'import json,sys; b=json.loads(sys.argv[1]); assert b["status"]=="running" and b["lag"] is not None, b' "$base" \
|| die "flysim is not running normally; not starting the shadow ($base)"
printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
chown fly:fly "$SHADOW_DIR/baseline.json"
log "baseline: $base"
mkdir -p "$DROPIN_DIR" mkdir -p "$DROPIN_DIR"
cat > "$DROPIN" <<EOF cat > "$DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop. # written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service] [Service]
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace 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
systemctl start flyshadow.service systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat.
for _ in $(seq 1 60); do
[ -f "$SHADOW_DIR/trace/consumer" ] && break
sleep 1
done
[ -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
log "started. Read progress with: fly-shadow-run status" systemctl start flyshadow-guard.timer
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
}
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
stop_all() {
systemctl stop flyshadow-guard.timer 2>/dev/null || true
systemctl stop flyshadow.service 2>/dev/null || true
rm -f "$DROPIN"
systemctl daemon-reload
log "stopped the shadow: $1"
} }
stop() { stop() {
@ -68,26 +173,50 @@ stop() {
*) die "stop: unknown option $arg" ;; *) die "stop: unknown option $arg" ;;
esac esac
done done
systemctl stop flyshadow.service || true stop_all "fly-shadow-run stop"
rm -f "$DROPIN"
systemctl daemon-reload
if [ "$restart_flysim" = 1 ]; then if [ "$restart_flysim" = 1 ]; then
systemctl restart flysim.service systemctl restart flysim.service
log "flysim.service restarted without the trace" log "flysim.service restarted without the trace"
else else
log "flysim keeps writing its current trace file until its next restart (capped at 4 GiB)" log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
fi fi
rm -f "$SHADOW_DIR/baseline.json"
if [ "$keep" = 0 ]; then if [ "$keep" = 0 ]; then
rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work" rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
# The running flysim still holds its file open; removing the name frees the space when it
# exits, and a restarted flysim writes no new one.
find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
fi fi
log "stopped; the verdict stays in $SHADOW_DIR/verdict.json" log "the verdict stays in $SHADOW_DIR/verdict.json"
}
guard() {
need_root
[ -f "$SHADOW_DIR/baseline.json" ] || { log "no baseline: nothing to guard"; exit 0; }
local now tmp verdict
now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
tmp="$(mktemp)"
printf '%s\n' "$now" > "$tmp"
if verdict="$(decide "$SHADOW_DIR/baseline.json" "$tmp")"; then
case "$verdict" in
rebaseline*) printf '%s\n' "${verdict#rebaseline }" > "$SHADOW_DIR/baseline.json" ;;
esac
rm -f "$tmp"
log "guard: $verdict ($now)"
exit 0
fi
rm -f "$tmp"
log "guard TRIPPED: $verdict ($now)"
stop_all "guard: $verdict"
rm -f "$SHADOW_DIR/baseline.json"
python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
"$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
systemctl restart flysim.service
log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
} }
status() { status() {
systemctl is-active flyshadow.service || true systemctl is-active flyshadow.service || true
systemctl is-active flyshadow-guard.timer || true
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
[ -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
@ -98,7 +227,7 @@ print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f
f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}") f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, " print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}") f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
print(f" checkpoints {c['checkpoints']}; skipped {len(v['skipped'])}; spool evicted {v['spoolEvicted']}") print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}") print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
if v["firstDivergence"]: if v["firstDivergence"]:
print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}") print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
@ -112,8 +241,9 @@ check() {
# shellcheck disable=SC1091 # shellcheck disable=SC1091
. /etc/fly/fly.env . /etc/fly/fly.env
set +a set +a
# The binary CUT-01 switches to: SERVE-01's session runtime, from the release the shadow ran in. # The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" "$@" "$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \
--binary flysim-session "$@"
} }
cmd="${1:-}" cmd="${1:-}"
@ -123,5 +253,7 @@ case "$cmd" in
stop) stop "$@" ;; stop) stop "$@" ;;
status) status ;; status) status ;;
check) check "$@" ;; check) check "$@" ;;
*) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]" >&2; exit 2 ;; guard) guard ;;
decide) [ $# = 2 ] || die "decide BASELINE SAMPLE"; decide "$1" "$2" ;;
*) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|decide BASELINE SAMPLE" >&2; exit 2 ;;
esac esac

View file

@ -451,40 +451,63 @@ 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 # trace on, flyshadow.service, 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 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 off, trace off pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
``` ```
- **Start** installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`, - **Start** first records the live fly's baseline over 10 s: `fly_realtime_factor`,
`FLY_TRACE_LEDGERS=60`), starts `flyshadow.service`, and restarts `flysim.service` once. The `fly_lag_seconds` and `fly_uptime_seconds`. It refuses unless flysim is running normally. Then it:
restart is the same one the unstick rule uses: the rung is kept and the ledgers are cleared. It 1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
is needed because flysim reads the trace switches only at start, and because the shadow can only `FLY_TRACE_LEDGERS=60`);
follow a process from that process's own startup save. A previous `verdict.json` is kept beside 2. starts `flyshadow.service` and waits for its heartbeat;
the new one, renamed with its time. 3. restarts `flysim.service` once;
4. starts `flyshadow-guard.timer`.
The restart is the same one the unstick rule uses: the rung is kept and the ledgers are
cleared. A previous `verdict.json` is kept beside the new one, renamed with its time.
- **The guard** (every 60 s, automatic) stops the shadow and the guard, removes the drop-in and
restarts flysim without the trace. It does this as soon as either of these happens while flysim
runs (a paused fly is not judged):
- `fly_lag_seconds` grows by 1 s in the same flysim process;
- the 10-s mean `fly_realtime_factor` falls below min(0.97, baseline - 0.03).
It records why in `/srv/fly/shadow/guard-tripped.json`, and `status` shows it. The live stream
never pays for the shadow. A trip is not a divergence: fix the resources, then `start` again.
- **While it runs**, every later flysim restart (the unstick rule, the watchdog, - **While it runs**, every later flysim restart (the unstick rule, the watchdog,
`fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on `fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on
its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes. its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes.
Stopping or restarting `flyshadow.service` itself starts the window again. Stopping or restarting `flyshadow.service` itself starts the window again.
- **Pass**: `status` shows `verdict pass` once 10,800 brain seconds are compared with zero - **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence:
divergence. The shadow keeps following, and the verdict stays `pass` only while nothing - 10,800 brain seconds are compared;
diverges. CUT-01 reads it with `check` at the moment it cuts over. - at least one live save per 10 brain minutes has been compared byte for byte.
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). It leaves
`verdict.json` at `diverged` and `/srv/fly/shadow/divergence.json` with the field, both values The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01
and the 30 transitions before it. The live fly is untouched. Keep the trace and spool for the runs `check` at the moment it cuts over. `check` also requires all of these:
review (`stop --keep`), pull `divergence.json`, and do not cut over. - the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
other shadowed binary unchanged;
- the shadow is caught up (at most about a minute behind);
- no segment was skipped for a reason other than the live side's own.
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure
of the session runtime itself counts: it did not start, the restore gate refused the live save,
or a step failed. The shadow leaves `verdict.json` at `diverged` and
`/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it.
On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so
flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the
files for the review, and do not cut over.
- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
deletes every file it has compared.
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It - **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It
runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its
`cpuset.conf`). It also pauses for a minute whenever flysim's `fly_lag_seconds` grows, which `cpuset.conf`), and pauses for a minute whenever flysim's `fly_lag_seconds` grows. Disk: about
happens when the live loop has fallen more than a second behind. If the stream 160 MB of trace per live hour, and a spool of at most 512 MiB.
stutters while it runs, stop it: `stop --restart-flysim`. Disk: about 170 MB of trace per live - **Stop** stops the unit and the guard, removes the drop-in, and deletes the trace and the spool
hour (about 850 bytes a frame). A process's file is deleted once the shadow has compared it, (`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
when the next process starts. The spool holds at most 512 MiB. Each trace file is capped at within a minute, because its consumer is gone.
4 GiB, so a forgotten trace cannot fill the disk.
- **Stop** stops the unit, removes the drop-in, and deletes the trace and the spool (`--keep`
keeps them). Without `--restart-flysim`, the running flysim keeps writing its current file until
its next restart.
## CPU partition (cpuset) ## CPU partition (cpuset)

View file

@ -552,6 +552,39 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR
else else
pass "07-enable.sh and verify.sh leave flyshadow.service alone" pass "07-enable.sh and verify.sh leave flyshadow.service alone"
fi fi
for u in flyshadow-guard.timer flyshadow-guard.service; do
if [ ! -f "$INFRA_DIR/units/$u" ]; then
fail "units/$u is missing"
elif grep -qE '^\[Install\]' "$INFRA_DIR/units/$u"; then
fail "$u has an [Install] section; fly-shadow-run starts and stops it"
else
pass "$u is never enabled (started by fly-shadow-run only)"
fi
done
# The guard's rule, driven for real (python3 is on every container this repo provisions).
if command -v python3 >/dev/null 2>&1; then
g_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-guard.XXXXXX")"
printf '%s\n' '{"status":"running","rtMean":1.0,"lag":3.0,"uptime":1000}' > "$g_tmp/base"
guard_case() { # name, sample json, expected exit, expected output prefix
printf '%s\n' "$2" > "$g_tmp/now"
local out rc=0
out="$("$INFRA_DIR/bin/fly-shadow-run" decide "$g_tmp/base" "$g_tmp/now")" || rc=$?
if [ "$rc" = "$3" ] && [ "${out#"$4"}" != "$out" ]; then
pass "fly-shadow-run guard: $1"
else
fail "fly-shadow-run guard: $1 (exit $rc, '$out')"
fi
}
guard_case "steady live fly is ok" '{"status":"running","rtMean":0.995,"lag":3.0,"uptime":1060}' 0 ok
guard_case "lag growth trips" '{"status":"running","rtMean":1.0,"lag":4.2,"uptime":1060}' 1 trip
guard_case "a realtime-factor drop trips" '{"status":"running","rtMean":0.9,"lag":3.0,"uptime":1060}' 1 trip
guard_case "a paused fly is not judged" '{"status":"paused","rtMean":0.0,"lag":9.0,"uptime":1060}' 0 ok
guard_case "a restarted flysim rebaselines its lag" '{"status":"running","rtMean":1.0,"lag":0.0,"uptime":30}' 0 rebaseline
guard_case "a restarted flysim that already lags trips" '{"status":"running","rtMean":1.0,"lag":1.5,"uptime":30}' 1 trip
rm -rf "$g_tmp"
else
fail "python3 is needed to test fly-shadow-run's guard rule"
fi
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

@ -0,0 +1,15 @@
# infra/units/flyshadow-guard.service — triggered by flyshadow-guard.timer.
#
# `fly-shadow-run guard` compares the live fly with the baseline `fly-shadow-run start` recorded
# before it started the shadow: if flysim's fly_lag_seconds has grown (the loop fell more than a
# second behind real time) or its mean fly_realtime_factor over 10 s fell below the baseline's
# bound, it stops flyshadow.service, removes the trace drop-in and restarts flysim without the
# trace. The live stream never pays for the shadow. Root, because it installs no file but
# removes one in /etc/systemd and restarts flysim.
[Unit]
Description=fly-shadow-run guard: the live-impact check of the shadow run (SHADOW-01)
ConditionPathExists=/srv/fly/shadow/baseline.json
[Service]
Type=oneshot
ExecStart=/opt/fly/bin/fly-shadow-run guard

View file

@ -0,0 +1,11 @@
# infra/units/flyshadow-guard.timer — SHADOW-01's live-impact guard, every 60 s while a shadow
# runs. Started by `fly-shadow-run start`, stopped by `fly-shadow-run stop` and by the guard
# itself when it trips. No [Install]: it is never enabled, so a reboot does not start it.
[Unit]
Description=Stop the shadow run if the live fly pays for it (SHADOW-01)
[Timer]
OnActiveSec=60s
OnUnitActiveSec=60s
AccuracySec=5s
Unit=flyshadow-guard.service

View file

@ -21,10 +21,15 @@
# fly, the page or the encoder wants, so it runs SCHED_IDLE (it only gets CPU # fly, the page or the encoder wants, so it runs SCHED_IDLE (it only gets CPU
# nobody else is using), off flysim's cpuset (05-deploy.sh writes # nobody else is using), off flysim's cpuset (05-deploy.sh writes
# AllowedCPUs= for it from the page and encoder groups), and it pauses for a # AllowedCPUs= for it from the page and encoder groups), and it pauses for a
# minute whenever flysim's own fly_lag_seconds grows (the live loop fell more # minute whenever flysim's own fly_lag_seconds grows. flyshadow-guard.timer
# than a second behind; `--max-live-lag-seconds`). It is lag-tolerant: the # (fly-shadow-run guard) stops it and restarts flysim without the trace if
# trace and the spool are on disk, so running behind real time only delays # the live fly loses real time anyway. It is lag-tolerant: the trace and the
# the verdict (the 512 MiB spool covers about 15 minutes of lag for hot saves). # spool are on disk, so running behind real time only delays the verdict (the
# 512 MiB spool covers about 15 minutes of lag for hot saves).
#
# Its heartbeat (<trace dir>/consumer, every 30 s, removed when it stops) is
# what keeps flysim tracing: a stopped, diverged or crashed shadow turns the
# live trace off within a minute of a stale heartbeat, with no root action.
[Unit] [Unit]
Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only) Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only)
After=flysim.service After=flysim.service