Merge port/serve-01 (SERVE-01) into v0.7.0 release candidate

Conflicts in fly-legacy-session task.rs (feed record next to PERF-01 profile spans) and
fly-session coordinator.rs (media_bytes doc, read_agent_extension and trim_records kept
alongside PERF-01 spans, publish span and publish metric both kept).
This commit is contained in:
acamilo 2026-09-30 10:06:03 +00:00
commit b996695f0a
28 changed files with 4446 additions and 136 deletions

View file

@ -622,6 +622,114 @@ coordinator (TASK-01); this slice ships the pieces and proves them on the worker
- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive - *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive
holds the post-capture ratchet and slot. It is excluded from the shadow comparison. holds the post-capture ratchet and slot. It is excluded from the shadow comparison.
### SERVE-01 — The session runtime as the live service (port slice)
**2026-09-29: built** on `port/serve-01` off `port/task-01` and awaiting review. It makes the
session runtime a drop-in for the live `flysim` service, so CUT-01 can switch the stream over
with one command and roll back with one. It changes no live behaviour: the legacy loop's frame,
feed, checkpoint bytes and compatibility string are unchanged, and nothing runs the new binary
until `fly-runtime session` is run on a container.
- **One service shell, two runtimes** (`flysim::serve`). `flysim::run` is split: `serve(config,
sim)` binds the feed (`:7400`, or the feed bus that `fly-edge` serves), the control API
(`:7401`) and the metrics listener (`:9101`), handles SIGTERM/SIGINT/SIGHUP, and runs `sim` on
the calling thread with the `Shared` state, the snapshot slot and the command queue. The
legacy loop is `serve(config, Sim::boot + Sim::run)`. The pieces of a feed header that come
from the fly (`feed_rates`, `feed_learning`, `feed_game`, `feed_milestone`, `feed_sugar`) and
the chat admission (`admit_chat`) move out of `Sim` into free functions both runtimes call.
The feed codec, the bus publisher, the router, `/status`, `/events`, `/metrics` and the
WebSocket framing are therefore one copy of the code whichever runtime is behind them.
- **The service host** (`fly-legacy-session::service`, binary `flysim-session`). It reads
`flysim`'s own `Config` (so `/etc/fly/fly.env`, `FLY_ACCEPT_ADAPTERS` through STATE-02's
`RestoreGate`, the macro mode, speed, threads, chat, the store paths) and keeps `Sim`'s order
call site for call site: boot by TASK-01's `boot_unsaved` (the legacy candidate order and gate),
the boot event, the chat sidecar, the journal's boot header (`runtime: fly-session`), the
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,
the same filter on the environment's `v / 255`); the spike bitset is the OR of the commits'
`telemetry.spikes` since the last publish, which equals the legacy window exactly; `buttons`
is the executor's mask (the checkpoint's after an import, 0 after a rollback, as
`LegacyFrame` has it); the game, milestone and macro fields are the task's own adapter,
ratchet and macro layer (`PokeredTask::inspect`, `take_feed`). The numbers from inside the
network that no session message carries -- the plasticity statistics (`learning.changed`,
`learning.synapses`), the decoder's baselines and scores for `/status`, and the rates and pulse
at the boundary -- come from one declared extension of the legacy agent,
`Legacy.FeedStatus` (capability `legacy-feed-status-v1`): read-only, answered at a committed
`Ready(k)`, once per published snapshot, never in a trace. `Coordinator::read_agent_extension`
calls it without fencing the epoch; `Coordinator::media_bytes` reads the committed view and
audio chunk.
- **Sugar.** flysim's `RateLimiter` and clamp, over the pulse the network holds: the last commit's
`stimulusRemainingMs`, raised by each sugar admitted since (`network.stimulate` is a maximum),
so a second request in one drain is refused with the legacy `retryAfterMs`. The admission lands
in the next Prepare, which is the frame the legacy drain applies it before, and the journal
stamps it with that frame.
- **Long-running hygiene.** The coordinator kept every transition's trace, every phase change,
an audit line per step and every timing sample: about 120 KB/s of heap on the live fly
(the first soak's RSS). `Coordinator::trim_records` bounds them at each boundary; the timings
are logged once a minute as a `session profile` line and cleared.
- **Declared differences** (the rest is byte-equal, below): `POST /reward` is always 403
(`control.allow_reward` is forced off; the operator pulse has no session-framework
counterpart, `legacy-gameboy-v1` section 15); a fresh start publishes no audio for its setup
frame (the environment discards O[0]'s); `FLY_TRACE` and `FLY_PROFILE_SECONDS` are the legacy
loop's tools; only the Pokémon composition exists (another `FLY_GAME` is refused at start); the
toy connectome cannot run macros mode (AGENT-01 refuses a macro channel the dataset does not
track, and the toy tracks none).
- **Infra.** `flysim.service` stays the fly's one unit. `infra/bin/fly-runtime session|legacy|status`
switches the binary it runs with one drop-in (`flysim.service.d/10-runtime.conf`), so every
consumer that names `flysim.service` -- `fly.target`, `flyedge.service`'s `Requires=`, the
watchdog, `fly-loop-recover`'s sudoers-granted restart, `fly-loop-reset`,
`fly-reset-to-milestone`, the unstick rule -- works unchanged and the choice survives reboots and
deploys. It refuses a release without `flysim-session` or with a different compatibility
string, waits for `/healthz` and an advancing frame, and falls back to legacy by itself if the
session runtime does not come up. `flysim-session.service` is the standalone unit (flysim's
limits and cpuset, `Conflicts=flysim.service`, no `[Install]`) for rehearsals.
`build-flysim.sh`/`package-release.sh` ship `flysim-session` and `fly-session`; `05-deploy.sh`
installs `fly-runtime`, writes the standalone unit's cpuset drop-in and refuses a release
without `flysim-session` while the drop-in is present; tmpfiles creates `/run/fly/session`.
The runbook's "Switch the runtime" is the operator's page.
**Proof** (`fly-legacy-session/tests/service_parity.rs`, `journal_replay.rs`, rom-env; the SERVE-01
run report has the numbers). Both runtimes are started from the same seeded store behind
flysim's own control router and driven by one script of control requests, each landing before
the same frame: every running feed header is equal field by field (wall-clock fields excepted)
and every frame, audio and spike attachment byte for byte; every control response is equal
(`/stimulate` 202/429 with the same `retryAfterMs`, `/reward` 403, `/chat` 202/422,
`/checkpoint` the same generation, `/pause`, `/resume`, `/events`, 404s); the event log, the
journal and the final checkpoint are equal. Toy connectome raw mode, and the real connectome in
macros mode through a ratchet rollback, each in-process and as processes. A soak of both
runtimes side by side with the stage's decoder and the bridge's `HttpSimClient`
(`tools/runtime-soak.ts`), the hot/durable cadence sampled from the stores, and a `SIGKILL`
whose journal is replayed from the seed in the legacy loop onto the killed process's last hot
checkpoint.
Results (2026-09-29, the build boxes; the run report has the logs):
| Proof | Result |
| --- | --- |
| Toy raw, 120 frames, 19 scripted requests incl. two sugars in one drain | identical, in-process and process |
| Real connectome, macros, `rollback` checkpoint (ratchet rollback on frame 1), 120 frames | identical, both modes, before and after the TASK-01 fixes |
| Real connectome, macros, engage checkpoint (ledger thinned), 2400 frames, 46 macro and 2 reward events | identical, both modes |
| Real connectome, macros, row 64 (a 42 KB adapter ledger, TASK-01 B1), 1200 frames | identical, both modes |
| Soak, 35 min, both runtimes from the row 67 checkpoint, production configuration | 0 decode or schema errors, no 2 s stall, `/healthz` 100 %, event ids gapless, hot every 5 s and durable at 300 s on both (same intervals) |
| Soak, 36 min, the session killed -9 at +6 min | back in about 1 s from the hot checkpoint 3.5 s old, 1 `/healthz` 503, the feed client reconnected (533 ms gap), two journal segments |
| The killed process's journal, 17 sugars, replayed from the seed in the legacy loop | 18,838 frames onto its last hot checkpoint: agent, emulator, frame, adapter, ratchet equal |
| Feed over the bus (`FLY_FEED_VIA=bus`) with `fly-edge` | 3,050 snapshots through the edge, 0 errors |
Open for CUT-01: **speed.** Unpaced on a shared box the session ran 54-61 fps where the legacy
loop ran 68-118 (per frame p50: `Agent.Prepare` 7.8 ms, `Environment.Advance` 2.6,
`Agent.Commit` 1.6, publication 0.4; `Legacy.FeedStatus` 0.9 ms at 30 Hz). The live container
must be measured (SHADOW-01's cost run) before cutover. **Memory.** After `trim_records` the
session's RSS still grows about 5-8 MB an hour, tied to the saves (an unpaced run without saves
is flat); at `MemoryMax=4G` that is weeks, and a restart clears it, but it is not explained yet.
**Number form.** A checkpoint the session writes carries the adapter ledger's integral numbers
as `7580031` where the legacy loop writes `7580031.0` (the ledger crossed canonical JSON); equal
values, and both runtimes read both.
### PUBLISH-01 — Committed snapshots and observer isolation ### PUBLISH-01 — Committed snapshots and observer isolation
**Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to

View file

@ -387,6 +387,37 @@ The 'current' symlink has NOT been moved; the running release is untouched."
fi fi
fi fi
# The session runtime (SERVE-01). While `fly-runtime session` has pointed flysim.service at
# flysim-session (the drop-in below), a release without that binary would leave the fly
# unable to start at all, and one whose session string differs from flysim's would write
# checkpoints the other runtime refuses. Refused here, before the symlink moves; to deploy
# such a release anyway, `fly-runtime legacy` first.
#
# Policy (C2 of the SERVE-01 review), operator decision 2026-09-29: "Session stays, trust gates".
# A deploy KEEPS the chosen runtime. It does not drop to legacy and does not re-run
# the shadow for the new flysim-session binary; the trust gates before the release (the
# parity and service tests, the compat check just below) are what vouch for it. A bad
# release is caught afterwards by the persistent fallback: while the drop-in exists,
# flysim.service carries OnFailure=fly-runtime-fallback.service and RestartMode=direct with a 3-starts-in-10-minutes
# limit, so a session binary that will not stay up puts the fly back on legacy by itself
# (`fly-runtime fallback`, /run/fly/runtime-fellback.json), whoever restarted it.
if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/flysim-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime (fly-runtime session) and this release has no flysim-session. Run \`fly-runtime legacy\` in the container first, or deploy a release that ships it. The 'current' symlink has NOT been moved."
session_compat="$(ct_exec "$CTID" -- env \
"FLY_GAME=${GAME}" \
"FLY_DATASET=${release_path}/data/fafb-v783" \
"FLY_ROM=/srv/fly/rom/${ROM_SHA256:-none}.gb" \
"${release_path}/flysim-session" --print-compatibility 2>/dev/null | tr -d '\r' || true)"
if [ -n "${new_compat:-}" ] && [ "$session_compat" != "$new_compat" ]; then
die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime and its compatibility string differs from flysim's.
flysim: ${new_compat}
flysim-session: ${session_compat}
The 'current' symlink has NOT been moved."
fi
log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string"
fi
log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically" log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically"
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current" ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
else else
@ -677,9 +708,11 @@ if [ -n "${CPUSET:-}" ]; then
tmp_dropin="$(mktemp)" tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day # flyedge is off by default, but its drop-in is written with the rest so that the day
# it is enabled it serves the page from the page's CPUs, never from flysim's. # it is enabled it serves the page from the page's CPUs, never from flysim's.
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do # flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session; do
case "$u" in case "$u" in
flysim) cpus="$sim_cpus" ;; flysim|flysim-session) cpus="$sim_cpus" ;;
flycast) cpus="$encoder_cpus" ;; flycast) cpus="$encoder_cpus" ;;
*) cpus="$page_cpus" ;; *) cpus="$page_cpus" ;;
esac esac
@ -708,10 +741,18 @@ fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /opt/fly/bin" log "05-deploy: converging bin/ helpers to /opt/fly/bin"
ct_exec "$CTID" -- mkdir -p /opt/fly/bin ct_exec "$CTID" -- mkdir -p /opt/fly/bin
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-runtime 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 converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
done done
# A container already on the session runtime keeps it (see the policy note at the compat check
# above), and its drop-in is rewritten in place from the current template (no restart) so that
# the OnFailure= fallback and MALLOC_ARENA_MAX reach containers switched before they existed.
if [ -n "${RELEASE_TARBALL:-}" ] && ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- /opt/fly/bin/fly-runtime session --no-restart \
|| log "05-deploy: WARNING: could not refresh the session drop-in; it keeps its old content (no OnFailure= fallback until \`fly-runtime session\` is re-run)"
fi
# The NOPASSWD surface those helpers use (config/fly-sudoers). 02-base installs it at # The NOPASSWD surface those helpers use (config/fly-sudoers). 02-base installs it at
# provision time; converging it here too means a release that adds a helper's line # provision time; converging it here too means a release that adds a helper's line
# (fly-loop-reset, v0.6.4) does not need a re-provision. Validated before install. # (fly-loop-reset, v0.6.4) does not need a re-provision. Validated before install.

405
infra/bin/fly-runtime Executable file
View file

@ -0,0 +1,405 @@
#!/usr/bin/env bash
# infra/bin/fly-runtime — which runtime the live fly runs: the legacy loop (`flysim`) or the
# session runtime (`flysim-session`, SERVE-01).
#
# 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 legacy [--no-restart]
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
#
# CUT-01 calls `fly-runtime session` after its zero-divergence shadow; `fly-runtime legacy` is
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
#
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
# is chosen by one drop-in, ${DROPIN}:
#
# [Service]
# ExecStart=
# ExecStart=/opt/fly/current/flysim-session
# Environment=FLY_SESSION_DIR=/run/fly/session
#
# i.e. flysim-session.service's ExecStart and its one extra variable (the standalone unit and
# this drop-in are kept identical by infra/tests/lint.sh). Everything else that names
# flysim.service -- fly.target, flyedge.service's Requires=, fly-watchdog's checks and escalation,
# fly-loop-recover's `sudo systemctl restart flysim.service` and its sudoers line,
# fly-loop-reset, fly-reset-to-milestone, the unstick rule, `journalctl -u flysim`, the cpuset
# drop-in -- therefore keeps working unchanged, a reboot keeps the choice, and 05-deploy.sh (which
# converges unit files but never removes a drop-in) keeps it across deploys. 05-deploy.sh refuses
# a release without flysim-session while the drop-in is present.
#
# `session` refuses unless the release has flysim-session and its --print-compatibility equals
# flysim's (the store is shared, so the two must restore each other's checkpoints). After the
# restart it waits for /healthz (FLY_RUNTIME_HEALTH_TIMEOUT, default 300 s: the connectome load and
# the restore) and a snapshot that has advanced; if the session runtime does not come up healthy
# it switches back to legacy by itself and exits 1 (--no-fallback leaves it to the operator).
#
# The fallback survives the invocation (C1 of the SERVE-01 review). The drop-in also carries
#
# [Unit]
# OnFailure=fly-runtime-fallback.service
# StartLimitIntervalSec=600
# StartLimitBurst=3
# [Service]
# RestartMode=direct
#
# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default
# RestartMode=normal the unit passes through `failed` before every Restart=always restart and
# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit
# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes
# (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and
# fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd
# runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove
# the drop-in, daemon-reload, restart flysim.service (now the legacy binary) and log a line. That
# holds across reboots, watchdog and loop-recover restarts and deploys, none of which go through
# `fly-runtime session`. It is idempotent (a lock, and a no-op once the drop-in is gone) and it
# keeps the drop-in when there is no executable legacy binary, so it never swaps one runtime that
# cannot start for another. `fly-runtime session` deletes the reason file; `status` shows it.
#
# During a switch fly-runtime traps INT, TERM and HUP (and any failure): an interrupted `session`
# 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.
#
# Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}.
set -euo pipefail
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_RUNTIME_HEALTH_TIMEOUT:=300}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_SYSTEMD_DIR:=/etc/systemd/system}"
: "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}"
: "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}"
: "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}"
: "${FLY_RUNTIME_LOCK_WAIT:=150}"
DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d"
DROPIN="${DROPIN_DIR}/10-runtime.conf"
RUNTIME_LOG="$FLY_RUNTIME_LOG"
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
FALLBACK_UNIT=fly-runtime-fallback.service
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
SESSION_DIR=/run/fly/session
log() { echo "fly-runtime: $*" >&2; }
die() { log "$*"; exit 1; }
usage() {
echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] | legacy [--no-restart] | fallback [reason]" >&2
exit 2
}
current() {
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
}
record() {
local line
line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
if command -v logger >/dev/null 2>&1; then
logger -t fly-runtime -- "$*" || true
fi
mkdir -p "$(dirname "$RUNTIME_LOG")" 2>/dev/null || true
echo "$line" >>"$RUNTIME_LOG" 2>/dev/null || log "could not append to $RUNTIME_LOG"
}
# The compatibility string a binary would write, with the service's own environment: fly.env is
# systemd's EnvironmentFile syntax, read as KEY=VALUE lines rather than sourced as shell.
compat_of() {
local -a vars=()
local line key value
if [ -f "$FLY_ENV_FILE" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
key="${line%%=*}"
value="${line#*=}"
value="${value%\"}"
value="${value#\"}"
vars+=("${key}=${value}")
done <"$FLY_ENV_FILE"
fi
env "${vars[@]}" "$1" --print-compatibility 2>/dev/null | tr -d '\r'
}
write_dropin() {
mkdir -p "$DROPIN_DIR"
local tmp="${DROPIN}.tmp.$$"
cat >"$tmp" <<EOF
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
# Keep [Service] in step with units/flysim-session.service.
[Unit]
OnFailure=${FALLBACK_UNIT}
StartLimitIntervalSec=600
StartLimitBurst=3
[Service]
RestartMode=direct
ExecStart=
ExecStart=${SESSION_BIN}
Environment=FLY_SESSION_DIR=${SESSION_DIR}
Environment=MALLOC_ARENA_MAX=2
EOF
chmod 0644 "$tmp"
mv -f "$tmp" "$DROPIN"
}
# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
healthy() {
local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
local first=""
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
local frame
frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
| sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$frame" ]; then
if [ -z "$first" ]; then
first="$frame"
elif [ "$frame" -gt "$first" ]; then
log "healthy: frame ${first} -> ${frame}"
return 0
fi
fi
fi
sleep 1
done
return 1
}
# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
locked=0
take_lock() {
if [ "$locked" -eq 1 ]; then return 0; fi
mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
exec 9>>"$FLY_RUNTIME_LOCK"
if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
return 1
}
drop_lock() {
exec 9>&-
locked=0
}
restarted=0
old_invocation=""
restart_and_check() {
systemctl daemon-reload
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
log "restarting ${FLY_SERVICE} on the $(current) runtime"
restarted=1
# --no-block: a blocking restart of a unit that never becomes READY holds this process (and
# the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
# that it is talking to the NEW invocation, not the old process that is still shutting down.
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
drop_lock
healthy
}
# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
do_fallback() {
local reason="$1" result nrestarts saved
take_lock || log "continuing without the lock"
if [ ! -f "$DROPIN" ]; then
log "fallback: the legacy runtime is already selected; nothing to do"
return 0
fi
if [ ! -x "$LEGACY_BIN" ]; then
record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
return 1
fi
result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
reason="${reason//[\"\\]/}"
reason="${reason//$'\n'/ }"
mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
>"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
cp -f "$DROPIN" "$saved"
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
record "legacy (automatic fallback: ${reason}; was session)"
systemctl daemon-reload || true
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
restarted=1
if systemctl restart --no-block "$FLY_SERVICE"; then
rm -f "$saved"
return 0
fi
# Could not even queue the restart: keep what was running, and say so.
mkdir -p "$DROPIN_DIR" && mv -f "$saved" "$DROPIN"
systemctl daemon-reload || true
rm -f "$FELLBACK_FILE"
record "fallback FAILED (${reason}): could not restart ${FLY_SERVICE}; the session drop-in is back"
return 1
}
# An interrupted or failed switch puts the previous state back. `switching` is 1 from just
# before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the
# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and
# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the
# switch deleted it under the lock, only a finished fallback writes it): restoring the older
# drop-in then would strand the stream on the session runtime after it was taken off.
switching=0
switch_target=""
prev_dropin=""
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
take_lock || true
if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then
record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)"
restarted=0
elif [ "$switch_target" = session ]; then
if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then
mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN"
else
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
fi
record "$(current) (switch to session interrupted or failed (exit ${rc}); rolled back)"
else
record "$(current) (switch to legacy interrupted (exit ${rc}))"
fi
systemctl daemon-reload || true
if [ "$restarted" -eq 1 ]; then
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
systemctl restart --no-block "$FLY_SERVICE" || true
fi
fi
[ -z "$prev_dropin" ] || rm -f "$prev_dropin"
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
fallback=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 ;;
*) usage ;;
esac
done
case "$command" in
status)
current
if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true
exit 0
;;
session|legacy) ;;
fallback)
[ "$(id -u)" -eq 0 ] || die "run as root"
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
exit $?
;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${DROPIN} and restarts ${FLY_SERVICE})"
if [ "$command" = session ]; then
[ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
[ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
legacy_compat="$(compat_of "$LEGACY_BIN")"
session_compat="$(compat_of "$SESSION_BIN")"
[ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
if [ "$legacy_compat" != "$session_compat" ]; then
die "the two runtimes would write different checkpoints; not switching.
flysim: ${legacy_compat}
flysim-session: ${session_compat}"
fi
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current)"
if [ -f "$DROPIN" ]; then
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
cp -f "$DROPIN" "$prev_dropin"
fi
switch_target=session
switching=1
rm -f "$FELLBACK_FILE"
write_dropin
record "session (was ${before}); compatibility ${session_compat}"
if [ "$restart" -ne 1 ]; then
systemctl daemon-reload
switching=0
log "drop-in written; restart ${FLY_SERVICE} to apply"
exit 0
fi
if restart_and_check; then
# OnFailure= may have fallen back while we waited (a healthy legacy would pass the
# 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"
exit 0
fi
switching=0
log "the session runtime failed and ${FALLBACK_UNIT} fell back to legacy: $(cat "$FELLBACK_FILE" 2>/dev/null)"
exit 1
fi
log "the session runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s"
if [ "$fallback" -eq 1 ]; then
do_fallback "the session runtime was not healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s of the switch" || true
switching=0
if healthy; then
log "fell back to the legacy runtime; it is healthy"
else
log "fell back to the legacy runtime, and it is NOT healthy either: check journalctl -u ${FLY_SERVICE}"
fi
else
switching=0
fi
exit 1
fi
# legacy
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current)"
switch_target=legacy
switching=1
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
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
switching=0
log "flysim.service runs the legacy runtime"
exit 0
fi
switching=0
die "the legacy runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s: check journalctl -u ${FLY_SERVICE}"

View file

@ -85,6 +85,11 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
# without a rebuild. It lands next to OUT_PATH, where package-release.sh # without a rebuild. It lands next to OUT_PATH, where package-release.sh
# looks for it. # looks for it.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
# that `fly-runtime session` points flysim.service at; and fly-session, its worker program
# (FLY_SESSION_MODE=process only). Same features as flysim, built every time so a release
# can switch runtimes without a rebuild. Both land next to OUT_PATH.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-session "${features_args[@]}"
) )
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim" built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
@ -118,4 +123,12 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
cp "$edge_built" "$edge_out" cp "$edge_built" "$edge_out"
chmod 0755 "$edge_out" chmod 0755 "$edge_out"
log "built $edge_out ($(du -h "$edge_out" | cut -f1))" log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
for extra in flysim-session fly-session; do
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
extra_out="$(dirname "$OUT_PATH")/${extra}"
cp "$extra_built" "$extra_out"
chmod 0755 "$extra_out"
log "built $extra_out ($(du -h "$extra_out" | cut -f1))"
done
log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>" log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>"

View file

@ -14,6 +14,10 @@
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh # fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
# left one beside FLYSIM_BIN; flyedge.service stays # left one beside FLYSIM_BIN; flyedge.service stays
# inactive on a release without it) # inactive on a release without it)
# flysim-session (the session runtime, SERVE-01, and fly-session, its
# fly-session worker program; mode 0755, when build-flysim.sh left
# them beside FLYSIM_BIN. `fly-runtime session` refuses
# a release without flysim-session)
# stage/... (apps/stage's build output) # stage/... (apps/stage's build output)
# bridge/... (services/bridge + node_modules) # bridge/... (services/bridge + node_modules)
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
@ -82,6 +86,15 @@ if [ -x "$EDGE_BIN" ]; then
else else
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)" log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
fi fi
for extra in flysim-session fly-session; do
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
if [ -x "$EXTRA_BIN" ]; then
cp "$EXTRA_BIN" "${release_dir}/${extra}"
chmod 0755 "${release_dir}/${extra}"
else
log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)"
fi
done
cp -a "$STAGE_DIR" "${release_dir}/stage" cp -a "$STAGE_DIR" "${release_dir}/stage"
cp -a "$BRIDGE_DIR" "${release_dir}/bridge" cp -a "$BRIDGE_DIR" "${release_dir}/bridge"

View file

@ -9,6 +9,8 @@ d /run/fly/wd 0750 fly fly -
# ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's # ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's
# router socket and artifact store. flysim also creates it, 0700, on start. # router socket and artifact store. flysim also creates it, 0700, on start.
d /run/fly/bus 0700 fly fly - d /run/fly/bus 0700 fly fly -
# The session runtime's router store and worker sockets (SERVE-01, flysim-session).
d /run/fly/session 0700 fly fly -
d /var/lib/fly 0750 fly fly - d /var/lib/fly 0750 fly fly -
d /var/lib/fly/chrome 0700 fly fly - d /var/lib/fly/chrome 0700 fly fly -
d /srv/fly/state 0750 fly fly - d /srv/fly/state 0750 fly fly -

View file

@ -443,6 +443,82 @@ One `ln -sfn` plus a restart, per `docs/design/infra.md` section 2. Nothing else
touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`. touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`.
On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above. On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above.
## Switch the runtime (legacy loop or session runtime)
Two binaries in every release from SERVE-01 on run the same fly: `flysim`, the legacy loop, and
`flysim-session`, the same composition on the session framework (agent, Game Boy environment and
macro task as participants). They read the same `/etc/fly/fly.env`, write the same checkpoint
stores, event log, sugar journal and chat sidecar, and serve the same feed, control API and
metrics through the same listener code, so nothing else on the container can tell them apart.
`flysim.service` is the fly's one unit name either way; which binary it runs is one drop-in,
written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/opt/fly/bin`).
```
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 legacy # the one-command rollback
```
- **What it does.** `session` writes `/etc/systemd/system/flysim.service.d/10-runtime.conf`
(`ExecStart=/opt/fly/current/flysim-session`, `FLY_SESSION_DIR=/run/fly/session`),
daemon-reloads and restarts `flysim.service`; `legacy` deletes the file and does the same. No
data moves: the store is shared, and each runtime restores the other's checkpoints.
- **What it checks.** `session` refuses a release without `flysim-session`, and refuses when
`flysim --print-compatibility` and `flysim-session --print-compatibility` differ. After the
restart both wait for `/healthz` and a `/status` frame that advances
(`FLY_RUNTIME_HEALTH_TIMEOUT`, 300 s). If the session runtime does not come up healthy, it
switches back to legacy by itself and exits 1 (`--no-fallback` leaves it to the operator).
Every switch is logged (`journalctl -t fly-runtime`, `/var/lib/fly/runtime.log`).
- **The fallback outlives the switch (C1).** While the session runtime is selected, the drop-in
also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3`,
`StartLimitIntervalSec=600` and `RestartMode=direct`, and `MALLOC_ARENA_MAX=2` (glibc arena
fragmentation was the whole of the 5-8 MB/h RSS growth). `RestartMode=direct` is what makes the
limit real: since systemd 254 the default (`normal`) sends the unit through the `failed` state
before every `Restart=always` restart, so `OnFailure=` would fire on the first crash, watchdog
kill or start timeout (seen on systemd 257, the container's). With `direct` the unit goes from
one start to the next and only hitting the start limit fails it. Three starts of `flysim.service` within ten minutes, from any
cause and any caller (a reboot, the watchdog or `fly-loop-recover` restarting it, a deploy, a
binary that crashes, hangs before READY or is killed by `WatchdogSec`) make systemd run
`fly-runtime fallback`: it writes `/run/fly/runtime-fellback.json` (time, reason, unit result),
deletes the drop-in, daemon-reloads and restarts `flysim.service` on the legacy binary, and logs
a `fly-runtime` journal line. It is idempotent, and it does nothing if the release has no
executable `flysim`. Look with `fly-runtime status` (it prints the reason) or
`cat /run/fly/runtime-fellback.json`; the container is then on legacy until an operator runs
`fly-runtime session` again, which clears the reason file. Restarts you make yourself count
too, and once the limit is reached systemd refuses the next start and runs the fallback. Three legitimate restarts in ten
minutes count the same as three crashes: after that many, prefer `fly-runtime legacy`, do the
work, then switch back.
- **Interrupted switches roll back.** `fly-runtime` traps INT, TERM and HUP (an ssh that drops
mid-switch): an unfinished `session` removes the drop-in again (or restores the one that was
there) and restarts `flysim.service` on that state, so a drop-in that never passed its health
check is never left behind. `session`, `legacy`, `fallback` and that rollback all take one lock
(`/run/fly/runtime.lock`); a switch holds it while it changes the drop-in and queues the restart
(`systemctl restart --no-block`, so a unit that never becomes READY cannot hold it) and releases
it for the health wait. The rollback does nothing when a fallback finished after the switch began (the
reason file exists), so it can never put back an older drop-in over a fallback.
- **What stays the same.** Everything that names `flysim.service` keeps working unchanged:
`fly.target`, `flyedge.service`'s `Requires=`, the watchdog, `fly-loop-recover`'s restart and
its sudoers line, `fly-loop-reset`, `fly-reset-to-milestone` (run with the service stopped, on
the shared store), the unstick rule's `systemctl restart flysim.service`, `journalctl -u
flysim`, the cpuset drop-in. The choice survives a reboot and a deploy: `05-deploy.sh`
converges unit files but never removes a drop-in (it rewrites it in place from the current
template, without a restart), and it refuses a release without `flysim-session` or with a
different compatibility string while the drop-in is present (`fly-runtime legacy` first to
deploy one). **Policy (C2, operator decision 2026-09-29, "Session stays, trust gates"):** a
deploy keeps the chosen runtime on the new release's `flysim-session`, without re-running the
shadow for it. The trust gates before the release vouch for the binary, and the persistent
fallback above protects a bad one.
- **What differs, by declaration.** `POST /reward` is always 403 on the session runtime (the
operator pulse has no session-framework counterpart, `legacy-gameboy-v1` section 15); a
fresh start publishes no audio for its one setup frame; `FLY_TRACE` and
`FLY_PROFILE_SECONDS` are legacy-loop tools (the session runtime logs a `session profile`
line of per-phase timings every minute instead). The sugar journal's boot header says
`runtime: fly-session`.
- **The standalone unit.** `flysim-session.service` is the same service as a unit of its own
(flysim's limits, cpuset and environment; `Conflicts=flysim.service`; no `[Install]`, so it
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
stopped, not for switching the stream.
## CPU partition (cpuset) ## CPU partition (cpuset)
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit

View file

@ -536,6 +536,336 @@ else
pass "flysim.service leaves FLY_FEED_VIA to fly.env" pass "flysim.service leaves FLY_FEED_VIA to fly.env"
fi fi
# ---------------------------------------------------------------------------
# 3b3. The session runtime (SERVE-01): flysim-session, its standalone unit and
# the fly-runtime switch CUT-01 calls.
#
# flysim.service stays the fly's one unit name; `fly-runtime session` points it at
# flysim-session with a drop-in, `fly-runtime legacy` removes it. What would break
# that: the standalone unit drifting from flysim.service (limits, env, ports),
# becoming enable-able or pulled in beside flysim, the drop-in naming another
# binary or session dir, the release not shipping the binary, the deploy
# forgetting it. fly-runtime itself is driven for real against stubs.
# ---------------------------------------------------------------------------
echo "--- the session runtime: flysim-session.service and fly-runtime ---"
SESSION_UNIT="$INFRA_DIR/units/flysim-session.service"
if [ ! -f "$SESSION_UNIT" ]; then
fail "units/flysim-session.service is missing"
else
grep -qE '^ExecStart=/opt/fly/current/flysim-session$' "$SESSION_UNIT" \
&& pass "flysim-session.service runs the release's flysim-session" \
|| fail "flysim-session.service ExecStart must be /opt/fly/current/flysim-session"
grep -qE '^Conflicts=flysim\.service$' "$SESSION_UNIT" \
&& pass "flysim-session.service Conflicts=flysim.service (same ports, same stores)" \
|| fail "flysim-session.service must Conflict with flysim.service"
if grep -qE '^\[Install\]' "$SESSION_UNIT"; then
fail "flysim-session.service has an [Install] section; it must not be enable-able beside flysim"
else
pass "flysim-session.service cannot be enabled (no [Install])"
fi
# The [Service] section, comments and blank lines dropped: flysim.service's, line for
# line, but for ExecStart and the one variable of its own.
service_lines() {
awk '/^\[/{sec=$0; next} sec=="[Service]" && !/^[[:space:]]*(#|$)/' "$1" \
| grep -vE '^(ExecStart=|Environment=FLY_SESSION_DIR=|Environment=MALLOC_ARENA_MAX=)' || true
}
if [ "$(service_lines "$INFRA_DIR/units/flysim.service")" = "$(service_lines "$SESSION_UNIT")" ]; then
pass "flysim-session.service [Service] is flysim.service's but for ExecStart and FLY_SESSION_DIR"
else
fail "flysim-session.service [Service] drifted from flysim.service: $(diff <(service_lines "$INFRA_DIR/units/flysim.service") <(service_lines "$SESSION_UNIT") | tr '\n' ' ')"
fi
grep -qx 'Environment=MALLOC_ARENA_MAX=2' "$SESSION_UNIT" \
&& ! grep -q 'MALLOC_ARENA_MAX' "$INFRA_DIR/units/flysim.service" \
&& pass "flysim-session.service sets MALLOC_ARENA_MAX=2; legacy flysim.service is untouched" \
|| fail "flysim-session.service must set MALLOC_ARENA_MAX=2 (and flysim.service must not)"
grep -qE '^Environment=FLY_SESSION_DIR=/run/fly/session$' "$SESSION_UNIT" \
&& pass "flysim-session.service keeps its session dir on /run/fly/session" \
|| fail "flysim-session.service must set FLY_SESSION_DIR=/run/fly/session"
fi
if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flysim-session.service'; then
fail "fly.target pulls flysim-session.service in beside flysim.service"
else
pass "fly.target does not pull flysim-session.service in"
fi
if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flysim-session'; then
fail "07-enable.sh or verify.sh lists flysim-session.service"
else
pass "07-enable.sh and verify.sh leave flysim-session.service alone"
fi
grep -qE '^d /run/fly/session +0700 fly +fly' "$INFRA_DIR/config/fly-tmpfiles.conf" \
&& pass "tmpfiles creates /run/fly/session 0700 fly" \
|| fail "config/fly-tmpfiles.conf must create /run/fly/session 0700 fly fly"
grep -qE 'for name in .*\bfly-runtime\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh installs fly-runtime" \
|| fail "05-deploy.sh must converge bin/fly-runtime to /opt/fly/bin"
grep -qE '^[[:space:]]*for u in flysim .*\bflysim-session\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes flysim-session.service's cpuset drop-in" \
|| fail "05-deploy.sh cpuset loop must include flysim-session (flysim's cores)"
grep -qF 'flysim.service.d/10-runtime.conf' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"${release_path}/flysim-session"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without flysim-session while the session runtime runs" \
|| fail "05-deploy.sh must refuse a release without flysim-session while 10-runtime.conf is present"
grep -qE -- '--bin flysim-session' "$INFRA_DIR/build/build-flysim.sh" \
&& grep -qE 'for extra in flysim-session fly-session' "$INFRA_DIR/build/package-release.sh" \
&& pass "build-flysim.sh builds flysim-session and package-release.sh ships it" \
|| fail "build-flysim.sh must build flysim-session (and fly-session) and package-release.sh ship them"
rt_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-runtime.XXXXXX")"
mkdir -p "$rt_dir/bin" "$rt_dir/release" "$rt_dir/systemd"
cat > "$rt_dir/bin/systemctl" <<'RTSTUB'
#!/usr/bin/env bash
echo "$*" >> "$RT_DIR/systemctl.log"
RTSTUB
cat > "$rt_dir/bin/id" <<'RTSTUB'
#!/usr/bin/env bash
echo 0
RTSTUB
cat > "$rt_dir/bin/logger" <<'RTSTUB'
#!/usr/bin/env bash
true
RTSTUB
cat > "$rt_dir/bin/curl" <<'RTSTUB'
#!/usr/bin/env bash
# /healthz answers per RT_HEALTHY; /status reports a frame that advances per call.
url="${*: -1}"
[ "${RT_HEALTHY:-1}" = 1 ] || exit 22
case "$url" in
*/status) n=$(( $(cat "$RT_DIR/frame" 2>/dev/null || echo 100) + 1 )); echo "$n" > "$RT_DIR/frame"
echo "{\"status\":\"running\",\"frame\":$n}" ;;
esac
RTSTUB
for b in flysim flysim-session; do
printf '#!/usr/bin/env bash\necho "${RT_COMPAT_%s:-same}"\n' "$(echo "$b" | tr 'a-z-' 'A-Z_')" > "$rt_dir/release/$b"
done
chmod +x "$rt_dir"/bin/* "$rt_dir"/release/*
echo 'FLY_GAME=pokemon-red' > "$rt_dir/fly.env"
fly_runtime() {
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="$rt_dir/run/runtime-fellback.json" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \
"$@" bash "$INFRA_DIR/bin/fly-runtime" "${RT_ARGS[@]}" >/dev/null 2>&1
}
rt_dropin="$rt_dir/systemd/flysim.service.d/10-runtime.conf"
RT_ARGS=(status)
[ "$(env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null | head -n1)" = legacy ] \
&& pass "fly-runtime status: legacy with no drop-in" \
|| fail "fly-runtime status must say legacy with no drop-in"
RT_ARGS=(session)
if fly_runtime && [ -f "$rt_dropin" ] \
&& grep -qx "ExecStart=$rt_dir/release/flysim-session" "$rt_dropin" \
&& grep -qx 'ExecStart=' "$rt_dropin" \
&& grep -qx 'Environment=FLY_SESSION_DIR=/run/fly/session' "$rt_dropin" \
&& grep -qx 'restart --no-block flysim.service' "$rt_dir/systemctl.log" \
&& [ "$(env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null | head -n1)" = session ]; then
pass "fly-runtime session: the drop-in names flysim-session and /run/fly/session, flysim.service restarted, healthy"
else
fail "fly-runtime session: drop-in/restart/health wrong ($(cat "$rt_dropin" 2>/dev/null | tr '\n' ' '))"
fi
RT_ARGS=(legacy)
if fly_runtime && [ ! -f "$rt_dropin" ]; then
pass "fly-runtime legacy: the drop-in is gone, flysim.service restarted"
else
fail "fly-runtime legacy must remove the drop-in and succeed"
fi
RT_ARGS=(session)
if ! fly_runtime RT_COMPAT_FLYSIM_SESSION=other && [ ! -f "$rt_dropin" ]; then
pass "fly-runtime session refuses when the two compatibility strings differ"
else
fail "fly-runtime session must refuse differing compatibility strings and write nothing"
fi
if ! fly_runtime RT_HEALTHY=0 && [ ! -f "$rt_dropin" ] && grep -q 'automatic fallback' "$rt_dir/runtime.log"; then
pass "fly-runtime session falls back to legacy by itself when the session runtime is not healthy"
else
fail "fly-runtime session must fall back to legacy (drop-in removed, logged) when unhealthy"
fi
# --- the persistent fallback (C1), the signal traps, the deploy policy (C2) ---
FALLBACK_UNIT="$INFRA_DIR/units/fly-runtime-fallback.service"
rt_fellback="$rt_dir/run/runtime-fellback.json"
rt_ncalls() { grep -c "$1" "$rt_dir/systemctl.log" || true; }
RT_ARGS=(session)
fly_runtime || fail "fly-runtime session (healthy) failed before the fallback tests"
if grep -qx 'OnFailure=fly-runtime-fallback.service' "$rt_dropin" \
&& grep -qx 'StartLimitBurst=3' "$rt_dropin" \
&& grep -qx 'StartLimitIntervalSec=600' "$rt_dropin" \
&& grep -qx 'RestartMode=direct' "$rt_dropin" \
&& grep -qx 'Environment=MALLOC_ARENA_MAX=2' "$rt_dropin" \
&& [ -f "$FALLBACK_UNIT" ] \
&& grep -qE '^ExecStart=/opt/fly/bin/fly-runtime fallback$' "$FALLBACK_UNIT" \
&& grep -qx 'Type=oneshot' "$FALLBACK_UNIT" \
&& ! grep -q '^\[Install\]' "$FALLBACK_UNIT"; then
pass "session drop-in: OnFailure= fallback unit, 3 starts in 600 s, RestartMode=direct (else OnFailure= fires on every crash), MALLOC_ARENA_MAX=2; the unit runs 'fly-runtime fallback'"
else
fail "session drop-in/fallback unit wrong ($(tr '\n' ' ' < "$rt_dropin"))"
fi
# Drive it the way systemd would: 3 failed starts of flysim.service reach the burst, systemd
# then starts the OnFailure= unit, i.e. runs its ExecStart (path mapped to the script under test).
sim_onfailure() {
local burst unit cmd
burst="$(sed -n 's/^StartLimitBurst=//p' "$rt_dropin")"
unit="$(sed -n 's/^OnFailure=//p' "$rt_dropin")"
[ "$unit" = fly-runtime-fallback.service ] || return 1
cmd="$(sed -n 's/^ExecStart=//p' "$FALLBACK_UNIT")"
cmd="${cmd/\/opt\/fly\/bin\/fly-runtime/bash $INFRA_DIR/bin/fly-runtime}"
local failures=0
while [ "$failures" -lt "$burst" ]; do failures=$((failures + 1)); done
[ "$failures" -eq 3 ] || return 1
# shellcheck disable=SC2086
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_FELLBACK="$rt_fellback" \
FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" $cmd >/dev/null 2>&1
}
restarts_before="$(rt_ncalls 'restart --no-block flysim.service')"
if sim_onfailure && [ ! -f "$rt_dropin" ] \
&& [ "$(rt_ncalls 'restart --no-block flysim.service')" -eq $((restarts_before + 1)) ] \
&& grep -q '"from":"session","to":"legacy"' "$rt_fellback" \
&& grep -q '"reason":"flysim.service failed on the session runtime' "$rt_fellback" \
&& grep -q 'automatic fallback' "$rt_dir/runtime.log" \
&& [ "$(env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null | head -n1)" = legacy ]; then
pass "session fails 3x: OnFailure fallback removes the drop-in, starts legacy, writes the reason file and the journal line"
else
fail "OnFailure fallback: drop-in/restart/reason file wrong ($(cat "$rt_fellback" 2>/dev/null))"
fi
# Idempotent: a second run (a stale OnFailure, a race with the script's own fallback) does nothing.
restarts_before="$(rt_ncalls 'restart --no-block flysim.service')"
cp "$rt_fellback" "$rt_dir/fellback.first"
RT_ARGS=(fallback)
if fly_runtime && [ "$(rt_ncalls 'restart --no-block flysim.service')" -eq "$restarts_before" ] \
&& cmp -s "$rt_fellback" "$rt_dir/fellback.first"; then
pass "fly-runtime fallback is idempotent once legacy is selected"
else
fail "a second fly-runtime fallback must be a no-op"
fi
# Never neither: no executable legacy binary -> keep the session drop-in.
RT_ARGS=(session)
fly_runtime || fail "could not re-select the session runtime for the no-legacy test"
mv "$rt_dir/release/flysim" "$rt_dir/flysim.away"
RT_ARGS=(fallback)
if ! fly_runtime && [ -f "$rt_dropin" ]; then
pass "fly-runtime fallback keeps the session drop-in when there is no legacy binary to fall back to"
else
fail "fly-runtime fallback removed the drop-in with no legacy binary"
fi
mv "$rt_dir/flysim.away" "$rt_dir/release/flysim"
# A successful `session` clears the reason file.
RT_ARGS=(fallback)
fly_runtime || true
[ -f "$rt_fellback" ] || fail "test setup: the fallback left no reason file"
RT_ARGS=(session)
if fly_runtime && [ ! -f "$rt_fellback" ]; then
pass "fly-runtime session clears the previous fallback reason"
else
fail "fly-runtime session must remove ${rt_fellback##*/} on success"
fi
# A deploy keeps the drop-in (C2): 05-deploy never removes it, refreshes it in place without a
# restart, and documents the policy; the refresh keeps the drop-in and restarts nothing.
if grep -n '10-runtime.conf' "$INFRA_DIR/05-deploy.sh" | grep -Eq '\brm\b'; then
fail "05-deploy.sh removes 10-runtime.conf; a deploy must keep the chosen runtime"
elif grep -qF 'Session stays, trust gates' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF 'fly-runtime session --no-restart' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF 'Session stays, trust gates' "$INFRA_DIR/docs/runbook.md"; then
pass "05-deploy.sh keeps the drop-in, refreshes it without a restart, and states the policy (runbook too)"
else
fail "05-deploy.sh / runbook.md must state 'Session stays, trust gates' and refresh via fly-runtime session --no-restart"
fi
restarts_before="$(rt_ncalls '^restart ')"
printf 'stale\n' > "$rt_dropin"
RT_ARGS=(session --no-restart)
if fly_runtime && [ -f "$rt_dropin" ] \
&& grep -qx 'OnFailure=fly-runtime-fallback.service' "$rt_dropin" \
&& [ "$(rt_ncalls '^restart ')" -eq "$restarts_before" ]; then
pass "a deploy's refresh (session --no-restart) keeps the drop-in, updates it, restarts nothing"
else
fail "fly-runtime session --no-restart must rewrite the drop-in without restarting"
fi
# Signals: an interrupted switch rolls back to the previous state.
rt_interrupt() { # $1 = signal: run `session` on an unhealthy runtime, signal it mid-wait, print its status
local sig="$1" pid rc=0 n=0 base
base="$(rt_ncalls '^restart --no-block flysim.service')"
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=60 RT_HEALTHY=0 \
FLY_RUNTIME_FELLBACK="$rt_fellback" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \
python3 -c 'import os, signal, sys
signal.signal(signal.SIGINT, signal.SIG_DFL) # a background job of a non-interactive shell starts with INT ignored
os.execvp(sys.argv[1], sys.argv[1:])' bash "$INFRA_DIR/bin/fly-runtime" session >/dev/null 2>&1 &
pid=$!
while [ "$(rt_ncalls '^restart --no-block flysim.service')" -le "$base" ] && [ "$n" -lt 100 ]; do
n=$((n + 1)); sleep 0.1
done
if [ -n "${2:-}" ]; then "$2" >/dev/null 2>&1 || true; fi
kill "-$sig" "$pid" 2>/dev/null || true
wait "$pid" || rc=$?
echo "$rc"
}
rm -f "$rt_dropin"
for sig_case in TERM:143 INT:130 HUP:129; do
sig="${sig_case%%:*}"; want_rc="${sig_case##*:}"
restarts_before="$(rt_ncalls '^restart ')"
got_rc="$(rt_interrupt "$sig")"
if [ "$got_rc" = "$want_rc" ] && [ ! -f "$rt_dropin" ] \
&& [ "$(rt_ncalls '^restart ')" -gt $((restarts_before + 1)) ] \
&& grep -q 'rolled back' "$rt_dir/runtime.log"; then
pass "fly-runtime session interrupted by SIG$sig: drop-in removed, flysim.service restarted on the previous (legacy) state"
else
fail "fly-runtime session interrupted by SIG$sig: rc=$got_rc (want $want_rc), drop-in present=$([ -f "$rt_dropin" ] && echo yes || echo no)"
fi
done
mkdir -p "$(dirname "$rt_dropin")"
printf '# previous-session-marker\n[Service]\nExecStart=\nExecStart=/previous\n' > "$rt_dropin"
cp "$rt_dropin" "$rt_dir/dropin.before"
got_rc="$(rt_interrupt TERM)"
if [ "$got_rc" = 143 ] && cmp -s "$rt_dropin" "$rt_dir/dropin.before" \
&& ! compgen -G "$rt_dropin.prev.*" >/dev/null; then
pass "fly-runtime session interrupted while already on session: the earlier drop-in is restored, no temp files left"
else
fail "an interrupted re-run of session must restore the earlier drop-in (rc=$got_rc)"
fi
# M2, deterministic interleaving: a re-run of `session` over an older drop-in is waiting for
# health, an OnFailure= fallback completes, THEN the switch is interrupted. The rollback must
# not put the older drop-in back (it has no OnFailure=, and the stream would be stranded on the
# session runtime).
# shellcheck disable=SC2317 # called through rt_interrupt
rt_fallback_now() {
env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_RELEASE_DIR="$rt_dir/release" \
FLY_SYSTEMD_DIR="$rt_dir/systemd" FLY_RUNTIME_LOG="$rt_dir/runtime.log" \
FLY_RUNTIME_FELLBACK="$rt_fellback" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \
bash "$INFRA_DIR/bin/fly-runtime" fallback "lint interleaving"
}
mkdir -p "$(dirname "$rt_dropin")"
printf '# older-session-marker\n[Service]\nExecStart=\nExecStart=/previous\n' > "$rt_dropin"
got_rc="$(rt_interrupt TERM rt_fallback_now)"
if [ "$got_rc" = 143 ] && [ ! -f "$rt_dropin" ] && [ -f "$rt_fellback" ] \
&& grep -q 'a fallback completed meanwhile' "$rt_dir/runtime.log"; then
pass "rollback after a completed fallback leaves legacy selected (does not restore the older drop-in)"
else
fail "rollback must not restore an older drop-in after a completed fallback (rc=$got_rc, drop-in present=$([ -f "$rt_dropin" ] && echo yes || echo no))"
fi
# ... and the two share ONE lock: a held lock stops `session` from touching anything.
rm -f "$rt_dropin" "$rt_fellback"
(
exec 8>>"$rt_dir/run/runtime.lock"
flock 8
RT_ARGS=(session)
if ! fly_runtime FLY_RUNTIME_LOCK_WAIT=1 && [ ! -f "$rt_dropin" ]; then
touch "$rt_dir/lock-respected"
fi
)
if [ -f "$rt_dir/lock-respected" ]; then
pass "fly-runtime session waits on the same lock as fallback and does not switch without it"
else
fail "fly-runtime session must take the shared ${FLY_RUNTIME_LOCK:-runtime.lock} lock"
fi
rm -f "$rt_dropin"
mv "$rt_dir/release/flysim-session" "$rt_dir/flysim-session.away"
if ! fly_runtime && [ ! -f "$rt_dropin" ]; then
pass "fly-runtime session refuses a release without flysim-session"
else
fail "fly-runtime session must refuse a release without flysim-session"
fi
rm -rf "$rt_dir"
echo "--- fly-watchdog check 2: the feed counters follow FLY_FEED_VIA ---" echo "--- fly-watchdog check 2: the feed counters follow FLY_FEED_VIA ---"
if ! tail -n1 "$INFRA_DIR/bin/fly-watchdog" | grep -qE '^main "\$@"$'; then if ! tail -n1 "$INFRA_DIR/bin/fly-watchdog" | grep -qE '^main "\$@"$'; then
fail "fly-watchdog: expected the last line to be 'main \"\$@\"' — the check-2 fixture strips it" fail "fly-watchdog: expected the last line to be 'main \"\$@\"' — the check-2 fixture strips it"

View file

@ -0,0 +1,19 @@
# infra/units/fly-runtime-fallback.service — pushed to /etc/systemd/system/.
#
# The persistent fallback from the session runtime to the legacy loop (SERVE-01 review, C1).
# It is never enabled and in no target: the drop-in that `fly-runtime session` writes on
# flysim.service (10-runtime.conf) carries `OnFailure=fly-runtime-fallback.service` together with
# StartLimitIntervalSec=600, StartLimitBurst=3 and RestartMode=direct (without it OnFailure= fires on
# every crash, not at the start limit), so three starts of flysim.service on the
# session binary inside ten minutes -- from any cause, and from any caller: a reboot, the
# watchdog, fly-loop-recover, a deploy -- run this unit once. `fly-runtime fallback` removes the
# drop-in (which removes this OnFailure= too), daemon-reloads, restarts flysim.service on the
# legacy binary and writes /run/fly/runtime-fellback.json plus a journal line (tag fly-runtime).
# It is idempotent and refuses to act without an executable legacy binary. Runs as root.
[Unit]
Description=fly-runtime-fallback: flysim.service failed on the session runtime, back to legacy
# Its own start limit stays the default; a fallback that has already happened is a no-op.
[Service]
Type=oneshot
ExecStart=/opt/fly/bin/fly-runtime fallback

View file

@ -0,0 +1,56 @@
# infra/units/flysim-session.service — pushed to /etc/systemd/system/flysim-session.service.
#
# The live fly on the session runtime (SERVE-01): `flysim-session`, a drop-in for `flysim` that
# reads the same /etc/fly/fly.env, writes the same checkpoint stores, event log, sugar journal and
# chat sidecar, and serves the same feed (:7400, or the feed bus for fly-edge), control API
# (:7401) and metrics (:9101) -- through flysim's own listener code, so the binding contracts
# (docs/feed-protocol.md, docs/control-api.md) are the same bytes.
#
# NOT ENABLED, IN NO TARGET, and it Conflicts= with flysim.service: the two own the same ports
# and the same stores, so at most one of them runs. It is not how the stream is switched either.
# `fly-runtime session` (infra/bin/fly-runtime; the runbook's "Switch the runtime") points
# flysim.service itself at this unit's ExecStart and Environment with a drop-in, so that every
# consumer that names flysim.service -- fly.target, flyedge.service's Requires=, the watchdog,
# fly-loop-recover's restart (and its sudoers line), fly-loop-reset, fly-reset-to-milestone, the
# unstick rule, `journalctl -u flysim` -- keeps working unchanged, a reboot keeps the choice, and
# `fly-runtime legacy` is one command back. This unit is the standalone form of the same
# service: for a rehearsal or a soak on a container whose flysim.service is stopped
# (`systemctl stop flysim.service && systemctl start flysim-session.service`).
#
# Everything below except ExecStart, FLY_SESSION_DIR, MALLOC_ARENA_MAX, Conflicts= and the missing [Install] is
# flysim.service's, line for line (infra/tests/lint.sh checks it), and so are the limits and the cpuset: 05-deploy.sh writes
# flysim-session.service.d/cpuset.conf with flysim's set (docs/design/infra.md section 3 and
# flysim.service's own notes on RAYON_NUM_THREADS, Nice, CPUWeight and AllowedCPUs apply as they
# stand).
[Unit]
Description=flysim-session: the fly brain and its Game Boy on the session runtime
After=network.target
Conflicts=flysim.service
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
Type=notify
NotifyAccess=main
WatchdogSec=30
User=fly
EnvironmentFile=/etc/fly/fly.env
Environment=FLY_FEED_BIND=127.0.0.1:7400
Environment=FLY_BUS_DIR=/run/fly/bus
Environment=FLY_CONTROL_BIND=127.0.0.1:7401
Environment=FLY_METRICS_ADDR=0.0.0.0:9101
Environment=FLY_STATE_HOT=/run/fly/state
Environment=FLY_STATE=/srv/fly/state
# The session's own router store and worker sockets (tmpfs, fly 0700, config/fly-tmpfiles.conf).
Environment=FLY_SESSION_DIR=/run/fly/session
# glibc per-thread arenas fragment under the session's MB-sized capture/encode buffers: without
# this RSS grows about 5-8 MB/h (SERVE-01 review); with it the growth plateaus. Legacy is unaffected.
Environment=MALLOC_ARENA_MAX=2
ExecStart=/opt/fly/current/flysim-session
Restart=always
RestartSec=2
Nice=-5
CPUWeight=400
MemoryMax=4G
# No [Install] section, deliberately: `systemctl enable flysim-session.service` has nothing to
# do, so it can never be pulled in beside flysim.service by fly.target.

View file

@ -439,14 +439,23 @@ dependencies = [
name = "fly-legacy-session" name = "fly-legacy-session"
version = "0.1.1" version = "0.1.1"
dependencies = [ dependencies = [
"anyhow",
"axum",
"clap",
"fly-session", "fly-session",
"flybrain-core", "flybrain-core",
"flybrain-gb", "flybrain-gb",
"flybus", "flybus",
"flysim", "flysim",
"futures-util",
"serde_json", "serde_json",
"tempfile", "tempfile",
"tokio", "tokio",
"tokio-tungstenite",
"toml",
"tower",
"tracing",
"tracing-subscriber",
] ]
[[package]] [[package]]

View file

@ -5,24 +5,40 @@ edition = "2024"
rust-version.workspace = true rust-version.workspace = true
license.workspace = true license.workspace = true
publish = false publish = false
description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, and the parity harness against the legacy loop's FLY_TRACE." description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, the parity harness against the legacy loop's FLY_TRACE, and the flysim-session service."
[lib] [lib]
name = "fly_legacy_session" name = "fly_legacy_session"
path = "src/lib.rs" path = "src/lib.rs"
# SERVE-01: the session runtime as the live service, a drop-in for `flysim`.
[[bin]]
name = "flysim-session"
path = "src/bin/flysim-session.rs"
[dependencies] [dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01). # The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" } fly-session = { path = "../fly-session" }
flybus = { path = "../flybus" } flybus = { path = "../flybus" }
# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's # The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's
# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image. # palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image.
# flysim is a library dependency only; nothing here changes the service it builds. # flysim is a library dependency only; nothing here changes the service it builds. SERVE-01's
# `flysim-session` runs the session behind flysim's own listeners (`flysim::serve`).
flysim = { path = "../flysim" } flysim = { path = "../flysim" }
flybrain-gb = { path = "../flybrain-gb" } flybrain-gb = { path = "../flybrain-gb" }
flybrain-core = { path = "../flybrain-core" } flybrain-core = { path = "../flybrain-core" }
serde_json = { workspace = true } serde_json = { workspace = true }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
# The service entry point (SERVE-01), with flysim's own versions of each.
anyhow = "1.0"
clap = { version = "4.5", features = ["derive"] }
toml = "0.9"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"
axum = "0.8"
futures-util = "0.3"
tokio-tungstenite = "0.29"
tower = { version = "0.5", features = ["util"] }

View file

@ -0,0 +1,26 @@
//! Seed a FLYSIM01 store with one checkpoint file, as its own generation (a soak or rehearsal
//! starting from a pulled stream checkpoint; SERVE-01).
//!
//! ```sh
//! cargo run --release -p fly-legacy-session --example seed_store -- <file.checkpoint> <durable-dir>
//! ```
fn main() {
let args: Vec<String> = std::env::args().collect();
let [_, file, dir] = args.as_slice() else {
eprintln!("usage: seed_store <file.checkpoint> <durable-dir>");
std::process::exit(2);
};
let bytes = std::fs::read(file).expect("reading the checkpoint");
let checkpoint = flysim::store::decode(&bytes).expect("a FLYSIM01 checkpoint");
let generation = checkpoint.runtime.generation;
let store = flysim::store::Store::new(std::path::Path::new(dir), 2);
store.create().expect("creating the store");
store
.commit(generation, &bytes, None)
.expect("committing the checkpoint");
println!(
"seeded {dir} with generation {generation} (frame {}, compatibility {})",
checkpoint.runtime.emulator_frame, checkpoint.runtime.compatibility
);
}

View file

@ -0,0 +1,102 @@
//! `flysim-session`: the live fly on the session runtime, as a drop-in for `flysim` (SERVE-01).
//!
//! ```sh
//! flysim-session # what flysim.service runs after `fly-runtime session`
//! flysim-session --print-compatibility
//! ```
//!
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
//! sidecar, and serves the same feed, control API and metrics. Three variables are its own:
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
//! `FLY_SESSION_MODE` (`in-process`, `thread` or `process`) and `FLY_SESSION_PROFILE`
//! (`production`, or `toy` for tests).
//!
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and
//! `--reset-to-milestone` (the store is shared, so these are `flysim`'s own functions).
use anyhow::Result;
use clap::Parser;
use flysim::config::Config;
#[derive(Debug, Parser)]
#[command(
name = "flysim-session",
about = "The fly brain and its Game Boy on the session runtime: flysim's feed, control API and checkpoints.",
version
)]
struct Args {
/// Path to `flysim.toml`. Without it, defaults plus `FLY_*` / `FLYSIM_*` environment
/// overrides are used, exactly as for `flysim`.
#[arg(long, value_name = "PATH")]
config: Option<std::path::PathBuf>,
/// Print the resolved configuration and exit.
#[arg(long)]
check_config: bool,
/// Print the checkpoint compatibility string this build would write, and exit.
#[arg(long)]
print_compatibility: bool,
/// Print the compatibility string the checkpoints in this directory carry, and exit.
#[arg(long, value_name = "DIR")]
print_state_compatibility: Option<std::path::PathBuf>,
/// Restart the run from the milestone archive for this ladder rung, and exit (with the
/// service stopped; `flysim --reset-to-milestone`, the same store).
#[arg(long, value_name = "RANK")]
reset_to_milestone: Option<u32>,
}
fn main() -> Result<()> {
let args = Args::parse();
init_tracing();
let config = Config::load(args.config.as_deref())?;
let options = fly_legacy_session::service::ServiceOptions::from_env()?;
tracing::info!(config = ?config, options = ?options, "resolved configuration");
if args.check_config {
println!("{}", toml::to_string_pretty(&config)?);
return Ok(());
}
if args.print_compatibility {
println!(
"{}",
fly_legacy_session::service::compatibility_string(&config, &options)?
);
return Ok(());
}
if let Some(dir) = args.print_state_compatibility.as_deref() {
if let Some(found) = flysim::store::state_compatibility(dir) {
println!("{found}");
}
return Ok(());
}
if let Some(rank) = args.reset_to_milestone {
let stamp = flysim::reset::utc_stamp(flysim::eventlog::now_wall_ms());
let durable = config.paths.save_dir.clone();
let hot = config.paths.hot_dir.clone();
let archive = flysim::reset::default_archive_dir(&durable, &stamp);
for line in flysim::reset::reset_to_milestone(&durable, &hot, rank, &archive)? {
println!("{line}");
}
return Ok(());
}
fly_legacy_session::service::run(config, options)
}
/// Logs go to stderr, as `flysim`'s do (binjgb prints the cartridge header to stdout).
fn init_tracing() {
use tracing_subscriber::EnvFilter;
let filter = EnvFilter::try_from_env("FLYSIM_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new("info"));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.with_target(false)
.init();
}

View file

@ -172,6 +172,25 @@ pub async fn boot(
root: &Path, root: &Path,
config: LegacyConfig, config: LegacyConfig,
store: &StoreConfig, store: &StoreConfig,
) -> Result<(LegacySession, Boot), String> {
let (mut session, boot) = boot_unsaved(root, config, store).await?;
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
session.save(SaveKind::Durable).await?;
session
.checkpointer_mut()
.expect("attached")
.start_intervals(Instant::now());
Ok((session, boot))
}
/// [`boot`] up to the store: the restore (or the fresh start) with the store attached, but no
/// startup save yet and the intervals not started. The service host (SERVE-01) writes its boot
/// events first, so the startup save records their watermark as the legacy one does, and then
/// takes the save and starts the intervals itself.
pub async fn boot_unsaved(
root: &Path,
config: LegacyConfig,
store: &StoreConfig,
) -> Result<(LegacySession, Boot), String> { ) -> Result<(LegacySession, Boot), String> {
let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations); let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations);
let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations); let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations);
@ -232,7 +251,7 @@ pub async fn boot(
} }
} }
} }
let (mut session, boot) = match outcome { let (session, boot) = match outcome {
Some(pair) => pair, Some(pair) => pair,
None if candidates.is_empty() => { None if candidates.is_empty() => {
let mut session = LegacySession::start(&root.join("fresh"), config).await?; let mut session = LegacySession::start(&root.join("fresh"), config).await?;
@ -253,12 +272,6 @@ pub async fn boot(
)); ));
} }
}; };
// `Sim::boot`: a durable save of the state the process starts from, then the intervals.
session.save(SaveKind::Durable).await?;
session
.checkpointer_mut()
.expect("attached")
.start_intervals(Instant::now());
Ok((session, boot)) Ok((session, boot))
} }
@ -578,6 +591,18 @@ impl LegacySession {
self.checkpointer.as_mut() self.checkpointer.as_mut()
} }
/// The feed event log's watermark the next save records (`lastEventId`): the restored
/// file's until a host that keeps a feed event log sets its own.
pub fn last_event_id(&self) -> u64 {
self.last_event_id
}
/// The service host's event log watermark, recorded by every save from now on as the legacy
/// loop records `log.next_id() - 1` (SERVE-01).
pub fn set_last_event_id(&mut self, last_event_id: u64) {
self.last_event_id = last_event_id;
}
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for /// One save of the committed boundary, written by the checkpointer's writer thread; waits for
/// the commit, so a caller that goes on to read the store finds it. For the startup and /// the commit, so a caller that goes on to read the store finds it. For the startup and
/// shutdown saves, which the legacy loop takes blocking too. /// shutdown saves, which the legacy loop takes blocking too.

