docs: SHADOW-01 (legacy-gameboy-v1 section 18, implementation guide) and the rehearsal script

Section 18 fixes what the 3-hour zero-divergence gate means: the inputs,
the architecture (the live legacy fly stays primary; the shadow follows
its trace), what is compared, the declared differences, the window and
the verdict contract. tools/shadow-rehearsal.sh runs the real service and
the real shadow side by side from one checkpoint.
This commit is contained in:
acamilo 2026-09-29 21:19:40 +00:00
parent 095cf7b1da
commit c09ac100ce
3 changed files with 395 additions and 0 deletions

View file

@ -440,6 +440,118 @@ B1, N1 and N3.
plus the world's and the agent's artifact seals and reads. plus the world's and the agent's artifact seals and reads.
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks. - Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
- The report `claude-task-01` has the per-phase table and what would close the rest. - The report `claude-task-01` has the per-phase table and what would close the rest.
### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
live behaviour. flysim gains trace switches that are off unless set, and the compatibility string
is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs,
the architecture, what is compared, the declared differences, the window and the verdict CUT-01
reads.
- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only:
- `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE`
path.
- `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB.
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions.
- `frame::ledgers_string` is now the one definition of the ledger string. The session task's
`ledgers_of` calls it.
- **`fly-legacy-session::shadow`** and the binary `fly-shadow`:
- `follow` reads the per-process files. It hands out complete lines only, and a file ends when
a newer one exists.
- `spool` copies every new store generation as it appears. It keeps a floor and a byte bound,
and never writes to a live store.
- `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the
live file byte for byte, after `host-fields` and `archive-order`.
- `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`,
`fly-shadow check`).
- The runner boots each segment from the live process's startup save (TASK-01's import). It
replays the admissions, runs the transition, and takes the live captures in the live order
around a deferred rollback. It compares with `trace::compare_line`, which is now shared with
`trace::compare`. It stops on the first divergence and writes `divergence.json` with 30
transitions of context.
- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to
flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the
commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the
unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship
`fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a
"Shadow run (SHADOW-01)" section.
- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real
`fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service
restarts. It runs on a build box, never on a host.
**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real
service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every
run. It totalled **3,489 brain seconds (58 brain minutes), 208,410 transitions, 11 processes and
zero divergence**:
| Run | Start | Brain s | Transitions | What it covered |
| --- | --- | --- | --- | --- |
| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary |
| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves |
| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward |
| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` |
| smoke | row 67, unthrottled | 122 | 7,305 | the first run |
The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and
finished 12 minutes behind. Every save was still compared, from the spool.
`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart
under a shadow, then plants four differences on copies of that run's trace and spool. Each one
stops a fresh shadow with the right kind, field and step:
- a work-RAM digest;
- a ledger digest;
- a sugar removed, which diverges on the brain at that transition;
- a live save's `rankSinceMs`.
**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other
agents' runs made paired measurements vary by up to 2x.
- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The
live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a
frame, so the session runtime costs about what the legacy loop does (x1.05).
- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the
main trace unthrottled gave these means:
- in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms;
- thread mode with 2 threads: 18.5 ms;
- process mode with 2 threads: 18.5 ms.
Every replay was identical again.
- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB.
- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best
paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has
1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is
160 MB per live hour.
The resource plan for the release container is in the SHADOW-01 run report and in
`units/flyshadow.service`:
- `SCHED_IDLE` on the page and encoder CPUs, never flysim's;
- 2 sweep threads;
- a back-off whenever the live `fly_lag_seconds` grows;
- a 3 GB memory ceiling;
- a ledger digest every 60 transitions.
To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace
is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later.
**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An
emulator imported from a state therefore drifts from a powered-on one in its channel accumulators.
The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores
through an import in both runtimes, so the two agree. A fresh start does not import, and the
shadow follows one by powering on as well.
**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast`
had three failures, each accounted for:
- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes
alone.
- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main.
- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load
22.
`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures,
typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is
648 B `8ce67b97...` in raw and macros mode, unchanged.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery

View file

