From c1f0dde9e95ae314493a587f4b02961cde04dafe Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 12:58:05 +0000 Subject: [PATCH] infra: CUT-01 speed probation after fly-runtime session fly-runtime session now starts fly-runtime-probation (timer every 60 s, 30 minutes): after a 300 s warm-up, a sustained median realtime factor below 0.97 or lag growth over 30 s in a 10-minute window runs fly-runtime fallback with reason speed. A pass writes /run/fly/runtime-probation.json and stops the timer; fly-runtime legacy and every fallback cancel it; state on disk resumes it after a reboot. Lint drives it over synthetic traces; runbook gets the end-to-end cutover procedure. --- infra/05-deploy.sh | 2 +- infra/bin/fly-runtime | 37 ++- infra/bin/fly-runtime-probation | 299 ++++++++++++++++++++++ infra/docs/runbook.md | 87 ++++++- infra/tests/lint.sh | 168 ++++++++++++ infra/units/fly-runtime-probation.service | 13 + infra/units/fly-runtime-probation.timer | 18 ++ 7 files changed, 619 insertions(+), 5 deletions(-) create mode 100755 infra/bin/fly-runtime-probation create mode 100644 infra/units/fly-runtime-probation.service create mode 100644 infra/units/fly-runtime-probation.timer diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index ff58a1b..2e0b49c 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -745,7 +745,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 fly-runtime fly-shadow-run 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-runtime fly-runtime-probation 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-runtime b/infra/bin/fly-runtime index 6247f65..5b8d10a 100755 --- a/infra/bin/fly-runtime +++ b/infra/bin/fly-runtime @@ -4,7 +4,7 @@ # # Usage (INSIDE the container, as root): # fly-runtime status print `legacy` or `session`, and what flysim.service runs -# fly-runtime session [--no-restart] [--no-fallback] +# fly-runtime session [--no-restart] [--no-fallback] [--no-probation] # fly-runtime legacy [--no-restart] # fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent) # @@ -61,6 +61,14 @@ # puts the previous state back (drop-in removed, or the earlier one restored) and restarts # flysim.service on it, so a dropped ssh never leaves a drop-in that was not health-checked. # +# The speed probation (CUT-01). Operator decision 2026-09-30: the session runtime stays only if it +# sustains >= 1.0x real time on the release container. A `session` that restarted flysim and saw +# it healthy therefore starts infra/bin/fly-runtime-probation (fly-runtime-probation.timer, every +# 60 s for 30 minutes): a sustained speed failure ends in `fly-runtime fallback "speed: ..."`, the +# same fallback as above under the same lock. `legacy` and every fallback cancel it. `--no-restart` +# (05-deploy's refresh of the drop-in) and `--no-probation` (rehearsals) start none. If the +# probation cannot be started, `session` falls back: an unguarded cutover is not allowed. +# # Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}. set -euo pipefail @@ -82,12 +90,19 @@ FALLBACK_UNIT=fly-runtime-fallback.service SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session" LEGACY_BIN="${FLY_RELEASE_DIR}/flysim" SESSION_DIR=/run/fly/session +PROBATION_BIN="${FLY_PROBATION_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime-probation}" log() { echo "fly-runtime: $*" >&2; } + +# The speed probation's hooks (best effort except `start`, which the caller checks). +probation() { + [ -x "$PROBATION_BIN" ] || return 0 + "$PROBATION_BIN" "$@" || log "fly-runtime-probation $1 failed" +} die() { log "$*"; exit 1; } usage() { - echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] | legacy [--no-restart] | fallback [reason]" >&2 + echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] [--no-probation] | legacy [--no-restart] | fallback [reason]" >&2 exit 2 } @@ -240,6 +255,7 @@ do_fallback() { cp -f "$DROPIN" "$saved" rm -f "$DROPIN" rmdir "$DROPIN_DIR" 2>/dev/null || true + probation cancel --quiet record "legacy (automatic fallback: ${reason}; was session)" systemctl daemon-reload || true systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true @@ -304,12 +320,14 @@ trap 'exit 129' HUP command="$1"; shift restart=1 fallback=1 +probe=1 fallback_reason="" if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi for arg in "$@"; do case "$arg" in --no-restart) restart=0 ;; --no-fallback) fallback=0 ;; + --no-probation) probe=0 ;; *) usage ;; esac done @@ -318,6 +336,7 @@ case "$command" in status) current if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi + if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true exit 0 ;; @@ -365,7 +384,18 @@ if [ "$command" = session ]; then # check above too): only report success if the session drop-in is still what runs. if [ -f "$DROPIN" ] && [ ! -f "$FELLBACK_FILE" ]; then switching=0 - log "flysim.service runs the session runtime" + if [ "$probe" -eq 1 ]; then + if [ ! -x "$PROBATION_BIN" ] || ! "$PROBATION_BIN" start; then + log "the speed probation could not be started; an unguarded cutover is not allowed" + if [ "$fallback" -eq 1 ]; then + do_fallback "the speed probation could not be started" || true + fi + exit 1 + fi + log "flysim.service runs the session runtime, on probation: fly-runtime-probation status" + else + log "flysim.service runs the session runtime (no probation)" + fi exit 0 fi switching=0 @@ -394,6 +424,7 @@ switch_target=legacy switching=1 rm -f "$DROPIN" rmdir "$DROPIN_DIR" 2>/dev/null || true +probation cancel record "legacy (was ${before})" [ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; } if restart_and_check; then diff --git a/infra/bin/fly-runtime-probation b/infra/bin/fly-runtime-probation new file mode 100755 index 0000000..356b68d --- /dev/null +++ b/infra/bin/fly-runtime-probation @@ -0,0 +1,299 @@ +#!/usr/bin/env bash +# infra/bin/fly-runtime-probation -- CUT-01's speed probation after `fly-runtime session`. +# Pushed to /opt/fly/bin by 05-deploy.sh. Root, inside the container. Normally nobody runs it by +# hand: `fly-runtime session` starts it, `fly-runtime legacy` and every fallback cancel it, and +# fly-runtime-probation.timer runs `tick` every 60 s. +# +# fly-runtime-probation start begin a probation (enables and starts the timer) +# fly-runtime-probation cancel end it without a verdict (disables the timer) +# fly-runtime-probation status state, latest samples, result +# fly-runtime-probation tick (timer) one sample and one decision +# fly-runtime-probation simulate CHECKS.jsonl the rule over recorded samples (lint) +# +# Operator decision 2026-09-30: cut over only if the session runtime sustains >= 1.0x real time on +# the release container. Only that box can measure it, so the switch is guarded. The rule: +# - A sample is one fly_realtime_factor mean over 10 one-second reads of flysim's /metrics (the +# same sampling as fly-shadow-run's guard), with fly_lag_seconds and fly_uptime_seconds. +# - Warm-up: a flysim process is not judged before it has been up FLY_PROBATION_WARMUP (300 s: +# the connectome load, the restore, the first minutes). A restart (uptime goes backwards) +# starts the window again; so does a paused or not running fly: it is not judged. +# - Window: the judged samples of the last FLY_PROBATION_WINDOW (600 s), at least +# FLY_PROBATION_MIN_SAMPLES (8). FAIL when the window's MEDIAN realtime factor is below +# FLY_PROBATION_MIN_RTF (0.97), or the lag grew by more than FLY_PROBATION_MAX_LAG_GROWTH +# (30 s) between the start and the end of the window (median of the first and of the last 3 +# samples). The median is the same robust statistic fly-shadow-run's baseline uses: one +# stalled sample, or two, never fails it. +# - PASS when FLY_PROBATION_SECONDS (1800) have passed since `start` and the latest window is +# full and healthy. A probation that cannot fill a window within FLY_PROBATION_MAX_SECONDS +# (7200: a fly that never runs) fails as inconclusive: no proof of 1.0x, no cutover. +# FAIL runs `fly-runtime fallback "speed: ..."` (the ordinary fallback: lock, reason file +# /run/fly/runtime-fellback.json, journal line, flysim.service restarted on legacy). It is retried +# every minute until it succeeds. PASS writes ${RESULT} (passed: true) and disables the timer. +# Nothing judges the speed afterwards: the watchdog and the start-limit fallback are unchanged. +# +# State is ${DIR}/state.json (on disk, so a reboot resumes the probation: the timer is enabled, +# and OnBootSec= runs it after boot); ${DIR}/last.json keeps the last verdict. +set -euo pipefail + +: "${FLY_PROBATION_DIR:=/var/lib/fly/probation}" +: "${FLY_PROBATION_RESULT:=/run/fly/runtime-probation.json}" +: "${FLY_PROBATION_TIMER:=fly-runtime-probation.timer}" +: "${FLY_PROBATION_READS:=10}" +: "${FLY_METRICS_URL:=http://127.0.0.1:9101}" +: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}" +RUNTIME_BIN="${FLY_RUNTIME_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime}" +STATE="$FLY_PROBATION_DIR/state.json" +LAST="$FLY_PROBATION_DIR/last.json" + +log() { echo "fly-runtime-probation: $*" >&2; } +die() { log "$*"; exit 1; } +journal() { + if command -v logger >/dev/null 2>&1; then logger -t fly-runtime -- "probation: $*" || true; fi + log "$*" +} +need_root() { [ "$(id -u)" = 0 ] || die "run as root"; } + +take_lock() { + mkdir -p "$FLY_PROBATION_DIR" + exec 8>>"$FLY_PROBATION_DIR/lock" + flock -w 60 8 || die "could not take $FLY_PROBATION_DIR/lock" +} +drop_lock() { exec 8>&-; } + +# One sample of the live fly: {t, status, rtMean, lag, uptime} (fly-shadow-run's format). +sample() { + python3 - "$FLY_METRICS_URL" "$FLY_CONTROL_URL" "$FLY_PROBATION_READS" <<'PY' +import json, sys, time, urllib.request +metrics_url, control_url, reads = sys.argv[1], sys.argv[2], int(sys.argv[3]) +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 i in range(reads): + factors.append(metrics().get("fly_realtime_factor", 0.0)) + if i + 1 < reads: + 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({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors), + "lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")})) +PY +} + +PROBATION_PY=' +import json, os, sys +def env(name, default): + return type(default)(os.environ.get(name, default)) +WARMUP = env("FLY_PROBATION_WARMUP", 300.0) +WINDOW = env("FLY_PROBATION_WINDOW", 600.0) +MIN_SAMPLES = env("FLY_PROBATION_MIN_SAMPLES", 8) +MIN_RTF = env("FLY_PROBATION_MIN_RTF", 0.97) +MAX_LAG_GROWTH = env("FLY_PROBATION_MAX_LAG_GROWTH", 30.0) +DURATION = env("FLY_PROBATION_SECONDS", 1800.0) +MAX_SECONDS = env("FLY_PROBATION_MAX_SECONDS", 7200.0) + +def running(s): + return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None + +def median(xs): + xs = sorted(xs) + n = len(xs) + return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2 + +def step(state, s): + """Returns (state, verdict, detail): verdict is wait, ok, pass or fail.""" + started = state["startedAt"] + history = state.get("history", []) + elapsed = s["t"] - started + if not running(s): + return state, "wait", "flysim is %s: not judged" % s.get("status") + if history and s["uptime"] < history[-1]["uptime"]: + history = [] + if s["uptime"] < WARMUP: + state["history"] = [] + return state, "wait", "warming up (flysim up %.0f of %.0f s)" % (s["uptime"], WARMUP) + history = [h for h in history if h["t"] > s["t"] - WINDOW] + [s] + state["history"] = history + n = len(history) + if n < MIN_SAMPLES: + if elapsed >= MAX_SECONDS: + return state, "fail", "speed: probation inconclusive after %.0f s (%d judged samples in the window): no proof of 1.0x" % (elapsed, n) + return state, "wait", "collecting %d of %d samples" % (n, MIN_SAMPLES) + rtf = median([h["rtMean"] for h in history]) + lag_growth = median([h["lag"] for h in history[-3:]]) - median([h["lag"] for h in history[:3]]) + detail = "median realtime factor %.3f over %d samples, lag growth %+.1f s over %.0f s" % ( + rtf, n, lag_growth, history[-1]["t"] - history[0]["t"]) + state["last"] = {"medianRtf": rtf, "lagGrowth": lag_growth, "samples": n} + why = [] + if rtf < MIN_RTF: + why.append("median realtime factor %.3f < %.2f" % (rtf, MIN_RTF)) + if lag_growth > MAX_LAG_GROWTH: + why.append("lag grew %.1f s > %.0f s" % (lag_growth, MAX_LAG_GROWTH)) + if why: + return state, "fail", "speed: " + ", ".join(why) + " over %d samples / %.0f s" % ( + n, history[-1]["t"] - history[0]["t"]) + if elapsed >= DURATION: + return state, "pass", detail + return state, "ok", detail + " (%.0f of %.0f s)" % (elapsed, DURATION) + +mode = sys.argv[1] +if mode == "step": + state = json.load(open(sys.argv[2])) + state, verdict, detail = step(state, json.loads(sys.argv[3])) + json.dump(state, open(sys.argv[2], "w")) + print(verdict + " " + detail) +elif mode == "simulate": + samples = [json.loads(l) for l in open(sys.argv[2]) if l.strip()] + state = {"startedAt": samples[0]["t"] - 60, "history": []} + verdict, detail = "wait", "" + for n, s in enumerate(samples, 1): + state, verdict, detail = step(state, s) + if verdict in ("pass", "fail"): + print("%s at check %d: %s" % (verdict, n, detail)) + sys.exit(0 if verdict == "pass" else 1) + print("undecided after %d checks: %s %s" % (len(samples), verdict, detail)) + sys.exit(3) +' + +now_iso() { date -u '+%Y-%m-%dT%H:%M:%SZ'; } + +enabled_timer() { systemctl "$1" --now "$FLY_PROBATION_TIMER" >/dev/null 2>&1; } + +start() { + need_root + take_lock + mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true + rm -f "$FLY_PROBATION_RESULT" + printf '{"startedAt":%s,"startedAtIso":"%s","history":[]}\n' "$(date +%s.%N)" "$(now_iso)" >"$STATE.tmp.$$" + mv -f "$STATE.tmp.$$" "$STATE" + if ! enabled_timer enable; then + rm -f "$STATE" + die "could not enable --now $FLY_PROBATION_TIMER (is the unit installed?)" + fi + journal "started: ${FLY_PROBATION_SECONDS:-1800} s, median realtime factor >= ${FLY_PROBATION_MIN_RTF:-0.97} over ${FLY_PROBATION_WINDOW:-600} s after ${FLY_PROBATION_WARMUP:-300} s warm-up, lag growth <= ${FLY_PROBATION_MAX_LAG_GROWTH:-30} s; else fallback to legacy" +} + +cancel() { + local quiet=0 + [ "${1:-}" = --quiet ] && quiet=1 + need_root + take_lock + local had=0 + if [ -f "$STATE" ]; then had=1; fi + rm -f "$STATE" "$FLY_PROBATION_RESULT" + enabled_timer disable || true + if [ "$had" -eq 1 ] || [ "$quiet" -eq 0 ]; then journal "cancelled"; fi +} + +# The verdict, persisted in last.json (and in ${RESULT} on a pass). +finish() { # passed(true|false) detail state-file + local tmp="$LAST.tmp.$$" + python3 - "$1" "$2" "$3" >"$tmp" <<'PY' +import json, sys, datetime +passed, detail = sys.argv[1] == "true", sys.argv[2] +st = {} +try: + st = json.load(open(sys.argv[3])) +except Exception: + pass +out = {"passed": passed, "at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "startedAt": st.get("startedAtIso"), "detail": detail} +out.update(st.get("last", {})) +print(json.dumps(out)) +PY + mv -f "$tmp" "$LAST" + if [ "$1" = true ]; then + mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true + cp -f "$LAST" "$FLY_PROBATION_RESULT" + fi +} + +tick() { + need_root + local sample_json="" now out verdict detail rc + if [ "${1:-}" = --sample-json ]; then sample_json="$2"; fi # the test seam: a recorded sample + if [ ! -f "$STATE" ]; then + log "no probation: disabling $FLY_PROBATION_TIMER" + enabled_timer disable || true + exit 0 + fi + # Only the session runtime is judged: a fallback, a legacy switch or a deploy that removed the + # drop-in ended it. + if [ "$("$RUNTIME_BIN" status 2>/dev/null | head -n1)" != session ]; then + journal "the session runtime is not selected; probation ends" + cancel --quiet + exit 0 + fi + if [ -n "$sample_json" ]; then now="$sample_json"; else now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }; fi + take_lock + [ -f "$STATE" ] || { log "cancelled while sampling"; exit 0; } + rc=0 + out="$(python3 -c "$PROBATION_PY" step "$STATE" "$now")" || rc=$? + [ "$rc" -eq 0 ] || die "probation rule failed: $out" + verdict="${out%% *}" + detail="${out#* }" + case "$verdict" in + wait|ok) drop_lock; log "$verdict: $detail" ;; + pass) + finish true "$detail" "$STATE" + rm -f "$STATE" + enabled_timer disable || true + journal "PASSED: $detail" + ;; + fail) + cp -f "$STATE" "$STATE.failed.$$" + drop_lock + journal "FAILED: $detail; falling back to legacy" + if "$RUNTIME_BIN" fallback "$detail"; then + take_lock + finish false "$detail" "$STATE.failed.$$" + rm -f "$STATE" "$STATE.failed.$$" + enabled_timer disable || true + else + rm -f "$STATE.failed.$$" + log "fallback did not complete; probation stays and retries in a minute" + exit 1 + fi + ;; + *) die "unexpected verdict: $out" ;; + esac +} + +status() { + if [ -f "$STATE" ]; then + python3 - "$STATE" <<'PY' +import json, sys +s = json.load(open(sys.argv[1])) +print("probation running since %s; %d judged samples in the window; last %s" % ( + s.get("startedAtIso"), len(s.get("history", [])), json.dumps(s.get("last")))) +PY + else + echo "no probation running" + fi + if [ -f "$LAST" ]; then echo "last verdict: $(cat "$LAST")"; fi + if [ -f "$FLY_PROBATION_RESULT" ]; then echo "passed: $FLY_PROBATION_RESULT"; fi +} + +cmd="${1:-}" +[ $# -gt 0 ] && shift +case "$cmd" in + start) start ;; + cancel) cancel "$@" ;; + tick) tick "$@" ;; + status) status ;; + simulate) [ $# = 1 ] || die "simulate CHECKS.jsonl"; python3 -c "$PROBATION_PY" simulate "$1" ;; + *) echo "usage: fly-runtime-probation start|cancel|status|tick|simulate CHECKS.jsonl" >&2; exit 2 ;; +esac diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 15bf2c6..0033077 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -455,7 +455,7 @@ written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/op ``` pct exec $CTID -- /opt/fly/bin/fly-runtime status # legacy | session -pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict +pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict (starts the speed probation) pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback ``` @@ -596,6 +596,91 @@ pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, (`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace within a minute, because its consumer is gone. +## Cutover to the session runtime (CUT-01) + +Operator decision (2026-09-30): the stream moves to the session runtime only if that runtime +sustains at least 1.0x real time on the release container, otherwise it stays on legacy. Only the +release container can measure that, so the switch is guarded by a **probation**. Claim the +container in the host log first, as for any host work. + +``` +# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy. +# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy) +# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact: +pct exec $CTID -- /opt/fly/bin/fly-shadow-run start +pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass +# 3. Cutover: the shadow's gate, then the switch. One command line: +pct exec $CTID -- sh -c '/opt/fly/bin/fly-shadow-run check && /opt/fly/bin/fly-runtime session' +# 4. Watch the probation (30 minutes after the switch): +pct exec $CTID -- /opt/fly/bin/fly-runtime-probation status +pct exec $CTID -- /opt/fly/bin/fly-runtime status +# 5. Pass, or automatic fallback (below). Then stop the shadow: +pct exec $CTID -- /opt/fly/bin/fly-shadow-run stop --restart-flysim +# Manual rollback, any time (cancels the probation too): +pct exec $CTID -- /opt/fly/bin/fly-runtime legacy +``` + +- **Step 3 in detail.** `check` refuses unless the verdict, the guard and the release all line + up (Shadow run above). `session` then does what "Switch the runtime" describes (compatibility + check, drop-in, restart, health wait) and, once flysim is healthy on the session runtime, starts + the probation. `session` returns 0 at that point: the probation is judged later, by the timer. + Stop the shadow only after the probation has passed (step 5): its trace costs the live fly, and + the session runtime is being measured. Until then `fly-shadow-run stop --restart-flysim` would + restart flysim inside the probation, which only restarts the warm-up. +- **The probation** (`infra/bin/fly-runtime-probation`, `fly-runtime-probation.timer` every 60 s, + root). Each tick takes one sample of flysim's `/metrics` (`fly_realtime_factor` averaged over 10 + one-second reads, `fly_lag_seconds`, `fly_uptime_seconds`; the same sampling as the shadow + guard). It judges the session runtime only: + - *Warm-up.* A flysim process is not judged before it has been up 300 s (connectome load, + restore, first minutes). A restart, a pause or a fly that is not `running` starts the window + again; it is never counted as slow. + - *Failure*, sustained and not one sample: over the judged samples of the last 10 minutes (at + least 8 of them) the **median** realtime factor is below **0.97**, or the lag grew by more than + **30 s** from the window's start to its end (median of the first and of the last three + samples). The median is the robust statistic the shadow guard's baseline uses: one or two + stalled minutes do not fail it, a steady 0.85x does, at the earliest about 13 minutes after the + switch (5 min warm-up, 8 samples). A lag step of more than 30 s inside the window counts as + lag growth. + - *Pass*: 30 minutes since the switch, and the latest window is full and healthy. A probation + that cannot fill a window within 2 h (a fly that never runs) fails as inconclusive: no proof + of 1.0x, no cutover. `FLY_PROBATION_*` variables tune every number (tests and rehearsals only). + - **On failure** it runs `fly-runtime fallback "speed: ..."`, exactly the fallback of "Switch + the runtime": under the same lock, `/run/fly/runtime-fellback.json` with the reason + (`"speed: median realtime factor 0.850 < 0.97 ..."`), the drop-in removed, flysim restarted on + legacy, a `fly-runtime` journal line (`journalctl -t fly-runtime`, + `/var/lib/fly/runtime.log`), and the probation ended (`/var/lib/fly/probation/last.json` + says `passed: false`). If that fallback cannot complete (no executable `flysim`) it is retried + every minute. The container is then on legacy and the decision is "no cutover": do not retry + `session` without a fix (or a new measurement) for the cause. + - **On pass** it writes `/run/fly/runtime-probation.json` (`{"passed": true, "at", "startedAt", + "medianRtf", "lagGrowth", "samples", "detail"}`; also kept in + `/var/lib/fly/probation/last.json` because `/run` is cleared by a reboot) and disables its + timer. **Nothing judges the speed afterwards.** A continuous guard would make a passing + cutover fall back at 03:00 on one noisy hour, on a stream that has proven itself, and the + watchdog already covers a stuck or dead loop. The start-limit fallback also stays as it is. +- **Cancel and resume.** `fly-runtime legacy` cancels the probation, as does every fallback + (including the start-limit one), and a tick that finds the legacy runtime selected ends it + without a verdict. The state is `/var/lib/fly/probation/state.json` and the timer is enabled while + a probation runs (`[Install] WantedBy=timers.target`; nothing else enables it), so a reboot + during the probation resumes it: `OnBootSec=90s` runs the first tick, flysim's new process + starts a new warm-up and window, and the 30 minutes keep counting from the original switch. + `fly-runtime session --no-restart` (05-deploy's refresh of the drop-in) starts no probation; + `fly-runtime session --no-probation` is for rehearsals. A `session` that cannot start the + probation (helper or timer unit missing) falls back: an unguarded cutover is not allowed. +- **Reading the result honestly.** The probation is absolute, as decided: a container on which the + legacy loop itself runs below 0.97x (the release container has been measured at 0.66, and 0.77-0.99 + after its cpuset rebalance) will fail it, and the session runtime was measured at 1.25-1.35x + legacy's time per frame on the dev box. A fallback with reason `speed` therefore means "this box + cannot hold real time on the session runtime", not necessarily "the session runtime is + broken"; compare with `fly-shadow-run`'s baseline (`/srv/fly/shadow/baseline.json`) before + anything else. The `check` before it measures the live fly against itself; this measures it + against the clock. +- **Rehearsal** without a host: `fly-runtime-probation simulate CHECKS.jsonl` runs the rule over + recorded samples (`{t, status, rtMean, lag, uptime}`, one a minute); `infra/tests/lint.sh` drives + the real `fly-runtime` and the probation over synthetic traces (healthy, 0.85x, a stall, lag + growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real + systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume). + ## 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 0f8f105..9907caa 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -795,6 +795,7 @@ fly_runtime() { FLY_ENV_FILE="$rt_dir/fly.env" FLY_SYSTEMD_DIR="$rt_dir/systemd" \ FLY_RUNTIME_LOG="$rt_dir/runtime.log" FLY_RUNTIME_HEALTH_TIMEOUT=4 \ FLY_RUNTIME_FELLBACK="$rt_dir/run/runtime-fellback.json" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \ + FLY_PROBATION_DIR="$rt_dir/probation" FLY_PROBATION_RESULT="$rt_dir/run/runtime-probation.json" \ "$@" bash "$INFRA_DIR/bin/fly-runtime" "${RT_ARGS[@]}" >/dev/null 2>&1 } rt_dropin="$rt_dir/systemd/flysim.service.d/10-runtime.conf" @@ -1015,6 +1016,173 @@ if ! fly_runtime && [ ! -f "$rt_dropin" ]; then else fail "fly-runtime session must refuse a release without flysim-session" fi +mv "$rt_dir/flysim-session.away" "$rt_dir/release/flysim-session" + +# CUT-01's speed probation (fly-runtime-probation), driven end to end with the real fly-runtime +# against the stubs above: `session` starts it, `tick --sample-json` feeds one recorded sample a +# minute (the sample times are synthetic, so 30 "minutes" take a second), and the outcome is read +# from the drop-in, the fallback reason file, the result file and the stubbed systemctl. +echo "--- the speed probation ---" +PROBATION="$INFRA_DIR/bin/fly-runtime-probation" +pr_state="$rt_dir/probation/state.json" +pr_result="$rt_dir/run/runtime-probation.json" +pr_fellback="$rt_dir/run/runtime-fellback.json" +pr_env() { + env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_RELEASE_DIR="$rt_dir/release" \ + FLY_ENV_FILE="$rt_dir/fly.env" FLY_SYSTEMD_DIR="$rt_dir/systemd" \ + FLY_RUNTIME_LOG="$rt_dir/runtime.log" FLY_RUNTIME_HEALTH_TIMEOUT=4 \ + FLY_RUNTIME_FELLBACK="$pr_fellback" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \ + FLY_PROBATION_DIR="$rt_dir/probation" FLY_PROBATION_RESULT="$pr_result" "$@" +} +pr_reset() { + rm -rf "$rt_dir/probation" "$pr_result" "$pr_fellback" "$rt_dir/systemd/flysim.service.d" + : > "$rt_dir/systemctl.log" +} +pr_traces() { # case, n, t0 -> JSON samples, one a minute: {t,status,rtMean,lag,uptime} + python3 - "$1" "$2" "$3" <<'PRPY' +import json, sys +case, n, t0 = sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) +lag, up = 2.0, 3600.0 +for i in range(1, n + 1): + rtf, status = 1.0 + (0.008 if i % 2 else -0.008), "running" + if case == "slow": # a steady 0.85x + rtf = 0.85 + (0.01 if i % 2 else -0.01); lag += 0.15 * 60 + elif case == "stall" and i in (12, 13): # two stalled minutes (a GC, a disk hiccup): 18 s of lag + rtf = 0.1; lag += 18 if i == 12 else 0 + elif case == "lag": # at real time on average, but 5 s more behind each minute + lag += 5 + elif case == "warmup": # a slow restore: the first 5 samples are before the warm-up + up = 30.0 + 60 * i if i <= 5 else 3600.0 + 60 * i + if i <= 5: + rtf = 0.2 + elif case == "restart" and i == 10: # flysim restarted (uptime goes backwards), then a warm-up again + up, lag = 20.0, 2.0 + if case in ("slow", "stall", "lag", "healthy"): + up = 3600.0 + 60 * i + elif case == "restart": + up = up + 60 if i != 10 else up + print(json.dumps({"t": t0 + 60 * i, "status": status, "rtMean": rtf, "lag": lag, "uptime": up})) +PRPY +} +pr_ticks() { # case, n: feed n samples to tick; leaves the last exit code in pr_rc + local t0 line + t0="$(date +%s)" + pr_rc=0 + while IFS= read -r line; do + pr_env bash "$PROBATION" tick --sample-json "$line" >/dev/null 2>&1 || pr_rc=$? + [ -f "$pr_state" ] || break + done < <(pr_traces "$1" "$2" "$t0") +} +pr_session() { pr_reset; rm -f "$rt_dir/systemd/flysim.service.d/10-runtime.conf"; RT_ARGS=(session); fly_runtime; } +pr_case() { # name, case, samples, expect: pass|fallback-speed|fallback-lag|no-verdict + pr_session || { fail "probation $1: fly-runtime session failed"; return; } + if [ ! -f "$pr_state" ] || ! grep -qx 'enable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + fail "probation $1: fly-runtime session did not start the probation (state file, timer)" + return + fi + pr_ticks "$2" "$3" + case "$4" in + pass) + if [ -f "$pr_result" ] && grep -q '"passed": true' "$pr_result" && [ -f "$rt_dropin" ] \ + && [ ! -f "$pr_fellback" ] && [ ! -f "$pr_state" ] \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "probation $1: passes, writes runtime-probation.json, stops its timer, stays on session" + else + fail "probation $1: expected a pass with the session drop-in kept (result: $(cat "$pr_result" 2>/dev/null))" + fi ;; + fallback-*) + if [ ! -f "$rt_dropin" ] && [ ! -f "$pr_result" ] && [ ! -f "$pr_state" ] \ + && grep -q '"reason":"speed: ' "$pr_fellback" 2>/dev/null \ + && grep -q "${4#fallback-}" "$pr_fellback" \ + && grep -q 'legacy (automatic fallback: speed: ' "$rt_dir/runtime.log" \ + && grep -q '"passed": false' "$rt_dir/probation/last.json" \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "probation $1: falls back to legacy with reason speed (reason file, journal line, timer off)" + else + fail "probation $1: expected a speed fallback ($(cat "$pr_fellback" 2>/dev/null), drop-in $([ -f "$rt_dropin" ] && echo present || echo gone))" + fi ;; + no-verdict) + if [ -f "$rt_dropin" ] && [ -f "$pr_state" ] && [ ! -f "$pr_fellback" ] && [ ! -f "$pr_result" ]; then + pass "probation $1: no verdict yet, still on probation, no fallback" + else + fail "probation $1: expected it to be running undecided" + fi ;; + esac +} +pr_case "healthy session at 1.0x" healthy 32 pass +pr_case "a session at 0.85x, sustained" slow 40 fallback-speed +pr_case "a transient stall (2 stalled minutes, 18 s of lag)" stall 32 pass +pr_case "lag growth at real time (5 s a minute)" lag 40 fallback-lag +pr_case "a slow restore before the warm-up ends is not judged" warmup 36 pass +pr_case "a flysim restart inside the window starts it again" restart 50 pass +pr_case "a healthy session before 30 minutes" healthy 20 no-verdict +# A probation that has not finished is still there, with its state on disk, after a "reboot": a +# new process reads state.json and goes on (the timer stays enabled; nothing is held in memory). +pr_session && pr_ticks healthy 12 +if [ -f "$pr_state" ] && [ "$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["history"]))' "$pr_state")" -ge 8 ]; then + pass "probation state is persisted on disk between ticks (a reboot resumes it)" +else + fail "probation state was not persisted" +fi +# fly-runtime legacy cancels a probation in progress. +RT_ARGS=(legacy) +if fly_runtime && [ ! -f "$pr_state" ] && [ ! -f "$rt_dropin" ] \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "fly-runtime legacy cancels the probation (state gone, timer disabled)" +else + fail "fly-runtime legacy must cancel the probation" +fi +# A tick with the legacy runtime selected ends a leftover probation and judges nothing. +pr_session && rm -f "$rt_dropin" +pr_env bash "$PROBATION" tick --sample-json '{"t":1,"status":"running","rtMean":0.1,"lag":1,"uptime":9999}' >/dev/null 2>&1 || true +if [ ! -f "$pr_state" ] && [ ! -f "$pr_fellback" ]; then + pass "probation tick with the legacy runtime selected cancels itself, no fallback" +else + fail "probation tick must end when the legacy runtime is selected" +fi +# A switch without a restart (05-deploy's refresh) or with --no-probation starts none. +pr_reset +RT_ARGS=(session --no-restart); fly_runtime +if [ ! -f "$pr_state" ]; then pass "fly-runtime session --no-restart starts no probation"; else fail "session --no-restart must not start a probation"; fi +pr_reset +rm -f "$rt_dropin" +RT_ARGS=(session --no-probation); fly_runtime +if [ ! -f "$pr_state" ] && [ -f "$rt_dropin" ]; then pass "fly-runtime session --no-probation starts no probation"; else fail "session --no-probation must not start a probation"; fi +# No probation helper, no cutover: an unguarded switch falls back. +pr_reset +rm -f "$rt_dropin" +RT_ARGS=(session) +if ! fly_runtime FLY_PROBATION_BIN="$rt_dir/none" && [ ! -f "$rt_dropin" ] && grep -q 'probation could not be started' "$pr_fellback"; then + pass "fly-runtime session falls back when the probation cannot be started" +else + fail "fly-runtime session must not leave an unguarded session runtime" +fi +# The rule over recorded traces, the way fly-shadow-run simulate does it. +pr_sim="$rt_dir/sim.jsonl" +pr_traces slow 40 1790000000 > "$pr_sim" +pr_out="$(bash "$PROBATION" simulate "$pr_sim" 2>&1)" && pr_rc=0 || pr_rc=$? +if [ "$pr_rc" = 1 ]; then pass "probation simulate: ${pr_out%%:*}, a steady 0.85x: ${pr_out#*: }"; else fail "probation simulate: slow trace: rc $pr_rc: $pr_out"; fi +pr_traces healthy 35 1790000000 > "$pr_sim" +pr_out="$(bash "$PROBATION" simulate "$pr_sim" 2>&1)" && pr_rc=0 || pr_rc=$? +if [ "$pr_rc" = 0 ]; then pass "probation simulate: healthy trace passes"; else fail "probation simulate: healthy trace: rc $pr_rc: $pr_out"; fi +# The unit files. +for u in fly-runtime-probation.service fly-runtime-probation.timer; do + [ -f "$INFRA_DIR/units/$u" ] || fail "units/$u is missing" +done +if grep -qx 'ExecStart=/opt/fly/bin/fly-runtime-probation tick' "$INFRA_DIR/units/fly-runtime-probation.service" \ + && grep -qx 'OnUnitActiveSec=60s' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && grep -qx 'OnBootSec=90s' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && grep -qx 'WantedBy=timers.target' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && ! grep -q 'fly-runtime-probation' "$INFRA_DIR/units/fly.target" "$INFRA_DIR/07-enable.sh"; then + pass "fly-runtime-probation units: a 60 s timer, enabled only by fly-runtime-probation start (boot resumes it)" +else + fail "fly-runtime-probation units are wrong" +fi +if grep -qE 'for name in .*\bfly-runtime-probation\b.*; do$' "$INFRA_DIR/05-deploy.sh"; then + pass "05-deploy.sh installs fly-runtime-probation" +else + fail "05-deploy.sh must converge bin/fly-runtime-probation to /opt/fly/bin" +fi rm -rf "$rt_dir" echo "--- fly-watchdog check 2: the feed counters follow FLY_FEED_VIA ---" diff --git a/infra/units/fly-runtime-probation.service b/infra/units/fly-runtime-probation.service new file mode 100644 index 0000000..f1d628b --- /dev/null +++ b/infra/units/fly-runtime-probation.service @@ -0,0 +1,13 @@ +# infra/units/fly-runtime-probation.service -- triggered by fly-runtime-probation.timer. +# +# One sample (10 s of flysim's /metrics) and one decision of CUT-01's speed probation: see +# infra/bin/fly-runtime-probation. On a sustained speed failure it runs `fly-runtime fallback +# "speed: ..."`. With no probation running it disables its own timer. Root: the fallback removes a +# drop-in in /etc/systemd and restarts flysim. +[Unit] +Description=fly-runtime-probation: is the session runtime at real time? (CUT-01) + +[Service] +Type=oneshot +ExecStart=/opt/fly/bin/fly-runtime-probation tick +TimeoutStartSec=240 diff --git a/infra/units/fly-runtime-probation.timer b/infra/units/fly-runtime-probation.timer new file mode 100644 index 0000000..0f809b9 --- /dev/null +++ b/infra/units/fly-runtime-probation.timer @@ -0,0 +1,18 @@ +# infra/units/fly-runtime-probation.timer -- CUT-01's speed probation, every 60 s. +# +# Not enabled by provisioning or deploy. `fly-runtime session` runs `fly-runtime-probation start` +# (systemctl enable --now), which is why this unit has an [Install] section: the enablement is +# what makes a probation survive a reboot (OnBootSec= then runs the first tick). The probation +# disables the timer when it passes, fails over to legacy, or is cancelled (`fly-runtime legacy`). +[Unit] +Description=fly-runtime-probation: the session runtime's speed probation, every minute (CUT-01) + +[Timer] +OnBootSec=90s +OnActiveSec=60s +OnUnitActiveSec=60s +AccuracySec=5s +Unit=fly-runtime-probation.service + +[Install] +WantedBy=timers.target