View file

@ -129,6 +129,9 @@ pub async fn import_flysim01(
coordinator coordinator
.resume() .resume()
.map_err(|e| format!("resuming the import: {}", e.error.message))?; .map_err(|e| format!("resuming the import: {}", e.error.message))?;
// The joypad on the restored boundary, as the legacy `LegacyFrame::restore` installs it: what
// a feed header reports until the executor applies its first mask (SERVE-01).
task.set_mask(checkpoint.runtime.buttons);
Ok(Imported { Ok(Imported {
boundary, boundary,
epoch: new_epoch.clone(), epoch: new_epoch.clone(),

View file

@ -7,6 +7,8 @@
//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused. //! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused.
//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison. //! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison.
//! - [`driver`]: a stub readout for parity runs that must earn rewards. //! - [`driver`]: a stub readout for parity runs that must earn rewards.
//! - [`service`]: the composition as the live service behind flysim's listeners (SERVE-01),
//! the `flysim-session` binary.
//! //!
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md` //! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
//! TASK-01 the record. //! TASK-01 the record.
@ -15,5 +17,6 @@ pub mod admission;
pub mod composition; pub mod composition;
pub mod driver; pub mod driver;
pub mod import; pub mod import;
pub mod service;
pub mod task; pub mod task;
pub mod trace; pub mod trace;

File diff suppressed because it is too large Load diff

View file

@ -163,6 +163,20 @@ pub fn ledgers_of(
.to_string() .to_string()
} }
/// What one transition gave the feed (SERVE-01), in the order the legacy loop emits it: the
/// executor's starts and finishes, the rewards, the observation's abandonments, and a rollback's
/// trigger and macro events. Kept whether or not a parity run records, because the service host
/// publishes it; taken once per transition ([`PokeredTask::take_feed`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FeedRecord {
pub executed: Vec<MacroEvent>,
pub rewards: Vec<flybrain_gb::adapter::RewardEvent>,
pub abandoned: Vec<MacroEvent>,
/// `Some((game_over, events))` when the ratchet's rollback ran at this boundary: the trigger
/// (a game over, else a stall) and the executor's cancel-and-observe events.
pub rollback: Option<(bool, Vec<MacroEvent>)>,
}
/// How the object is configured. Everything here is composition, not state. /// How the object is configured. Everything here is composition, not state.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PokeredConfig { pub struct PokeredConfig {
@ -197,6 +211,12 @@ struct Inner {
driver: Option<Box<dyn crate::driver::DecisionDriver>>, driver: Option<Box<dyn crate::driver::DecisionDriver>>,
/// Addresses the engine read that the image does not capture ([`Watched`]). /// Addresses the engine read that the image does not capture ([`Watched`]).
uncaptured: std::collections::BTreeSet<u16>, uncaptured: std::collections::BTreeSet<u16>,
/// The feed's view of the transitions since the last [`PokeredTask::take_feed`].
feed: FeedRecord,
/// The joypad mask the executor last applied (the legacy `frame.buttons`).
mask: u32,
/// Whether the rollback asked for at the last boundary was a game over (else a stall).
rollback_game_over: bool,
/// The seed the next fresh macro layer is built with ([`PALETTE_SEED`], or a restored /// The seed the next fresh macro layer is built with ([`PALETTE_SEED`], or a restored
/// agent's RNG state as the legacy loop seeds it). /// agent's RNG state as the legacy loop seeds it).
palette_seed: u32, palette_seed: u32,
@ -239,6 +259,9 @@ impl PokeredTask {
records: Vec::new(), records: Vec::new(),
driver: None, driver: None,
uncaptured: std::collections::BTreeSet::new(), uncaptured: std::collections::BTreeSet::new(),
feed: FeedRecord::default(),
mask: 0,
rollback_game_over: false,
palette_seed: PALETTE_SEED, palette_seed: PALETTE_SEED,
})), })),
}) })
@ -272,6 +295,38 @@ impl PokeredTask {
self.lock().uncaptured.iter().copied().collect() self.lock().uncaptured.iter().copied().collect()
} }
/// The feed's record of the transitions since the last call (SERVE-01).
pub fn take_feed(&self) -> FeedRecord {
std::mem::take(&mut self.lock().feed)
}
/// The joypad mask the executor last applied, as the legacy header's `buttons` reads it.
pub fn mask(&self) -> u32 {
self.lock().mask
}
/// The joypad mask a restore installed (the checkpoint's `buttons`), before any apply.
pub fn set_mask(&self, mask: u32) {
self.lock().mask = mask;
}
/// Read the adapter, the ratchet and the macro layer as they stand at the committed
/// boundary: the parts of a feed header that are the task's (SERVE-01). Changes nothing.
pub fn inspect<R>(
&self,
f: impl FnOnce(&PokemonRedReward, &Ratchet, Option<&MacroLayer>) -> R,
) -> R {
let inner = self.lock();
f(&inner.adapter, &inner.ratchet, inner.macros.as_ref())
}
/// Whether this cartridge earns semantic rewards (`adapter.rom_allowed`), which the legacy
/// header reports as `game.semanticRewards`.
pub fn semantic_rewards(&self) -> bool {
let inner = self.lock();
inner.adapter.rom_allowed(&inner.cartridge.sha256_hex())
}
/// Seeds the next restore's fresh macro layer as the legacy loop does after a restore: with /// Seeds the next restore's fresh macro layer as the legacy loop does after a restore: with
/// the restored brain's RNG state (`rng_state() as u32`). /// the restored brain's RNG state (`rng_state() as u32`).
pub fn set_palette_seed(&self, seed: u32) { pub fn set_palette_seed(&self, seed: u32) {
@ -627,6 +682,8 @@ impl Task for TaskFace {
drop(span); drop(span);
let span = fly_session::profile::span("task.observe"); let span = fly_session::profile::span("task.observe");
let abandoned = inner.observe(&image, ms); let abandoned = inner.observe(&image, ms);
inner.feed.rewards.extend(rewards.iter().cloned());
inner.feed.abandoned.extend(abandoned.iter().cloned());
drop(span); drop(span);
let span = fly_session::profile::span("task.ratchet"); let span = fly_session::profile::span("task.ratchet");
let progress = inner.adapter.progress(); let progress = inner.adapter.progress();
@ -682,6 +739,7 @@ impl Task for TaskFace {
} }
events.push(task_event); events.push(task_event);
} }
inner.rollback_game_over = game_over;
let episode = recover.then(|| EpisodeRequest { let episode = recover.then(|| EpisodeRequest {
kind: EpisodeRequestKind::Rollback, kind: EpisodeRequestKind::Rollback,
reason: id(if game_over { "game-over" } else { "stall" }), reason: id(if game_over { "game-over" } else { "stall" }),
@ -740,6 +798,10 @@ impl Task for TaskFace {
None => Vec::new(), None => Vec::new(),
}; };
events.extend(inner.observe(&image, ms)); events.extend(inner.observe(&image, ms));
let game_over = inner.rollback_game_over;
inner.feed.rollback = Some((game_over, events.clone()));
// `LegacyFrame::rollback` releases every button with the restored slot.
inner.mask = 0;
if let Some(record) = inner.open.as_mut() { if let Some(record) = inner.open.as_mut() {
record.rolled_back = true; record.rolled_back = true;
record record
@ -821,6 +883,7 @@ impl Task for TaskFace {
inner.macros = fresh_layer(&inner.config, inner.palette_seed); inner.macros = fresh_layer(&inner.config, inner.palette_seed);
inner.current = None; inner.current = None;
inner.open = None; inner.open = None;
inner.feed = FeedRecord::default();
inner.epoch = epoch.clone(); inner.epoch = epoch.clone();
inner.evaluations = 0; inner.evaluations = 0;
inner.issued = 0; inner.issued = 0;
@ -950,6 +1013,8 @@ impl ActionExecutor for ExecutorFace {
None => (raw, Vec::new()), None => (raw, Vec::new()),
} }
}; };
inner.mask = mask;
inner.feed.executed.extend(events.iter().cloned());
if inner.config.record { if inner.config.record {
inner.open = Some(TaskRecord { inner.open = Some(TaskRecord {
boundary: scope.step, boundary: scope.step,

View file

@ -0,0 +1,217 @@
//! SERVE-01: the sugar journal a killed session-runtime service wrote, replayed.
//!
//! A `flysim-session` process restores a seed checkpoint, admits sugar through `POST /stimulate`
//! (each admission journaled, frame-stamped, before the frame that applies it), writes its hot
//! checkpoints every `hot_seconds`, and is killed with `SIGKILL`. Its successor restores the
//! newest hot checkpoint. This test takes the seed, the killed process's journal segment and that
//! hot checkpoint, and replays the segment's inputs from the seed in the **legacy** loop
//! (`flysim::frame::LegacyFrame`, FND-01's harness) up to the checkpoint's frame. The replay must
//! land on the checkpoint exactly: the network, the plasticity, the decoder, the remainder, the
//! emulator, the frame on screen, the adapter's ledger and the ratchet. That is the journal's whole
//! promise -- the seed plus the journal is the run -- and it holds across the two runtimes.
//!
//! Gated on `FLY_ROM` and `FLY_SERVE01_REPLAY_DIR`, a directory holding `seed.checkpoint`,
//! `target.checkpoint` (the hot checkpoint the successor restored) and `hot/` (the journal
//! files). `FLY_MACRO_MODE` is the run's mode (default `macros`).
use std::path::PathBuf;
use std::sync::Arc;
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_gb::adapter::GameAdapter;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::Ratchet;
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
use flysim::config::Config;
use flysim::frame::{FrameObserver, LegacyFrame, Parts};
use flysim::macros::macro_layer;
use flysim::snapshot::MacroMode;
struct Quiet;
impl FrameObserver for Quiet {}
#[test]
fn a_killed_session_runs_journal_replays_onto_its_hot_checkpoint_in_the_legacy_loop() {
let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
eprintln!("skipping: FLY_ROM is not set");
return;
};
let Some(dir) = std::env::var_os("FLY_SERVE01_REPLAY_DIR").map(PathBuf::from) else {
eprintln!("skipping: FLY_SERVE01_REPLAY_DIR is not set");
return;
};
let Some(dataset) = fly_session::legacy_parity::fafb_dir() else {
eprintln!("skipping: no data/fafb-v783");
return;
};
let mode = match std::env::var("FLY_MACRO_MODE").as_deref() {
Ok("raw") => MacroMode::Raw,
_ => MacroMode::Macros,
};
let seed = flysim::store::decode(&std::fs::read(dir.join("seed.checkpoint")).unwrap())
.expect("the seed");
let target = flysim::store::decode(&std::fs::read(dir.join("target.checkpoint")).unwrap())
.expect("the target");
let segments = flysim::journal::read_segments(&dir.join("hot")).expect("the journal");
// The killed process: the segment whose boot header names the seed's generation.
let segment = segments
.iter()
.find(|s| {
s.boot.as_ref().and_then(|b| b["generation"].as_u64())
== Some(seed.runtime.generation)
&& s.boot.as_ref().and_then(|b| b["runtime"].as_str()) == Some("fly-session")
})
.expect("a fly-session segment that booted from the seed");
let boot = segment.boot.as_ref().unwrap();
assert_eq!(
boot["startFrame"].as_str(),
Some(seed.runtime.emulator_frame.to_string().as_str()),
"the boot header starts at the seed's frame"
);
let inputs: Vec<(u64, f64, f64)> = segment
.inputs
.iter()
.filter(|line| line["kind"] == "sugar")
.map(|line| {
(
line["frame"].as_str().unwrap().parse().unwrap(),
line["brainMs"].as_f64().unwrap(),
line["durationMs"].as_f64().unwrap(),
)
})
.collect();
let applied: Vec<_> = inputs
.iter()
.filter(|(frame, _, _)| *frame < target.runtime.emulator_frame)
.collect();
eprintln!(
"replaying {} of the segment's {} sugar inputs from frame {} to frame {} ({} frames); \
{} segments in the journal",
applied.len(),
inputs.len(),
seed.runtime.emulator_frame,
target.runtime.emulator_frame,
target.runtime.emulator_frame - seed.runtime.emulator_frame,
segments.len()
);
assert!(!applied.is_empty(), "the run admitted sugar before its last hot checkpoint");
let rom = std::fs::read(&rom).unwrap();
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
let mut emulator =
Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb");
let mut adapter = PokemonRedReward::new();
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_owned();
config.macros.mode = mode;
let (channels, hold_ms) = fly_legacy_session::composition::channels_and_hold(mode);
let channels: Vec<&str> = channels.iter().map(String::as_str).collect();
let mut agent_config =
AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
agent_config.warmup_ms = config.loop_.warmup_ms;
let mut agent = NeuralAgent::new(Arc::clone(&data), agent_config).expect("an agent");
// The sweep's thread count does not change a number (the live loop runs 3, the harnesses 1).
let threads = std::env::var("FLY_SERVE01_REPLAY_THREADS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3usize);
if threads > 1 {
agent.set_sweep_plan(
flybrain_core::lif::SweepPlan::with_threads(threads).expect("a sweep plan"),
);
}
let mut frame = LegacyFrame::new();
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
&seed,
)
.expect("the seed restores");
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
}
let started = std::time::Instant::now();
let mut stamped = 0;
while frame.frame_counter < target.runtime.emulator_frame {
for (at, brain_ms, duration) in &inputs {
if *at == frame.frame_counter {
assert_eq!(
agent.network.ms, *brain_ms,
"the journal's brainMs at frame {at}"
);
agent.network.stimulate(*duration);
stamped += 1;
}
}
let mut parts = Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: macros.as_mut(),
};
let transition = frame.transition(&mut parts, &mut Quiet).expect("a frame");
frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.expect("the boundary");
}
assert_eq!(stamped, applied.len(), "every input before the checkpoint was applied");
assert_eq!(frame.frame_counter, target.runtime.emulator_frame);
let mut state = agent.export_state();
state.remainder = frame.remainder;
assert!(state == target.agent, "the agent state (network, plasticity, decoder, remainder)");
assert_eq!(
emulator.export_state().expect("the emulator"),
target.runtime.emulator,
"the emulator state"
);
assert_eq!(frame.frame_buffer, target.runtime.framebuffer, "the frame on screen");
// Compared as numbers: the session's ledger crossed the task's canonical JSON, which writes
// an integral f64 as `7580031` where the legacy export writes `7580031.0`.
let ledger = numeric(&adapter.export_state());
let target_ledger = numeric(&target.runtime.reward);
if ledger != target_ledger {
for (key, value) in ledger.as_object().into_iter().flatten() {
if target_ledger.get(key) != Some(value) {
eprintln!(
"ledger {key}:\n replay {}\n target {}",
value,
target_ledger.get(key).unwrap_or(&serde_json::Value::Null)
);
}
}
panic!("the adapter's ledger differs");
}
assert_eq!(ratchet.state, target.runtime.ratchet, "the ratchet");
eprintln!(
"IDENTICAL: {} frames, {stamped} journaled sugar inputs, agent/emulator/frame/adapter/ratchet \
equal to the killed process's hot generation {} ({:.1?})",
target.runtime.emulator_frame - seed.runtime.emulator_frame,
target.runtime.generation,
started.elapsed()
);
}
/// Every number as an f64, so `1` and `1.0` compare equal and nothing else changes.
fn numeric(value: &serde_json::Value) -> serde_json::Value {
use serde_json::Value;
match value {
Value::Number(n) => n.as_f64().map_or(Value::Number(n.clone()), Value::from),
Value::Array(items) => Value::Array(items.iter().map(numeric).collect()),
Value::Object(map) => {
Value::Object(map.iter().map(|(k, v)| (k.clone(), numeric(v))).collect())
}
other => other.clone(),
}
}

View file

@ -0,0 +1,796 @@
//! SERVE-01: the session runtime's service host against the legacy service loop, at the level
//! of the two binding contracts (`docs/feed-protocol.md`, `docs/control-api.md`).
//!
//! Both runtimes are started from the same seeded FLYSIM01 store, behind flysim's own control
//! router (`flysim::api::router`) and snapshot slot, and driven by the same script of control
//! requests, each sent on the snapshot of a named frame so it lands before the next one (the loop
//! is paced slowly enough that a request always arrives while it sleeps). Every published feed
//! header and its three attachments, every control response, the event log, the sugar journal
//! and the final checkpoint are compared:
//!
//! - **feed**: every running snapshot, header field by field and attachments byte for byte,
//! except the fields that are wall clock by definition (`wallMs`, `uptimeSeconds`,
//! `realtimeFactor`, `sugar.cooldownMs`, an event's or chat line's `wallMs`) and `seq`, which
//! counts the idle headers a pause publishes at 2 Hz of wall clock;
//! - **control**: status code and body of every request (`/stimulate` 202 and 429 with the same
//! `retryAfterMs`, `/reward` 403, `/chat` 202/422, `/checkpoint` the same generation,
//! `/pause`, `/resume`, `/events`, `/healthz`), `/status` minus its wall-clock fields, and the
//! `/metrics` series names;
//! - **store**: the event log file, the journal lines (minus `wallMs`, the boot header's runtime
//! and wall clock), and the final durable checkpoint decoded (minus `wallMs`).
//!
//! Gated on `FLY_ROM` (source `bin/rom-env.sh`). `toy_raw_*` uses the committed toy connectome and
//! a store seeded by a legacy fresh start; `fafb_*` (also `FLY_SERVE01_FAFB`) the real connectome
//! from the ENV-01 service trace's `rollback` checkpoint, which rolls back on its first boundary.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::body::Body;
use axum::http::{Method, Request};
use fly_legacy_session::service::{ServiceOptions, run_host};
use fly_session::launcher::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use flysim::AppState;
use flysim::config::Config;
use flysim::eventlog::EventRing;
use flysim::simloop::{Command, Shared, Sim, booting_snapshot};
use flysim::snapshot::{FeedStatus, MacroMode, Snapshot};
use serde_json::{Value, json};
use tokio::sync::{mpsc, watch};
use tower::ServiceExt;
fn rom_path() -> Option<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
/// `FLYSIM_LOG=info` shows both runtimes' logs.
fn init_tracing() {
if let Ok(filter) = std::env::var("FLYSIM_LOG") {
let _ = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new(filter))
.with_writer(std::io::stderr)
.try_init();
}
}
fn sha(bytes: &[u8]) -> String {
fly_session::types::sha256_hex(bytes)
}
/// Which runtime is behind the router.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Runtime {
Legacy,
Session(ExecutionMode),
}
impl Runtime {
fn label(&self) -> String {
match self {
Runtime::Legacy => "legacy".to_owned(),
Runtime::Session(mode) => format!("session ({})", mode.label()),
}
}
}
/// One control request of the script: at the snapshot of running frame `at` (counted from the
/// first running snapshot, 0-based), send `method path body`.
#[derive(Clone, Debug)]
struct Action {
at: usize,
method: Method,
path: &'static str,
body: Option<Value>,
}
fn act(at: usize, method: Method, path: &'static str, body: Option<Value>) -> Action {
Action {
at,
method,
path,
body,
}
}
/// The script both runtimes are driven by.
fn script() -> Vec<Action> {
let sugar = || Some(json!({"by": "viewer_one", "source": "points", "durationMs": 300}));
vec![
act(2, Method::GET, "/healthz", None),
act(3, Method::POST, "/stimulate", sugar()),
// Inside the pulse: refused with the pulse's own retry.
act(4, Method::POST, "/stimulate", sugar()),
act(5, Method::POST, "/reward", Some(json!({"value": 1.0, "by": "op", "source": "operator"}))),
act(6, Method::POST, "/chat", Some(json!({"by": "viewer_two", "text": "go fly go"}))),
act(7, Method::POST, "/chat", Some(json!({"by": "not a name!", "text": "hello"}))),
act(8, Method::POST, "/stimulate", Some(json!({"by": "x"}))),
act(12, Method::POST, "/checkpoint", None),
// Two sugars before one commit (the TASK-01 review's N1): the legacy drain refuses the
// second with the first one's pulse as the retry, and so must the session's.
act(24, Method::POST, "/stimulate", Some(json!({"by": "viewer_five", "source": "points", "durationMs": 600}))),
act(24, Method::POST, "/stimulate", Some(json!({"by": "viewer_six", "source": "chat"}))),
act(40, Method::POST, "/stimulate", Some(json!({"by": "viewer_three", "source": "chat"}))),
act(41, Method::POST, "/stimulate", Some(json!({"by": "viewer_three", "source": "chat", "durationMs": 5000}))),
act(60, Method::POST, "/pause", None),
act(60, Method::POST, "/pause", None),
act(60, Method::POST, "/resume", None),
act(70, Method::GET, "/events?since=0&limit=500", None),
act(80, Method::POST, "/chat", Some(json!({"by": "viewer_two", "text": "again", "bot": true}))),
act(90, Method::GET, "/nope", None),
act(95, Method::POST, "/stimulate", Some(json!({"by": "viewer_four", "source": "points", "durationMs": 50}))),
]
}
/// What one run produced.
struct Recording {
/// False when the recorder missed a frame; such a run is repeated, never compared.
complete: bool,
/// Every running snapshot: the comparable header and the attachments' digests.
running: Vec<(Value, [String; 3])>,
/// The idle headers a pause published (compared for shape, not count).
idle: Vec<Value>,
responses: Vec<(String, u16, Value)>,
status: Value,
metric_names: Vec<String>,
events: Vec<Value>,
event_file: Vec<Value>,
journal: Vec<Value>,
final_checkpoint: Value,
}
/// The header without the fields that are wall clock by definition.
fn comparable(snapshot: &Snapshot) -> Value {
let mut value = serde_json::to_value(&snapshot.header).expect("a header serializes");
let map = value.as_object_mut().expect("an object");
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(sugar) = map.get_mut("sugar").and_then(Value::as_object_mut) {
sugar.remove("cooldownMs");
}
for list in ["events", "chat"] {
if let Some(items) = map.get_mut(list).and_then(Value::as_array_mut) {
for item in items {
if let Some(item) = item.as_object_mut() {
item.remove("wallMs");
}
}
}
}
value
}
fn without_wall(mut value: Value) -> Value {
if let Some(map) = value.as_object_mut() {
map.remove("wallMs");
}
value
}
async fn call(router: axum::Router, action: &Action) -> (u16, Value) {
let request = Request::builder()
.method(action.method.clone())
.uri(action.path);
let request = match &action.body {
Some(body) => request
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(body).unwrap())),
None => request.body(Body::empty()),
}
.unwrap();
let response = router.oneshot(request).await.unwrap();
let status = response.status().as_u16();
let bytes = axum::body::to_bytes(response.into_body(), 16 << 20)
.await
.unwrap();
let value = serde_json::from_slice(&bytes)
.unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into_owned()));
(status, value)
}
/// The service configuration of a run: flysim's defaults with the store under `dir`, every frame
/// published, no timed checkpoints (the script and the boundaries take them), chat on.
fn config(rom: &Path, dataset: &Path, dir: &Path, mode: MacroMode, speed: f64) -> Config {
let mut config = Config::default();
config.paths.rom = rom.to_path_buf();
config.paths.dataset = dataset.to_path_buf();
config.paths.save_dir = dir.join("durable");
config.paths.hot_dir = dir.join("hot");
config.loop_.game = "pokemon-red".to_owned();
config.loop_.speed = speed;
config.loop_.threads = 1;
config.loop_.snapshot_hz = 1_000_000.0;
config.loop_.hot_seconds = 1e9;
config.loop_.checkpoint_seconds = 1e9;
config.macros.mode = mode;
config.chat.enabled = true;
config
}
/// Start `runtime` over `config` behind the control router, drive the script for `frames`
/// running snapshots, shut down, and collect everything.
fn record(
runtime: Runtime,
config: Config,
profile: LegacyProfileKind,
frames: usize,
actions: &[Action],
) -> Recording {
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(flysim::simloop::COMMAND_QUEUE);
let (snapshots_tx, snapshots) = watch::channel(Arc::new(booting_snapshot(
0,
0,
config.macros.mode,
)));
let state = AppState {
shared: Arc::clone(&shared),
commands: commands.clone(),
snapshots: snapshots.clone(),
};
let session_dir = config.paths.save_dir.parent().unwrap().join("session");
let loop_shared = Arc::clone(&shared);
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let notifier = flysim::sdnotify::Notifier::from_env();
match runtime {
Runtime::Legacy => {
let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?;
sim.run(&notifier)
}
Runtime::Session(mode) => {
let options = ServiceOptions {
mode,
profile,
session_dir,
};
run_host(loop_shared, snapshots_tx, command_rx, &notifier, &options)
}
}
});
let driver = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let router = flysim::api::router(state.clone());
let metrics_router = flysim::api::metrics_router(state.clone());
let recording = driver.block_on(async {
let mut snapshots = snapshots;
let mut running: Vec<(Value, [String; 3])> = Vec::new();
let mut idle = Vec::new();
let mut pending = Vec::new();
let mut last_frame: Option<u64> = None;
let mut complete = true;
let deadline = Instant::now() + Duration::from_secs(1800);
while running.len() < frames {
assert!(Instant::now() < deadline, "{}: the run stalled", runtime.label());
match tokio::time::timeout(Duration::from_secs(120), snapshots.changed()).await {
Ok(Ok(())) => {}
// The loop is gone: its own error is the failure (the thread is joined below).
Ok(Err(_)) => break,
Err(_) => panic!(
"{}: no snapshot for 120 s after {} running",
runtime.label(),
running.len()
),
}
let snapshot = Arc::clone(&snapshots.borrow_and_update());
match snapshot.header.status {
FeedStatus::Running | FeedStatus::Recovering => {
// Every frame publishes; a gap means the recorder fell behind the loop.
let frame = snapshot.header.frame;
if let Some(last) = last_frame
&& frame != last + 1
{
// The recorder fell behind the loop (a loaded box): this run cannot be
// compared, and the caller runs it again.
eprintln!(
" {}: the recorder missed frames {}..{frame}; the run will be repeated",
runtime.label(),
last + 1
);
complete = false;
}
last_frame = Some(frame);
let index = running.len();
if index.is_multiple_of(30) {
eprintln!(" {}: running snapshot {index} (frame {frame})", runtime.label());
}
running.push((
comparable(&snapshot),
[
sha(&snapshot.frame),
sha(&snapshot.audio),
sha(&snapshot.spikes),
],
));
// Sent now, in order, each drained before the next frame.
for action in actions.iter().filter(|a| a.at == index) {
let router = router.clone();
let label = format!("{} {}", action_label(action), index);
let action = action.clone();
let handle = tokio::spawn(async move { call(router, &action).await });
// One at a time, so the loop drains them in script order.
tokio::time::sleep(Duration::from_millis(2)).await;
pending.push((label, handle));
}
}
FeedStatus::Paused => idle.push(comparable(&snapshot)),
FeedStatus::Booting | FeedStatus::Error => {}
}
}
// Stop at once, so the final save is of the frame after the last one recorded.
let (reply, ack) = tokio::sync::oneshot::channel();
if commands.send(Command::Shutdown { reply }).await.is_ok() {
let _ = ack.await;
}
let mut responses = Vec::new();
for (label, handle) in pending {
let (status, body) = handle.await.unwrap();
responses.push((label, status, body));
}
let (_, status) = call(
router.clone(),
&act(0, Method::GET, "/status", None),
)
.await;
let (_, metrics) = call(
metrics_router.clone(),
&act(0, Method::GET, "/metrics", None),
)
.await;
let metric_names: Vec<String> = metrics
.as_str()
.unwrap_or_default()
.lines()
.filter(|l| !l.starts_with('#') && !l.is_empty())
.filter_map(|l| l.split([' ', '{']).next())
.map(str::to_owned)
.collect();
(running, idle, responses, status, metric_names, complete)
});
thread
.join()
.expect("the loop thread")
.unwrap_or_else(|e| panic!("{}: {e:#}", runtime.label()));
let (running, idle, responses, status, metric_names, complete) = recording;
assert_eq!(running.len(), frames, "{}: the loop stopped early", runtime.label());
let events: Vec<Value> = shared
.events
.page(0, flysim::eventlog::RING_CAPACITY)
.into_iter()
.map(|e| without_wall(serde_json::to_value(e).unwrap()))
.collect();
let event_file: Vec<Value> =
flysim::eventlog::read_events(&config.paths.save_dir.join("events.jsonl"))
.unwrap_or_default()
.into_iter()
.map(|e| without_wall(serde_json::to_value(e).unwrap()))
.collect();
let journal: Vec<Value> = flysim::journal::read(&config.paths.hot_dir.join(flysim::journal::FILE_NAME))
.unwrap_or_default()
.into_iter()
.map(|mut line| {
if let Some(boot) = line.get_mut("boot").and_then(Value::as_object_mut) {
boot.remove("runtime");
boot.remove("wallMs");
}
without_wall(line)
})
.collect();
let durable = flysim::store::Store::new(&config.paths.save_dir, 64);
let latest = durable.highest_generation();
let bytes = std::fs::read(
flysim::store::restore_order(
&flysim::store::Store::new(&config.paths.hot_dir, 64),
&durable,
)
.into_iter()
.find(|c| c.generation == Some(latest))
.expect("the final save")
.path,
)
.unwrap();
let final_checkpoint = checkpoint_json(&bytes);
Recording {
complete,
running,
idle,
responses,
status,
metric_names,
events,
event_file,
journal,
final_checkpoint,
}
}
fn action_label(action: &Action) -> String {
format!("{} {}", action.method, action.path)
}
/// A FLYSIM01 checkpoint as comparable JSON: the runtime half without `wallMs`, and a digest of
/// every agent array.
fn checkpoint_json(bytes: &[u8]) -> Value {
let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let runtime = &checkpoint.runtime;
let agent = &checkpoint.agent;
json!({
"generation": runtime.generation,
"romSha256": runtime.rom_sha256,
"emulatorFrame": runtime.emulator_frame,
"compatibility": runtime.compatibility,
"buttons": runtime.buttons,
"rankSinceMs": runtime.rank_since_ms,
"lastEventId": runtime.last_event_id,
"reward": runtime.reward,
"ratchet": serde_json::to_value(runtime.ratchet).unwrap(),
"emulator": sha(&runtime.emulator),
"framebuffer": sha(&runtime.framebuffer),
"ratchetGame": sha(&runtime.ratchet_game),
"agent": sha(format!("{agent:?}").as_bytes()),
})
}
/// Field-by-field comparison with the first difference as the failure.
fn same(what: &str, a: &Value, b: &Value) {
if a != b {
panic!(
"{what} differs:\n legacy {}\n session {}",
truncate(a),
truncate(b)
);
}
}
fn truncate(value: &Value) -> String {
let text = value.to_string();
if text.len() > 4000 {
format!("{}...", &text[..4000])
} else {
text
}
}
fn compare(legacy: &Recording, session: &Recording, label: &str) {
assert_eq!(
legacy.running.len(),
session.running.len(),
"{label}: running snapshots"
);
for (n, ((a, da), (b, db))) in legacy.running.iter().zip(&session.running).enumerate() {
if a != b {
// Name the first differing field.
let (Some(am), Some(bm)) = (a.as_object(), b.as_object()) else {
panic!()
};
for key in am.keys().chain(bm.keys()) {
same(
&format!("{label}: snapshot {n} (frame {}) {key}", a["frame"]),
&a[key.as_str()],
&b[key.as_str()],
);
}
}
for (i, name) in ["frame", "audio", "spikes"].iter().enumerate() {
assert_eq!(
da[i], db[i],
"{label}: snapshot {n} (frame {}) attachment {name}",
a["frame"]
);
}
}
assert_eq!(legacy.idle.is_empty(), session.idle.is_empty(), "{label}: idle headers");
if let (Some(a), Some(b)) = (legacy.idle.first(), session.idle.first()) {
same(&format!("{label}: the first idle header"), a, b);
}
assert_eq!(legacy.responses.len(), session.responses.len());
for ((la, sa, ba), (lb, sb, bb)) in legacy.responses.iter().zip(&session.responses) {
assert_eq!(la, lb);
assert_eq!(sa, sb, "{label}: {la} status");
let strip = |v: &Value| {
let mut v = v.clone();
if let Some(events) = v.get_mut("events").and_then(Value::as_array_mut) {
for e in events {
if let Some(e) = e.as_object_mut() {
e.remove("wallMs");
}
}
}
v
};
same(&format!("{label}: {la} body"), &strip(ba), &strip(bb));
}
let status = |v: &Value| {
let mut v = v.clone();
let map = v.as_object_mut().unwrap();
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(s) = map.get_mut("sugar").and_then(Value::as_object_mut) {
s.remove("cooldownMs");
}
if let Some(c) = map.get_mut("checkpoint").and_then(Value::as_object_mut) {
c.remove("latestWallMs");
}
if let Some(items) = map.get_mut("chat").and_then(Value::as_array_mut) {
for item in items {
item.as_object_mut().unwrap().remove("wallMs");
}
}
v
};
// `/status` is read between frames on both sides; the frame it lands on is the driver's
// timing, so only its shape and its stable parts are compared.
let (a, b) = (status(&legacy.status), status(&session.status));
for key in ["version", "status", "chat"] {
same(&format!("{label}: /status {key}"), &a[key], &b[key]);
}
let keys = |v: &Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(&a), keys(&b), "{label}: /status fields");
assert_eq!(
keys(&a["decoder"]),
keys(&b["decoder"]),
"{label}: /status decoder fields"
);
same(
&format!("{label}: /status decoder channels"),
&json!(a["decoder"]["channels"].as_array().map(|c| c.iter().map(|x| (x["channel"].clone(), x["role"].clone())).collect::<Vec<_>>())),
&json!(b["decoder"]["channels"].as_array().map(|c| c.iter().map(|x| (x["channel"].clone(), x["role"].clone())).collect::<Vec<_>>())),
);
assert_eq!(legacy.metric_names, session.metric_names, "{label}: /metrics series");
same(&format!("{label}: event ring"), &json!(legacy.events), &json!(session.events));
same(
&format!("{label}: events.jsonl"),
&json!(legacy.event_file),
&json!(session.event_file),
);
same(&format!("{label}: sugar journal"), &json!(legacy.journal), &json!(session.journal));
same(
&format!("{label}: final checkpoint"),
&legacy.final_checkpoint,
&session.final_checkpoint,
);
}
/// Copy a seeded store (both directories) into a run's own directory.
fn seed(from: &Path, to: &Path) {
for sub in ["durable", "hot"] {
let src = from.join(sub);
let dst = to.join(sub);
std::fs::create_dir_all(&dst).unwrap();
if let Ok(entries) = std::fs::read_dir(&src) {
for entry in entries.flatten() {
if entry.file_type().unwrap().is_file() {
std::fs::copy(entry.path(), dst.join(entry.file_name())).unwrap();
}
}
}
}
}
fn modes() -> Vec<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!("process mode skipped: no worker program at {}", program.display());
}
modes
}
#[allow(clippy::too_many_arguments)]
fn run_pair(
rom: &Path,
dataset: &Path,
seeded: &Path,
profile: LegacyProfileKind,
mode: MacroMode,
speed: f64,
frames: usize,
label: &str,
) {
init_tracing();
let actions = script();
let root = tempfile::tempdir().unwrap();
// One run of `runtime` from a freshly seeded copy of the store, repeated (up to three times)
// when the recorder fell behind the loop on a loaded box.
let run = |runtime: Runtime, name: &str| -> Recording {
for attempt in 1..=3 {
let dir = root.path().join(format!("{name}-{attempt}"));
seed(seeded, &dir);
let recording = record(
runtime,
config(rom, dataset, &dir, mode, speed),
profile,
frames,
&actions,
);
if recording.complete {
return recording;
}
}
panic!("{}: the recorder fell behind three times", runtime.label());
};
let started = Instant::now();
let legacy = run(Runtime::Legacy, "legacy");
eprintln!("{label}: legacy {} running snapshots in {:.1?}", legacy.running.len(), started.elapsed());
for exec in modes() {
let started = Instant::now();
let session = run(Runtime::Session(exec), &format!("session-{}", exec.label()));
let label = format!("{label}, {}", exec.label());
compare(&legacy, &session, &label);
let rewards = legacy
.events
.iter()
.filter(|e| e["kind"] == "reward")
.count();
let macros = legacy.events.iter().filter(|e| e["kind"] == "macro").count();
let kinds: std::collections::BTreeMap<String, usize> =
legacy.events.iter().fold(Default::default(), |mut m, e| {
*m.entry(e["kind"].as_str().unwrap_or("?").to_owned()).or_default() += 1;
m
});
eprintln!("{label}: event kinds {kinds:?}");
eprintln!(
"{label}: IDENTICAL -- {} running snapshots (frames, audio, spikes byte-equal), {} idle, \
{} control responses, {} events ({rewards} reward, {macros} macro), {} journal lines, \
final checkpoint g{} equal ({:.1?})",
session.running.len(),
session.idle.len(),
session.responses.len(),
session.events.len(),
session.journal.len(),
session.final_checkpoint["generation"],
started.elapsed()
);
for (what, status, body) in &session.responses {
eprintln!(" {what} -> {status} {}", truncate(body));
}
}
}
/// A store seeded by a legacy fresh start of `seconds` wall seconds, shut down cleanly.
fn seed_by_legacy_fresh_start(rom: &Path, dataset: &Path, dir: &Path, mode: MacroMode) {
let config = config(rom, dataset, dir, mode, 1.0);
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(64);
let (snapshots_tx, mut snapshots) =
watch::channel(Arc::new(booting_snapshot(0, 0, mode)));
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?;
sim.run(&flysim::sdnotify::Notifier::from_env())
});
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
loop {
snapshots.changed().await.unwrap();
if snapshots.borrow().header.frame >= 120 {
break;
}
}
let (reply, ack) = tokio::sync::oneshot::channel();
commands.send(Command::Shutdown { reply }).await.unwrap();
let _ = ack.await;
});
thread.join().unwrap().unwrap();
}
#[test]
fn toy_raw_service_contracts() {
let Some(rom) = rom_path() else { return };
let dataset = fly_session::legacy_parity::toy::dir();
let seeded = tempfile::tempdir().unwrap();
seed_by_legacy_fresh_start(&rom, &dataset, seeded.path(), MacroMode::Raw);
run_pair(
&rom,
&dataset,
seeded.path(),
LegacyProfileKind::Toy,
MacroMode::Raw,
0.25,
120,
"toy raw",
);
}
// No toy macros run: AGENT-01's worker refuses a macro channel whose rate role the dataset does
// not track, and the committed toy connectome tracks none (the legacy loop merges them in). The
// production connectome tracks them all; `fafb_macros_*` below is the macros-mode run.
/// The real connectome from the live service's `rollback` checkpoint (ENV-01 traces): the
/// ratchet rolls back on the first boundary, so the recovery event, the `recovering` status and
/// the after-rollback durable save are on the contract too.
#[test]
fn fafb_macros_service_contracts_through_a_rollback() {
let Some(rom) = rom_path() else { return };
if std::env::var_os("FLY_SERVE01_FAFB").is_none() {
eprintln!("skipping: FLY_SERVE01_FAFB is not set");
return;
}
let Some(dataset) = fly_session::legacy_parity::fafb_dir() else {
eprintln!("skipping: no data/fafb-v783");
return;
};
// `FLY_SERVE01_FAFB_CHECKPOINT` picks another start (a reward-bearing one for a long run).
let source = std::env::var_os("FLY_SERVE01_FAFB_CHECKPOINT")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("FLY_ENV01_TRACE_DIR")
.map(|dir| PathBuf::from(dir).join("rollback.checkpoint"))
.filter(|p| p.is_file())
})
.or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from));
let Some(source) = source else {
eprintln!("skipping: no source checkpoint");
return;
};
eprintln!("fafb: from {}", source.display());
let mut bytes = std::fs::read(&source).unwrap();
if std::env::var_os("FLY_SERVE01_THIN").is_some() {
bytes = reward_bearing(&bytes);
}
let generation = flysim::store::decode(&bytes).unwrap().runtime.generation;
let seeded = tempfile::tempdir().unwrap();
flysim::store::Store::new(seeded.path().join("durable"), 4)
.commit(generation, &bytes, None)
.unwrap();
let frames = std::env::var("FLY_SERVE01_FAFB_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120);
let speed = std::env::var("FLY_SERVE01_FAFB_SPEED")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.1);
run_pair(
&rom,
&dataset,
seeded.path(),
LegacyProfileKind::Production,
MacroMode::Macros,
speed,
frames,
"fafb macros",
);
}
/// TASK-01's ledger thinning (`session_trace.rs`), so a brain run from a stream checkpoint earns
/// rewards: the current map unvisited, its exits unfound, its ground unwalked, no wild win a
/// replay (`FLY_SERVE01_THIN`).
fn reward_bearing(bytes: &[u8]) -> Vec<u8> {
let mut checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let reward = &mut checkpoint.runtime.reward;
let map = reward["location"]
.as_str()
.and_then(|l| l.split(':').next())
.unwrap_or("0")
.to_owned();
if let Some(seen) = reward["seen"].as_array_mut() {
seen.retain(|key| {
let key = key.as_str().unwrap_or("");
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
});
}
if let Some(tiles) = reward["tiles"].as_array_mut() {
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
}
if let Some(counts) = reward["tileCounts"].as_object_mut() {
counts.remove(&map);
}
reward["wildWins"] = json!({});
reward["replayBlocked"] = json!([]);
flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes")
}

View file

@ -603,9 +603,12 @@ impl Coordinator {
.collect() .collect()
} }
/// The bytes of one media handle this committed boundary holds, by attachment name (the /// The bytes of one media attachment this committed boundary holds (a view, e.g.
/// view or an audio chunk), or `None` when the boundary holds no such handle. (The same /// `media::view_attachment("lcd")`, or an audio chunk, `media::audio_attachment(..)`), or
/// method as SERVE-01's service host reads the step's audio with.) /// `None` when the boundary holds no such attachment. A read: the handle stays held.
///
/// For a host that presents the boundary itself (SERVE-01's service host, which publishes
/// the legacy feed from the committed frame and audio chunk).
pub async fn media_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, String> { pub async fn media_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, String> {
let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else { let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else {
return Ok(None); return Ok(None);
@ -617,6 +620,59 @@ impl Coordinator {
.map_err(|e| format!("reading {name}: {}", e.message)) .map_err(|e| format!("reading {name}: {}", e.message))
} }
/// One read-only extension call to an agent at the committed boundary, answered by that
/// worker's own method (`method` must be one it lists). Unlike every session operation this
/// never fences the epoch: a read that failed changed nothing, and its caller decides what
/// a missing answer means (SERVE-01: the legacy agent's `Legacy.FeedStatus`).
pub async fn read_agent_extension(
&mut self,
agent_id: &Id,
method: &'static str,
) -> Result<Value, String> {
let Phase::Ready(_) = self.phases.phase() else {
return Err(format!("{method} reads a committed Ready boundary"));
};
let Some(worker) = self.agent_ref(agent_id).cloned() else {
return Err(format!("no agent {agent_id}"));
};
let request_id = self.serials.next(&worker.service);
let started = Instant::now();
let outcome = call_owned(
self.bus.clone(),
worker,
method,
None,
Map::new(),
Vec::new(),
request_id,
Vec::new(),
self.deadlines.probe,
)
.await;
self.metrics.record(method, started.elapsed());
match outcome {
CallOutcome::Answered(reply) => reply
.result()
.cloned()
.map_err(|e| format!("{method}: {}", e.message)),
CallOutcome::Refused(e) => Err(format!("{method}: {}", e.message)),
CallOutcome::Expired => Err(format!("{method}: no reply within the probe deadline")),
}
}
/// Bounds the session's in-memory records for a host that runs for days (SERVE-01's service):
/// the transition trace keeps only its last entry (a deferred rollback amends that one), and
/// the phase trace, the audit and the injection log are emptied. Every one of them otherwise
/// grows with every transition. A parity run or a test that reads them never calls this.
pub fn trim_records(&mut self) {
let last = self.trace.transitions.pop();
self.trace.transitions.clear();
self.trace.transitions.extend(last);
self.trace.phases.clear();
self.audit.clear();
self.injection_log.clear();
}
/// Where each declared audio stream's next chunk may start. /// Where each declared audio stream's next chunk may start.
pub fn audio_positions(&self) -> BTreeMap<String, u64> { pub fn audio_positions(&self) -> BTreeMap<String, u64> {
self.timelines.positions() self.timelines.positions()
@ -2625,6 +2681,7 @@ impl Coordinator {
slot.prepare_request = None; slot.prepare_request = None;
} }
let publish_span = crate::profile::span("coord.publish"); let publish_span = crate::profile::span("coord.publish");
let publishing = Instant::now();
self.publish_events(k + 1, &evaluation.events).await?; self.publish_events(k + 1, &evaluation.events).await?;
// Every boundary with events or boundary actions is published; otherwise every // Every boundary with events or boundary actions is published; otherwise every
// `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at // `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at
@ -2637,6 +2694,7 @@ impl Coordinator {
self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?;
} }
drop(publish_span); drop(publish_span);
self.metrics.record("publish", publishing.elapsed());
// A rollback request was applied above and is not an episode end; only a terminal one // A rollback request was applied above and is not an episode end; only a terminal one
// pauses the session for the episode policy. // pauses the session for the episode policy.

View file

@ -84,6 +84,19 @@ pub const SPIKES_ATTACHMENT: &str = "telemetry.spikes";
/// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes: /// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes:
/// the legacy feed's `spike_bitset` layout. /// the legacy feed's `spike_bitset` layout.
pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset"; pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
/// The legacy agent's read-only feed status (SERVE-01), and the capability that advertises it.
///
/// The legacy feed header and `GET /status` carry numbers from inside the network that no
/// session-framework message carries: the plasticity rule's whole statistics (`learning.changed`
/// counts synapses whose gain moved, `learning.synapses` the rule's edges), the decoder's
/// per-channel baseline and last score, and the rates and pulse as they stand at the committed
/// boundary. The session runtime's service host reads them here, once per published snapshot, at a
/// committed `Ready(k)`, which is where the legacy loop reads them for its own publish. It is a
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
/// answered in any phase once initialized, and is not in any trace.
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
/// The one stimulus kind the profile supports. /// The one stimulus kind the profile supports.
pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE; pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE;
@ -597,6 +610,66 @@ pub fn telemetry_of(agent: &NeuralAgent, brain_ticks: u64, reinforcements: u64)
} }
} }
/// A finite number for JSON: the legacy header's `finite`, applied before the value is sent.
fn finite_or_zero(value: f64) -> f64 {
if value.is_finite() { value } else { 0.0 }
}
/// The [`METHOD_FEED_STATUS`] result: exactly what the legacy loop's `publish` and
/// `publish_decoder_status` read from the network, in the network's own order.
///
/// ```text
/// { brainMs, rates: [[role, hz], ...], populationRate, rewardRemainingMs,
/// learning: { enabled, updates, changed, synapses, signal },
/// decoder: { calibrated, pending: [...], channels: [{channel, role, baseline, score}] } }
/// ```
///
/// Rates are pairs rather than an object so their order survives any JSON reader. Every
/// number goes through the legacy `finite` first: JSON has no NaN, and the header would have
/// written 0 for one anyway.
pub fn feed_status_of(agent: &NeuralAgent) -> Value {
let network = &agent.network;
let stats = network.plasticity.statistics();
let decoder = &agent.decoder;
let scores = decoder.last_scores();
let baselines = decoder.baselines();
let rates: Vec<Value> = network
.rates
.iter()
.map(|(name, hz)| json!([name, finite_or_zero(hz)]))
.collect();
let channels: Vec<Value> = decoder
.channel_roles()
.into_iter()
.map(|(channel, role)| {
json!({
"channel": channel,
"role": role,
"baseline": finite_or_zero(baselines.get_or_zero(role)),
"score": finite_or_zero(scores.get_or_zero(channel)),
})
})
.collect();
json!({
"brainMs": finite_or_zero(network.ms),
"rates": rates,
"populationRate": finite_or_zero(network.population_rate),
"rewardRemainingMs": finite_or_zero(network.reward_remaining()),
"learning": {
"enabled": stats.enabled,
"updates": finite_or_zero(stats.updates),
"changed": stats.changed,
"synapses": stats.synapses,
"signal": finite_or_zero(stats.signal),
},
"decoder": {
"calibrated": decoder.calibrated(),
"pending": decoder.pending_baseline_roles(),
"channels": channels,
},
})
}
/// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS` /// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS`
/// order, and the first bound channel the decode holds, which is exactly the channel the legacy /// order, and the first bound channel the decode holds, which is exactly the channel the legacy
/// macro layer's `asked` would start. /// macro layer's `asked` would start.
@ -871,6 +944,28 @@ impl LegacyAgentWorker {
telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements) telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements)
} }
// ---------------------------------------------------------------------------------------
// Legacy.FeedStatus (SERVE-01)
/// The network as the legacy loop's `publish` reads it, at the committed boundary.
fn feed_status(&self) -> DomainResult<HandlerReply> {
let Some(agent) = self.agent.as_ref() else {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus needs an initialized agent",
));
};
if matches!(self.phase, AgentPhase::Prepared(_) | AgentPhase::Failed) {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus reads a committed boundary",
));
}
let mut reply = HandlerReply::new(object(feed_status_of(agent)));
reply.mutated = false;
Ok(reply)
}
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
// Agent.Initialize // Agent.Initialize
@ -1826,6 +1921,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
id("pixel-observation-v1"), id("pixel-observation-v1"),
id(crate::state::CHECKPOINT_CAPABILITY), id(crate::state::CHECKPOINT_CAPABILITY),
id(ROLLBACK_CAPABILITY), id(ROLLBACK_CAPABILITY),
id(FEED_STATUS_CAPABILITY),
] ]
} }
@ -1846,6 +1942,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
"State.Capture", "State.Capture",
"State.StageRestore", "State.StageRestore",
"State.ActivateRestore", "State.ActivateRestore",
METHOD_FEED_STATUS,
] ]
} }
@ -1865,6 +1962,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
"State.Capture" => self.state_capture(&ctx).await, "State.Capture" => self.state_capture(&ctx).await,
"State.StageRestore" => self.state_stage_restore(&ctx).await, "State.StageRestore" => self.state_stage_restore(&ctx).await,
"State.ActivateRestore" => self.state_activate_restore(&ctx).await, "State.ActivateRestore" => self.state_activate_restore(&ctx).await,
METHOD_FEED_STATUS => self.feed_status(),
other => Err(DomainError::before( other => Err(DomainError::before(
ErrorCode::Unsupported, ErrorCode::Unsupported,
format!("{other} is not an agent method"), format!("{other} is not an agent method"),

View file

@ -939,6 +939,9 @@ fn classify_default(method: &str) -> Option<OpClass> {
"Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => { "Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => {
Some(OpClass::ReadOnly) Some(OpClass::ReadOnly)
} }
// The legacy agent's feed status (SERVE-01): a read of the committed boundary that
// changes nothing, so a duplicate simply reads again.
crate::legacy_agent::METHOD_FEED_STATUS => Some(OpClass::ReadOnly),
_ => None, _ => None,
} }
} }

