diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index efcf767..cdb38b5 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -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 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 **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index 5601d69..bed05cb 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -387,6 +387,37 @@ The 'current' symlink has NOT been moved; the running release is untouched." 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" ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current" else @@ -677,9 +708,11 @@ if [ -n "${CPUSET:-}" ]; then tmp_dropin="$(mktemp)" # flyedge is off by default, but its drop-in is written with the rest so that the day # it is enabled it serves the page from the page's CPUs, never from flysim's. - for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do + # 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 - flysim) cpus="$sim_cpus" ;; + flysim|flysim-session) cpus="$sim_cpus" ;; flycast) cpus="$encoder_cpus" ;; *) cpus="$page_cpus" ;; esac @@ -708,10 +741,18 @@ fi # --------------------------------------------------------------------------- log "05-deploy: converging bin/ helpers to /opt/fly/bin" ct_exec "$CTID" -- mkdir -p /opt/fly/bin -for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do +for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-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 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 # 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. diff --git a/infra/bin/fly-runtime b/infra/bin/fly-runtime new file mode 100755 index 0000000..6247f65 --- /dev/null +++ b/infra/bin/fly-runtime @@ -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" <= 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}" diff --git a/infra/build/build-flysim.sh b/infra/build/build-flysim.sh index 3a56ca7..97d1799 100755 --- a/infra/build/build-flysim.sh +++ b/infra/build/build-flysim.sh @@ -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 # looks for it. 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" @@ -118,4 +123,12 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge" cp "$edge_built" "$edge_out" chmod 0755 "$edge_out" log "built $edge_out ($(du -h "$edge_out" | cut -f1))" +for extra in 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 " diff --git a/infra/build/package-release.sh b/infra/build/package-release.sh index 0610db2..32d43e2 100755 --- a/infra/build/package-release.sh +++ b/infra/build/package-release.sh @@ -14,6 +14,10 @@ # fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh # left one beside FLYSIM_BIN; flyedge.service stays # inactive on a release without it) +# 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) # bridge/... (services/bridge + node_modules) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) @@ -82,6 +86,15 @@ if [ -x "$EDGE_BIN" ]; then else log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)" fi +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 "$BRIDGE_DIR" "${release_dir}/bridge" diff --git a/infra/config/fly-tmpfiles.conf b/infra/config/fly-tmpfiles.conf index 4aafd6a..870e96b 100644 --- a/infra/config/fly-tmpfiles.conf +++ b/infra/config/fly-tmpfiles.conf @@ -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 # router socket and artifact store. flysim also creates it, 0700, on start. 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/chrome 0700 fly fly - d /srv/fly/state 0750 fly fly - diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 4808f90..3aaa033 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -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`. On the release container, `` 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) `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index ef42b50..f791d06 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -536,6 +536,336 @@ else pass "flysim.service leaves FLY_FEED_VIA to fly.env" 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 ---" 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" diff --git a/infra/units/fly-runtime-fallback.service b/infra/units/fly-runtime-fallback.service new file mode 100644 index 0000000..6f3d5d4 --- /dev/null +++ b/infra/units/fly-runtime-fallback.service @@ -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 diff --git a/infra/units/flysim-session.service b/infra/units/flysim-session.service new file mode 100644 index 0000000..55736f8 --- /dev/null +++ b/infra/units/flysim-session.service @@ -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. diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index f0447b9..f52e37c 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -439,14 +439,23 @@ dependencies = [ name = "fly-legacy-session" version = "0.1.1" dependencies = [ + "anyhow", + "axum", + "clap", "fly-session", "flybrain-core", "flybrain-gb", "flybus", "flysim", + "futures-util", "serde_json", "tempfile", "tokio", + "tokio-tungstenite", + "toml", + "tower", + "tracing", + "tracing-subscriber", ] [[package]] diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml index dba2810..450bb77 100644 --- a/services/flysim/crates/fly-legacy-session/Cargo.toml +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -5,24 +5,40 @@ edition = "2024" rust-version.workspace = true license.workspace = true 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] name = "fly_legacy_session" 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] # The session framework and its legacy workers (AGENT-01, ENV-01). fly-session = { path = "../fly-session" } flybus = { path = "../flybus" } # 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. -# 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" } flybrain-gb = { path = "../flybrain-gb" } flybrain-core = { path = "../flybrain-core" } serde_json = { workspace = true } 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] tempfile = "3" +axum = "0.8" +futures-util = "0.3" +tokio-tungstenite = "0.29" +tower = { version = "0.5", features = ["util"] } diff --git a/services/flysim/crates/fly-legacy-session/examples/seed_store.rs b/services/flysim/crates/fly-legacy-session/examples/seed_store.rs new file mode 100644 index 0000000..ee62d47 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/examples/seed_store.rs @@ -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 -- +//! ``` + +fn main() { + let args: Vec = std::env::args().collect(); + let [_, file, dir] = args.as_slice() else { + eprintln!("usage: seed_store "); + 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 + ); +} diff --git a/services/flysim/crates/fly-legacy-session/src/bin/flysim-session.rs b/services/flysim/crates/fly-legacy-session/src/bin/flysim-session.rs new file mode 100644 index 0000000..ccbc140 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/bin/flysim-session.rs @@ -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, + + /// 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, + + /// 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, +} + +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(); +} diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index bc72304..ae0148e 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -172,6 +172,25 @@ pub async fn boot( root: &Path, config: LegacyConfig, 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> { let hot = flysim::store::Store::new(&store.hot_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, None if candidates.is_empty() => { 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)) } @@ -578,6 +591,18 @@ impl LegacySession { 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 /// 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. diff --git a/services/flysim/crates/fly-legacy-session/src/import.rs b/services/flysim/crates/fly-legacy-session/src/import.rs index ccf2b32..d5c1284 100644 --- a/services/flysim/crates/fly-legacy-session/src/import.rs +++ b/services/flysim/crates/fly-legacy-session/src/import.rs @@ -129,6 +129,9 @@ pub async fn import_flysim01( coordinator .resume() .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 { boundary, epoch: new_epoch.clone(), diff --git a/services/flysim/crates/fly-legacy-session/src/lib.rs b/services/flysim/crates/fly-legacy-session/src/lib.rs index d1cda7c..f0e390d 100644 --- a/services/flysim/crates/fly-legacy-session/src/lib.rs +++ b/services/flysim/crates/fly-legacy-session/src/lib.rs @@ -7,6 +7,8 @@ //! - [`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. //! - [`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` //! TASK-01 the record. @@ -15,5 +17,6 @@ pub mod admission; pub mod composition; pub mod driver; pub mod import; +pub mod service; pub mod task; pub mod trace; diff --git a/services/flysim/crates/fly-legacy-session/src/service.rs b/services/flysim/crates/fly-legacy-session/src/service.rs new file mode 100644 index 0000000..6dc871f --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/service.rs @@ -0,0 +1,1389 @@ +//! The session runtime as the live service (SERVE-01): `flysim-session`. +//! +//! The legacy composition ([`crate::composition`]) runs here as a long-lived process behind the +//! very listeners `flysim` serves: [`flysim::serve`] binds the feed (`:7400`, or the feed bus for +//! `fly-edge`), the control API (`:7401`) and the metrics listener (`:9101`), handles the signals, +//! and hands this host the same three things it hands the legacy loop -- the [`Shared`] state, the +//! snapshot slot and the command queue. The feed and control contracts are therefore served by +//! the same code; what this module adds is the loop that fills them from a session instead of +//! from `flysim::simloop::Sim`, keeping `Sim`'s order, cadence and bookkeeping call site for call +//! site: +//! +//! | legacy `Sim` | here | +//! | --- | --- | +//! | `boot`: restore or warm up, versions, chat sidecar, journal boot header, startup durable save | [`SessionHost::boot`]: [`crate::composition::boot_unsaved`], the same, header `runtime: fly-session` | +//! | `drain_commands`: stimulate, reward, chat, checkpoint, pause, resume, shutdown | [`SessionHost::drain_commands`]; sugar by `RateLimiter` over the last commit's pulse, admitted at the next Prepare | +//! | `step_frame`: the frame, macro/reward events, `track_rank` + milestone archive, ratchet rollback + recovery | [`SessionHost::step_frame`]: `Coordinator::step`, the task's [`crate::task::FeedRecord`], the checkpointer's rank, `apply_pending_rollback` | +//! | `publish`: the header from the network, the adapter and the macro layer | [`SessionHost::publish`]: the agent's `Legacy.FeedStatus`, the task's parts, the committed view, the step's audio and spikes, through flysim's own `feed_*` builders | +//! | `checkpoint_if_due` (hot 5 s, durable 300 s, wall clock), pause, forced, shutdown | the same, through [`crate::composition::LegacySession::queue_save`] and STATE-02's `LegacyCheckpointer` | +//! | the sugar journal (`crate::journal` of flysim) | the same journal, `runtime: fly-session` | +//! +//! Declared differences from the legacy service (SERVE-01, `implementation.md`): +//! +//! - `POST /reward` is always refused (403): `control.allow_reward` is forced off, because the +//! operator reward 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 not implemented here; SHADOW-01 compares runs. +//! - Only the Pokémon Red composition exists on the session runtime. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, anyhow, bail}; +use serde_json::Value; +use tokio::sync::{mpsc, oneshot, watch}; + +use fly_session::fly_session_types::gameboy; +use fly_session::launcher::ExecutionMode; +use fly_session::legacy_agent::{LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT}; +use fly_session::legacy_checkpoint::{RankChange, SaveKind, SaveReport, SaveTicket}; +use fly_session::types::*; +use flybrain_gb::adapter::GameAdapter; +use flysim::chat::{ChatLimiter, ChatRefusal, ChatRing, DenyList}; +use flysim::config::Config; +use flysim::eventlog::{EventLog, NewEvent, now_wall_ms, utc_day}; +use flysim::journal::{BootHeader, Entry, Input, SugarJournal}; +use flysim::metrics::Metrics; +use flysim::pacing::{Pacer, RealtimeWindow}; +use flysim::ratelimit::{RateLimiter, Refusal}; +use flysim::simloop::{ + COMMAND_QUEUE, Command, DecoderChannelStatus, DecoderStatus, Shared, Versions, admit_chat, + feed_game, feed_milestone, feed_rates, feed_sugar, sugar_label, +}; +use flysim::snapshot::{ + AttachmentKind, DcBlocker, FeedEvent, FeedEventKind, FeedHeader, FeedLearning, FeedStatus, + PROTOCOL, RewardKind, Snapshot, f32_bytes, finite, +}; + +use crate::composition::{Boot, LegacyConfig, LegacySession, StoreConfig, boot_unsaved}; +use crate::task::GAME; + +/// The runtime name the sugar journal's boot header records. +pub const RUNTIME: &str = "fly-session"; + +/// Where the session's own router store and worker sockets live (tmpfs on the containers). +pub const SESSION_DIR_ENV: &str = "FLY_SESSION_DIR"; +pub const DEFAULT_SESSION_DIR: &str = "/run/fly/session"; +/// `in-process` (the default), `thread` or `process` (`fly-session`'s launcher modes). +pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE"; +/// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only). +pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE"; + +/// How the service composes its session, beyond flysim's own [`Config`]. +#[derive(Clone, Debug)] +pub struct ServiceOptions { + pub mode: ExecutionMode, + pub profile: LegacyProfileKind, + pub session_dir: PathBuf, +} + +impl ServiceOptions { + /// From `FLY_SESSION_MODE`, `FLY_SESSION_PROFILE` and `FLY_SESSION_DIR`. + pub fn from_env() -> Result { + let mode = match std::env::var(SESSION_MODE_ENV).ok().as_deref() { + None | Some("") | Some("in-process") => ExecutionMode::InProcess, + Some("thread") => ExecutionMode::Thread, + Some("process") => ExecutionMode::Process, + Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"), + }; + let profile = match std::env::var(SESSION_PROFILE_ENV).ok().as_deref() { + None | Some("") | Some("production") => LegacyProfileKind::Production, + Some("toy") => LegacyProfileKind::Toy, + Some(other) => bail!("{SESSION_PROFILE_ENV}={other}: production or toy"), + }; + let session_dir = std::env::var_os(SESSION_DIR_ENV) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR)); + Ok(ServiceOptions { + mode, + profile, + session_dir, + }) + } +} + +/// The session's composition from the service configuration, refusing what the session runtime +/// cannot run rather than running something else. +pub fn legacy_config(config: &Config, options: &ServiceOptions) -> Result { + if config.loop_.game != GAME { + bail!( + "the session runtime runs {GAME} only; FLY_GAME is {:?} (switch back with \ + `fly-runtime legacy`)", + config.loop_.game + ); + } + if config.loop_.warmup_ms != gameboy::WARMUP_MS { + bail!( + "loop.warmup_ms is {} but the legacy profile's warm-up is {} ms", + config.loop_.warmup_ms, + gameboy::WARMUP_MS + ); + } + let audio = fly_session::legacy_env::BackendConfig::legacy("0".repeat(64).as_str()) + .audio_sample_rate; + if u64::from(config.feed.audio_hz) != audio { + bail!( + "feed.audio_hz is {} but the legacy environment runs its audio at {audio} Hz", + config.feed.audio_hz + ); + } + Ok(LegacyConfig { + mode: options.mode, + rom_path: config.paths.rom.clone(), + dataset_dir: config.paths.dataset.clone(), + profile: options.profile, + macro_mode: config.macros.mode, + agent_id: id("fly"), + agent_threads: config.loop_.threads.max(1), + record: false, + }) +} + +/// The legacy store the service writes: flysim's `[paths]` and `[loop]`. +pub fn store_config(config: &Config) -> StoreConfig { + StoreConfig { + hot_dir: config.paths.hot_dir.clone(), + durable_dir: config.paths.save_dir.clone(), + keep_generations: config.loop_.keep_generations, + hot_seconds: config.loop_.hot_seconds, + checkpoint_seconds: config.loop_.checkpoint_seconds, + speed: config.loop_.speed, + } +} + +/// The compatibility string this build would write (`flysim-session --print-compatibility`): +/// the session's own, from the profile, which must equal `flysim --print-compatibility`. +pub fn compatibility_string(config: &Config, options: &ServiceOptions) -> Result { + Ok(crate::composition::compatibility_of(&legacy_config( + config, options, + )?)) +} + +/// The configuration the session runtime serves under: flysim's, with `control.allow_reward` +/// forced off (the operator pulse is refused on this runtime, so `POST /reward` answers 403 as +/// it does on every shipped legacy configuration). +pub fn service_config(mut config: Config) -> Config { + if config.control.allow_reward { + tracing::warn!( + "control.allow_reward is on, but the session runtime has no operator reward pulse \ + (legacy-gameboy-v1 section 15): POST /reward answers 403" + ); + config.control.allow_reward = false; + } + config +} + +/// Run the service until a signal or a fatal error: [`flysim::serve`] around a [`SessionHost`]. +pub fn run(config: Config, options: ServiceOptions) -> Result<()> { + let config = service_config(config); + // Refuse a configuration the session cannot run before any listener is bound. + legacy_config(&config, &options)?; + for (variable, what) in [ + (flysim::trace::ENV, "the per-frame trace"), + ("FLY_PROFILE_SECONDS", "the per-phase profile"), + ] { + if std::env::var_os(variable).is_some() { + tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored"); + } + } + flysim::serve(config, move |shared, snapshots, commands, notifier| { + run_host(shared, snapshots, commands, notifier, &options) + }) +} + +/// The runtime [`flysim::serve`] runs: boot a [`SessionHost`] on a session runtime of its own, +/// report ready, run it until a shutdown, stop every worker. Also what a test runs in place of +/// the listeners, as the legacy side runs `Sim::boot` and `Sim::run`. +pub fn run_host( + shared: Arc, + snapshots: watch::Sender>, + commands: mpsc::Receiver, + notifier: &flysim::sdnotify::Notifier, + options: &ServiceOptions, +) -> Result<()> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("fly-session") + .enable_all() + .build() + .context("building the session runtime")?; + let result = runtime.block_on(async { + let mut host = SessionHost::boot(shared, snapshots, commands, options).await?; + notifier.notify("READY=1\nSTATUS=session running\n"); + let result = host.run(notifier).await; + notifier.notify("STOPPING=1\n"); + host.stop().await; + result + }); + runtime.shutdown_timeout(Duration::from_secs(2)); + result +} + +/// A queued save and what waits on it. +struct PendingSave { + ticket: SaveTicket, + wall_ms: u64, + reply: Option>>, +} + +/// The agent's side of one published header ([`METHOD_FEED_STATUS`]). +#[derive(Clone, Debug)] +struct AgentFeed { + brain_ms: f64, + rates: Vec<(String, f64)>, + population_rate: f64, + reward_remaining_ms: f64, + learning: FeedLearning, + decoder: DecoderStatus, +} + +impl Default for AgentFeed { + fn default() -> AgentFeed { + AgentFeed { + brain_ms: 0.0, + rates: Vec::new(), + population_rate: 0.0, + reward_remaining_ms: 0.0, + learning: FeedLearning { + enabled: false, + updates: 0, + changed: 0, + synapses: 0, + signal: 0.0, + }, + decoder: DecoderStatus::default(), + } + } +} + +impl AgentFeed { + fn parse(value: &Value) -> Result { + let number = |v: &Value, what: &str| { + v.as_f64() + .ok_or_else(|| anyhow!("Legacy.FeedStatus: {what} is not a number")) + }; + let rates = value["rates"] + .as_array() + .ok_or_else(|| anyhow!("Legacy.FeedStatus: no rates"))? + .iter() + .map(|pair| { + let name = pair[0] + .as_str() + .ok_or_else(|| anyhow!("Legacy.FeedStatus: a rate without a role"))?; + Ok((name.to_owned(), number(&pair[1], "a rate")?)) + }) + .collect::>>()?; + let learning = &value["learning"]; + let stats = flybrain_core::plasticity::LearningStats { + version: String::new(), + enabled: learning["enabled"].as_bool().unwrap_or(false), + synapses: learning["synapses"].as_u64().unwrap_or(0) as usize, + mushroom: 0, + output: 0, + updates: number(&learning["updates"], "learning.updates")?, + changed: learning["changed"].as_u64().unwrap_or(0), + mean_change: 0.0, + max_change: 0.0, + signal: number(&learning["signal"], "learning.signal")?, + }; + let decoder = &value["decoder"]; + let channels = decoder["channels"] + .as_array() + .into_iter() + .flatten() + .map(|channel| { + Ok(DecoderChannelStatus { + channel: channel["channel"].as_str().unwrap_or_default().to_owned(), + role: channel["role"].as_str().unwrap_or_default().to_owned(), + baseline: number(&channel["baseline"], "a baseline")?, + score: number(&channel["score"], "a score")?, + }) + }) + .collect::>>()?; + Ok(AgentFeed { + brain_ms: number(&value["brainMs"], "brainMs")?, + rates, + population_rate: number(&value["populationRate"], "populationRate")?, + reward_remaining_ms: number(&value["rewardRemainingMs"], "rewardRemainingMs")?, + learning: flysim::simloop::feed_learning(&stats), + decoder: DecoderStatus { + calibrated: decoder["calibrated"].as_bool().unwrap_or(false), + pending: decoder["pending"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + channels, + }, + }) + } +} + +/// The service host: the session, and everything `Sim` keeps around its frame. +pub struct SessionHost { + shared: Arc, + snapshots: watch::Sender>, + commands: mpsc::Receiver, + session: LegacySession, + agent_id: Id, + log: EventLog, + journal: SugarJournal, + + status: FeedStatus, + pending_recovery: bool, + seq: u64, + started: Instant, + realtime: RealtimeWindow, + next_publish: Instant, + + pending_saves: Vec, + + limiter: RateLimiter, + sugar_last_by: Option, + sugar_today: u64, + sugar_day: String, + /// The pulse the network holds now, as the admission rule reads it: the last commit's + /// `stimulusRemainingMs`, raised by every sugar admitted since (`network.stimulate` is a + /// maximum), so two admissions in one drain see what the legacy loop's second one sees. + remaining_ms: f64, + sugar_serial: u64, + + chat_ring: ChatRing, + chat_limits: ChatLimiter, + deny_list: DenyList, + + /// The audio of the transitions since the last publish, DC-blocked (the legacy + /// `pending_audio`). + pending_audio: Vec, + dc_blocker: DcBlocker, + /// The OR of the commits' spike bitsets since the last publish: exactly the legacy + /// `spike_bitset(last_spike_ms, last_publish_ms, ms)` (a neuron's last spike is at or after + /// the window's start iff it is at or after the start of one of the commits inside it). + spikes: Vec, + /// The agent's feed status as last read, for a publish whose read failed. + last_feed: AgentFeed, + + semantic_rewards: bool, + next_profile: Instant, +} + +/// How often the coordinator's timings are logged and cleared. +pub const PROFILE_PERIOD: Duration = Duration::from_secs(60); + +/// The legacy reward event label, value and kind. +fn reward_event(event: &flybrain_gb::adapter::RewardEvent) -> NewEvent { + let mut new = NewEvent::new(FeedEventKind::Reward, event.label.clone()).value(event.value); + if let Some(kind) = RewardKind::from_adapter(event.kind) { + new = new.reward_kind(kind); + } + new +} + +fn f32_samples(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +impl SessionHost { + /// `Sim::boot` on the session runtime. + pub async fn boot( + shared: Arc, + snapshots: watch::Sender>, + commands: mpsc::Receiver, + options: &ServiceOptions, + ) -> Result { + let config = shared.config.clone(); + let started = Instant::now(); + let legacy = legacy_config(&config, options)?; + let store = store_config(&config); + let compatibility = crate::composition::compatibility_of(&legacy); + + let rom = std::fs::read(&config.paths.rom) + .with_context(|| format!("reading ROM {}", config.paths.rom.display()))?; + let rom_sha256 = sha256_hex(&rom); + if let Some(expected) = config + .control + .expect_rom_sha256 + .as_deref() + .filter(|expected| *expected != rom_sha256) + { + tracing::warn!( + expected, + actual = %rom_sha256, + "FLY_ROM_SHA256 does not match the cartridge on disk" + ); + } + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let semantic_rewards = adapter.rom_allowed(&rom_sha256); + if !semantic_rewards { + tracing::warn!( + rom = %rom_sha256, + "this cartridge is not the audited one: semantic rewards are off" + ); + } + let profile = legacy.profile.profile(); + let _ = shared.versions.set(Versions { + kernel: gameboy::KERNEL_VERSION.to_owned(), + plasticity: gameboy::PLASTICITY_VERSION.to_owned(), + adapter: adapter.id().to_owned(), + binjgb: flybrain_gb::compatibility::BINJGB_REVISION.to_owned(), + dataset: profile.dataset_fingerprint.clone(), + compatibility: compatibility.clone(), + }); + + // The session's router store and sockets: this process's alone, so whatever a crashed + // predecessor left there is removed first (the directory itself may be tmpfiles'). + let root = options.session_dir.clone(); + std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; + for entry in std::fs::read_dir(&root).with_context(|| format!("reading {}", root.display()))? { + let path = entry?.path(); + let removed = if path.is_dir() { + std::fs::remove_dir_all(&path) + } else { + std::fs::remove_file(&path) + }; + removed.with_context(|| format!("clearing {}", path.display()))?; + } + + let log = EventLog::open(&config.paths.save_dir, shared.events.clone())?; + let (session, boot) = boot_unsaved(&root, legacy.clone(), &store) + .await + .map_err(|e| anyhow!("{e}"))?; + + let now = Instant::now(); + let mut host = SessionHost { + agent_id: legacy.agent_id.clone(), + limiter: RateLimiter::new(config.control.sugar_per_minute), + session, + log, + journal: SugarJournal::new(&config.paths.hot_dir), + status: FeedStatus::Booting, + pending_recovery: false, + seq: 0, + started, + realtime: RealtimeWindow::new(Duration::from_secs(1)), + next_publish: now, + pending_saves: Vec::new(), + sugar_last_by: None, + sugar_today: 0, + sugar_day: utc_day(now_wall_ms()), + remaining_ms: 0.0, + sugar_serial: 0, + chat_ring: ChatRing::new(config.chat.ring), + chat_limits: ChatLimiter::default(), + deny_list: if config.chat.enabled { + DenyList::load(config.chat.deny_list.as_deref(), now) + } else { + DenyList::empty(now) + }, + pending_audio: Vec::new(), + dc_blocker: DcBlocker::default(), + spikes: Vec::new(), + last_feed: AgentFeed::default(), + semantic_rewards, + next_profile: now + PROFILE_PERIOD, + shared, + snapshots, + commands, + }; + + // The service reads every transition's commit (the spike bitset) and paces itself by + // flysim's `Pacer`, as the legacy loop does. + host.session.coordinator.disable_pacing(); + host.session + .coordinator + .request_commit_attachments(&[SPIKES_ATTACHMENT]); + host.session.coordinator.digest_views(false); + + let origin = match &boot { + Boot::Fresh => { + tracing::info!("no checkpoint to restore: warmed up a fresh fly"); + host.emit(NewEvent::new( + FeedEventKind::System, + "Fresh start: the fly woke up", + )); + ("fresh start".to_owned(), None) + } + Boot::Restored { + candidate, + skipped, + migrated_from, + imported, + } => { + for (refused, reason) in skipped { + tracing::error!( + origin = %refused.origin, + error = %reason, + "checkpoint candidate refused" + ); + } + if !skipped.is_empty() { + Metrics::set(&host.shared.metrics.restore_fallback, 1); + tracing::warn!( + origin = %candidate.origin, + skipped = skipped.len(), + "restored from a fallback candidate" + ); + } + if let Some(from) = migrated_from { + tracing::warn!( + from = %from, + "restoring a checkpoint from an earlier adapter, by the migration \ + FLY_ACCEPT_ADAPTERS opted this deploy into" + ); + } + tracing::info!( + origin = %candidate.origin, + frame = host.frame_counter(), + boundary = imported.boundary, + brain_ms = host.session.task.brain_ms(), + rank = host.session.task.rank(), + "restored" + ); + host.log.resume_from(host.session.last_event_id()); + host.emit(NewEvent::new( + FeedEventKind::System, + format!("Restored from {}", candidate.origin), + )); + (candidate.origin.clone(), candidate.generation) + } + }; + + if config.chat.enabled { + let restored = host + .chat_ring + .load_sidecar(&config.paths.hot_dir, now_wall_ms()); + if restored > 0 { + tracing::info!(lines = restored, "restored the on-screen chat ring"); + } + } + // The pulse the first admission reads, before any commit of this process. + let feed = host.read_feed().await?; + host.remaining_ms = feed.reward_remaining_ms; + host.last_feed = feed; + host.journal.boot(&BootHeader { + runtime: RUNTIME.to_owned(), + start_frame: host.frame_counter(), + brain_ms: host.session.task.brain_ms(), + origin: origin.0, + generation: origin.1, + compatibility, + wall_ms: now_wall_ms(), + }); + host.status = FeedStatus::Running; + // A durable commit immediately after startup or restore, then both intervals from it. + host.checkpoint_blocking(SaveKind::Durable).await?; + host.session + .checkpointer_mut() + .expect("attached by boot") + .start_intervals(Instant::now()); + Ok(host) + } + + /// The emulator frame counter at the committed boundary (the legacy `frame_counter`): the + /// boundary's `engineFrame`. + pub fn frame_counter(&self) -> u64 { + self.session + .coordinator + .observation() + .and_then(|o| o.engine_frame.as_deref()) + .and_then(|f| f.parse().ok()) + .unwrap_or(0) + } + + /// The session, for tests and the shadow harness. + pub fn session(&self) -> &LegacySession { + &self.session + } + + fn emit(&mut self, event: NewEvent) -> FeedEvent { + Metrics::incr(&self.shared.metrics.events_total); + let ms = self.session.task.brain_ms(); + self.log.append(now_wall_ms(), ms, event) + } + + // -- the loop -------------------------------------------------------------------------- + + /// `Sim::run`: until a shutdown command or a fatal error. + pub async fn run(&mut self, notifier: &flysim::sdnotify::Notifier) -> Result<()> { + let (running_period, idle_period) = self.shared.config.publish_periods(); + let mut pacer = Pacer::new( + flybrain_core::agent::GAMEBOY_MS_PER_FRAME, + self.shared.config.loop_.speed, + Instant::now(), + ); + let mut recovering = false; + let watchdog_period = notifier.watchdog_interval(); + let mut next_watchdog = Instant::now(); + + loop { + self.shared.beat(); + if let Some(period) = watchdog_period { + let now = Instant::now(); + if now >= next_watchdog { + next_watchdog = now + period; + notifier.watchdog(); + } + } + if !self.drain_commands().await? { + self.shutdown().await; + return Ok(()); + } + self.reload_deny_list_if_due(); + self.poll_saves(); + self.drain_ended_admissions(); + + if self.status == FeedStatus::Paused { + let now = Instant::now(); + if now >= self.next_publish { + self.next_publish = now + idle_period; + self.publish(false).await; + } + tokio::time::sleep(Duration::from_millis(5)).await; + continue; + } + + let started = Instant::now(); + self.step_frame().await?; + self.session + .coordinator + .metrics + .record("host.frame", started.elapsed()); + if std::mem::take(&mut self.pending_recovery) { + recovering = true; + } + + let now = Instant::now(); + self.realtime.record(now, self.session.task.brain_ms()); + if now >= self.next_publish { + self.next_publish += running_period; + if self.next_publish <= now { + self.next_publish = now + running_period; + } + if recovering { + self.status = FeedStatus::Recovering; + } + let started = Instant::now(); + self.publish(true).await; + self.session + .coordinator + .metrics + .record("host.publish", started.elapsed()); + if recovering { + self.status = FeedStatus::Running; + recovering = false; + } + } + + let started = Instant::now(); + self.checkpoint_if_due(now).await?; + self.session + .coordinator + .metrics + .record("host.checkpoint", started.elapsed()); + self.profile_if_due(now); + if let Err(error) = self.log.flush() { + tracing::warn!(%error, "could not fsync the event log"); + } + + Metrics::set( + &self.shared.metrics.lag_ms, + (pacer.lag_seconds() * 1000.0) as u64, + ); + if pacer.should_warn() { + tracing::warn!( + lag_seconds = pacer.lag_seconds(), + realtime_factor = self.realtime.factor(), + "the simulation is behind real time; no frames are being skipped" + ); + } + let sleep = pacer.next_sleep(Instant::now()); + if !sleep.is_zero() { + tokio::time::sleep(sleep).await; + } + } + } + + /// The coordinator reports every admission applied or aborted; the legacy loop has no abort + /// (its sugar is applied on the spot), so an aborted one is only logged. Drained every + /// iteration so the reports do not accumulate. + fn drain_ended_admissions(&mut self) { + for (admission, end) in self.session.coordinator.admissions().take_ended() { + if !matches!(end, fly_session::coordinator::AdmissionEnd::Applied { .. }) { + tracing::warn!( + interaction = %admission.interaction_id(), + ?end, + "an admitted sugar was not applied" + ); + } + } + } + + fn reload_deny_list_if_due(&mut self) { + if !self.shared.config.chat.enabled { + return; + } + let forced = self + .shared + .chat_reload + .swap(false, std::sync::atomic::Ordering::Relaxed); + self.deny_list.maybe_reload(Instant::now(), forced); + } + + /// One transition and the legacy loop's boundary work, in `Sim::step_frame`'s order. + async fn step_frame(&mut self) -> Result<()> { + self.session + .coordinator + .step() + .await + .map_err(|e| anyhow!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?; + Metrics::incr(&self.shared.metrics.sim_frames); + if let Some(details) = self.session.coordinator.take_details() { + if let Some((_, result)) = details.commits.iter().find(|(id, _)| *id == self.agent_id) + && let Some(remaining) = result.telemetry.stimulus_remaining_ms + { + self.remaining_ms = remaining; + } + for (agent, name, bytes) in &details.commit_attachments { + if *agent == self.agent_id && name == SPIKES_ATTACHMENT { + if self.spikes.len() < bytes.len() { + self.spikes.resize(bytes.len(), 0); + } + for (acc, byte) in self.spikes.iter_mut().zip(bytes) { + *acc |= byte; + } + } + } + } + // This transition's audio chunk, read before a rollback replaces the boundary's media. + let audio_name = + fly_session::media::audio_attachment(fly_session::legacy_env::AUDIO_STREAM_ID); + if let Some(bytes) = self + .session + .coordinator + .media_bytes(&audio_name) + .await + .map_err(|e| anyhow!(e))? + { + self.dc_blocker + .process_f32_into(&f32_samples(&bytes), &mut self.pending_audio); + } + + // The feed events, in the order the phases produced them: the executor's starts and + // finishes, the rewards, then the observation's abandonment. + let feed = self.session.task.take_feed(); + self.emit_macro_events(&feed.executed); + for event in &feed.rewards { + self.emit(reward_event(event)); + } + self.emit_macro_events(&feed.abandoned); + + // `track_rank`: the milestone event, and the archive on a climb. + let rank = self.session.task.rank(); + let ms = self.session.task.brain_ms(); + let change = self + .session + .checkpointer_mut() + .expect("attached") + .observe_rank(rank, ms); + if let Some(change) = change { + let label = self + .session + .task + .inspect(|adapter, _, _| adapter.progress().rank_label.to_owned()); + let (climbed, rank) = match change { + RankChange::Climbed(rank) => (true, rank), + RankChange::FellBack(rank) => (false, rank), + }; + self.emit( + NewEvent::new( + FeedEventKind::Milestone, + format!( + "{} {label}", + if climbed { "Reached" } else { "Fell back to" } + ), + ) + .value(f64::from(rank)), + ); + if climbed && let Err(error) = self.checkpoint(SaveKind::Milestone(rank), None).await { + tracing::error!(%error, "could not archive the milestone checkpoint"); + } + } + + // `Ready(k+1)`: the ratchet's rollback, captured first (above), then applied. + let rolled_back = self + .session + .coordinator + .apply_pending_rollback() + .await + .map_err(|e| anyhow!("rollback ({} at {}): {}", e.detail, e.phase, e.error.message))?; + if rolled_back { + let feed = self.session.task.take_feed(); + let (game_over, events) = feed.rollback.unwrap_or_default(); + self.recovered(game_over, &events).await; + } + // The coordinator's trace, audit and timing samples grow with every transition; a + // service keeps none of them past the boundary (the timings are logged, below). + self.session.coordinator.trim_records(); + Ok(()) + } + + /// Every [`PROFILE_PERIOD`]: the coordinator's per-phase timings (p50/p95/max, ms) as one + /// log line, then cleared -- the session runtime's counterpart of the legacy loop's + /// `FLY_PROFILE_SECONDS` table, always on because it is also what bounds the samples. + fn profile_if_due(&mut self, now: Instant) { + if now < self.next_profile { + return; + } + self.next_profile = now + PROFILE_PERIOD; + let metrics = &mut self.session.coordinator.metrics; + let mut line = String::new(); + for name in metrics.names() { + if let Some(p) = metrics.percentiles(&name) { + line.push_str(&format!( + " {name}={}x{:.1}/{:.1}/{:.1}", + p.count, + p.p50_us() / 1000.0, + p.p95_us() / 1000.0, + p.max_ns as f64 / 1e6 + )); + } + } + metrics.clear(); + tracing::info!( + realtime_factor = self.realtime.factor(), + "session profile (count x p50/p95/max ms):{line}" + ); + } + + /// `Sim::recovered`: the ticker, the metric, the `recovering` status and a durable save. + async fn recovered(&mut self, game_over: bool, events: &[flysim::macros::MacroEvent]) { + let reason = if game_over { "Game over" } else { "Stuck" }; + Metrics::incr(&self.shared.metrics.recoveries_total); + let (attempts, label) = self.session.task.inspect(|adapter, ratchet, _| { + (ratchet.state.attempts, adapter.progress().rank_label.to_owned()) + }); + let rank = self.session.checkpointer().expect("attached").rank(); + self.emit( + NewEvent::new( + FeedEventKind::Recovery, + format!("{reason}: rolled back to {label} (attempt {attempts})"), + ) + .value(f64::from(rank)), + ); + self.emit_macro_events(events); + self.pending_recovery = true; + if let Err(error) = self.checkpoint(SaveKind::Durable, None).await { + tracing::error!(%error, "could not checkpoint after a recovery"); + } + } + + fn emit_macro_events(&mut self, events: &[flysim::macros::MacroEvent]) { + for event in events { + self.emit( + NewEvent::new(FeedEventKind::Macro, event.label()).value(f64::from(event.slot)), + ); + } + } + + // -- commands -------------------------------------------------------------------------- + + /// `Sim::drain_commands`. Returns false when a shutdown was requested. + async fn drain_commands(&mut self) -> Result { + for _ in 0..COMMAND_QUEUE { + let command = match self.commands.try_recv() { + Ok(command) => command, + Err(mpsc::error::TryRecvError::Empty) => break, + Err(mpsc::error::TryRecvError::Disconnected) => return Ok(false), + }; + match command { + Command::Stimulate { + duration_ms, + by, + source, + reply, + } => { + let outcome = self.stimulate(duration_ms, &by, &source); + let _ = reply.send(outcome); + } + Command::Reward { reply, by, .. } => { + // Unreachable in service: the API answers 403 first, because + // `service_config` forces `control.allow_reward` off. Dropping the reply + // makes the API answer 503 rather than claim a pulse that never happened. + tracing::warn!(by, "{}", crate::admission::OPERATOR_REWARD_REFUSED); + drop(reply); + } + Command::Chat { + by, + text, + bot, + reply, + } => { + let outcome = self.chat(&by, &text, bot); + let _ = reply.send(outcome); + } + Command::Checkpoint { reply } => { + match self.checkpoint(SaveKind::Durable, Some(reply)).await { + Ok(generation) => tracing::info!(generation, "checkpoint forced"), + Err(error) => tracing::error!(%error, "forced checkpoint failed"), + } + } + Command::Pause { reply } => { + if self.status != FeedStatus::Paused { + self.status = FeedStatus::Paused; + self.emit(NewEvent::new(FeedEventKind::System, "Paused by the operator")); + // A pause must never hold a begun save (TASK-01 review R2-1). This host + // saves through `queue_save`, which hands its capture over at once, so + // there is normally nothing to flush; a begun capture would reach the + // writer here rather than sit until the next step. + if let Err(error) = self.session.flush_captures().await { + tracing::error!(%error, "could not hand over the pending captures on pause"); + } + if let Err(error) = self.checkpoint(SaveKind::Durable, None).await { + tracing::error!(%error, "could not checkpoint on pause"); + } + self.publish(false).await; + } + let _ = reply.send(self.status); + } + Command::Resume { reply } => { + if self.status == FeedStatus::Paused { + self.status = FeedStatus::Running; + self.next_publish = Instant::now(); + self.emit(NewEvent::new(FeedEventKind::System, "Resumed by the operator")); + } + let _ = reply.send(self.status); + } + Command::Shutdown { reply } => { + let _ = reply.send(()); + return Ok(false); + } + } + } + Ok(true) + } + + /// `POST /stimulate`: flysim's rules over the pulse as it stands, admitted into the next + /// Prepare (`preStepStimulations`), which is the next frame: where the legacy loop's + /// `stimulate` lands too. + fn stimulate( + &mut self, + duration_ms: Option, + by: &str, + source: &str, + ) -> std::result::Result { + let now_ms = now_wall_ms(); + if let Err(refusal) = self.limiter.admit(now_ms, self.remaining_ms) { + Metrics::incr(&self.shared.metrics.sugar_refused_total); + tracing::info!( + by, + source, + retry_after_ms = refusal.retry_after_ms(), + "sugar refused" + ); + return Err(refusal); + } + let control = &self.shared.config.control; + let duration = duration_ms + .unwrap_or(control.sugar_default_ms) + .clamp(1.0, control.sugar_max_ms) + .min(control.sugar_max_ms); + self.session + .coordinator + .admissions() + .admit(fly_session::coordinator::Admission::Stimulus { + agent_id: self.agent_id.clone(), + interaction_id: id(&format!("sugar-{}", self.sugar_serial + 1)), + kind_id: id(gameboy::STIMULUS_REWARD_PULSE), + duration_ms: duration, + }); + self.sugar_serial += 1; + // `network.stimulate` is a maximum. + self.remaining_ms = self.remaining_ms.max(duration); + + let day = utc_day(now_ms); + if day != self.sugar_day { + self.sugar_day = day; + self.sugar_today = 0; + } + self.sugar_today += 1; + self.sugar_last_by = Some(by.to_string()); + Metrics::incr(&self.shared.metrics.sugar_accepted_total); + let event = self.emit( + NewEvent::new(FeedEventKind::Sugar, sugar_label(by)) + .by(by) + .value(duration), + ); + self.journal.record(&Entry { + frame: self.frame_counter(), + brain_ms: self.session.task.brain_ms(), + input: Input::Sugar { + duration_ms: duration, + }, + by, + source, + event_id: event.id, + wall_ms: event.wall_ms, + }); + tracing::info!(by, source, duration_ms = duration, "sugar accepted"); + Ok(event.id) + } + + fn chat(&mut self, by: &str, text: &str, bot: bool) -> std::result::Result { + let ms = self.session.task.brain_ms(); + let Self { + shared, + chat_ring, + chat_limits, + deny_list, + log, + .. + } = self; + 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) + }, + ) + } + + async fn shutdown(&mut self) { + tracing::info!("shutting down: taking a final durable checkpoint"); + self.emit(NewEvent::new(FeedEventKind::System, "Shutting down")); + if let Err(error) = self.checkpoint_blocking(SaveKind::Durable).await { + tracing::error!(%error, "the final checkpoint failed"); + } + if let Err(error) = self.log.flush() { + tracing::error!(%error, "the final event log flush failed"); + } + self.status = FeedStatus::Paused; + self.publish(false).await; + if let Some(checkpointer) = self.session.checkpointer_mut() { + checkpointer.close(); + } + self.poll_saves(); + } + + /// Stops every worker. After [`SessionHost::run`] returned, or on a fatal error. + pub async fn stop(self) { + self.session.stop().await; + } + + // -- checkpoints ----------------------------------------------------------------------- + + async fn checkpoint_if_due(&mut self, now: Instant) -> Result<()> { + let due = self + .session + .checkpointer_mut() + .expect("attached") + .due(now); + if let Some(kind) = due { + self.checkpoint(kind, None).await.map_err(|e| anyhow!(e))?; + } + Ok(()) + } + + /// `Sim::checkpoint_with_reply`: capture the committed boundary now, write it on the + /// checkpointer's thread, emit the durable save's event. Returns the generation. + async fn checkpoint( + &mut self, + kind: SaveKind, + reply: Option>>, + ) -> std::result::Result { + // `lastEventId` is the log's watermark before this save's own event. + self.session + .set_last_event_id(self.log.next_id().saturating_sub(1)); + let wall_ms = now_wall_ms(); + let ticket = match self.session.queue_save(kind).await { + Ok(ticket) => ticket, + Err(error) => { + Metrics::incr(&self.shared.metrics.checkpoint_failures_total); + if let Some(reply) = reply { + let _ = reply.send(Err(error.clone())); + } + return Err(error); + } + }; + let generation = ticket.generation; + if ticket.durable { + self.emit( + NewEvent::new( + FeedEventKind::Checkpoint, + format!("Checkpoint {generation} saved"), + ) + .value(generation as f64), + ); + } + self.pending_saves.push(PendingSave { + ticket, + wall_ms, + reply, + }); + Ok(generation) + } + + /// A durable save that has really hit the disk before returning (startup, shutdown). + async fn checkpoint_blocking(&mut self, kind: SaveKind) -> Result<()> { + let (tx, mut rx) = oneshot::channel(); + self.checkpoint(kind, Some(tx)) + .await + .map_err(|e| anyhow!(e))?; + // The writer answers the ticket; `poll_saves` forwards the answer to `rx`. + loop { + self.poll_saves(); + match rx.try_recv() { + Ok(Ok(_)) => return Ok(()), + Ok(Err(error)) => bail!(error), + Err(oneshot::error::TryRecvError::Empty) => { + tokio::time::sleep(Duration::from_millis(2)).await; + } + Err(oneshot::error::TryRecvError::Closed) => { + bail!("the checkpoint writer dropped the reply") + } + } + } + } + + /// The writer's answers: metrics, `/status`'s checkpoint, and any reply waiting on one. + fn poll_saves(&mut self) { + let mut still = Vec::with_capacity(self.pending_saves.len()); + for mut pending in std::mem::take(&mut self.pending_saves) { + let result: std::result::Result = + match pending.ticket.reply.try_recv() { + Ok(result) => result, + Err(oneshot::error::TryRecvError::Empty) => { + still.push(pending); + continue; + } + Err(oneshot::error::TryRecvError::Closed) => { + Err("the checkpoint writer stopped".to_owned()) + } + }; + let metrics = &self.shared.metrics; + match &result { + Ok(report) => { + Metrics::incr(&metrics.checkpoints_written_total); + if report.durable { + Metrics::set(&metrics.checkpoint_generation, report.generation); + Metrics::set(&metrics.checkpoint_wall_ms, pending.wall_ms); + if let Ok(mut status) = self.shared.checkpoint.lock() { + status.generation = report.generation; + status.latest_wall_ms = pending.wall_ms; + } + } + tracing::debug!( + generation = report.generation, + durable = report.durable, + bytes = report.bytes, + "checkpoint committed" + ); + } + Err(error) => { + Metrics::incr(&metrics.checkpoint_failures_total); + tracing::error!( + %error, + generation = pending.ticket.generation, + durable = pending.ticket.durable, + "checkpoint commit failed" + ); + } + } + if let Some(reply) = pending.reply.take() { + let _ = reply.send( + result + .map(|report| report.generation) + .map_err(|error| error.to_string()), + ); + } + } + self.pending_saves = still; + } + + // -- publishing ------------------------------------------------------------------------ + + async fn read_feed(&mut self) -> Result { + let agent_id = self.agent_id.clone(); + let value = self + .session + .coordinator + .read_agent_extension(&agent_id, METHOD_FEED_STATUS) + .await + .map_err(|e| anyhow!(e))?; + AgentFeed::parse(&value) + } + + /// `Sim::publish`: one snapshot of the committed boundary. `with_attachments` is false while + /// not running, which is the protocol's header-only idle cadence. + async fn publish(&mut self, with_attachments: bool) { + match self.read_feed().await { + Ok(feed) => self.last_feed = feed, + Err(error) => tracing::warn!(%error, "the agent's feed status: publishing the last one"), + } + if let Ok(mut status) = self.shared.decoder.lock() { + *status = self.last_feed.decoder.clone(); + } + let feed = self.last_feed.clone(); + let ms = feed.brain_ms; + let cooldown = self.limiter.cooldown_ms(now_wall_ms()); + + let (frame, audio, spikes, spike_count, attachments) = if with_attachments { + let view = fly_session::media::view_attachment(gameboy::VIEW_ID); + let frame = match self.session.coordinator.media_bytes(&view).await { + Ok(Some(bytes)) => bytes, + Ok(None) => Vec::new(), + Err(error) => { + tracing::warn!(%error, "the committed view"); + Vec::new() + } + }; + let spikes = std::mem::take(&mut self.spikes); + let count = spikes.iter().map(|b| u64::from(b.count_ones())).sum(); + let audio = f32_bytes(&self.pending_audio); + self.pending_audio.clear(); + ( + Arc::new(frame), + Arc::new(audio), + Arc::new(spikes), + count, + AttachmentKind::ALL.to_vec(), + ) + } else { + // The spike window restarts at every publish, attachments or not (the legacy + // `last_publish_ms`). + self.spikes.clear(); + ( + Arc::new(Vec::new()), + Arc::new(Vec::new()), + Arc::new(Vec::new()), + 0, + Vec::new(), + ) + }; + + let rank_since_ms = self + .session + .checkpointer() + .map_or(0.0, |checkpointer| checkpointer.rank_since_ms()); + let macro_mode = self.shared.config.macros.mode; + let semantic_rewards = self.semantic_rewards; + let (game, milestone) = self.session.task.inspect(|adapter, ratchet, macros| { + let progress = adapter.progress(); + ( + feed_game(adapter, &progress, semantic_rewards, macros, macro_mode, ms), + feed_milestone(adapter, &progress, rank_since_ms, ms, ratchet.state.attempts), + ) + }); + + self.seq += 1; + let header = FeedHeader { + protocol: PROTOCOL, + seq: self.seq, + wall_ms: now_wall_ms(), + status: self.status, + realtime_factor: finite(self.realtime.factor()), + uptime_seconds: self.started.elapsed().as_secs_f64(), + run_seconds: finite(ms / 1000.0).max(0.0), + brain_ms: finite(ms).max(0.0), + frame: self.frame_counter(), + buttons: self.session.task.mask() & 0xff, + rates: feed_rates(feed.rates.iter().map(|(name, hz)| (name, *hz))), + population_rate: finite(feed.population_rate).max(0.0), + spike_count, + learning: feed.learning, + game, + milestone, + sugar: feed_sugar( + feed.reward_remaining_ms, + cooldown, + self.sugar_last_by.clone(), + self.sugar_today, + ), + events: self.log.take_pending(), + chat: if self.shared.config.chat.enabled { + Some(self.chat_ring.lines()) + } else { + None + }, + attachments, + }; + let snapshot = Snapshot { + header, + frame, + audio, + spikes, + }; + Metrics::incr(&self.shared.metrics.snapshots_published); + let _ = self.snapshots.send(Arc::new(snapshot)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The environment's native audio through the f32 DC blocker is the legacy loop's u8 audio + /// through its own, bit for bit, across chunk boundaries. + #[test] + fn the_session_audio_path_is_the_legacy_audio_path() { + let mut raw = Vec::new(); + let mut x: u32 = 12345; + for _ in 0..4096 { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12345); + raw.push((x >> 16) as u8); + } + let (mut legacy, mut session) = (DcBlocker::default(), DcBlocker::default()); + let (mut a, mut b) = (Vec::new(), Vec::new()); + for chunk in raw.chunks(1600) { + legacy.process_into(chunk, &mut a); + let native = fly_session::legacy_env::audio_f32le(chunk); + session.process_f32_into(&f32_samples(&native), &mut b); + } + assert_eq!(f32_bytes(&a), f32_bytes(&b)); + } + + /// `Legacy.FeedStatus` carries exactly what the legacy `publish` reads from the network. + #[test] + fn the_feed_status_is_the_networks_own_numbers() { + let data = std::sync::Arc::new( + flybrain_core::dataset::load_brain_dataset_from_dir( + fly_session::legacy_parity::toy::dir(), + ) + .expect("the toy connectome"), + ); + let mut agent = flybrain_core::agent::NeuralAgent::new( + data, + flybrain_core::agent::AgentConfig::with_decoder( + flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros(&[]), + ), + ) + .expect("an agent"); + agent.network.step(40); + agent.network.stimulate(250.0); + let feed = + AgentFeed::parse(&fly_session::legacy_agent::feed_status_of(&agent)).expect("parses"); + let stats = agent.network.plasticity.statistics(); + let learning = flysim::simloop::feed_learning(&stats); + assert_eq!(feed.learning, learning); + assert_eq!(feed.brain_ms, agent.network.ms); + assert_eq!(feed.reward_remaining_ms, 250.0); + assert_eq!(feed.population_rate, agent.network.population_rate); + let rates = feed_rates(feed.rates.iter().map(|(n, hz)| (n, *hz))); + assert_eq!(rates, feed_rates(agent.network.rates.iter())); + assert_eq!( + feed.decoder.channels.len(), + agent.decoder.channel_roles().len() + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs index 305dc84..7bcab1e 100644 --- a/services/flysim/crates/fly-legacy-session/src/task.rs +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -163,6 +163,20 @@ pub fn ledgers_of( .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, + pub rewards: Vec, + pub abandoned: Vec, + /// `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)>, +} + /// How the object is configured. Everything here is composition, not state. #[derive(Clone, Debug)] pub struct PokeredConfig { @@ -197,6 +211,12 @@ struct Inner { driver: Option>, /// Addresses the engine read that the image does not capture ([`Watched`]). uncaptured: std::collections::BTreeSet, + /// 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 /// agent's RNG state as the legacy loop seeds it). palette_seed: u32, @@ -239,6 +259,9 @@ impl PokeredTask { records: Vec::new(), driver: None, uncaptured: std::collections::BTreeSet::new(), + feed: FeedRecord::default(), + mask: 0, + rollback_game_over: false, palette_seed: PALETTE_SEED, })), }) @@ -272,6 +295,38 @@ impl PokeredTask { 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( + &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 /// the restored brain's RNG state (`rng_state() as u32`). pub fn set_palette_seed(&self, seed: u32) { @@ -627,6 +682,8 @@ impl Task for TaskFace { drop(span); let span = fly_session::profile::span("task.observe"); let abandoned = inner.observe(&image, ms); + inner.feed.rewards.extend(rewards.iter().cloned()); + inner.feed.abandoned.extend(abandoned.iter().cloned()); drop(span); let span = fly_session::profile::span("task.ratchet"); let progress = inner.adapter.progress(); @@ -682,6 +739,7 @@ impl Task for TaskFace { } events.push(task_event); } + inner.rollback_game_over = game_over; let episode = recover.then(|| EpisodeRequest { kind: EpisodeRequestKind::Rollback, reason: id(if game_over { "game-over" } else { "stall" }), @@ -740,6 +798,10 @@ impl Task for TaskFace { None => Vec::new(), }; 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() { record.rolled_back = true; record @@ -821,6 +883,7 @@ impl Task for TaskFace { inner.macros = fresh_layer(&inner.config, inner.palette_seed); inner.current = None; inner.open = None; + inner.feed = FeedRecord::default(); inner.epoch = epoch.clone(); inner.evaluations = 0; inner.issued = 0; @@ -950,6 +1013,8 @@ impl ActionExecutor for ExecutorFace { None => (raw, Vec::new()), } }; + inner.mask = mask; + inner.feed.executed.extend(events.iter().cloned()); if inner.config.record { inner.open = Some(TaskRecord { boundary: scope.step, diff --git a/services/flysim/crates/fly-legacy-session/tests/journal_replay.rs b/services/flysim/crates/fly-legacy-session/tests/journal_replay.rs new file mode 100644 index 0000000..49abb40 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/journal_replay.rs @@ -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(), + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/service_parity.rs b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs new file mode 100644 index 0000000..c6245b6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs @@ -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 { + 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, +} + +fn act(at: usize, method: Method, path: &'static str, body: Option) -> Action { + Action { + at, + method, + path, + body, + } +} + +/// The script both runtimes are driven by. +fn script() -> Vec { + 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, + responses: Vec<(String, u16, Value)>, + status: Value, + metric_names: Vec, + events: Vec, + event_file: Vec, + journal: Vec, + 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::(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(¬ifier) + } + Runtime::Session(mode) => { + let options = ServiceOptions { + mode, + profile, + session_dir, + }; + run_host(loop_shared, snapshots_tx, command_rx, ¬ifier, &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 = 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 = 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 = 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 = + 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 = 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::>(); + 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::>())), + &json!(b["decoder"]["channels"].as_array().map(|c| c.iter().map(|x| (x["channel"].clone(), x["role"].clone())).collect::>())), + ); + 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 { + 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 = + 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::(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 { + 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") +} diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 6357801..84aa4b7 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -603,9 +603,12 @@ impl Coordinator { .collect() } - /// The bytes of one media handle this committed boundary holds, by attachment name (the - /// view or an audio chunk), or `None` when the boundary holds no such handle. (The same - /// method as SERVE-01's service host reads the step's audio with.) + /// The bytes of one media attachment this committed boundary holds (a view, e.g. + /// `media::view_attachment("lcd")`, or an audio chunk, `media::audio_attachment(..)`), or + /// `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>, String> { let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else { return Ok(None); @@ -617,6 +620,59 @@ impl Coordinator { .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 { + 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. pub fn audio_positions(&self) -> BTreeMap { self.timelines.positions() @@ -2625,6 +2681,7 @@ impl Coordinator { slot.prepare_request = None; } let publish_span = crate::profile::span("coord.publish"); + let publishing = Instant::now(); self.publish_events(k + 1, &evaluation.events).await?; // 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 @@ -2637,6 +2694,7 @@ impl Coordinator { self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; } 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 // pauses the session for the episode policy. diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 43a3cb8..883536d 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -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: /// the legacy feed's `spike_bitset` layout. 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. 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 = network + .rates + .iter() + .map(|(name, hz)| json!([name, finite_or_zero(hz)])) + .collect(); + let channels: Vec = 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` /// order, and the first bound channel the decode holds, which is exactly the channel the legacy /// macro layer's `asked` would start. @@ -871,6 +944,28 @@ impl LegacyAgentWorker { 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 { + 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 @@ -1826,6 +1921,7 @@ impl WorkerEndpoint for LegacyAgentWorker { id("pixel-observation-v1"), id(crate::state::CHECKPOINT_CAPABILITY), id(ROLLBACK_CAPABILITY), + id(FEED_STATUS_CAPABILITY), ] } @@ -1846,6 +1942,7 @@ impl WorkerEndpoint for LegacyAgentWorker { "State.Capture", "State.StageRestore", "State.ActivateRestore", + METHOD_FEED_STATUS, ] } @@ -1865,6 +1962,7 @@ impl WorkerEndpoint for LegacyAgentWorker { "State.Capture" => self.state_capture(&ctx).await, "State.StageRestore" => self.state_stage_restore(&ctx).await, "State.ActivateRestore" => self.state_activate_restore(&ctx).await, + METHOD_FEED_STATUS => self.feed_status(), other => Err(DomainError::before( ErrorCode::Unsupported, format!("{other} is not an agent method"), diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index 4a18bcc..d62a3b3 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -939,6 +939,9 @@ fn classify_default(method: &str) -> Option { "Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => { 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, } } diff --git a/services/flysim/crates/flysim/src/lib.rs b/services/flysim/crates/flysim/src/lib.rs index 80adc21..ceb0721 100644 --- a/services/flysim/crates/flysim/src/lib.rs +++ b/services/flysim/crates/flysim/src/lib.rs @@ -80,6 +80,34 @@ impl AppState { /// 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. 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(config: Config, sim: F) -> Result<()> +where + F: FnOnce( + Arc, + watch::Sender>, + mpsc::Receiver, + &sdnotify::Notifier, + ) -> Result<()>, +{ let ring = EventRing::new(); let shared = Arc::new(Shared::new(config.clone(), ring)); 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))); let notifier = sdnotify::Notifier::from_env(); - let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?; - notifier.notify("READY=1\nSTATUS=simulation running\n"); - let result = sim.run(¬ifier); - notifier.notify("STOPPING=1\n"); - drop(sim); + let result = sim(shared, snapshots_tx, command_rx, ¬ifier); if let Some((bus_runtime, bus)) = bus_runtime { // 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 diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index f83d831..2382471 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -317,7 +317,7 @@ struct WriteJob { } /// 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") } @@ -1163,44 +1163,12 @@ impl Sim { /// Nothing here touches the network, the emulator, the decoder or plasticity. That is the /// whole point: chat is a caption track, not an input. fn chat(&mut self, by: &str, text: &str, bot: bool) -> Result { - let refuse = |sim: &Self, refusal: ChatRefusal| { - sim.shared.metrics.chat_rejected(refusal.reason()); - refusal - }; - - 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) + let ms = self.agent.network.ms; + let Self { shared, chat_ring, chat_limits, deny_list, log, .. } = self; + 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) + }) } /// 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(); let ms = self.agent.network.ms; 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 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 (bitset, count) = @@ -1502,59 +1454,26 @@ impl Sim { brain_ms: finite(ms).max(0.0), frame: self.frame.frame_counter, 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), spike_count, - learning: 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), - }, - game: FeedGame { - 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)), - ), - }, - // `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. - milestone: FeedMilestone { - rank, - label: progress.rank_label.to_string(), - next: next_label(ladder, rank, progress.rank_label, next_rung).to_string(), - 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, - }, + learning: feed_learning(&stats), + game: feed_game( + self.adapter.as_ref(), + &progress, + self.semantic_rewards, + self.macros.as_ref(), + self.shared.config.macros.mode, + ms, + ), + milestone: feed_milestone( + self.adapter.as_ref(), + &progress, + self.rank_since_ms, + ms, + self.ratchet.state.attempts, + ), + sugar: feed_sugar(remaining, cooldown, self.sugar_last_by.clone(), self.sugar_today), events: self.log.take_pending(), // The kill switch omits the field rather than sending an empty array. 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 { + 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` /// 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) } +/// 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) -> Map { + 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, + 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 /// 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) } diff --git a/services/flysim/crates/flysim/src/snapshot.rs b/services/flysim/crates/flysim/src/snapshot.rs index 4084566..272b6dd 100644 --- a/services/flysim/crates/flysim/src/snapshot.rs +++ b/services/flysim/crates/flysim/src/snapshot.rs @@ -667,15 +667,27 @@ impl DcBlocker { pub fn process_into(&mut self, raw: &[u8], out: &mut Vec) { out.reserve(raw.len()); for (index, sample) in raw.iter().enumerate() { - 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]; - self.previous_in[channel] = input; - self.previous_out[channel] = output; - out.push(output); + 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) { + 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) { + let channel = index & 1; + let output = input - self.previous_in[channel] + DC_BLOCK_POLE * self.previous_out[channel]; + self.previous_in[channel] = input; + self.previous_out[channel] = output; + out.push(output); + } } /// Little-endian bytes of an f32 slice, as a `Float32Array` holds them. diff --git a/tools/runtime-soak.ts b/tools/runtime-soak.ts new file mode 100644 index 0000000..41b79c0 --- /dev/null +++ b/tools/runtime-soak.ts @@ -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; + 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; + 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 = {}; +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; +} +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> { + try { + const text = await (await fetch(`${metricsUrl}/metrics`, { signal: AbortSignal.timeout(3000) })).text(); + const out: Record = {}; + 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) { + 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);