@ -680,3 +680,120 @@ graph validation for new bundles, and the composite behaviour identity of FOUNDA
**not** in this document. They ship with PROF-02b, before DATA-01, as their own contract. **not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
Nothing here constrains them, except that a new profile never reuses this profile's id or its Nothing here constrains them, except that a new profile never reuses this profile's id or its
legacy exception. legacy exception.
## 18. The shadow run (SHADOW-01)
**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic
cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that
means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit
`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`.
**The inputs.** The legacy loop is deterministic, given two things: the state a process starts
from and the admissions applied at the top of each frame. Every nondeterministic input reaches
the fly through one of those two:
| Input | How it reaches the fly | How the shadow gets it |
| --- | --- | --- |
| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g<N>`); the shadow boots a new session from it through the ordinary FLYSIM01 import |
| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) |
| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared |
| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where |
| Chat | A caption track; it reaches nothing the fly does | Not needed |
| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own |
So "the same inputs" means *the same start state per process and the same admissions per
transition*. Admission itself is not compared. The session runtime decides admission against a
pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on
its own clock would diverge by design, not by fault.
**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live
service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a
behaviour field or anything the fly does:
- `FLY_TRACE_DIR` writes one file per process, `trace-<start wall ms>-<pid>.jsonl`.
- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode).
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of
`flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the
executor's scene, bound set, running macro, counts and "nearer".
`fly-shadow` follows the files in start order. For each file it takes these steps:
1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup
save. A fresh start is different: the stores were empty and the startup save is at boundary 0.
In that case the shadow runs the same power-on scaffold and warm-up
(`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own
boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio
resampler phase is not in its exported state, so the channel accumulators of an imported
emulator drift from those of a powered-on one, in the exported state only. Both restores of a
restart import, so they agree.
2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a
capture wherever the live trace records one, before or after the boundary's rollback as the
live loop took it, then applies the deferred rollback.
3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and
compares it with the live line, field by field.
A spool thread copies every new store generation as it appears, because a hot file lives only
about ten seconds. The shadow never writes to the live stores.
The reverse arrangement was considered: the session runtime as primary, with legacy as the
checker. It would make the shadow run the cutover itself, and a divergence would already be on
the stream. A second legacy process in lockstep was also considered. It adds nothing, because the
live process's own trace *is* the legacy behaviour.
**What is compared, per boundary.**
- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`,
`brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`,
`macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary`
and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and
the rollbacks.
- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same
string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's
ledgers, which no checkpoint carries.
- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same
boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export
byte for byte with the live file after the substitutions named below. `compatibility`,
`speed` and `rankSinceMs` are the shadow's own, so they are compared too.
**Declared differences**, excluded by name. The verdict lists the same names.
| Name | What is excluded |
| --- | --- |
| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") |
| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) |
| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. The session runtime has no feed event log before EDGE-01, and as a shadow it allocates no generations |
| `admission-replay` | Sugar is replayed, not re-decided (above) |
| `operator-reward-pulse` | A segment with one is reported uncompared from that transition on |
**The window.** The verdict is `pass` once the compared transitions add up to **10,800 s of
live brain time** (the sum of `ticksAdvanced`, 3 h at real time) with zero divergence. That time
may span several processes. A process whose startup save is already gone when the shadow reaches
it (the shadow started late, or the spool bound evicted it) is listed under `skipped` and adds
nothing. A process killed hard loses its unflushed tail, and those transitions are not compared.
The first difference of any kind stops the shadow with `diverged` (exit status 3) and writes
`divergence.json` with the 30 transition pairs before it:
- a trace field;
- the ledgers;
- the checkpoint bytes;
- a session error;
- a startup save the session runtime cannot restore.
A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference.
**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
automatically only if all of the following hold when it reads the file, at the moment of cutting
over:
- `status` is `pass` and `firstDivergence` is `null`;
- `compared.brainSeconds` ≥ `required.brainSeconds`;
- the session-runtime binary being switched to is one of `candidate.binaries`, by file name and
SHA-256. These are the release binaries beside the shadow: the shadow proves the release it
shipped in, and SERVE-01's service is built from the same tree;
- `candidate.compatibility` is the live `--print-compatibility`;
- `updatedAt` is recent: the shadow is still following.
`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
CUT-01's.

166
tools/shadow-rehearsal.sh Executable file
View file

@ -0,0 +1,166 @@
#!/usr/bin/env bash
# tools/shadow-rehearsal.sh -- SHADOW-01's offline rehearsal: the real `flysim` service and the
# real `fly-shadow` side by side on one machine, exactly as the release container runs them, from
# one FLYSIM01 checkpoint, with sugar posted to the control API and service restarts.
#
# FLY_ROM=<cartridge> tools/shadow-rehearsal.sh --checkpoint FILE [options]
#
# Options:
# --checkpoint FILE the live checkpoint the fly starts from (required)
# --brain-minutes N stop the live service after N brain minutes (default 30)
# --restart-at LIST restart flysim at these brain minutes, comma separated (default: none)
# --sugar-every S POST /stimulate about every S wall seconds (default 20; 0 = never)
# --speed X flysim loop.speed (default 0 = unthrottled; 1 = real time)
# --live-threads N flysim RAYON_NUM_THREADS (default 3, the release value)
# --mode M --threads N the shadow's execution mode and agent threads (in-process, 2)
# --ledgers N FLY_TRACE_LEDGERS (default 1: every boundary)
# --out DIR where everything goes (default: a new temporary directory)
# --bin DIR flysim, fly-shadow (and fly-session for --mode process); default
# $CARGO_TARGET_DIR/release or services/flysim/target/release
# --port N first of three local ports (default 17400)
# --guard S the shadow's --max-live-lag-seconds against the live metrics (0.5, as
# on the container; 0 disables)
#
# Environment: FLY_ROM (required); FLYSIM_PATHS_DATASET (default data/fafb-v783);
# FLY_ACCEPT_ADAPTERS passes through. Nothing here touches a host: every path is under --out.
#
# Result: <out>/shadow/verdict.json (and divergence.json on a divergence) and <out>/summary.txt:
# live and shadow CPU seconds per wall second, live frames per wall second, the verdict.
set -euo pipefail
die() { echo "shadow-rehearsal: $*" >&2; exit 2; }
repo="$(cd "$(dirname "$0")/.." && pwd)"
checkpoint=""; brain_minutes=30; restart_at=""; sugar_every=20; speed=0; live_threads=3
mode=in-process; threads=2; ledgers=1; out=""; bin=""; port=17400; guard=0.5
while [ $# -gt 0 ]; do
case "$1" in
--checkpoint) checkpoint="$2"; shift 2 ;;
--brain-minutes) brain_minutes="$2"; shift 2 ;;
--restart-at) restart_at="$2"; shift 2 ;;
--sugar-every) sugar_every="$2"; shift 2 ;;
--speed) speed="$2"; shift 2 ;;
--live-threads) live_threads="$2"; shift 2 ;;
--mode) mode="$2"; shift 2 ;;
--threads) threads="$2"; shift 2 ;;
--ledgers) ledgers="$2"; shift 2 ;;
--out) out="$2"; shift 2 ;;
--bin) bin="$2"; shift 2 ;;
--port) port="$2"; shift 2 ;;
--guard) guard="$2"; shift 2 ;;
*) die "unknown option $1" ;;
esac
done
[ -n "$checkpoint" ] && [ -f "$checkpoint" ] || die "--checkpoint FILE is required"
: "${FLY_ROM:?FLY_ROM must name the cartridge}"
[ -n "$bin" ] || bin="${CARGO_TARGET_DIR:-$repo/services/flysim/target}/release"
for b in flysim fly-shadow; do [ -x "$bin/$b" ] || die "no $bin/$b (cargo build --release --bins)"; done
dataset="${FLYSIM_PATHS_DATASET:-$repo/data/fafb-v783}"
[ -n "$out" ] || out="$(mktemp -d "${TMPDIR:-/tmp}/shadow-rehearsal.XXXXXX")"
live="$out/live"; shadow_dir="$out/shadow"
mkdir -p "$live/hot" "$live/durable" "$live/trace" "$shadow_dir"
cp "$checkpoint" "$live/durable/1.checkpoint"
printf '{"generation":1,"latest":1,"previous":null,"archives":{}}\n' > "$live/durable/manifest.json"
# The live service's configuration; the shadow reads the same (Config::load, as on the container).
export FLYSIM_PATHS_ROM="$FLY_ROM" FLYSIM_PATHS_DATASET="$dataset" FLYSIM_LOOP_GAME=pokemon-red
export FLY_STATE="$live/durable" FLY_STATE_HOT="$live/hot" FLY_MACRO_MODE=macros
export FLY_FEED_BIND="127.0.0.1:$port" FLY_CONTROL_BIND="127.0.0.1:$((port + 1))"
export FLY_METRICS_ADDR="127.0.0.1:$((port + 2))" FLY_CHAT_ENABLED=false
export FLYSIM_LOOP_SPEED="$speed"
control="http://127.0.0.1:$((port + 1))"
cpu_seconds() { # utime+stime of a pid and its children that have been reaped, in seconds
awk -v hz="$(getconf CLK_TCK)" '{ print ($14 + $15 + $16 + $17) / hz }' "/proc/$1/stat" 2>/dev/null || echo 0
}
status_ms() { # brain ms of a running (not booting) service, else empty
curl -fsS --max-time 2 "$control/status" 2>/dev/null | python3 -c '
import json, sys
v = json.load(sys.stdin)
if v.get("status") == "running" and v.get("brainMs"):
print(int(v["brainMs"]))' 2>/dev/null || true; }
live_pid=""; live_n=0; live_cpu=0
start_live() {
live_n=$((live_n + 1))
RAYON_NUM_THREADS="$live_threads" FLY_TRACE_DIR="$live/trace" FLY_TRACE_LEDGERS="$ledgers" \
"$bin/flysim" > "$live/flysim-$live_n.log" 2>&1 &
live_pid=$!
for _ in $(seq 1 600); do
[ -n "$(status_ms)" ] && return 0
kill -0 "$live_pid" 2>/dev/null || { tail -20 "$live/flysim-$live_n.log" >&2; die "flysim exited"; }
sleep 0.5
done
die "flysim did not come up"
}
stop_live() {
local c; c=$(cpu_seconds "$live_pid"); live_cpu=$(awk -v a="$live_cpu" -v b="$c" 'BEGIN{print a+b}')
kill -TERM "$live_pid"; wait "$live_pid" || true
}
wall0=$(date +%s.%N)
"$bin/fly-shadow" run --out "$shadow_dir" --trace-dir "$live/trace" --all-files --keep-traces --keep-spool \
--mode "$mode" --threads "$threads" --max-live-lag-seconds "$guard" \
--required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 &
shadow_pid=$!
start_live
echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)"
brain_done=0; seg_start="$(status_ms)"; seg_last="$seg_start"; next_sugar=$(date +%s); sugar_posted=0
IFS=',' read -r -a restarts <<< "$restart_at"
restart_i=0
while :; do
sleep 1
ms="$(status_ms)"; [ -n "$ms" ] && seg_last="$ms"
elapsed=$(( brain_done + seg_last - seg_start ))
kill -0 "$shadow_pid" 2>/dev/null || { echo "shadow-rehearsal: fly-shadow exited early" >&2; break; }
if [ "$sugar_every" != 0 ] && [ "$(date +%s)" -ge "$next_sugar" ]; then
duration=$(( 200 + RANDOM % 800 ))
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 -X POST "$control/stimulate" \
-H 'content-type: application/json' \
-d "{\"durationMs\":$duration,\"by\":\"rehearsal\",\"source\":\"operator\"}" || true)
case "$code" in 2*) sugar_posted=$((sugar_posted + 1)) ;; esac
next_sugar=$(( $(date +%s) + sugar_every / 2 + RANDOM % (sugar_every + 1) ))
fi
if [ "$restart_i" -lt "${#restarts[@]}" ] && [ -n "${restarts[$restart_i]}" ] \
&& [ "$elapsed" -ge $(( ${restarts[$restart_i]} * 60000 )) ]; then
echo "shadow-rehearsal: restarting flysim at brain $((elapsed / 1000)) s"
stop_live; brain_done=$elapsed
start_live; seg_start="$(status_ms)"; seg_last="$seg_start"
restart_i=$((restart_i + 1))
fi
[ "$elapsed" -ge $(( brain_minutes * 60000 )) ] && break
done
stop_live
live_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}')
total=$(cat "$live"/trace/trace-*.jsonl | grep -c '"behaviour"' || true)
echo "shadow-rehearsal: live stopped after $((elapsed / 1000)) brain s, $total transitions traced; waiting for the shadow"
while kill -0 "$shadow_pid" 2>/dev/null; do
compared=$(python3 -c 'import json,sys; v=json.load(open(sys.argv[1])); print(v["compared"]["transitions"] + sum(s["transitionsCompared"] for s in v["skipped"]))' "$shadow_dir/verdict.json" 2>/dev/null || echo 0)
[ "$compared" -ge "$total" ] && break
sleep 2
done
shadow_cpu=$(cpu_seconds "$shadow_pid")
shadow_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}')
kill -TERM "$shadow_pid" 2>/dev/null || true
rc=0; wait "$shadow_pid" || rc=$?
{
echo "checkpoint: $(basename "$checkpoint")"
echo "live: $live_n process(es), $total transitions, $((elapsed / 1000)) brain s, ${live_wall%.*} wall s, sugar posted $sugar_posted"
awk -v c="$live_cpu" -v w="$live_wall" -v t="$total" 'BEGIN{printf "live: %.2f cores, %.1f frames per wall second\n", c/w, t/w}'
awk -v c="$shadow_cpu" -v w="$shadow_wall" -v t="$total" 'BEGIN{printf "shadow (%s, %s threads): %.2f cores over %.0f wall s, %.1f frames per wall second\n", "'"$mode"'", "'"$threads"'", c/w, w, t/w}'
echo "shadow exit: $rc"
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['transitions']} transitions, {c['brainSeconds']} brain s, {c['segments']} segments, "
f"{c['sugar']} sugar, {c['rewards']} rewards {c['rewardKinds']}, {c['macroEvents']} macro events, "
f"{c['slotSaves']} slot saves, {c['rollbacks']} rollbacks, {c['ledgerChecks']} ledger checks, "
f"checkpoints {c['checkpoints']}")
print(f"skipped: {v['skipped']}")
print(f"cost: {v['cost']}")
if v["firstDivergence"]:
print(f"FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
PY
} | tee "$out/summary.txt"