From 095cf7b1dadf177b0293a50ff7f760617ed77994 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 21:19:40 +0000 Subject: [PATCH] infra: flyshadow.service and fly-shadow-run (SHADOW-01) Report-only unit, off by default, not bound to flysim, SCHED_IDLE on the page and encoder CPUs, stays stopped after a divergence (exit 3). fly-shadow-run start|stop|status|check installs the flysim trace drop-in, restarts flysim once and reads the verdict. Deploy, build and packaging ship fly-shadow and fly-session; lint holds the unit to its rules; the runbook has a Shadow run section. --- infra/05-deploy.sh | 8 ++- infra/bin/fly-shadow-run | 127 +++++++++++++++++++++++++++++++++ infra/build/build-flysim.sh | 11 +++ infra/build/package-release.sh | 12 ++++ infra/docs/runbook.md | 43 +++++++++++ infra/tests/lint.sh | 50 +++++++++++++ infra/units/flyshadow.service | 60 ++++++++++++++++ 7 files changed, 309 insertions(+), 2 deletions(-) create mode 100755 infra/bin/fly-shadow-run create mode 100644 infra/units/flyshadow.service diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index c10d480..823464e 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -676,10 +676,14 @@ if [ -n "${CPUSET:-}" ]; then tmp_dropin="$(mktemp)" # flyedge is off by default, but its drop-in is written with the rest so that the day # it is enabled it serves the page from the page's CPUs, never from flysim's. - for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do + # flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not + # flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder + # leave idle and never a cycle of the live fly's. + for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flyshadow; do case "$u" in flysim) cpus="$sim_cpus" ;; flycast) cpus="$encoder_cpus" ;; + flyshadow) cpus="${page_cpus},${encoder_cpus}" ;; *) cpus="$page_cpus" ;; esac { @@ -707,7 +711,7 @@ fi # --------------------------------------------------------------------------- log "05-deploy: converging bin/ helpers to /opt/fly/bin" ct_exec "$CTID" -- mkdir -p /opt/fly/bin -for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do +for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null done diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run new file mode 100755 index 0000000..9b31c46 --- /dev/null +++ b/infra/bin/fly-shadow-run @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# infra/bin/fly-shadow-run — start, stop and read SHADOW-01's shadow run on the release container. +# Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the 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 stop stop flyshadow.service, turn the trace off (at flysim's next restart; +# --restart-flysim restarts it now), remove the trace and the spool +# 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 +# +# 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 +# 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. +# +# Files (all owned by fly): +# /srv/fly/shadow/trace/trace--.jsonl flysim's per-process trace (capped at 4 GiB each) +# /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/divergence.json the first divergence with its context +set -euo pipefail + +SHADOW_DIR=/srv/fly/shadow +DROPIN_DIR=/etc/systemd/system/flysim.service.d +DROPIN="$DROPIN_DIR/shadow-trace.conf" +BIN=/opt/fly/current/fly-shadow +# 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. +LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}" + +die() { echo "fly-shadow-run: $*" >&2; exit 2; } +log() { echo "fly-shadow-run: $*"; } + +need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; } + +start() { + need_root + [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01" + systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running" + 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. + if [ -f "$SHADOW_DIR/verdict.json" ]; then + mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json" + fi + rm -f "$SHADOW_DIR/divergence.json" + mkdir -p "$DROPIN_DIR" + cat > "$DROPIN" </dev/null || true + fi + log "stopped; the verdict stays in $SHADOW_DIR/verdict.json" +} + +status() { + systemctl is-active flyshadow.service || true + [ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; } + python3 - "$SHADOW_DIR/verdict.json" <<'PY' +import json, sys +v = json.load(open(sys.argv[1])) +c = v["compared"] +print(f"verdict {v['status']}: {v['reason']}") +print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s " + f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}") +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']}") +print(f" checkpoints {c['checkpoints']}; skipped {len(v['skipped'])}; spool evicted {v['spoolEvicted']}") +print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}") +if v["firstDivergence"]: + print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}") +PY +} + +check() { + [ -x "$BIN" ] || die "$BIN is missing" + # The live service's configuration, for its compatibility string. + set -a + # shellcheck disable=SC1091 + . /etc/fly/fly.env + set +a + # The binary CUT-01 switches to: SERVE-01's session runtime, from the release the shadow ran in. + "$BIN" check --verdict "$SHADOW_DIR/verdict.json" "$@" +} + +cmd="${1:-}" +[ $# -gt 0 ] && shift +case "$cmd" in + start) start ;; + stop) stop "$@" ;; + status) status ;; + check) check "$@" ;; + *) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]" >&2; exit 2 ;; +esac diff --git a/infra/build/build-flysim.sh b/infra/build/build-flysim.sh index 3a56ca7..6abb4d8 100755 --- a/infra/build/build-flysim.sh +++ b/infra/build/build-flysim.sh @@ -85,6 +85,10 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw # without a rebuild. It lands next to OUT_PATH, where package-release.sh # looks for it. RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge + # fly-shadow (SHADOW-01, infra/units/flyshadow.service): the session runtime shadowing the + # live fly, and fly-session, its worker program for the process execution mode. Both land + # next to OUT_PATH, where package-release.sh looks for them. + RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-shadow --bin fly-session ) built="${crate_dir}/target/${CARGO_TARGET}/release/flysim" @@ -118,4 +122,11 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge" cp "$edge_built" "$edge_out" chmod 0755 "$edge_out" log "built $edge_out ($(du -h "$edge_out" | cut -f1))" +for extra in fly-shadow fly-session; do + extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}" + [ -x "$extra_built" ] || die "expected binary not found after build: $extra_built" + cp "$extra_built" "$(dirname "$OUT_PATH")/${extra}" + chmod 0755 "$(dirname "$OUT_PATH")/${extra}" + log "built $(dirname "$OUT_PATH")/${extra}" +done log "next: infra/build/package-release.sh VERSION $OUT_PATH " diff --git a/infra/build/package-release.sh b/infra/build/package-release.sh index 0610db2..59efae0 100755 --- a/infra/build/package-release.sh +++ b/infra/build/package-release.sh @@ -14,6 +14,9 @@ # fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh # left one beside FLYSIM_BIN; flyedge.service stays # inactive on a release without it) +# fly-shadow, fly-session (SHADOW-01's shadow and its worker program, when +# build-flysim.sh left them; flyshadow.service stays +# inactive on a release without them) # stage/... (apps/stage's build output) # bridge/... (services/bridge + node_modules) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) @@ -82,6 +85,15 @@ if [ -x "$EDGE_BIN" ]; then else log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)" fi +# SHADOW-01: the shadow and its worker program, when build-flysim.sh built them. +for extra in fly-shadow fly-session; do + if [ -x "$(dirname "$FLYSIM_BIN")/${extra}" ]; then + cp "$(dirname "$FLYSIM_BIN")/${extra}" "${release_dir}/${extra}" + chmod 0755 "${release_dir}/${extra}" + else + log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" + fi +done cp -a "$STAGE_DIR" "${release_dir}/stage" cp -a "$BRIDGE_DIR" "${release_dir}/bridge" diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index a8748a2..03f2137 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -443,6 +443,49 @@ One `ln -sfn` plus a restart, per `docs/design/infra.md` section 2. Nothing else touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`. On the release container, `` is a tag (e.g. `v0.1.0`) — "Cutting a release" above. +## Shadow run (SHADOW-01) + +The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The +contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is +report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim +the release container in the host log first, as for any host work. + +``` +pct exec -- /opt/fly/bin/fly-shadow-run start # trace on, flyshadow.service, one flysim restart +pct exec -- /opt/fly/bin/fly-shadow-run status # the verdict in one screen +pct exec -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed +pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow off, trace off +``` + +- **Start** installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`, + `FLY_TRACE_LEDGERS=60`), starts `flyshadow.service`, and restarts `flysim.service` once. The + restart is the same one the unstick rule uses: the rung is kept and the ledgers are cleared. It + is needed because flysim reads the trace switches only at start, and because the shadow can only + follow a process from that process's own startup save. A previous `verdict.json` is kept beside + the new one, renamed with its time. +- **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 + 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. +- **Pass**: `status` shows `verdict pass` once 10,800 brain seconds are compared with zero + divergence. The shadow keeps following, and the verdict stays `pass` only while nothing + diverges. CUT-01 reads it with `check` at the moment it cuts over. +- **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 + and the 30 transitions before it. The live fly is untouched. Keep the trace and spool for the + review (`stop --keep`), pull `divergence.json`, and do not cut over. +- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It + runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its + `cpuset.conf`). It also pauses for a minute whenever flysim's `fly_lag_seconds` grows, which + happens when the live loop has fallen more than a second behind. If the stream + stutters while it runs, stop it: `stop --restart-flysim`. Disk: about 170 MB of trace per live + hour (about 850 bytes a frame). A process's file is deleted once the shadow has compared it, + when the next process starts. The spool holds at most 512 MiB. Each trace file is capped at + 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) `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 82e9897..28d0b51 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -507,6 +507,56 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR else pass "07-enable.sh and verify.sh leave flyedge.service alone" fi +# --------------------------------------------------------------------------- +# 3b3. The shadow run (SHADOW-01, infra/units/flyshadow.service). +# +# Report-only and off by default. What would break it is statically visible: the unit ending up +# in a target or 07-enable's list; being bound to flysim (every flysim restart would take the +# shadow with it, and it must follow restarts, not die of them); restarting after a divergence +# (the verdict must stay); losing its idle scheduling (it must never take a live cycle); or +# landing on flysim's cpuset. +# --------------------------------------------------------------------------- +echo "--- flyshadow.service: off by default, report-only, idle, never bound to flysim ---" +SHADOW_UNIT="$INFRA_DIR/units/flyshadow.service" +if [ ! -f "$SHADOW_UNIT" ]; then + fail "units/flyshadow.service is missing" +else + grep -qE '^ExecStart=/opt/fly/current/fly-shadow run$' "$SHADOW_UNIT" \ + && pass "flyshadow.service runs the release's fly-shadow" \ + || fail "flyshadow.service ExecStart must be /opt/fly/current/fly-shadow run" + grep -qE '^ConditionPathExists=/opt/fly/current/fly-shadow$' "$SHADOW_UNIT" \ + && pass "flyshadow.service stays inactive on a release without fly-shadow" \ + || fail "flyshadow.service needs ConditionPathExists=/opt/fly/current/fly-shadow" + if grep -qE '^(Requires|BindsTo|PartOf|Requisite)=.*flysim' "$SHADOW_UNIT"; then + fail "flyshadow.service must not be bound to flysim.service: it follows flysim's restarts" + else + pass "flyshadow.service outlives flysim restarts (not bound to flysim.service)" + fi + grep -qE '^RestartPreventExitStatus=3$' "$SHADOW_UNIT" \ + && pass "flyshadow.service stays stopped after a divergence (exit 3)" \ + || fail "flyshadow.service needs RestartPreventExitStatus=3 so a diverged verdict stays" + grep -qE '^CPUSchedulingPolicy=idle$' "$SHADOW_UNIT" \ + && pass "flyshadow.service runs SCHED_IDLE" \ + || fail "flyshadow.service must be CPUSchedulingPolicy=idle: it may only use idle CPU" + grep -qE '^\[Install\]' "$SHADOW_UNIT" \ + && fail "flyshadow.service has an [Install] section; it is started by fly-shadow-run only" \ + || pass "flyshadow.service has no [Install] section (never enabled)" +fi +if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flyshadow.service'; then + fail "fly.target pulls flyshadow.service in; it must stay off until fly-shadow-run starts it" +else + pass "fly.target does not pull flyshadow.service in" +fi +if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flyshadow'; then + fail "07-enable.sh or verify.sh lists flyshadow.service as always-on" +else + pass "07-enable.sh and verify.sh leave flyshadow.service alone" +fi +if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then + pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs" +else + fail "05-deploy.sh must give flyshadow.service the page and encoder CPUs, never flysim's" +fi if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \ && grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value" diff --git a/infra/units/flyshadow.service b/infra/units/flyshadow.service new file mode 100644 index 0000000..3e58a92 --- /dev/null +++ b/infra/units/flyshadow.service @@ -0,0 +1,60 @@ +# infra/units/flyshadow.service — pushed to /etc/systemd/system/flyshadow.service. +# +# SHADOW-01 (docs/design/session-framework/legacy-gameboy-v1.md section 18): the +# session runtime run beside the live fly. REPORT-ONLY: it presses no button, +# serves no port, and only READS flysim's stores and trace; it writes nothing +# but /srv/fly/shadow (verdict.json, divergence.json, its spool) and its +# runtime directory. DISABLED BY DEFAULT: in no target's Wants=/Requires=, +# not in 07-enable.sh. `fly-shadow-run start` (infra/bin) starts it, turns +# flysim's trace on and restarts flysim once so the shadow follows a process +# from its first frame; `fly-shadow-run stop` undoes both. +# +# Deliberately NOT bound to flysim (no Requires=/BindsTo=/PartOf=): every +# flysim restart (the unstick rule, the watchdog, fly-loop-recover, a +# milestone reset) is a new trace file the shadow follows on its own, so the +# shadow must outlive them. It stops itself on the first divergence with exit +# status 3 and a `diverged` verdict; RestartPreventExitStatus keeps it +# stopped so the verdict stays for the coordinator to read. +# +# Resources (the SHADOW-01 report, "resource plan"): a second whole brain, +# about the live fly's own CPU per frame. It must never take a cycle the live +# 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 +# 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 +# than a second behind; `--max-live-lag-seconds`). It is lag-tolerant: the +# trace and the 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). +[Unit] +Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only) +After=flysim.service +# A release that predates SHADOW-01 has no binary; stay cleanly inactive. +ConditionPathExists=/opt/fly/current/fly-shadow + +[Service] +Type=simple +User=fly +# The live service's configuration, read the way flysim reads it: the +# cartridge, the dataset, the macro mode, the speed. The store paths and the +# metrics listener are flysim.service's own Environment= lines, repeated. +EnvironmentFile=/etc/fly/fly.env +Environment=FLY_STATE_HOT=/run/fly/state +Environment=FLY_STATE=/srv/fly/state +Environment=FLY_METRICS_ADDR=0.0.0.0:9101 +# What flysim writes with the shadow's drop-in (fly-shadow-run), and where the +# verdict goes. The session's sockets and artifacts live on tmpfs. +Environment=FLY_TRACE_DIR=/srv/fly/shadow/trace +Environment=FLY_SHADOW_DIR=/srv/fly/shadow +Environment=FLY_SHADOW_WORK=/run/fly-shadow +RuntimeDirectory=fly-shadow +# The shadow agent's sweep threads (the report's measurements). +Environment=FLY_SHADOW_THREADS=2 +ExecStart=/opt/fly/current/fly-shadow run +Restart=on-failure +RestartSec=10 +RestartPreventExitStatus=3 +CPUSchedulingPolicy=idle +Nice=19 +CPUWeight=1 +IOSchedulingClass=idle +MemoryMax=3G