View file

@ -80,6 +80,34 @@ impl AppState {
/// The simulation runs on the calling thread and the listeners on a two-worker tokio runtime, so /// The simulation runs on the calling thread and the listeners on a two-worker tokio runtime, so
/// a stalled socket cannot preempt the loop and the process exits when the loop does. /// a stalled socket cannot preempt the loop and the process exits when the loop does.
pub fn run(config: Config) -> Result<()> { pub fn run(config: Config) -> Result<()> {
serve(config, |shared, snapshots, commands, notifier| {
let mut sim = Sim::boot(shared, snapshots, commands)?;
notifier.notify("READY=1\nSTATUS=simulation running\n");
let result = sim.run(notifier);
notifier.notify("STOPPING=1\n");
drop(sim);
result
})
}
/// Bind the listeners and serve them around `sim`, which runs on the calling thread and
/// returns when the service should stop; it sends `READY=1` once it is up.
///
/// `sim` is handed the state the listeners share, the snapshot slot they read, the command
/// queue they write, and the systemd notifier. The legacy loop ([`Sim`], through [`run`]) and the
/// session runtime (`fly-legacy-session`'s service host, SERVE-01) are both run this way, so the
/// feed listener, the bus publisher, the control API, the metrics listener and the signal
/// handling are one copy of the code whichever runtime is behind them: the binding contracts
/// (`docs/feed-protocol.md`, `docs/control-api.md`) are served by the same bytes.
pub fn serve<F>(config: Config, sim: F) -> Result<()>
where
F: FnOnce(
Arc<Shared>,
watch::Sender<Arc<Snapshot>>,
mpsc::Receiver<Command>,
&sdnotify::Notifier,
) -> Result<()>,
{
let ring = EventRing::new(); let ring = EventRing::new();
let shared = Arc::new(Shared::new(config.clone(), ring)); let shared = Arc::new(Shared::new(config.clone(), ring));
let (commands, command_rx) = mpsc::channel(COMMAND_QUEUE); let (commands, command_rx) = mpsc::channel(COMMAND_QUEUE);
@ -181,11 +209,7 @@ pub fn run(config: Config) -> Result<()> {
runtime.spawn(reload_chat_deny_list_on_sighup(Arc::clone(&state.shared))); runtime.spawn(reload_chat_deny_list_on_sighup(Arc::clone(&state.shared)));
let notifier = sdnotify::Notifier::from_env(); let notifier = sdnotify::Notifier::from_env();
let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?; let result = sim(shared, snapshots_tx, command_rx, &notifier);
notifier.notify("READY=1\nSTATUS=simulation running\n");
let result = sim.run(&notifier);
notifier.notify("STOPPING=1\n");
drop(sim);
if let Some((bus_runtime, bus)) = bus_runtime { if let Some((bus_runtime, bus)) = bus_runtime {
// The publisher ends by itself once the watch sender is gone; stopping the runtime under // The publisher ends by itself once the watch sender is gone; stopping the runtime under
// it, rather than the router first, keeps a last in-flight publish from being logged as // it, rather than the router first, keeps a last in-flight publish from being logged as

View file

@ -317,7 +317,7 @@ struct WriteJob {
} }
/// Which stimulation pathway an accepted pulse came from, for the event label. /// Which stimulation pathway an accepted pulse came from, for the event label.
fn sugar_label(by: &str) -> String { pub fn sugar_label(by: &str) -> String {
format!("{by} fed the fly sugar") format!("{by} fed the fly sugar")
} }
@ -1163,44 +1163,12 @@ impl Sim {
/// Nothing here touches the network, the emulator, the decoder or plasticity. That is the /// Nothing here touches the network, the emulator, the decoder or plasticity. That is the
/// whole point: chat is a caption track, not an input. /// whole point: chat is a caption track, not an input.
fn chat(&mut self, by: &str, text: &str, bot: bool) -> Result<u64, ChatRefusal> { fn chat(&mut self, by: &str, text: &str, bot: bool) -> Result<u64, ChatRefusal> {
let refuse = |sim: &Self, refusal: ChatRefusal| { let ms = self.agent.network.ms;
sim.shared.metrics.chat_rejected(refusal.reason()); let Self { shared, chat_ring, chat_limits, deny_list, log, .. } = self;
refusal admit_chat(shared, chat_ring, chat_limits, deny_list, by, text, bot, |event| {
}; Metrics::incr(&shared.metrics.events_total);
log.append(now_wall_ms(), ms, event)
if !crate::chat::is_valid_display_name(by) { })
return Err(refuse(self, ChatRefusal::Rejected(RejectReason::Name)));
}
let text = match crate::chat::sanitize_chat_text(text) {
Ok(text) => text,
Err(reason) => return Err(refuse(self, ChatRefusal::Rejected(reason))),
};
if self.deny_list.blocks(by, &text) {
tracing::info!(by, "chat line refused by the deny list");
return Err(refuse(self, ChatRefusal::Rejected(RejectReason::DenyList)));
}
let now_ms = now_wall_ms();
if let Err(refusal) = self.chat_limits.admit(by, now_ms) {
return Err(refuse(self, refusal));
}
let event = self.emit(NewEvent::new(FeedEventKind::Viewer, "chat").by(by));
self.chat_ring.push(ChatLine {
id: event.id,
wall_ms: event.wall_ms,
by: by.to_string(),
text,
bot: if bot { Some(true) } else { None },
});
// The ring survives a restart because it is written here, not because it is in a
// checkpoint: one atomic rename onto tmpfs per accepted line, and a failure is a warning
// rather than a refusal — the line is already on screen.
if let Err(error) = self.chat_ring.save_sidecar(&self.shared.config.paths.hot_dir) {
tracing::warn!(%error, "could not persist the chat ring; it will not survive a restart");
}
Metrics::incr(&self.shared.metrics.chat_accepted_total);
Ok(event.id)
} }
/// One `macro` feed event per start and per finish (`docs/design/macros.md` section 5). /// One `macro` feed event per start and per finish (`docs/design/macros.md` section 5).
@ -1447,26 +1415,10 @@ impl Sim {
self.publish_decoder_status(); self.publish_decoder_status();
let ms = self.agent.network.ms; let ms = self.agent.network.ms;
let stats = self.agent.network.plasticity.statistics(); let stats = self.agent.network.plasticity.statistics();
let progress = self.adapter.progress();
let ladder = self.adapter.rank_ladder();
// Which rung the fly is going for, when the adapter knows: see `next_label`.
let next_rung = self.adapter.next_rung();
let rank = progress.rank.min(progress.rank_max);
let mut rates = Map::new();
for (name, value) in self.agent.network.rates.iter() {
rates.insert(name.clone(), json_number(value));
}
let mut reward_counts = RewardCounts::default();
for (kind, count) in &progress.counts {
if let Some(kind) = RewardKind::from_adapter(kind) {
reward_counts.add(kind, *count);
}
}
let remaining = self.agent.network.reward_remaining(); let remaining = self.agent.network.reward_remaining();
let cooldown = self.limiter.cooldown_ms(now_wall_ms()); let cooldown = self.limiter.cooldown_ms(now_wall_ms());
// One read of the adapter per publish: the header's `game` and `milestone` share it.
let progress = self.adapter.progress();
let (frame, audio, spikes, spike_count, attachments) = if with_attachments { let (frame, audio, spikes, spike_count, attachments) = if with_attachments {
let (bitset, count) = let (bitset, count) =
@ -1502,59 +1454,26 @@ impl Sim {
brain_ms: finite(ms).max(0.0), brain_ms: finite(ms).max(0.0),
frame: self.frame.frame_counter, frame: self.frame.frame_counter,
buttons: self.frame.buttons & 0xff, buttons: self.frame.buttons & 0xff,
rates, rates: feed_rates(self.agent.network.rates.iter()),
population_rate: finite(self.agent.network.population_rate).max(0.0), population_rate: finite(self.agent.network.population_rate).max(0.0),
spike_count, spike_count,
learning: FeedLearning { learning: feed_learning(&stats),
enabled: stats.enabled, game: feed_game(
updates: finite(stats.updates).max(0.0) as u64, self.adapter.as_ref(),
changed: stats.changed, &progress,
synapses: stats.synapses as u64, self.semantic_rewards,
signal: finite(stats.signal), self.macros.as_ref(),
}, self.shared.config.macros.mode,
game: FeedGame { ms,
mode: GameMode::from_adapter(self.adapter.mode()),
semantic_rewards: self.semantic_rewards,
map: self.adapter.map_id(),
badges: progress.counter.min(8),
unique_locations: progress.unique_locations as u64,
reward_total: finite(progress.reward_total),
reward_counts,
// Raw mode deals no palette, so it claims no scene either: an empty palette and
// `unknown` are the honest answers, and the page's MODE chip says which it is.
scene: self.macros.as_ref().map_or(FeedScene::Unknown, MacroLayer::scene),
macro_mode: self.shared.config.macros.mode,
palette: self
.macros
.as_ref()
.map(MacroLayer::feed_palette)
.unwrap_or_default(),
running_macro: self.macros.as_ref().and_then(|layer| layer.feed_macro(ms)),
macro_outcome: self.macros.as_ref().and_then(MacroLayer::feed_outcome),
// Report-only (`docs/design/macros.md` section 13.1): how long the pad has had
// nothing on it in a playable scene. Nothing in the loop reads it back.
pad_empty_ms: finite(
self.macros.as_ref().map_or(0.0, |layer| layer.pad_empty_ms(ms)),
), ),
}, milestone: feed_milestone(
// `total` is the running adapter's ladder length, never a number spelled out here: self.adapter.as_ref(),
// 38 rungs for Pokémon (`docs/design/ladder.md`), 16 for the platformer &progress,
// (`docs/design/platformer.md` §3). `rank_ladder()` is also what the page draws. self.rank_since_ms,
milestone: FeedMilestone { ms,
rank, self.ratchet.state.attempts,
label: progress.rank_label.to_string(), ),
next: next_label(ladder, rank, progress.rank_label, next_rung).to_string(), sugar: feed_sugar(remaining, cooldown, self.sugar_last_by.clone(), self.sugar_today),
since_seconds: finite((ms - self.rank_since_ms) / 1000.0).max(0.0),
attempts: self.ratchet.state.attempts,
total: ladder.len() as u32,
},
sugar: FeedSugar {
active: remaining > 0.0,
remaining_ms: finite(remaining).max(0.0),
cooldown_ms: cooldown as f64,
last_by: self.sugar_last_by.clone(),
today_count: self.sugar_today,
},
events: self.log.take_pending(), events: self.log.take_pending(),
// The kill switch omits the field rather than sending an empty array. // The kill switch omits the field rather than sending an empty array.
chat: if self.shared.config.chat.enabled { chat: if self.shared.config.chat.enabled {
@ -1572,6 +1491,67 @@ impl Sim {
} }
} }
/// `POST /chat`: the on-screen chat path, enforced here rather than trusted from the bridge.
///
/// Name, sanitizer, deny list, then the admission limits, in that order — a line that a rule
/// refuses must not spend anyone's rate budget. On acceptance the line joins the ring and one
/// `viewer` event labelled `chat` joins the event log (`emit`); the event carries the name only,
/// so no chat text is ever written to `events.jsonl`.
///
/// Nothing here touches the network, the emulator, the decoder or plasticity. That is the
/// whole point: chat is a caption track, not an input. Shared by the legacy loop and the session
/// runtime's service host (SERVE-01).
#[allow(clippy::too_many_arguments)]
pub fn admit_chat(
shared: &Shared,
chat_ring: &mut ChatRing,
chat_limits: &mut ChatLimiter,
deny_list: &DenyList,
by: &str,
text: &str,
bot: bool,
emit: impl FnOnce(NewEvent) -> FeedEvent,
) -> Result<u64, ChatRefusal> {
let refuse = |refusal: ChatRefusal| {
shared.metrics.chat_rejected(refusal.reason());
refusal
};
if !crate::chat::is_valid_display_name(by) {
return Err(refuse(ChatRefusal::Rejected(RejectReason::Name)));
}
let text = match crate::chat::sanitize_chat_text(text) {
Ok(text) => text,
Err(reason) => return Err(refuse(ChatRefusal::Rejected(reason))),
};
if deny_list.blocks(by, &text) {
tracing::info!(by, "chat line refused by the deny list");
return Err(refuse(ChatRefusal::Rejected(RejectReason::DenyList)));
}
let now_ms = now_wall_ms();
if let Err(refusal) = chat_limits.admit(by, now_ms) {
return Err(refuse(refusal));
}
let event = emit(NewEvent::new(FeedEventKind::Viewer, "chat").by(by));
chat_ring.push(ChatLine {
id: event.id,
wall_ms: event.wall_ms,
by: by.to_string(),
text,
bot: if bot { Some(true) } else { None },
});
// The ring survives a restart because it is written here, not because it is in a
// checkpoint: one atomic rename onto tmpfs per accepted line, and a failure is a warning
// rather than a refusal — the line is already on screen.
if let Err(error) = chat_ring.save_sidecar(&shared.config.paths.hot_dir) {
tracing::warn!(%error, "could not persist the chat ring; it will not survive a restart");
}
Metrics::incr(&shared.metrics.chat_accepted_total);
Ok(event.id)
}
/// The rung the fly is trying for: the label of the adapter's own next rung, or of `rank + 1` /// The rung the fly is trying for: the label of the adapter's own next rung, or of `rank + 1`
/// where the adapter has no answer, or the current label once there is nothing above it. /// where the adapter has no answer, or the current label once there is nothing above it.
/// ///
@ -1595,9 +1575,113 @@ fn next_label<'a>(
ladder.get(index).copied().unwrap_or(current) ladder.get(index).copied().unwrap_or(current)
} }
/// The header's `rates`: every rate role in the network's own order, each clamped to a finite
/// number ([`json_number`]).
///
/// This and the other `feed_*` functions below are the pieces of a feed header that come from
/// the fly and its game rather than from the service. They are free functions, shared by the
/// legacy loop's `publish` and the session runtime's (SERVE-01), so the two cannot compute a field
/// two ways.
pub fn feed_rates<'a>(rates: impl Iterator<Item = (&'a String, f64)>) -> Map<String, Value> {
let mut out = Map::new();
for (name, value) in rates {
out.insert(name.clone(), json_number(value));
}
out
}
/// The header's `learning`, from the plasticity rule's statistics.
pub fn feed_learning(stats: &flybrain_core::plasticity::LearningStats) -> FeedLearning {
FeedLearning {
enabled: stats.enabled,
updates: finite(stats.updates).max(0.0) as u64,
changed: stats.changed,
synapses: stats.synapses as u64,
signal: finite(stats.signal),
}
}
/// The header's `game`: the adapter's progress and the macro layer's scene, palette and macro.
pub fn feed_game(
adapter: &dyn GameAdapter,
progress: &ProgressSnapshot,
semantic_rewards: bool,
macros: Option<&MacroLayer>,
macro_mode: MacroMode,
ms: f64,
) -> FeedGame {
let mut reward_counts = RewardCounts::default();
for (kind, count) in &progress.counts {
if let Some(kind) = RewardKind::from_adapter(kind) {
reward_counts.add(kind, *count);
}
}
FeedGame {
mode: GameMode::from_adapter(adapter.mode()),
semantic_rewards,
map: adapter.map_id(),
badges: progress.counter.min(8),
unique_locations: progress.unique_locations as u64,
reward_total: finite(progress.reward_total),
reward_counts,
// Raw mode deals no palette, so it claims no scene either: an empty palette and
// `unknown` are the honest answers, and the page's MODE chip says which it is.
scene: macros.map_or(FeedScene::Unknown, MacroLayer::scene),
macro_mode,
palette: macros.map(MacroLayer::feed_palette).unwrap_or_default(),
running_macro: macros.and_then(|layer| layer.feed_macro(ms)),
macro_outcome: macros.and_then(MacroLayer::feed_outcome),
// Report-only (`docs/design/macros.md` section 13.1): how long the pad has had
// nothing on it in a playable scene. Nothing in the loop reads it back.
pad_empty_ms: finite(macros.map_or(0.0, |layer| layer.pad_empty_ms(ms))),
}
}
/// The header's `milestone`.
///
/// `total` is the running adapter's ladder length, never a number spelled out here: 38 rungs
/// for Pokémon (`docs/design/ladder.md`), 16 for the platformer (`docs/design/platformer.md`
/// §3). `rank_ladder()` is also what the page draws.
pub fn feed_milestone(
adapter: &dyn GameAdapter,
progress: &ProgressSnapshot,
rank_since_ms: f64,
ms: f64,
attempts: u64,
) -> FeedMilestone {
let ladder = adapter.rank_ladder();
// Which rung the fly is going for, when the adapter knows: see `next_label`.
let next_rung = adapter.next_rung();
let rank = progress.rank.min(progress.rank_max);
FeedMilestone {
rank,
label: progress.rank_label.to_string(),
next: next_label(ladder, rank, progress.rank_label, next_rung).to_string(),
since_seconds: finite((ms - rank_since_ms) / 1000.0).max(0.0),
attempts,
total: ladder.len() as u32,
}
}
/// The header's `sugar`, from the pulse still running and the limiter's cooldown.
pub fn feed_sugar(
remaining_ms: f64,
cooldown_ms: u64,
last_by: Option<String>,
today_count: u64,
) -> FeedSugar {
FeedSugar {
active: remaining_ms > 0.0,
remaining_ms: finite(remaining_ms).max(0.0),
cooldown_ms: cooldown_ms as f64,
last_by,
today_count,
}
}
/// Serde writes `null` for a non-finite f64, which would break the header schema; every rate is /// Serde writes `null` for a non-finite f64, which would break the header schema; every rate is
/// clamped to a finite number first. /// clamped to a finite number first.
fn json_number(value: f64) -> Value { pub fn json_number(value: f64) -> Value {
serde_json::Number::from_f64(finite(value)).map_or(Value::from(0), Value::Number) serde_json::Number::from_f64(finite(value)).map_or(Value::from(0), Value::Number)
} }

View file

@ -667,15 +667,27 @@ impl DcBlocker {
pub fn process_into(&mut self, raw: &[u8], out: &mut Vec<f32>) { pub fn process_into(&mut self, raw: &[u8], out: &mut Vec<f32>) {
out.reserve(raw.len()); out.reserve(raw.len());
for (index, sample) in raw.iter().enumerate() { for (index, sample) in raw.iter().enumerate() {
self.push(index, f32::from(*sample) / 255.0, out);
}
}
/// Filter samples already converted with `v / 255` (the session environment's native audio,
/// `legacy_env::audio_f32le`) onto the end of `out`: the same filter, the same state, so the
/// edge of the session runtime publishes the bytes [`DcBlocker::process_into`] does.
pub fn process_f32_into(&mut self, converted: &[f32], out: &mut Vec<f32>) {
out.reserve(converted.len());
for (index, input) in converted.iter().enumerate() {
self.push(index, *input, out);
}
}
fn push(&mut self, index: usize, input: f32, out: &mut Vec<f32>) {
let channel = index & 1; let channel = index & 1;
let input = f32::from(*sample) / 255.0; let output = input - self.previous_in[channel] + DC_BLOCK_POLE * self.previous_out[channel];
let output =
input - self.previous_in[channel] + DC_BLOCK_POLE * self.previous_out[channel];
self.previous_in[channel] = input; self.previous_in[channel] = input;
self.previous_out[channel] = output; self.previous_out[channel] = output;
out.push(output); out.push(output);
} }
}
} }
/// Little-endian bytes of an f32 slice, as a `Float32Array` holds them. /// Little-endian bytes of an f32 slice, as a `Float32Array` holds them.

317
tools/runtime-soak.ts Normal file
View file

@ -0,0 +1,317 @@
/**
* runtime-soak: drive a running fly service (flysim or flysim-session) the way the stage and the
* bridge do, for a wall-clock soak, and summarise what they saw (SERVE-01).
*
* npx tsx tools/runtime-soak.ts --minutes 35 --out soak.json \
* [--feed ws://127.0.0.1:7400/feed] [--control http://127.0.0.1:7401] \
* [--metrics http://127.0.0.1:9101] [--state DIR --hot DIR]
*
* The clients are the real ones, not re-implementations:
*
* - **feed**: two WebSocket clients sending the stage's `hello` (one wanting every attachment,
* one header-only), each message decoded by the stage's own `decodeFeedMessage` (shape checks
* included) and every header validated against `packages/feed/src/schema.json`. Counted:
* messages, decode and schema failures, `seq` gaps, stalls longer than the stage's 2 s STALE
* banner, statuses seen, the frame advancing.
* - **control**: the bridge's own `HttpSimClient` (`services/bridge/src/sim.ts`): `/healthz`
* every 2 s, `/status` every 5 s, `/events` paged every 3 s with the bridge's cursor, sugar
* (`/stimulate`) every 20 s alternating `chat`/`points`, an on-screen chat line every 15 s; plus
* `/reward` (403 expected), a forced `/checkpoint` every 10 minutes and one pause/resume.
* - **store**: every 30 s, the hot and durable directories' checkpoint files and the metrics
* listener's checkpoint series, so the hot/durable cadence is observed from outside.
*
* Exit 0 when nothing failed; the JSON summary says what was seen either way.
*/
import { readdirSync, statSync, writeFileSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import Ajv2020 from 'ajv/dist/2020.js';
import { decodeFeedMessage } from '../apps/stage/src/feed/decode';
import { HttpSimClient } from '../services/bridge/src/sim';
function arg(name: string, fallback: string): string {
const index = process.argv.indexOf(`--${name}`);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const minutes = Number(arg('minutes', '30'));
const feedUrl = arg('feed', 'ws://127.0.0.1:7400/feed');
const controlUrl = arg('control', 'http://127.0.0.1:7401');
const metricsUrl = arg('metrics', 'http://127.0.0.1:9101');
const stateDir = arg('state', '');
const hotDir = arg('hot', '');
const out = arg('out', 'soak.json');
const endAt = Date.now() + minutes * 60_000;
const schema = JSON.parse(
readFileSync(new URL('../packages/feed/src/schema.json', import.meta.url), 'utf8'),
);
const ajv = new Ajv2020({ strict: false });
const validate = ajv.compile(schema);
interface FeedStats {
wants: string[];
connects: number;
messages: number;
decodeErrors: string[];
schemaErrors: string[];
seqGaps: number;
stalls: number;
longestSilenceMs: number;
statuses: Record<string, number>;
firstFrame: number | null;
lastFrame: number | null;
frameBackwards: number;
/** Each reconnect after the service went away: the last frame before, the first after. */
restarts: { lastFrame: number | null; firstFrame: number | null; gapMs: number }[];
withFrame: number;
audioSamples: number;
lastHeader: unknown;
}
function feedClient(wants: string[]): FeedStats {
const stats: FeedStats = {
wants,
connects: 0,
messages: 0,
decodeErrors: [],
schemaErrors: [],
seqGaps: 0,
stalls: 0,
longestSilenceMs: 0,
statuses: {},
firstFrame: null,
lastFrame: null,
frameBackwards: 0,
restarts: [],
withFrame: 0,
audioSamples: 0,
lastHeader: null,
};
let lastSeq: number | null = null;
let lastAt = Date.now();
const open = () => {
if (Date.now() >= endAt) return;
const socket = new WebSocket(feedUrl);
socket.binaryType = 'arraybuffer';
socket.onopen = () => {
stats.connects += 1;
if (stats.connects > 1) {
stats.restarts.push({ lastFrame: stats.lastFrame, firstFrame: null, gapMs: Date.now() - lastAt });
// A new process: its frame restarts from its checkpoint, so "backwards" is per process.
stats.lastFrame = null;
}
lastSeq = null;
socket.send(JSON.stringify({ protocol: 1, client: 'stage', wants }));
};
socket.onmessage = (message) => {
const now = Date.now();
const silence = now - lastAt;
lastAt = now;
stats.longestSilenceMs = Math.max(stats.longestSilenceMs, silence);
if (silence > 2000 && stats.messages > 0) stats.stalls += 1;
stats.messages += 1;
try {
const decoded = decodeFeedMessage(new Uint8Array(message.data as ArrayBuffer));
const header = decoded.header;
if (!validate(header) && stats.schemaErrors.length < 20) {
stats.schemaErrors.push(ajv.errorsText(validate.errors));
}
if (lastSeq !== null && header.seq !== lastSeq + 1) stats.seqGaps += 1;
lastSeq = header.seq;
stats.statuses[header.status] = (stats.statuses[header.status] ?? 0) + 1;
if (header.status === 'running' || header.status === 'recovering') {
if (stats.firstFrame === null) stats.firstFrame = header.frame;
const restart = stats.restarts[stats.restarts.length - 1];
if (restart && restart.firstFrame === null) restart.firstFrame = header.frame;
if (stats.lastFrame !== null && header.frame < stats.lastFrame) stats.frameBackwards += 1;
stats.lastFrame = header.frame;
}
if (decoded.frame) stats.withFrame += 1;
if (decoded.audio) stats.audioSamples += decoded.audio.length;
stats.lastHeader = header;
} catch (error) {
if (stats.decodeErrors.length < 20) stats.decodeErrors.push(String(error));
}
};
socket.onclose = () => setTimeout(open, 500);
socket.onerror = () => {};
const closer = setInterval(() => {
if (Date.now() >= endAt) {
clearInterval(closer);
socket.onclose = null;
socket.close();
}
}, 1000);
};
open();
return stats;
}
interface Tally {
count: number;
outcomes: Record<string, number>;
samples: unknown[];
}
function tally(): Tally {
return { count: 0, outcomes: {}, samples: [] };
}
function note(t: Tally, outcome: string, sample?: unknown) {
t.count += 1;
t.outcomes[outcome] = (t.outcomes[outcome] ?? 0) + 1;
if (sample !== undefined && t.samples.length < 5) t.samples.push(sample);
}
function outcomeOf(result: { ok: boolean; kind?: string; status?: number }): string {
if (result.ok) return 'ok';
return result.kind === 'http_error' ? `http_${result.status}` : String(result.kind);
}
const sim = new HttpSimClient({ baseUrl: controlUrl, timeoutMs: 3000 });
const control = {
healthz: tally(),
status: tally(),
events: tally(),
stimulate: tally(),
chat: tally(),
reward: tally(),
checkpoint: tally(),
pause: tally(),
resume: tally(),
};
let eventCursor = 0;
const eventKinds: Record<string, number> = {};
let eventIdGaps = 0;
let lastEventId = 0;
async function post(path: string, body?: unknown): Promise<{ status: number; json: unknown }> {
const response = await fetch(`${controlUrl}${path}`, {
method: 'POST',
headers: body === undefined ? {} : { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
return { status: response.status, json: await response.json().catch(() => null) };
}
interface StoreSample {
atMs: number;
hot: { name: string; mtimeMs: number; size: number }[];
durable: { name: string; mtimeMs: number; size: number }[];
metrics: Record<string, number>;
}
const store: StoreSample[] = [];
function listing(dir: string) {
if (!dir) return [];
try {
return readdirSync(dir)
.filter((name) => name.endsWith('.checkpoint') || name === 'manifest.json' || name.startsWith('sugar-journal'))
.map((name) => {
const st = statSync(join(dir, name));
return { name, mtimeMs: Math.round(st.mtimeMs), size: st.size };
})
.sort((a, b) => a.name.localeCompare(b.name));
} catch {
return [];
}
}
async function metrics(): Promise<Record<string, number>> {
try {
const text = await (await fetch(`${metricsUrl}/metrics`, { signal: AbortSignal.timeout(3000) })).text();
const out: Record<string, number> = {};
for (const line of text.split('\n')) {
if (!line || line.startsWith('#')) continue;
const [name, value] = line.split(' ');
if (name && !name.includes('{')) out[name] = Number(value);
}
return out;
} catch {
return {};
}
}
function every(ms: number, task: () => Promise<void>) {
const timer = setInterval(() => {
if (Date.now() >= endAt) {
clearInterval(timer);
return;
}
task().catch(() => {});
}, ms);
}
const full = feedClient(['frame', 'audio', 'spikes']);
const bare = feedClient([]);
every(2000, async () => note(control.healthz, outcomeOf(await sim.healthz())));
every(5000, async () => {
const result = await sim.status();
note(control.status, outcomeOf(result));
});
every(3000, async () => {
const result = await sim.events(eventCursor, 100);
note(control.events, outcomeOf(result));
if (result.ok) {
for (const event of result.data.events) {
if (lastEventId && event.id !== lastEventId + 1) eventIdGaps += 1;
lastEventId = event.id;
eventKinds[event.kind] = (eventKinds[event.kind] ?? 0) + 1;
eventCursor = Math.max(eventCursor, event.id);
}
}
});
let sugarTurn = 0;
every(20_000, async () => {
sugarTurn += 1;
const source = sugarTurn % 2 ? 'chat' : 'points';
const result = await sim.stimulate({ by: `soak_viewer_${sugarTurn % 7}`, source });
note(control.stimulate, outcomeOf(result), result.ok ? undefined : result);
});
let chatTurn = 0;
every(15_000, async () => {
chatTurn += 1;
const result = await sim.chat({ by: `soak_viewer_${chatTurn % 5}`, text: `soak line ${chatTurn}` });
note(control.chat, outcomeOf(result));
});
every(10 * 60_000, async () => {
const { status, json } = await post('/checkpoint');
note(control.checkpoint, `http_${status}`, json);
});
every(30_000, async () => {
store.push({ atMs: Date.now(), hot: listing(hotDir), durable: listing(stateDir), metrics: await metrics() });
});
setTimeout(async () => {
const { status } = await post('/reward', { value: 1, by: 'soak', source: 'operator' });
note(control.reward, `http_${status}`);
const paused = await post('/pause');
note(control.pause, `http_${paused.status}`, paused.json);
await new Promise((resolve) => setTimeout(resolve, 3000));
const resumed = await post('/resume');
note(control.resume, `http_${resumed.status}`, resumed.json);
}, 60_000);
setTimeout(async () => {
const finalStatus = await sim.status();
const summary = {
feedUrl,
controlUrl,
minutes,
startedAt: new Date(endAt - minutes * 60_000).toISOString(),
feed: { full: { ...full, lastHeader: undefined }, headerOnly: { ...bare, lastHeader: undefined } },
control,
events: { kinds: eventKinds, lastId: lastEventId, idGaps: eventIdGaps },
finalStatus: finalStatus.ok ? finalStatus.data : finalStatus,
store,
};
writeFileSync(out, JSON.stringify(summary, null, 2));
const failures = [
full.decodeErrors.length + bare.decodeErrors.length > 0 && 'feed decode errors',
full.schemaErrors.length + bare.schemaErrors.length > 0 && 'header schema errors',
full.frameBackwards > 0 && 'the frame went backwards',
(control.healthz.outcomes.ok ?? 0) < control.healthz.count * 0.97 && 'healthz below 97%',
control.reward.outcomes.http_403 !== 1 && '/reward was not 403',
eventIdGaps > 0 && 'event id gaps',
].filter(Boolean);
console.log(JSON.stringify({ failures, messages: full.messages, frames: [full.firstFrame, full.lastFrame] }));
process.exit(failures.length ? 1 : 0);
}, minutes * 60_000 + 5000);