diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index dfc81fe..0fff178 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -803,12 +803,20 @@ make sure of it: (`/consumer`) every 30 s and removes it when it stops. flysim starts no trace without a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than 10 minutes old, and keeps the directory under 8 GiB. -- *The guard* (`fly-shadow-run guard`, every 60 s, root) compares the live fly with the baseline - recorded before the shadow started. It stops everything and restarts flysim without the trace - when either of these happens while the fly runs: - - `fly_lag_seconds` grew by a second in the same process; - - the 10-s mean `fly_realtime_factor` fell below min(0.97, baseline - 0.03). -- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs, and pauses while the live lag grows. +- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace + before the shadow existed. The live fly does not always keep real time: the release container + has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start` + first measures a 10-minute baseline: the mean and spread of 10-s `fly_realtime_factor` means, + and the `fly_lag_seconds` growth rate. The guard trips only on a *sustained* degradation against + that baseline: 3 checks in a row in which the last 5 samples of the same process fall below the + baseline realtime factor, or grow lag faster than the baseline rate, by more than + max(0.05, 4 x spread / sqrt 5). A trip stops everything and restarts flysim without the trace. + The guard stops itself when the shadow is not running. `lint.sh` holds the rule to the release + container's profiles, synthesized, and to traces recorded from a real flysim with and without a + shadow. It found no false trip in 600 synthetic 3-hour runs. +- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs. It pauses for a minute while the live lag + grows faster than the baseline rate. When a pause does not help, the shadow is not the cause, + and it stops pausing for 10 minutes. **The verdict contract (for CUT-01).** The shadow writes `verdict.json` in the format `fly-shadow-verdict-v1` (`shadow::verdict`, whose module notes list the fields). CUT-01 cuts over @@ -816,7 +824,8 @@ automatically only if all of the following hold when it reads the file, at the m over: - `status` is `pass` and `firstDivergence` is `null`; -- `compared.brainSeconds` ≥ `required.brainSeconds`. +- `compared.brainSeconds` ≥ `required.brainSeconds`, and never less than the operator's 10,800 s, + whatever window the shadow was run with; - *Saves were compared.* At least one per 600 brain seconds was compared byte for byte, and at most 10 % of those the trace named were unavailable. - *The release.* `candidate.release` is the directory `/opt/fly/current` resolves to now. Every @@ -825,7 +834,9 @@ over: - `candidate.compatibility` is the live `--print-compatibility`; - every `skipped` entry is one of the live side's own kinds; - *the shadow is alive and caught up*: `updatedAt` is at most 5 minutes old and - `lagTransitions` is at most 3,600. + `lagTransitions` is at most 3,600, counted at every write (paused or not) over the rest of the + current file and every newer one; +- (`fly-shadow-run check`) the guard has not tripped and `flyshadow.service` is running. `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 diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run index db5938c..127d71e 100755 --- a/infra/bin/fly-shadow-run +++ b/infra/bin/fly-shadow-run @@ -4,7 +4,7 @@ # container, by the coordinator, with the container claimed in the host's agent claim log (one # agent at a time). # -# fly-shadow-run start baseline the live fly, 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 # 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 @@ -13,7 +13,8 @@ # 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) +# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples +# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give # # 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 @@ -25,14 +26,26 @@ # 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). +# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run +# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset +# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed: +# - `start` first measures a BASELINE over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means +# of fly_realtime_factor (their mean and spread) and the lag growth rate of fly_lag_seconds +# (seconds of lag per wall second: about 1 - RTF when the loop is behind real time). It +# refuses to start on fewer than half the samples running. +# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim +# process (a restart starts the window again) it compares the mean RTF and the lag growth +# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it +# scales with how noisy this fly already was. +# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below +# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it. +# A paused, booting or recovering fly is not judged. +# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples; +# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/). # 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. +# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow +# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own +# timer and changes nothing: it only ever acts against a running shadow. # # Files (all owned by fly): # /srv/fly/shadow/trace/trace--.jsonl flysim's per-process trace (4 GiB each, 8 in all) @@ -40,7 +53,8 @@ # /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 -# /srv/fly/shadow/baseline.json the guard's baseline +# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl) +# /srv/fly/shadow/guard-state.json the guard's recent samples set -euo pipefail SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}" @@ -52,14 +66,14 @@ 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 # offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work. LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}" -GUARD_LAG_SECONDS="${FLY_SHADOW_GUARD_LAG_SECONDS:-1}" +BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}" 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)"; } -# One JSON sample of the live fly: {status, rtMean, lag, uptime}, the realtime factor averaged +# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged # over 10 one-second reads. sample() { python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY' @@ -87,33 +101,92 @@ 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), +print(json.dumps({"t": time.time(), "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 " (a new -# flysim process: the lag count restarts) or "trip "; 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 -} +# The guard's rule, one definition for `baseline`, `decide` and `simulate`. +GUARD_PY=' +import json, math, sys +WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05 + +def running(s): + return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None + +def rate(samples): + """Lag growth per wall second over the longest same-process run of samples.""" + best, run = None, [] + for s in samples: + if run and s["uptime"] < run[-1]["uptime"]: + run = [] + run.append(s) + if len(run) >= 2 and (best is None or len(run) > len(best)): + best = list(run) + if not best or best[-1]["t"] <= best[0]["t"]: + return None + return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"])) + +def baseline(samples): + ok = [s for s in samples if running(s)] + if len(ok) < max(3, len(samples) // 2): + raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples))) + rtf = [s["rtMean"] for s in ok] + mean = sum(rtf) / len(rtf) + sd = math.sqrt(sum((x - mean) ** 2 for x in rtf) / max(1, len(rtf) - 1)) + lag_rate = rate(ok) + return {"rtfMean": mean, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0, + "samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))} + +def decide(base, state, s): + """Returns (state, verdict); the verdict starts with ok or trip.""" + history, run = state.get("history", []), state.get("degradedRun", 0) + if not running(s): + return state, "ok (flysim is %s: not judged)" % s.get("status") + if history and s["uptime"] < history[-1]["uptime"]: + history, run = [], 0 + history = (history + [s])[-WINDOW:] + state = {"history": history, "degradedRun": run} + if len(history) < WINDOW: + state["degradedRun"] = 0 + return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW) + rtf = sum(h["rtMean"] for h in history) / WINDOW + lag_rate = rate(history) or 0.0 + m = base["margin"] + why = [] + if rtf < base["rtfMean"] - m: + why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m)) + if lag_rate > base["lagRate"] + m: + why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m)) + state["degradedRun"] = run + 1 if why else 0 + if state["degradedRun"] >= SUSTAIN: + return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"] + if why: + return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why)) + return state, "ok" + +def load_jsonl(path): + return [json.loads(line) for line in open(path) if line.strip()] + +mode = sys.argv[1] +if mode == "baseline": + print(json.dumps(baseline(load_jsonl(sys.argv[2])))) +elif mode == "decide": + base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3])) + state, verdict = decide(base, state, json.load(open(sys.argv[4]))) + json.dump(state, open(sys.argv[3], "w")) + print(verdict) + sys.exit(1 if verdict.startswith("trip") else 0) +elif mode == "simulate": + base = baseline(load_jsonl(sys.argv[2])) + state, n = {}, 0 + for n, s in enumerate(load_jsonl(sys.argv[3]), 1): + state, verdict = decide(base, state, s) + if verdict.startswith("trip"): + print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base))) + sys.exit(1) + print("no trip over %d checks (baseline %s)" % (n, json.dumps(base))) +' start() { need_root @@ -125,13 +198,20 @@ start() { mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json" fi 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)" + log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists" + local n samples base + n=$(( BASELINE_SECONDS / 10 )) + [ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30" + samples="$SHADOW_DIR/baseline-samples.jsonl" + : > "$samples" + for _ in $(seq 1 "$n"); do + sample >> "$samples" || die "could not read flysim's metrics for the baseline" + done + base="$(python3 -c "$GUARD_PY" baseline "$samples")" \ + || die "flysim did not run normally during the baseline; not starting the shadow" printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json" - chown fly:fly "$SHADOW_DIR/baseline.json" + printf '{}\n' > "$SHADOW_DIR/guard-state.json" + chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json" log "baseline: $base" mkdir -p "$DROPIN_DIR" cat > "$DROPIN" </dev/null || true @@ -190,15 +270,24 @@ stop() { guard() { need_root - [ -f "$SHADOW_DIR/baseline.json" ] || { log "no baseline: nothing to guard"; exit 0; } + if [ ! -f "$SHADOW_DIR/baseline.json" ]; then + log "no baseline: nothing to guard" + systemctl stop flyshadow-guard.timer 2>/dev/null || true + exit 0 + fi + # The guard acts only against a running shadow: one that diverged, stopped or crashed costs + # the live fly nothing more, and flysim stops its trace without the shadow's heartbeat. + if ! systemctl is-active --quiet flyshadow.service; then + log "flyshadow.service is not running: the guard stops itself and changes nothing" + systemctl stop flyshadow-guard.timer 2>/dev/null || true + exit 0 + fi + [ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json" 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 + if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then rm -f "$tmp" log "guard: $verdict ($now)" exit 0 @@ -206,7 +295,7 @@ guard() { rm -f "$tmp" log "guard TRIPPED: $verdict ($now)" stop_all "guard: $verdict" - rm -f "$SHADOW_DIR/baseline.json" + rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.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 @@ -236,6 +325,16 @@ PY check() { [ -x "$BIN" ] || die "$BIN is missing" + # A tripped guard, or a shadow that is not running, never allows a cutover, whatever the + # verdict file says. + if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then + echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))" + exit 1 + fi + if ! systemctl is-active --quiet flyshadow.service; then + echo "cutover refused: flyshadow.service is not running" + exit 1 + fi # The live service's configuration, for its compatibility string. set -a # shellcheck disable=SC1091 @@ -254,6 +353,7 @@ case "$cmd" in status) status ;; check) check "$@" ;; 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 ;; + baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;; + simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;; + *) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;; esac diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 4138c91..d6fac69 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -457,24 +457,28 @@ pct exec -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off ``` -- **Start** first records the live fly's baseline over 10 s: `fly_realtime_factor`, - `fly_lag_seconds` and `fly_uptime_seconds`. It refuses unless flysim is running normally. Then it: +- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty + 10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth + rate. It refuses unless flysim ran normally for most of that time. Then it: 1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`, `FLY_TRACE_LEDGERS=60`); 2. starts `flyshadow.service` and waits for its heartbeat; 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. + `FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. 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** runs every 60 s, automatically, and judges the live fly against its own baseline, + not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a + sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process + fall below the baseline, or grow lag faster than it, by more than the margin. The margin is + max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a + real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and + restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and + `status` shows it. A paused fly is not judged, and a restarted one starts its window again. + Once the shadow is no longer running (diverged, stopped or crashed), the guard stops itself and + changes nothing. A trip is not a divergence: fix the resources, then `start` again. - **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. @@ -485,6 +489,8 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01 runs `check` at the moment it cuts over. `check` also requires all of these: + - at least 10,800 brain seconds, whatever window the shadow was started with; + - the guard has not tripped and `flyshadow.service` is running; - 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); @@ -503,7 +509,8 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, deletes every file it has compared. - **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its - `cpuset.conf`), and pauses for a minute whenever flysim's `fly_lag_seconds` grows. Disk: about + `cpuset.conf`). It pauses for a minute while flysim's lag grows faster than its baseline rate, and + it stops pausing when a pause does not help. Disk: about 160 MB of trace per live hour, and a spool of at most 512 MiB. - **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 diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 99daf40..f5496c5 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -561,26 +561,28 @@ for u in flyshadow-guard.timer flyshadow-guard.service; do 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). +# The guard's rule, driven for real (python3 is on every container this repo provisions) over +# RTF traces: synthetic ones shaped on the release CT's own numbers (tests/shadow_guard_traces.py) +# and ones recorded from a real flysim with and without a shadow (tests/fixtures/shadow-guard/). +# A fly that was already below real time must never trip it; a genuine degradation must. 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" + guard_trace() { # name, dir with baseline.jsonl and checks.jsonl, expect (pass|trip) 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" + out="$("$INFRA_DIR/bin/fly-shadow-run" simulate "$2/baseline.jsonl" "$2/checks.jsonl")" || rc=$? + if { [ "$3" = pass ] && [ "$rc" = 0 ]; } || { [ "$3" = trip ] && [ "$rc" = 1 ]; }; then + pass "fly-shadow-run guard, $1: ${out%% (baseline*}" else - fail "fly-shadow-run guard: $1 (exit $rc, '$out')" + fail "fly-shadow-run guard, $1: expected $3, got 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 + while read -r name expect; do + guard_trace "$name" "$g_tmp/$name" "$expect" + done < <(python3 "$INFRA_DIR/tests/shadow_guard_traces.py" "$g_tmp") + for d in "$INFRA_DIR"/tests/fixtures/shadow-guard/*/; do + [ -f "$d/expect" ] || continue + guard_trace "recorded $(basename "$d")" "$d" "$(cat "$d/expect")" + done rm -rf "$g_tmp" else fail "python3 is needed to test fly-shadow-run's guard rule" diff --git a/infra/tests/shadow_guard_traces.py b/infra/tests/shadow_guard_traces.py new file mode 100644 index 0000000..7fe5d6b --- /dev/null +++ b/infra/tests/shadow_guard_traces.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Synthetic live-fly RTF traces for fly-shadow-run's guard (SHADOW-01 review round 2, G1). + + shadow_guard_traces.py OUTDIR + +Writes /baseline.jsonl and /checks.jsonl in fly-shadow-run's sample format +({t, status, rtMean, lag, uptime}) and prints one line per case: ` `, where + is `pass` (the guard must not trip) or `trip` (it must). The baseline is 60 samples 10 s +apart (start's 10 minutes); the checks are one sample a minute for the given length. + +The lag follows flysim's pacer: a fly behind real time owes (1 - rtf) seconds per second, and the +pacer books it as lag only in chunks of more than a second (`pacing::MAX_CATCHUP`). + +The cases come from the release container's own numbers (the coordinator's samples, agents.log +2026-09-30 00:08Z): a flat 0.66 before the cpuset rebalance, 0.77-0.99 noisy after it, plus a fly +at real time; each alone (must pass), and each with a genuine degradation after the start (must +trip). +""" +import json +import os +import random +import sys + + +class Fly: + def __init__(self, seed): + self.rng = random.Random(seed) + self.t, self.uptime, self.lag, self.debt = 1_790_000_000.0, 3600.0, 12.0, 0.0 + + def run(self, seconds, rtf_of): + """Advances `seconds` of wall time at the realtime factors `rtf_of()` gives per second.""" + rtfs = [] + for _ in range(int(seconds)): + rtf = rtf_of(self.rng) + rtfs.append(rtf) + self.debt += max(0.0, 1.0 - rtf) + if self.debt > 1.0: + self.lag += self.debt + self.debt = 0.0 + self.t += 1 + self.uptime += 1 + return rtfs + + def sample(self, rtf_of, status="running"): + rtfs = self.run(10, rtf_of) + return {"t": self.t, "status": status, "rtMean": sum(rtfs) / len(rtfs), + "lag": round(self.lag, 3), "uptime": self.uptime} + + def restart(self): + self.uptime, self.lag, self.debt = 5.0, 0.0, 0.0 + + +def flat(v, jitter=0.01): + return lambda rng: v + rng.uniform(-jitter, jitter) + + +def noisy(lo, hi): + return lambda rng: rng.uniform(lo, hi) + + +def noisy_windows(lo, hi): + """Noise at the sample level: each 10 s holds one value in [lo, hi], so the 10-s means the + guard reads spread over the whole range (the coordinator's samples).""" + state = {"n": 0, "v": None} + + def pace(rng): + if state["n"] % 10 == 0: + state["v"] = rng.uniform(lo, hi) + state["n"] += 1 + return state["v"] + + return pace + + +def realtime(rng): + return min(1.0, 1.0 + rng.uniform(-0.004, 0.002)) + + +def case(seed, before, after, checks=180, degrade_at=None, events=None): + fly = Fly(seed) + baseline = [fly.sample(before) for _ in range(60)] + fly.restart() # start's own flysim restart + rows = [] + for n in range(checks): + pace = after if degrade_at is not None and n >= degrade_at else before + status = "running" + if events and n in events: + kind = events[n] + if kind == "restart": + fly.restart() + elif kind == "paused": + status = "paused" + elif kind == "hiccup": + fly.lag += 1.3 # one pacing shortfall of 1.3 s, nothing more + rows.append(fly.sample(pace, status)) + fly.run(50, pace) + return baseline, rows + + +CASES = { + # The release CT before the rebalance: a flat 0.66, 3 hours, with a restart and a pause. + "ct-flat-0.66": (case(1, flat(0.66), None, events={40: "restart", 90: "paused", 91: "paused"}), "pass"), + # After the rebalance: 0.77-0.99 noisy, 3 hours, a restart. + "ct-noisy-0.77-0.99": (case(2, noisy(0.77, 0.99), None, events={120: "restart"}), "pass"), + "ct-noisy-0.77-0.99-seed3": (case(3, noisy(0.77, 0.99), None), "pass"), + # The same spread at the level of the 10-s samples themselves, the harder case. + "ct-samples-0.77-0.99": (case(8, noisy_windows(0.77, 0.99), None, events={60: "restart"}), "pass"), + "ct-samples-0.77-0.99-seed9": (case(9, noisy_windows(0.77, 0.99), None), "pass"), + "ct-samples-0.77-0.99-seed10": (case(10, noisy_windows(0.77, 0.99), None), "pass"), + # At real time, with single pacing hiccups: never a trip. + "realtime-hiccups": (case(4, realtime, None, events={30: "hiccup", 100: "hiccup", 150: "hiccup"}), "pass"), + # A shadow that costs the fly real time. + "ct-flat-0.66-then-0.55": (case(5, flat(0.66), flat(0.55), checks=40, degrade_at=15), "trip"), + "ct-noisy-then-0.60-0.75": (case(6, noisy(0.77, 0.99), noisy(0.60, 0.75), checks=40, degrade_at=15), "trip"), + "realtime-then-0.90": (case(7, realtime, flat(0.90), checks=40, degrade_at=15), "trip"), + "ct-samples-then-0.55-0.75": ( + case(11, noisy_windows(0.77, 0.99), noisy_windows(0.55, 0.75), checks=40, degrade_at=15), + "trip", + ), +} + + +def main(): + out = sys.argv[1] + for name, ((baseline, checks), expect) in CASES.items(): + d = os.path.join(out, name) + os.makedirs(d, exist_ok=True) + for fname, rows in (("baseline.jsonl", baseline), ("checks.jsonl", checks)): + with open(os.path.join(d, fname), "w") as f: + for r in rows: + f.write(json.dumps(r) + "\n") + print(name, expect) + + +if __name__ == "__main__": + main() diff --git a/infra/units/flyshadow-guard.service b/infra/units/flyshadow-guard.service index 3cd5cee..2873fcc 100644 --- a/infra/units/flyshadow-guard.service +++ b/infra/units/flyshadow-guard.service @@ -1,10 +1,10 @@ # 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 +# `fly-shadow-run guard` compares the live fly with the 10-minute baseline `fly-shadow-run start` +# recorded before it started the shadow: on a sustained degradation of the realtime factor or the +# lag growth rate against that baseline (3 checks in a row, 5-sample windows), it stops +# flyshadow.service, removes the trace drop-in and restarts flysim without the trace. The live +# stream never pays for the shadow. It stops itself when the shadow is not running. 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) diff --git a/infra/units/flyshadow.service b/infra/units/flyshadow.service index cc207b9..a0c9f82 100644 --- a/infra/units/flyshadow.service +++ b/infra/units/flyshadow.service @@ -20,10 +20,11 @@ # 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. flyshadow-guard.timer -# (fly-shadow-run guard) stops it and restarts flysim without the trace if -# the live fly loses real time anyway. It is lag-tolerant: the trace and the +# AllowedCPUs= for it from the page and encoder groups). It pauses for a minute +# while flysim's lag grows faster than its pre-start baseline rate (and stops +# pausing when that does not help: then it is not the cause). +# flyshadow-guard.timer (fly-shadow-run guard) stops it and restarts flysim +# without the trace on a sustained degradation against that baseline. 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). #