diff --git a/docs/design/session-framework/README.md b/docs/design/session-framework/README.md index f4cbc1b..5bf4b0f 100644 --- a/docs/design/session-framework/README.md +++ b/docs/design/session-framework/README.md @@ -78,7 +78,10 @@ Application / supervisor Application presentation This diagram is connectivity, not execution order. The step contract defines causal order. One router can host several independent sessions and application consumers; a deployment may choose one router per application for fault isolation. A router crash affects all its clients, -so choose that boundary deliberately. In-process mode still exercises routing and ownership. +so choose that boundary deliberately. In-process mode still exercises routing and ownership, +unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1, +amendment 2026-09-30), as the legacy composition's in-process release configuration is; process +mode always goes through the router. Defaults: coordinator per session, worker per fly, environment worker per world. Task and per-agent executors begin as coordinator-local libraries. An environment helper may own a diff --git a/docs/design/session-framework/bus-v1.md b/docs/design/session-framework/bus-v1.md index 8a545cc..5e0a3db 100644 --- a/docs/design/session-framework/bus-v1.md +++ b/docs/design/session-framework/bus-v1.md @@ -523,3 +523,14 @@ this same section forbids to reject one. longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled illustrative. + +**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client +gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in +the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no +router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into +one under the same reference. They read, clone and retain without a router, and no router ever +learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish` +before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one +process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of +the same date); section 8's ownership rules apply to every artifact a router stores, which these +never are. diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index ffbd75a..0660719 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -344,6 +344,345 @@ CUT-01 shadow need. the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C, retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`. +### TASK-01 — The `pokered-macros-v1` task and executor (port slice) + +**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 + +ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of +the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it +the live fly's whole composition -- agent, world, task and executor -- runs on the session +framework, from a fresh start or from a FLYSIM01 checkpoint. + +- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one + object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds + any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide` + over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs + `PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's + decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe` + over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order; + there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is + retained until Phase C has read it. +- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the + coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the + agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A + declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with + `RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters + cover the backend and task config, the media, the decision schema, the world's state format and + per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's + `preStepStimulations` and reports every admission applied or aborted. `Coordinator::import` + installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are + kept for a parity run. +- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's + `legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves + go into each participant's own capture format, and the ordinary group restore installs them: + stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first, + because ENV-01 stages only on a replacement. The context the agent resumes with is computed + from the checkpoint's own memory image, and the coordinator holds the task to it after the + install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`. +- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's + `LegacyCheckpointer`). + - `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy + candidate order, holding each candidate to the legacy gate. Any refusal falls to the next + candidate; each attempt runs on a session of its own, because a refused install fences its + session. It is a fresh start when the stores are empty. After either, the startup durable + save is written and the intervals start. + - `advance` keeps the declared boundary order: the slot save (inside the step), the milestone + archive on a rank climb, the rollback (deferred by the coordinator until the host has + captured), a durable save after a rollback, then the interval saves. + - `shutdown_save` is the legacy shutdown's durable save. + - The session runtime writes no sugar journal yet: its admission is the coordinator's, and the + journal's boot header needs the edge. + - `lastEventId` carries the restored file's watermark; the runtime has no feed event log + before EDGE-01. +- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged, + against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the + next cut. +- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment. + +**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session +writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built +from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the +executor's batch, the view, the image and the boundary actions. It is compared field by field with +the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list +order. Where the legacy side runs in the test, the ledgers are compared after every boundary as +well: adapter export, ratchet state, and the executor's scene, bound channels, running macro, +counts and "nearer". Results: see the TASK-01 run report and the amendment below. + +**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted +N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover +B1, N1 and N3. + +- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB, + past the 32 KiB `TypedValue` bound. + - `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`. + - The coordinator files those attachments as `task-ledger-` payloads in captures and + imports. + - A bad ledger is an error, never a panic, so a boot falls to the next candidate. + - Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB). +- **N1: a sugar admitted before the next commit is an active pulse.** +- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the + seed is never read. +- **N4: saves are queued to the writer thread.** +- **N5: speed.** The profile is below. Changes: + - The world seals its three artifacts concurrently. + - Cache and caller holds are taken concurrently. + - In-process participants use the in-memory transport. + - A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded + history. + - `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside + the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state + under the lock, then encodes, digests and seals it off the lock. The coordinator's + `begin_capture` / `finish_capture` let the session step on while the payload is written. +- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`): + - The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a + few percent. + - What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a + quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit, + plus the world's and the agent's artifact seals and reads. + - Against it, the legacy loop spends about 0.7 ms per frame outside the ticks. + - The report `claude-task-01` has the per-phase table and what would close the rest. + +### PERF-01 — The session runtime's per-frame cost (port slice) + +**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and +awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the +in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy +loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame, +in-process and process, and the compatibility string is unchanged. + +- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30). + An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`, + `launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method. + The request still goes through the shell's admission, deduplication, arrival order and + endpoint, and the reply is the same outcome. Handler media over the lane are in-memory + artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy, + no retain or open round trip. A bus call or a publication carries a sealed copy + (`rpc::promote`), begun while the task and the commits run. Process mode is untouched. + `FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also + runs over the lane. +- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare + ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits, + proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs. +- **The session topic** gets a committed snapshot every 60th boundary in a service session (and + at every boundary with events or boundary actions), not every other one. Nothing in the + release subscribes; the stream is the legacy feed. +- Small ones: a single dispatch job is called in place, the shell moves the reply result + instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling + spans for the shell, the lane, each handler and the brain's own phase clock. +- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any + other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and + work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate + (an AGENT-01 amendment) was not needed once the bitset cost nothing. +- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`; + the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the + release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms + to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame + memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache + (about 0.5 ms together) and the task's evaluation, which the legacy loop does too. + +### SHADOW-01 — The session runtime beside the live fly (port slice) + +**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no +live behaviour. flysim gains trace switches that are off unless set, and the compatibility string +is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs, +the architecture, what is compared, the declared differences, the window and the verdict CUT-01 +reads. + +- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only: + - `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE` + path. + - `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB. + - `FLY_TRACE_LEDGERS=` adds `ledgersDigest` every *n* transitions. + - `frame::ledgers_string` is now the one definition of the ledger string. The session task's + `ledgers_of` calls it. +- **`fly-legacy-session::shadow`** and the binary `fly-shadow`: + - `follow` reads the per-process files. It hands out complete lines only, and a file ends when + a newer one exists. + - `spool` copies every new store generation as it appears. It keeps a floor and a byte bound, + and never writes to a live store. + - `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the + live file byte for byte, after `host-fields` and `archive-order`. + - `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`, + `fly-shadow check`). + - The runner boots each segment from the live process's startup save (TASK-01's import). It + replays the admissions, runs the transition, and takes the live captures in the live order + around a deferred rollback. It compares with `trace::compare_line`, which is now shared with + `trace::compare`. It stops on the first divergence and writes `divergence.json` with 30 + transitions of context. +- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to + flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the + commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the + unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship + `fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a + "Shadow run (SHADOW-01)" section. +- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real + `fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service + restarts. It runs on a build box, never on a host. + +**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real +service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every +run. It totalled **4,090 brain seconds (68 brain minutes), 244,327 transitions, 13 processes and +zero divergence**: + +| Run | Start | Brain s | Transitions | What it covered | +| --- | --- | --- | --- | --- | +| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary | +| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves | +| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward | +| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` | +| smoke | row 67, unthrottled | 122 | 7,305 | the first run | +| final | row 67, real time, the final binary, the lag guard on | 601 | 35,917 | the box was contended by other runs, so the live loop fell behind real time 5 times; each time the guard paused the shadow (667 s in all), and all 143 saves were still compared | + +The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and +finished 12 minutes behind. Every save was still compared, from the spool. + +`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart +under a shadow, then plants four differences on copies of that run's trace and spool. Each one +stops a fresh shadow with the right kind, field and step: + +- a work-RAM digest; +- a ledger digest; +- a sugar removed, which diverges on the brain at that transition; +- a live save's `rankSinceMs`. + +**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other +agents' runs made paired measurements vary by up to 2x. + +- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The + live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a + frame, so the session runtime costs about what the legacy loop does (x1.05). +- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the + main trace unthrottled gave these means: + - in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms; + - thread mode with 2 threads: 18.5 ms; + - process mode with 2 threads: 18.5 ms. + + Every replay was identical again: five more comparisons of 20,000 transitions each. +- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB. +- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best + paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has + 1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is + 160 MB per live hour. + +The resource plan for the release container is in the SHADOW-01 run report and in +`units/flyshadow.service`: + +- `SCHED_IDLE` on the page and encoder CPUs, never flysim's; +- 2 sweep threads; +- a back-off whenever the live `fly_lag_seconds` grows; +- a 3 GB memory ceiling; +- a ledger digest every 60 transitions. + +To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace +is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later. + +**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An +emulator imported from a state therefore drifts from a powered-on one in its channel accumulators. +The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores +through an import in both runtimes, so the two agree. A fresh start does not import, and the +shadow follows one by powering on as well. + +**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast` +had three failures, each accounted for: + +- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes + alone. +- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main. +- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load + 22. + +`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures, +typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is +648 B `8ce67b97...` in raw and macros mode, unchanged. + +**Review fix round, 2026-09-29** (APPROVE-WITH-NOTES). The branch was rebased onto port/task-01's +fix round, `2fc9fd7`: an artifact-backed task ledger, the palette seed, queued saves and bounded +history. The shadow now bounds its coordinator's history per segment. The fixes: + +- *R1.* The verdict hashes `flysim-session`, SERVE-01's service, with the other release binaries. + `check` defaults to `--binary flysim-session --current /opt/fly/current`. It requires the + verdict's release to be the directory the link resolves to, with every shadowed binary + unchanged there. +- *R2.* Every session-side failure is a divergence: + - a session that does not start; + - a restore-gate refusal (`tests/shadow.rs` now plants one); + - a capture with no agent; + - an unrecorded transition; + - an unbuildable trace line. + + Skips carry a kind, and only the live side's own kinds allow a cutover. +- *N1.* The live trace needs the shadow's heartbeat to start and to keep going, and flysim keeps + the trace directory under 8 GiB. The runbook's claim is corrected. +- *N2.* `fly-shadow-run` records a baseline and runs `flyshadow-guard.timer`. The guard stops + everything and restarts flysim without the trace on 1 s of lag growth, or when the realtime + factor drops below min(0.97, baseline - 0.03). `lint.sh` drives the rule on six cases. +- *N3.* Both `pass` and the cutover require one live save compared per 600 brain seconds, with at + most 10 % unavailable. The cutover also requires a shadow at most 3,600 transitions behind. + +**Cost re-measured on the rebased tip.** This was a 12-brain-minute rehearsal on the same box, +at real time, with a restart and the guard on. It had 43,104 transitions, 197 saves byte-identical +and zero divergence. The box was contended by other runs again; the guard paused the shadow for +911 s and it still passed. Unthrottled replays of its trace, all identical, gave these mean +milliseconds per frame: + +| Mode | ms per frame (mean) | +| --- | --- | +| in-process, 2 threads | 15.1 | +| in-process, 3 threads | 13.3 | +| thread mode, 3 threads | 14.9 | +| process mode, 2 threads | 15.4 | + +Earlier the same 2-thread and 3-thread in-process arms took 19.7 and 17.0 ms. With 3 threads the +shadow keeps real time with about 20 % to spare. + +**Review round 2, 2026-09-30** (APPROVE-WITH-NOTES; R3 and G1 were required before `start`). +The branch was rebased onto port/task-01 `eaf588d`, and main v0.6.7 was merged in: row 68 and +adapter `pokered-unique8-v8`. The live shadow will therefore carry the v8 compatibility string. +The fixtures were already v8 on main. + +- *R3.* `allows_cutover` floors the window at `REQUIRED_BRAIN_SECONDS` (10,800). A verdict run with + a shorter `--required-brain-seconds` passes as a rehearsal but never passes `check`. There is a + test case for this. +- *G1, the host guard.* + - `start` measures a 10-minute baseline of 60 samples before the shadow exists: the median RTF, + its spread as 1.4826 x MAD, and the lag growth rate over the most recent half. + - The guard trips only on a sustained degradation *against that baseline*: 3 checks in a row in + which the last 5 samples of the same process fall below it, in RTF or in lag rate, by more + than max(0.05, 4 x spread / sqrt 5). + - It stops itself when the shadow is not running. `check` refuses after a trip or with the + shadow down. + - Tested over two kinds of trace: + - *Synthetic*, shaped on the release container: a flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per + second and per sample, and real time with hiccups. There was no false trip in 800 3-hour + runs, and every one of 400 degradations tripped (to 0.55-0.75, and 0.66 to 0.58). + - *Recorded* from a real flysim, now fixtures: alone (at about 1.0, and at 0.4-1.0 under box + load) no trip; with a real idle shadow on other cpus no trip; with a real shadow on the fly's + own cpu (0.66 to 0.44-0.60) a trip at check 7. + - One recording had a load step inside its baseline, which widened a mean/sd baseline to a + 0.25 margin. That is why the baseline is robust. +- *G1, the in-shadow back-off* (`LagJudge`). It pauses the shadow while the live lag grows faster + than the baseline rate plus the margin (re-read from `baseline.json`). It lifts itself for + 10 minutes when a pause did not help, because then the shadow is not the cause. Tests show: + - a flat 0.66 fly is never paused; + - with no baseline, at most 1 minute in 11 is paused; + - a shadow that costs the fly time stays paused about half the time. +- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file + and every newer one, including while the shadow is backed off. + +**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not +a timing, load or segment-handling bug. +- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test. + `cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx + target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so + it wrote no trace at all. The failure was reproduced by running such a test binary against its + own stale `flysim`. +- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`, + with the same target directory and profile, which does nothing when the binary is current. + This was proved on a target that another tree's `flysim` had populated. +- *What production could miss, and now cannot.* A live process that runs without a trace is now + a `coverage` divergence (above). That covers a process whose consumer check failed, and one + whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer + stops flysim from starting. The test adds such a process, untraced, and the shadow fails. + ### STATE-01 — Coherent all-participant checkpoint/recovery **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. @@ -487,6 +826,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/docs/design/session-framework/ipc-v1.md b/docs/design/session-framework/ipc-v1.md index fddd8ee..b42339a 100644 --- a/docs/design/session-framework/ipc-v1.md +++ b/docs/design/session-framework/ipc-v1.md @@ -17,6 +17,37 @@ ownership. This document owns Scope, model-related scalar types, worker capabili domain operation deduplication and errors. Domain request identity is independent of the bus callId: a safe retry has a new transport callId but the original domain requestId/body. +**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker +RPC is a Flybus call", for participants that share the coordinator's process. The release +container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a +frame above the brain (three round trips through the router and four or five sealed store files +a frame), against 0.7 ms for everything the legacy loop does outside its ticks. + +- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator + directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods -- + step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to + that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks. +- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through + the same shell code as a bus request: section 5's classification, canonical body digest, + result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the + endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker, + incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and + resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped + before answering is a lost connection (mutation unknown). +- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1 + section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef` + (`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3 + holds as written: every `ArtifactRef` in a payload is backed by a live handle the message + carries. An in-memory artifact never crosses a router: a bus call or a publication that needs + one carries a sealed copy (the coordinator makes it), and the snapshot names the copy. + A sealed handle a handler returns over the lane reaches the caller in memory under the same + reference. +- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached + over the bus, so process mode keeps exercising routing and ownership, and the bus path stays + the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic + transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy + parity runs in-process (lane) and process (bus). + ## 2. Common domain types ```ts diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index d08f539..2cd8c2d 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -288,6 +288,37 @@ signal. The object serves exactly one agent on one port. - **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world the fly now stands in. +**Amendment, 2026-09-29 (TASK-01).** Choices the section above leaves open, fixed as built by +`fly-legacy-session::task`: + +- *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment + as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot". + So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot + save is asked for exactly when the legacy capture closure runs: safe, and rank above best. +- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's + lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past + the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet, + slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A + checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's + explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable + attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate. +- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette + from the brain's RNG state after boot. A restore does the same: it seeds with the restored + agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up, + so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro + has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge: + two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future + macro that draws from the generator fails there. +- *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the + warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's + `Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a + restore the layer observes at the restored brain time. +- *A reward event with `stimulation_ms` = 0* is one `Reward` and no `Stimulus`, because + `Stimulus.durationMs` is positive. The legacy `stimulate(0)` changes nothing. +- *Executor events.* Macro starts and finishes are not `executionEvents`. They are reported as + `FLY_TRACE` `macroEvents` (phases `execute`, `evaluate`, `rollback`). Reward events are the + task's `TaskEvent`s. + ## 11. Episode policy `legacy-ratchet-rollback-v1` The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during @@ -331,6 +362,14 @@ the adapter's persistent state. The first audio chunk after the rollback marks a discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent. Each half touches only its own state, so the order between the halves does not matter. +**Amendment, 2026-09-29 (TASK-01).** The coordinator applies the policy itself, as the section +describes. The phase is `RollingBack(k)`. The new epoch is the session's epoch root plus `.rb`, +which is deterministic, so two runs of one session name the same epochs. A composition that +declares the policy refuses to start unless every agent advertises `legacy-ratchet-rollback-v1`. +The task's rollback request carries `{slotId: best, trigger}`. The world must advertise +`gameboy-slots-v1` before anything is saved or restored. Service traces with a ratchet slot save +and a ratchet rollback reproduce as described in the implementation guide's TASK-01 entry. + ## 12. Composition declaration and digest ```ts @@ -376,6 +415,31 @@ interface LegacyGameboyComposition { for publication, traces and descriptor revisions, not a restore gate. This matches today's behaviour, where a decoder change does not refuse a checkpoint. +**Amendment, 2026-09-30 (PERF-01): the in-process release configuration.** Nothing in the +declaration, the digest or the compatibility string changes; these are execution choices of the +composition as `fly-legacy-session` builds it, recorded here because the shadow compares the +behaviour they must not change. + +- *In-process participants are called over the local lane* ([session RPCs](ipc-v1.md) section 1, + 2026-09-30): the frame, the memory image, the audio chunk and the spike bitset are in-memory + artifacts, handed over without a store file. Process mode is unchanged and still goes through + the router. `FLY_SESSION_LOCAL_LANE=0` puts an in-process session back on the bus. +- *`telemetry.spikes` is unchanged*: one bitset per transition, bit `i` set when neuron `i` + spiked in `[transition start, brain time)`, the legacy layout. The agent now builds it as the + union of the kernel's per-tick spike lists while Prepare ticks (`LifNetwork::tick_spikes`) + instead of scanning 139,255 last-spike times in Commit; the two are equal by construction and + by test, and the parity runs compare the bitset every frame. The AGENT-01 alternative -- attach + it only at the feed rate -- was not needed and was not made. +- *Committed snapshots on the session topic*: a service session publishes every 60th boundary and + every boundary with task events or boundary actions (it was every other boundary). The live + presentation is the legacy feed, which the service host builds from the committed boundary at + 30 Hz; nothing in the release subscribes to the session topic, and each publication seals a + store copy of the frame and the audio chunk. Every publication is still of a committed + boundary and still attaches the media it names (publishing-v1 section 3). +- *Nothing runs beside the brain's ticks.* On the release CPU with the sweep owning every core of + the flysim cpuset, work overlapping Prepare (a publication left in flight, for instance) slowed + the ticks by up to a third, so the coordinator finishes each boundary before the next Prepare. + ## 13. Machine-readable parts | Where | What | @@ -500,6 +564,27 @@ Resume tests compare against the legacy restore outcome, not against an uninterr unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps the rung. +**Amendment, 2026-09-29 (TASK-01): a FLYSIM01 checkpoint as the start.** A new-runtime session +starts from the live fly's own save through the ordinary group restore +(`Coordinator::import`, `fly-legacy-session::import`): + +- The world is ENV-01's `WorldState::from_flysim01` at `k = emulatorFrame - 1`, staged on a + replacement world. +- The agent is the checkpoint's agent state in the worker's own capture format: STATE-02's + `legacy_checkpoint::agent_payload`. It carries the file's reinforcement count and the file's + framebuffer as the next input, and its ids come from the file. +- The task is STATE-02's ledger `{reward, ratchet, slotFilled}`. + +A session boots from the live stores the way `Sim::boot` does: the legacy candidate order, the +legacy gate, the next candidate on any refusal, then a startup durable save. See the +implementation guide's TASK-01 entry. + +This section's resets then apply, and nothing else. The executor is fresh and observes the restored +image once, at the restored brain time. The agent's readout transient is a fresh process's. The +decision context is computed from the checkpoint's memory image before the install, and the +coordinator refuses the install if the task, re-observing the restored world, derives another +context. + ## 15. Sugar admission The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap @@ -523,6 +608,29 @@ applies it never commits, the admission is reported aborted and the edge refunds bridge's fulfil path and refund path both get tests in the slice that wires them ([workers-v1](workers-v1.md) section 5 amendment). +**Amendment, 2026-09-29 (TASK-01).** As built: + +- *Admission.* The coordinator's `AdmissionQueue` is cut at the top of each Prepare. It reports + every admission `applied` at the boundary its Prepare committed at, or `aborted` when the epoch + fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the + clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply. + After a restore the pulse is unknown and a request is refused with a retry of one frame. + *Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit + counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The + legacy `stimulate` activates the pulse the moment it admits, so this matches: + - two sugars between two commits get one admission and one `PulseActive`, as the legacy drain + gives them; + - the rate-limit slot is not spent on the refused one. + + The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the + ticks between drains; here it is undecayed until the commit reports it. +- *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless + an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API + answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside + `Agent.Commit` is not a session-framework operation. `LegacyAdmission::reward` therefore always + refuses. A legacy trace that carries a reward pulse cannot be reproduced; FND-01's checker + refuses one as well. + ## 16. Checkpoint format of record **Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)` @@ -597,3 +705,176 @@ graph validation for new bundles, and the composite behaviour identity of FOUNDA **not** in this document. They ship with PROF-02b, before DATA-01, as their own contract. Nothing here constrains them, except that a new profile never reuses this profile's id or its legacy exception. + +## 18. The shadow run (SHADOW-01) + +**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic +cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that +means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit +`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`. + +**The inputs.** The legacy loop is deterministic, given two things: the state a process starts +from and the admissions applied at the top of each frame. Every nondeterministic input reaches +the fly through one of those two: + +| Input | How it reaches the fly | How the shadow gets it | +| --- | --- | --- | +| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g`); the shadow boots a new session from it through the ordinary FLYSIM01 import | +| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) | +| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared | +| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where | +| Chat | A caption track; it reaches nothing the fly does | Not needed | +| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own | + +So "the same inputs" means *the same start state per process and the same admissions per +transition*. Admission itself is not compared. The session runtime decides admission against a +pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on +its own clock would diverge by design, not by fault. + +**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live +service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a +behaviour field or anything the fly does: + +- `FLY_TRACE_DIR` writes one file per process, `trace--.jsonl`. +- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode). +- `FLY_TRACE_LEDGERS=` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of + `flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the + executor's scene, bound set, running macro, counts and "nearer". + +`fly-shadow` follows the files in start order. For each file it takes these steps: + +1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup + save. A fresh start is different: the stores were empty and the startup save is at boundary 0. + In that case the shadow runs the same power-on scaffold and warm-up + (`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own + boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio + resampler phase is not in its exported state, so the channel accumulators of an imported + emulator drift from those of a powered-on one, in the exported state only. Both restores of a + restart import, so they agree. +2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a + capture wherever the live trace records one, before or after the boundary's rollback as the + live loop took it, then applies the deferred rollback. +3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and + compares it with the live line, field by field. + +A spool thread copies every new store generation as it appears, because a hot file lives only +about ten seconds. The shadow never writes to the live stores. + +The reverse arrangement was considered: the session runtime as primary, with legacy as the +checker. It would make the shadow run the cutover itself, and a divergence would already be on +the stream. A second legacy process in lockstep was also considered. It adds nothing, because the +live process's own trace *is* the legacy behaviour. + +**What is compared, per boundary.** + +- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`, + `brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`, + `macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary` + and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and + the rollbacks. +- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same + string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's + ledgers, which no checkpoint carries. +- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same + boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export + byte for byte with the live file after the substitutions named below. `compatibility`, + `speed` and `rankSinceMs` are the shadow's own, so they are compared too. + +**Declared differences**, excluded by name. The verdict lists the same names. + +| Name | What is excluded | +| --- | --- | +| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") | +| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) | +| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. They are host bookkeeping: the shadow keeps no feed event log (SERVE-01's service host keeps its own) and allocates no generations, because it writes no store | +| `admission-replay` | Sugar is replayed, not re-decided (above) | +| `operator-reward-pulse` | A segment with one is reported uncompared from that transition on | + +**The window.** The verdict is `pass` once the compared transitions add up to **10,800 s of +live brain time** (the sum of `ticksAdvanced`, 3 h at real time) with zero divergence, and at least +one live save per 600 of those brain seconds has been compared byte for byte. That time may span +several processes. + +*Skips* are only the live side's own events (`SKIP_KINDS`): + +- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it, + because the shadow started late or its spool evicted the file; +- `operator-reward-pulse`; +- `trace-cap`: the live trace stopped at its byte cap, or with no consumer; +- `no-transition`: a process that ran none. + +A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which +refuses the cutover. A process killed hard loses its unflushed tail, and those transitions are +not compared. + +The first difference of any kind stops the shadow with `diverged` (exit status 3) and writes +`divergence.json` with the 30 transition pairs before it. The same applies to every session-side +failure, which is **never** a skip: + +- a trace field; +- the ledgers; +- the checkpoint bytes; +- a session that does not start; +- a startup save the candidate's restore gate refuses or the session runtime cannot restore; +- a step, capture or rollback error; +- a transition the session did not record; +- *coverage*: a live flysim process that booted while the shadow ran and left no trace + (amended 2026-09-30). + +The shadow reads every boot header in the live sugar journal. Every flysim process writes one, +traced or not. It holds each header to a trace file created after the previous boot and before +this one. A process that ran untraced can never be compared, so the verdict fails. It does not +pass on the processes that were traced. + +A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference. + +**The live fly never pays for the shadow (amended by the SHADOW-01 review).** Three mechanisms +make sure of it: + +- *The trace is on only while a shadow consumes it.* The shadow writes a heartbeat + (`/consumer`) every 30 s and removes it when it stops. flysim starts no trace without + a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than + 10 minutes old, and keeps the directory under 8 GiB. A heartbeat dated ahead of flysim's clock + counts as fresh. A trace flysim cannot create (a full disk, the directory's permissions) never + stops the live fly from starting: that process runs untraced, and the shadow reports it as a + coverage divergence. +- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace + before the shadow existed. The live fly does not always keep real time: the release container + has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start` + first measures a 10-minute baseline over sixty 10-s `fly_realtime_factor` means. It records + their median and their spread (1.4826 x MAD), so a step in the window cannot set or widen it, + and the `fly_lag_seconds` growth rate over the most recent half. The guard trips only on a *sustained* degradation against + that baseline: 3 checks in a row in which the last 5 samples of the same process fall below the + baseline realtime factor, or grow lag faster than the baseline rate, by more than + max(0.05, 4 x spread / sqrt 5). A trip stops everything and restarts flysim without the trace. + The guard stops itself when the shadow is not running. `lint.sh` holds the rule to the release + container's profiles, synthesized, and to four traces recorded from a real flysim with and + without a real shadow (`infra/tests/fixtures/shadow-guard`). In 800 synthetic 3-hour runs it + found no false trip, and it caught all 400 degradations. +- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs. It pauses for a minute while the live lag + grows faster than the baseline rate. When a pause does not help, the shadow is not the cause, + and it stops pausing for 10 minutes. + +**The verdict contract (for CUT-01).** The shadow writes `verdict.json` in the format +`fly-shadow-verdict-v1` (`shadow::verdict`, whose module notes list the fields). CUT-01 cuts over +automatically only if all of the following hold when it reads the file, at the moment of cutting +over: + +- `status` is `pass` and `firstDivergence` is `null`; +- `compared.brainSeconds` ≥ `required.brainSeconds`, and never less than the operator's 10,800 s, + whatever window the shadow was run with; +- *Saves were compared.* At least one per 600 brain seconds was compared byte for byte, and at + most 10 % of those the trace named were unavailable. +- *The release.* `candidate.release` is the directory `/opt/fly/current` resolves to now. Every + binary in `candidate.binaries` still has its recorded SHA-256 there. The binary switched to, + `flysim-session` (SERVE-01's service), is one of them. +- `candidate.compatibility` is the live `--print-compatibility`; +- every `skipped` entry is one of the live side's own kinds; +- *the shadow is alive and caught up*: `updatedAt` is at most 5 minutes old and + `lagTransitions` is at most 3,600, counted at every write (paused or not) over the rest of the + current file and every newer one; +- (`fly-shadow-run check`) the guard has not tripped and `flyshadow.service` is running. + +`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when +it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is +CUT-01's. diff --git a/docs/design/session-framework/step-v1.md b/docs/design/session-framework/step-v1.md index bf8d167..a8a204a 100644 --- a/docs/design/session-framework/step-v1.md +++ b/docs/design/session-framework/step-v1.md @@ -12,6 +12,14 @@ ordering. Its frame order is this document's transaction order (legacy-gameboy-v maps it step by step), so the amendments below add capabilities to the protocol and change none of its ordering rules. +**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of +[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router: +the arrows below are then direct calls into the same worker shell, carrying the same requests and +replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that +overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the +coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the +world, the task and the commits run, and the snapshot is published before the next Prepare. + ## 1. Committed boundary At `Ready(epoch, k)`: @@ -65,6 +73,19 @@ amendment). The boundary number does not change; the epoch does. A pause request lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is not allowed in `RollingBack`. +**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session` +`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and +the boundary stays the same. One edge is added for a checkpoint of another format installed as a +session's start (the legacy composition's FLYSIM01 import): + +```text +Ready(0), no transition taken -> Restoring(k) -> Paused(k) +``` + +The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only +a session that has not advanced may take the edge; the coordinator enforces this, because the phase +alone cannot tell a fresh `Ready(0)` from a reset one. + ## 3. Transaction sequence ### Phase A: prepare all agents concurrently @@ -111,6 +132,12 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai the next request. Transport/control scaffolding may have a measured fixed latency; it must be declared in its descriptor and conformance tests. +*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is +`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the +legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches +the executor and the task as bytes: the coordinator holds each attachment the task declares +(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated. + ### Phase C: observe and evaluate the task The coordinator receives the environment result and verifies batch identity, boundary, diff --git a/docs/design/session-framework/workers-v1.md b/docs/design/session-framework/workers-v1.md index 9769270..d4a9732 100644 --- a/docs/design/session-framework/workers-v1.md +++ b/docs/design/session-framework/workers-v1.md @@ -426,6 +426,22 @@ composition that declares no rollback policy treats the request as a task failur "cannot reset the environment directly": the coordinator applies the policy through the section 7 methods. +**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`: + +- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the + bytes of every attachment the task declares (`Task::inspection_attachments`, for example + `inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value + it always was. +- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary + it reached. They are applied after every Commit, saves first. +- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next + contexts. +- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task + whose executor state is transient re-observes the restored world here, and returns the contexts + the coordinator holds against the checkpoint's. +- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared + state. + ## 5. Admission and audience boundary The first synthetic implementation has no audience input. Later integration maps permitted @@ -453,6 +469,13 @@ first and refunds the second, and the slice wiring the bridge tests both. This i accepted/applied/aborted distinction the paragraph above asks for, for this one interaction kind; paid interactions in general still need the public v2 contract. +**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the +admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it +ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The +legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted. +The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of +2026-09-29). + ## 6. Health, shutdown and extensions All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index 5601d69..2e0b49c 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,10 +708,16 @@ 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.) + # flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not + # flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder + # leave idle and never a cycle of the live fly's. + for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session flyshadow; do case "$u" in - flysim) cpus="$sim_cpus" ;; + flysim|flysim-session) cpus="$sim_cpus" ;; flycast) cpus="$encoder_cpus" ;; + flyshadow) cpus="${page_cpus},${encoder_cpus}" ;; *) cpus="$page_cpus" ;; esac { @@ -708,10 +745,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 fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null done +# 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..5af9b41 --- /dev/null +++ b/infra/bin/fly-runtime @@ -0,0 +1,455 @@ +#!/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] [--no-probation] +# 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. +# +# The speed probation (CUT-01). Operator decision 2026-09-30: the session runtime stays only if it +# sustains >= 1.0x real time on the release container. A `session` that restarted flysim and saw +# it healthy therefore starts infra/bin/fly-runtime-probation (fly-runtime-probation.timer, every +# 60 s for 30 minutes): a sustained speed failure ends in `fly-runtime fallback "speed: ..."`, the +# same fallback as above under the same lock. `legacy` and every fallback cancel it. `--no-restart` +# (05-deploy's refresh of the drop-in) and `--no-probation` (rehearsals) start none. If the +# probation cannot be started, `session` falls back: an unguarded cutover is not allowed. +# +# `session` also stops a running shadow and its guard (fly-shadow-run stop, no flysim restart) once +# flysim is healthy on the session runtime, so the procedure cannot be done wrong (review N1). +# +# 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 +SHADOW_RUN_BIN="${FLY_SHADOW_RUN_BIN:-$(dirname "$(readlink -f "$0")")/fly-shadow-run}" +PROBATION_BIN="${FLY_PROBATION_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime-probation}" + +log() { echo "fly-runtime: $*" >&2; } + +# The speed probation's hooks (best effort except `start`, which the caller checks). +probation() { + [ -x "$PROBATION_BIN" ] || return 0 + "$PROBATION_BIN" "$@" || log "fly-runtime-probation $1 failed" +} +die() { log "$*"; exit 1; } + +# CUT-01 (review N1): once flysim runs the session runtime the shadow and its guard are over. The +# guard would judge the session against the legacy baseline and restart flysim on a trip; the +# session writes no trace. Stops both WITHOUT restarting flysim. Best effort, never fails the switch. +stop_shadow() { + if systemctl is-active --quiet flyshadow.service 2>/dev/null \ + || systemctl is-active --quiet flyshadow-guard.timer 2>/dev/null; then + if [ -x "$SHADOW_RUN_BIN" ] && "$SHADOW_RUN_BIN" stop; then + log "the shadow and its guard are stopped (flysim.service not restarted)" + else + log "WARNING: could not stop the shadow; run: fly-shadow-run stop (never with --restart-flysim)" + fi + fi +} + +usage() { + echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] [--no-probation] | 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 + probation cancel --quiet + 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 +probe=1 +fallback_reason="" +if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi +for arg in "$@"; do + case "$arg" in + --no-restart) restart=0 ;; + --no-fallback) fallback=0 ;; + --no-probation) probe=0 ;; + *) usage ;; + esac +done + +case "$command" in + status) + current + if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi + if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi + systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true + exit 0 + ;; + 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 + stop_shadow + if [ "$probe" -eq 1 ]; then + if [ ! -x "$PROBATION_BIN" ] || ! "$PROBATION_BIN" start; then + log "the speed probation could not be started; an unguarded cutover is not allowed" + if [ "$fallback" -eq 1 ]; then + do_fallback "the speed probation could not be started" || true + fi + exit 1 + fi + log "flysim.service runs the session runtime, on probation: fly-runtime-probation status" + else + log "flysim.service runs the session runtime (no probation)" + fi + exit 0 + fi + switching=0 + 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 +probation cancel +record "legacy (was ${before})" +[ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; } +if restart_and_check; then + 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/bin/fly-runtime-probation b/infra/bin/fly-runtime-probation new file mode 100755 index 0000000..356b68d --- /dev/null +++ b/infra/bin/fly-runtime-probation @@ -0,0 +1,299 @@ +#!/usr/bin/env bash +# infra/bin/fly-runtime-probation -- CUT-01's speed probation after `fly-runtime session`. +# Pushed to /opt/fly/bin by 05-deploy.sh. Root, inside the container. Normally nobody runs it by +# hand: `fly-runtime session` starts it, `fly-runtime legacy` and every fallback cancel it, and +# fly-runtime-probation.timer runs `tick` every 60 s. +# +# fly-runtime-probation start begin a probation (enables and starts the timer) +# fly-runtime-probation cancel end it without a verdict (disables the timer) +# fly-runtime-probation status state, latest samples, result +# fly-runtime-probation tick (timer) one sample and one decision +# fly-runtime-probation simulate CHECKS.jsonl the rule over recorded samples (lint) +# +# Operator decision 2026-09-30: cut over only if the session runtime sustains >= 1.0x real time on +# the release container. Only that box can measure it, so the switch is guarded. The rule: +# - A sample is one fly_realtime_factor mean over 10 one-second reads of flysim's /metrics (the +# same sampling as fly-shadow-run's guard), with fly_lag_seconds and fly_uptime_seconds. +# - Warm-up: a flysim process is not judged before it has been up FLY_PROBATION_WARMUP (300 s: +# the connectome load, the restore, the first minutes). A restart (uptime goes backwards) +# starts the window again; so does a paused or not running fly: it is not judged. +# - Window: the judged samples of the last FLY_PROBATION_WINDOW (600 s), at least +# FLY_PROBATION_MIN_SAMPLES (8). FAIL when the window's MEDIAN realtime factor is below +# FLY_PROBATION_MIN_RTF (0.97), or the lag grew by more than FLY_PROBATION_MAX_LAG_GROWTH +# (30 s) between the start and the end of the window (median of the first and of the last 3 +# samples). The median is the same robust statistic fly-shadow-run's baseline uses: one +# stalled sample, or two, never fails it. +# - PASS when FLY_PROBATION_SECONDS (1800) have passed since `start` and the latest window is +# full and healthy. A probation that cannot fill a window within FLY_PROBATION_MAX_SECONDS +# (7200: a fly that never runs) fails as inconclusive: no proof of 1.0x, no cutover. +# FAIL runs `fly-runtime fallback "speed: ..."` (the ordinary fallback: lock, reason file +# /run/fly/runtime-fellback.json, journal line, flysim.service restarted on legacy). It is retried +# every minute until it succeeds. PASS writes ${RESULT} (passed: true) and disables the timer. +# Nothing judges the speed afterwards: the watchdog and the start-limit fallback are unchanged. +# +# State is ${DIR}/state.json (on disk, so a reboot resumes the probation: the timer is enabled, +# and OnBootSec= runs it after boot); ${DIR}/last.json keeps the last verdict. +set -euo pipefail + +: "${FLY_PROBATION_DIR:=/var/lib/fly/probation}" +: "${FLY_PROBATION_RESULT:=/run/fly/runtime-probation.json}" +: "${FLY_PROBATION_TIMER:=fly-runtime-probation.timer}" +: "${FLY_PROBATION_READS:=10}" +: "${FLY_METRICS_URL:=http://127.0.0.1:9101}" +: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}" +RUNTIME_BIN="${FLY_RUNTIME_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime}" +STATE="$FLY_PROBATION_DIR/state.json" +LAST="$FLY_PROBATION_DIR/last.json" + +log() { echo "fly-runtime-probation: $*" >&2; } +die() { log "$*"; exit 1; } +journal() { + if command -v logger >/dev/null 2>&1; then logger -t fly-runtime -- "probation: $*" || true; fi + log "$*" +} +need_root() { [ "$(id -u)" = 0 ] || die "run as root"; } + +take_lock() { + mkdir -p "$FLY_PROBATION_DIR" + exec 8>>"$FLY_PROBATION_DIR/lock" + flock -w 60 8 || die "could not take $FLY_PROBATION_DIR/lock" +} +drop_lock() { exec 8>&-; } + +# One sample of the live fly: {t, status, rtMean, lag, uptime} (fly-shadow-run's format). +sample() { + python3 - "$FLY_METRICS_URL" "$FLY_CONTROL_URL" "$FLY_PROBATION_READS" <<'PY' +import json, sys, time, urllib.request +metrics_url, control_url, reads = sys.argv[1], sys.argv[2], int(sys.argv[3]) +def metrics(): + text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode() + out = {} + for line in text.splitlines(): + if line.startswith("#"): + continue + parts = line.split() + if len(parts) == 2: + try: + out[parts[0]] = float(parts[1]) + except ValueError: + pass + return out +factors = [] +for i in range(reads): + factors.append(metrics().get("fly_realtime_factor", 0.0)) + if i + 1 < reads: + time.sleep(1) +m = metrics() +try: + status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status") +except Exception: + status = None +print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors), + "lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")})) +PY +} + +PROBATION_PY=' +import json, os, sys +def env(name, default): + return type(default)(os.environ.get(name, default)) +WARMUP = env("FLY_PROBATION_WARMUP", 300.0) +WINDOW = env("FLY_PROBATION_WINDOW", 600.0) +MIN_SAMPLES = env("FLY_PROBATION_MIN_SAMPLES", 8) +MIN_RTF = env("FLY_PROBATION_MIN_RTF", 0.97) +MAX_LAG_GROWTH = env("FLY_PROBATION_MAX_LAG_GROWTH", 30.0) +DURATION = env("FLY_PROBATION_SECONDS", 1800.0) +MAX_SECONDS = env("FLY_PROBATION_MAX_SECONDS", 7200.0) + +def running(s): + return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None + +def median(xs): + xs = sorted(xs) + n = len(xs) + return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2 + +def step(state, s): + """Returns (state, verdict, detail): verdict is wait, ok, pass or fail.""" + started = state["startedAt"] + history = state.get("history", []) + elapsed = s["t"] - started + if not running(s): + return state, "wait", "flysim is %s: not judged" % s.get("status") + if history and s["uptime"] < history[-1]["uptime"]: + history = [] + if s["uptime"] < WARMUP: + state["history"] = [] + return state, "wait", "warming up (flysim up %.0f of %.0f s)" % (s["uptime"], WARMUP) + history = [h for h in history if h["t"] > s["t"] - WINDOW] + [s] + state["history"] = history + n = len(history) + if n < MIN_SAMPLES: + if elapsed >= MAX_SECONDS: + return state, "fail", "speed: probation inconclusive after %.0f s (%d judged samples in the window): no proof of 1.0x" % (elapsed, n) + return state, "wait", "collecting %d of %d samples" % (n, MIN_SAMPLES) + rtf = median([h["rtMean"] for h in history]) + lag_growth = median([h["lag"] for h in history[-3:]]) - median([h["lag"] for h in history[:3]]) + detail = "median realtime factor %.3f over %d samples, lag growth %+.1f s over %.0f s" % ( + rtf, n, lag_growth, history[-1]["t"] - history[0]["t"]) + state["last"] = {"medianRtf": rtf, "lagGrowth": lag_growth, "samples": n} + why = [] + if rtf < MIN_RTF: + why.append("median realtime factor %.3f < %.2f" % (rtf, MIN_RTF)) + if lag_growth > MAX_LAG_GROWTH: + why.append("lag grew %.1f s > %.0f s" % (lag_growth, MAX_LAG_GROWTH)) + if why: + return state, "fail", "speed: " + ", ".join(why) + " over %d samples / %.0f s" % ( + n, history[-1]["t"] - history[0]["t"]) + if elapsed >= DURATION: + return state, "pass", detail + return state, "ok", detail + " (%.0f of %.0f s)" % (elapsed, DURATION) + +mode = sys.argv[1] +if mode == "step": + state = json.load(open(sys.argv[2])) + state, verdict, detail = step(state, json.loads(sys.argv[3])) + json.dump(state, open(sys.argv[2], "w")) + print(verdict + " " + detail) +elif mode == "simulate": + samples = [json.loads(l) for l in open(sys.argv[2]) if l.strip()] + state = {"startedAt": samples[0]["t"] - 60, "history": []} + verdict, detail = "wait", "" + for n, s in enumerate(samples, 1): + state, verdict, detail = step(state, s) + if verdict in ("pass", "fail"): + print("%s at check %d: %s" % (verdict, n, detail)) + sys.exit(0 if verdict == "pass" else 1) + print("undecided after %d checks: %s %s" % (len(samples), verdict, detail)) + sys.exit(3) +' + +now_iso() { date -u '+%Y-%m-%dT%H:%M:%SZ'; } + +enabled_timer() { systemctl "$1" --now "$FLY_PROBATION_TIMER" >/dev/null 2>&1; } + +start() { + need_root + take_lock + mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true + rm -f "$FLY_PROBATION_RESULT" + printf '{"startedAt":%s,"startedAtIso":"%s","history":[]}\n' "$(date +%s.%N)" "$(now_iso)" >"$STATE.tmp.$$" + mv -f "$STATE.tmp.$$" "$STATE" + if ! enabled_timer enable; then + rm -f "$STATE" + die "could not enable --now $FLY_PROBATION_TIMER (is the unit installed?)" + fi + journal "started: ${FLY_PROBATION_SECONDS:-1800} s, median realtime factor >= ${FLY_PROBATION_MIN_RTF:-0.97} over ${FLY_PROBATION_WINDOW:-600} s after ${FLY_PROBATION_WARMUP:-300} s warm-up, lag growth <= ${FLY_PROBATION_MAX_LAG_GROWTH:-30} s; else fallback to legacy" +} + +cancel() { + local quiet=0 + [ "${1:-}" = --quiet ] && quiet=1 + need_root + take_lock + local had=0 + if [ -f "$STATE" ]; then had=1; fi + rm -f "$STATE" "$FLY_PROBATION_RESULT" + enabled_timer disable || true + if [ "$had" -eq 1 ] || [ "$quiet" -eq 0 ]; then journal "cancelled"; fi +} + +# The verdict, persisted in last.json (and in ${RESULT} on a pass). +finish() { # passed(true|false) detail state-file + local tmp="$LAST.tmp.$$" + python3 - "$1" "$2" "$3" >"$tmp" <<'PY' +import json, sys, datetime +passed, detail = sys.argv[1] == "true", sys.argv[2] +st = {} +try: + st = json.load(open(sys.argv[3])) +except Exception: + pass +out = {"passed": passed, "at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "startedAt": st.get("startedAtIso"), "detail": detail} +out.update(st.get("last", {})) +print(json.dumps(out)) +PY + mv -f "$tmp" "$LAST" + if [ "$1" = true ]; then + mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true + cp -f "$LAST" "$FLY_PROBATION_RESULT" + fi +} + +tick() { + need_root + local sample_json="" now out verdict detail rc + if [ "${1:-}" = --sample-json ]; then sample_json="$2"; fi # the test seam: a recorded sample + if [ ! -f "$STATE" ]; then + log "no probation: disabling $FLY_PROBATION_TIMER" + enabled_timer disable || true + exit 0 + fi + # Only the session runtime is judged: a fallback, a legacy switch or a deploy that removed the + # drop-in ended it. + if [ "$("$RUNTIME_BIN" status 2>/dev/null | head -n1)" != session ]; then + journal "the session runtime is not selected; probation ends" + cancel --quiet + exit 0 + fi + if [ -n "$sample_json" ]; then now="$sample_json"; else now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }; fi + take_lock + [ -f "$STATE" ] || { log "cancelled while sampling"; exit 0; } + rc=0 + out="$(python3 -c "$PROBATION_PY" step "$STATE" "$now")" || rc=$? + [ "$rc" -eq 0 ] || die "probation rule failed: $out" + verdict="${out%% *}" + detail="${out#* }" + case "$verdict" in + wait|ok) drop_lock; log "$verdict: $detail" ;; + pass) + finish true "$detail" "$STATE" + rm -f "$STATE" + enabled_timer disable || true + journal "PASSED: $detail" + ;; + fail) + cp -f "$STATE" "$STATE.failed.$$" + drop_lock + journal "FAILED: $detail; falling back to legacy" + if "$RUNTIME_BIN" fallback "$detail"; then + take_lock + finish false "$detail" "$STATE.failed.$$" + rm -f "$STATE" "$STATE.failed.$$" + enabled_timer disable || true + else + rm -f "$STATE.failed.$$" + log "fallback did not complete; probation stays and retries in a minute" + exit 1 + fi + ;; + *) die "unexpected verdict: $out" ;; + esac +} + +status() { + if [ -f "$STATE" ]; then + python3 - "$STATE" <<'PY' +import json, sys +s = json.load(open(sys.argv[1])) +print("probation running since %s; %d judged samples in the window; last %s" % ( + s.get("startedAtIso"), len(s.get("history", [])), json.dumps(s.get("last")))) +PY + else + echo "no probation running" + fi + if [ -f "$LAST" ]; then echo "last verdict: $(cat "$LAST")"; fi + if [ -f "$FLY_PROBATION_RESULT" ]; then echo "passed: $FLY_PROBATION_RESULT"; fi +} + +cmd="${1:-}" +[ $# -gt 0 ] && shift +case "$cmd" in + start) start ;; + cancel) cancel "$@" ;; + tick) tick "$@" ;; + status) status ;; + simulate) [ $# = 1 ] || die "simulate CHECKS.jsonl"; python3 -c "$PROBATION_PY" simulate "$1" ;; + *) echo "usage: fly-runtime-probation start|cancel|status|tick|simulate CHECKS.jsonl" >&2; exit 2 ;; +esac diff --git a/infra/bin/fly-shadow-run b/infra/bin/fly-shadow-run new file mode 100755 index 0000000..18195ca --- /dev/null +++ b/infra/bin/fly-shadow-run @@ -0,0 +1,437 @@ +#!/usr/bin/env bash +# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release +# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the +# container, by the coordinator, with the container claimed in the host's agent claim log (one +# agent at a time). +# +# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service +# and the live-impact guard, restart flysim once +# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next +# restart; --restart-flysim restarts it now), remove trace and spool +# fly-shadow-run status the verdict in one screen +# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover +# into the release /opt/fly/current points to, onto flysim-session +# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim +# without the trace if the live fly pays for the shadow +# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples +# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give +# +# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once, +# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the +# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can +# only follow a process from that process's own startup save. +# +# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a +# minute, when the shadow's heartbeat (/consumer, every 30 s) is missing or older than +# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file +# it has compared. +# +# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run +# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset +# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed: +# - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means +# of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its +# spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent +# half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a +# step within the window neither sets the baseline nor widens the margin. It refuses to start +# on fewer than half the samples running. +# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim +# process (a restart starts the window again) it compares the mean RTF and the lag growth +# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it +# scales with how noisy this fly already was. +# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below +# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it. +# A paused, booting or recovering fly is not judged. +# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples; +# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/). +# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts +# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow +# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own +# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means +# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart +# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json. +# +# Files (all owned by fly): +# /srv/fly/shadow/trace/trace--.jsonl flysim's per-process trace (4 GiB each, 8 in all) +# /srv/fly/shadow/trace/consumer the shadow's heartbeat +# /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB) +# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract) +# /srv/fly/shadow/divergence.json the first divergence with its context +# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl) +# /srv/fly/shadow/guard-state.json the guard's recent samples +set -euo pipefail + +SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}" +DROPIN_DIR=/etc/systemd/system/flysim.service.d +DROPIN="$DROPIN_DIR/shadow-trace.conf" +BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}" +METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}" +CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}" +# The ledger digest period in transitions: about one a second. Every boundary is proved in the +# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work. +LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}" +BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}" + +die() { echo "fly-shadow-run: $*" >&2; exit 2; } +log() { echo "fly-shadow-run: $*"; } + +need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; } + +# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged +# over 10 one-second reads. +sample() { + python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY' +import json, sys, time, urllib.request +metrics_url, control_url = sys.argv[1], sys.argv[2] +def metrics(): + text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode() + out = {} + for line in text.splitlines(): + if line.startswith("#"): + continue + parts = line.split() + if len(parts) == 2: + try: + out[parts[0]] = float(parts[1]) + except ValueError: + pass + return out +factors = [] +for _ in range(10): + factors.append(metrics().get("fly_realtime_factor", 0.0)) + time.sleep(1) +m = metrics() +try: + status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status") +except Exception: + status = None +print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors), + "lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")})) +PY +} + +# The guard's rule, one definition for `baseline`, `decide` and `simulate`. +GUARD_PY=' +import json, math, sys +WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05 + +def running(s): + return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None + +def rate(samples): + """Lag growth per wall second over the longest same-process run of samples.""" + best, run = None, [] + for s in samples: + if run and s["uptime"] < run[-1]["uptime"]: + run = [] + run.append(s) + if len(run) >= 2 and (best is None or len(run) > len(best)): + best = list(run) + if not best or best[-1]["t"] <= best[0]["t"]: + return None + return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"])) + +def baseline(samples): + """Robust statistics of the running samples: a step in the live fly within the window (its own + warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long + as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the + median absolute deviation, which estimates the standard deviation without the step; the lag + growth rate is taken over the most recent half, after any early step.""" + ok = [s for s in samples if running(s)] + if len(ok) < max(3, len(samples) // 2): + raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples))) + recent = ok[len(ok) // 2:] + rtf = sorted(s["rtMean"] for s in ok) + median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2 + dev = sorted(abs(x - median) for x in rtf) + mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2 + sd = 1.4826 * mad + lag_rate = rate(recent) + return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0, + "samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))} + +def decide(base, state, s): + """Returns (state, verdict); the verdict starts with ok or trip.""" + history, run = state.get("history", []), state.get("degradedRun", 0) + if not running(s): + return state, "ok (flysim is %s: not judged)" % s.get("status") + if history and s["uptime"] < history[-1]["uptime"]: + history, run = [], 0 + history = (history + [s])[-WINDOW:] + state = {"history": history, "degradedRun": run} + if len(history) < WINDOW: + state["degradedRun"] = 0 + return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW) + rtf = sum(h["rtMean"] for h in history) / WINDOW + lag_rate = rate(history) or 0.0 + m = base["margin"] + why = [] + if rtf < base["rtfMean"] - m: + why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m)) + if lag_rate > base["lagRate"] + m: + why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m)) + state["degradedRun"] = run + 1 if why else 0 + if state["degradedRun"] >= SUSTAIN: + return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"] + if why: + return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why)) + return state, "ok" + +def load_jsonl(path): + return [json.loads(line) for line in open(path) if line.strip()] + +mode = sys.argv[1] +if mode == "baseline": + print(json.dumps(baseline(load_jsonl(sys.argv[2])))) +elif mode == "decide": + base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3])) + state, verdict = decide(base, state, json.load(open(sys.argv[4]))) + json.dump(state, open(sys.argv[3], "w")) + print(verdict) + sys.exit(1 if verdict.startswith("trip") else 0) +elif mode == "simulate": + base = baseline(load_jsonl(sys.argv[2])) + state, n = {}, 0 + for n, s in enumerate(load_jsonl(sys.argv[3]), 1): + state, verdict = decide(base, state, s) + if verdict.startswith("trip"): + print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base))) + sys.exit(1) + print("no trip over %d checks (baseline %s)" % (n, json.dumps(base))) +' + +# The shadow must never share a CPU with the live fly (review N2): refuse unless the unit's cpuset +# drop-in exists (05-deploy skips every cpuset drop-in when the CT conf and CPUSET disagree) and its +# AllowedCPUs is non-empty and disjoint from flysim.service's. +check_cpuset() { + local dropin="${FLY_SHADOW_CPUSET_DROPIN:-/etc/systemd/system/flyshadow.service.d/cpuset.conf}" + [ -f "$dropin" ] || die "$dropin is missing: flyshadow would run on every CPU, including flysim's. Run 05-deploy with CPUSET set; nothing started" + local shadow_cpus sim_cpus + shadow_cpus="$(systemctl show -p AllowedCPUs --value flyshadow.service 2>/dev/null || true)" + sim_cpus="$(systemctl show -p AllowedCPUs --value flysim.service 2>/dev/null || true)" + [ -n "$shadow_cpus" ] || die "flyshadow.service has an empty AllowedCPUs; nothing started" + [ -n "$sim_cpus" ] || die "flysim.service has an empty AllowedCPUs, so the shadow cannot be kept off it; nothing started" + local overlap rc=0 + overlap="$(python3 -c ' +import sys +def cpus(t): + out = set() + for part in t.replace(",", " ").split(): + a, _, b = part.partition("-") + out.update(range(int(a), int(b or a) + 1)) + return out +try: + both = cpus(sys.argv[1]) & cpus(sys.argv[2]) +except ValueError: + sys.exit(2) +if both: + print(",".join(str(c) for c in sorted(both))) + sys.exit(1) +' "$shadow_cpus" "$sim_cpus" 2>/dev/null)" || rc=$? + case "$rc" in + 0) ;; + 1) die "flyshadow.service AllowedCPUs ($shadow_cpus) overlaps flysim.service's ($sim_cpus) on CPU $overlap; nothing started" ;; + *) die "cannot parse AllowedCPUs (flyshadow '$shadow_cpus', flysim '$sim_cpus'); nothing started" ;; + esac +} + +start() { + need_root + [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01" + systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running" + check_cpuset + install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace" + # A previous run's verdict is kept beside, never read as this run's. + if [ -f "$SHADOW_DIR/verdict.json" ]; then + mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json" + fi + rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json" + log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists" + local n samples base + n=$(( BASELINE_SECONDS / 10 )) + [ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30" + samples="$SHADOW_DIR/baseline-samples.jsonl" + : > "$samples" + for _ in $(seq 1 "$n"); do + sample >> "$samples" || die "could not read flysim's metrics for the baseline" + done + base="$(python3 -c "$GUARD_PY" baseline "$samples")" \ + || die "flysim did not run normally during the baseline; not starting the shadow" + printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json" + printf '{}\n' > "$SHADOW_DIR/guard-state.json" + chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json" + log "baseline: $base" + mkdir -p "$DROPIN_DIR" + cat > "$DROPIN" </dev/null || true + systemctl stop flyshadow.service 2>/dev/null || true + rm -f "$DROPIN" + systemctl daemon-reload + log "stopped the shadow: $1" +} + +stop() { + need_root + local restart_flysim=0 keep=0 + for arg in "$@"; do + case "$arg" in + --restart-flysim) restart_flysim=1 ;; + --keep) keep=1 ;; + *) die "stop: unknown option $arg" ;; + esac + done + stop_all "fly-shadow-run stop" + if [ "$restart_flysim" = 1 ]; then + systemctl restart flysim.service + log "flysim.service restarted without the trace" + else + log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart" + fi + rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" + if [ "$keep" = 0 ]; then + rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work" + find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true + fi + log "the verdict stays in $SHADOW_DIR/verdict.json" +} + +# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit +# waiting out its restart delay, activating/auto-restart, from a stopped one). +unit_state() { + local out active + out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true + active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')" + # An unreadable state is not "stopped": the guard keeps running and judges the fly. + case "$active" in + active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;; + *) printf 'unknown\n' ;; + esac +} + +guard() { + need_root + if [ ! -f "$SHADOW_DIR/baseline.json" ]; then + log "no baseline: nothing to guard" + systemctl stop flyshadow-guard.timer 2>/dev/null || true + exit 0 + fi + # The guard acts only against a shadow that is up or on its way up. One that diverged, passed + # and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and + # flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay + # (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must + # keep running, or the restarted shadow runs unguarded while `check` still allows a cutover + # (SHADOW-01 review round 3, G1-a). + local active_state + active_state="$(unit_state flyshadow.service)" + case "$active_state" in + inactive|failed) + log "flyshadow.service is $active_state: the guard stops itself and changes nothing" + systemctl stop flyshadow-guard.timer 2>/dev/null || true + exit 0 + ;; + esac + [ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json" + local now tmp verdict + now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; } + tmp="$(mktemp)" + printf '%s\n' "$now" > "$tmp" + if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then + rm -f "$tmp" + log "guard: $verdict ($now)" + exit 0 + fi + rm -f "$tmp" + log "guard TRIPPED: $verdict ($now)" + stop_all "guard: $verdict" + rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" + python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \ + "$verdict" "$now" "$SHADOW_DIR/guard-tripped.json" + systemctl restart flysim.service + log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json" +} + +status() { + systemctl is-active flyshadow.service || true + systemctl is-active flyshadow-guard.timer || true + [ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")" + [ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; } + python3 - "$SHADOW_DIR/verdict.json" <<'PY' +import json, sys +v = json.load(open(sys.argv[1])) +c = v["compared"] +print(f"verdict {v['status']}: {v['reason']}") +print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s " + f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}") +print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, " + f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}") +print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}") +print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}") +if v["firstDivergence"]: + print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}") +PY +} + +check() { + # A tripped guard, a shadow that is not running, or a run that no guard watched never allows a + # cutover, whatever the verdict file says: the guard timer must be active and its baseline + # present (G1-a). + if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then + echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))" + exit 1 + fi + if ! systemctl is-active --quiet flyshadow.service; then + echo "cutover refused: flyshadow.service is not running" + exit 1 + fi + if ! systemctl is-active --quiet flyshadow-guard.timer; then + echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)" + exit 1 + fi + if [ ! -f "$SHADOW_DIR/baseline.json" ]; then + echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)" + exit 1 + fi + [ -x "$BIN" ] || die "$BIN is missing" + # The live service's configuration, for its compatibility string. + set -a + # shellcheck disable=SC1091 + . /etc/fly/fly.env + set +a + # The release CUT-01 switches into and the binary it switches to: SERVE-01's service there. + "$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \ + --binary flysim-session "$@" +} + +cmd="${1:-}" +[ $# -gt 0 ] && shift +case "$cmd" in + start) start ;; + stop) stop "$@" ;; + status) status ;; + check) check "$@" ;; + guard) guard ;; + baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;; + simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;; + *) echo "usage: fly-shadow-run start|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;; +esac diff --git a/infra/build/build-flysim.sh b/infra/build/build-flysim.sh index 3a56ca7..1e4a0c5 100755 --- a/infra/build/build-flysim.sh +++ b/infra/build/build-flysim.sh @@ -85,6 +85,13 @@ 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; fly-shadow (SHADOW-01, + # infra/units/flyshadow.service): the session runtime shadowing the live fly; and + # fly-session, their worker program (FLY_SESSION_MODE=process only). Same features as flysim, + # built every time so a release can switch runtimes without a rebuild. All land next to + # OUT_PATH, where package-release.sh looks for them. + RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-shadow --bin fly-session "${features_args[@]}" ) built="${crate_dir}/target/${CARGO_TARGET}/release/flysim" @@ -118,4 +125,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-shadow 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..d7f6521 100755 --- a/infra/build/package-release.sh +++ b/infra/build/package-release.sh @@ -14,6 +14,12 @@ # 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-shadow worker program; mode 0755, when build-flysim.sh left +# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses +# a release without flysim-session. fly-shadow is +# SHADOW-01's shadow; flyshadow.service stays inactive +# on a release without it) # 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 +88,18 @@ 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-shadow 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 + case "$extra" in + fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;; + *) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;; + esac + 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..3d8047c 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -443,6 +443,249 @@ 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 (starts the speed probation) +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. + +## Shadow run (SHADOW-01) + +The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The +contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is +report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim +the release container in the host log first, as for any host work. + +``` +pct exec -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, shadow + guard, one flysim restart +pct exec -- /opt/fly/bin/fly-shadow-run status # the verdict (and a guard trip) in one screen +pct exec -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed +pct exec -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off +``` + +- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty + 10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth + rate. It refuses unless flysim ran normally for most of that time. Then it: + 1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`, + `FLY_TRACE_LEDGERS=60`); + 2. starts `flyshadow.service` and waits for its heartbeat; + 3. restarts `flysim.service` once; + 4. starts `flyshadow-guard.timer`. + + `FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. The restart is the same one + the unstick rule uses: the rung is kept and the ledgers are cleared. A previous `verdict.json` + is kept beside the new one, renamed with its time. +- **The guard** runs every 60 s, automatically, and judges the live fly against its own baseline, + not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a + sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process + fall below the baseline, or grow lag faster than it, by more than the margin. The margin is + max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a + real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and + restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and + `status` shows it. A paused fly is not judged, and a restarted one starts its window again. + Once the shadow is down for good (`ActiveState` inactive or failed: diverged, stopped, given up), + the guard stops itself and changes nothing. While the shadow waits out its 10-s crash-restart delay + (`activating`) the guard keeps running. A trip is not a divergence: fix the resources, then `start` again. +- **While it runs**, every later flysim restart (the unstick rule, the watchdog, + `fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on + its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes. + Stopping or restarting `flyshadow.service` itself starts the window again. +- **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence: + - 10,800 brain seconds are compared; + - at least one live save per 10 brain minutes has been compared byte for byte. + + The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01 + runs `check` at the moment it cuts over. `check` also requires all of these: + - at least 10,800 brain seconds, whatever window the shadow was started with; + - the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and + `baseline.json` exists (a run no guard watched is never cut over); + - the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every + other shadowed binary unchanged; + - the shadow is caught up (at most about a minute behind); + - the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future + (a clock stepped back must not keep an old pass fresh); + - no segment was skipped for a reason other than the live side's own. +- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure + of the session runtime itself counts: it did not start, the restore gate refused the live save, + or a step failed. The shadow leaves `verdict.json` at `diverged` and + `/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it. + On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so + flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the + files for the review, and do not cut over. +- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh + heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the + heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was + stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow + deletes every file it has compared. +- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame. It + runs `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh writes its + `cpuset.conf`). It pauses for a minute while flysim's lag grows faster than its baseline rate, and + it stops pausing when a pause does not help. Disk: about + 160 MB of trace per live hour, and a spool of at most 512 MiB. +- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the + unit's `AllowedCPUs` (`systemctl show`) is disjoint from flysim.service's (05-deploy skips every + cpuset drop-in when the CT conf and CPUSET disagree). +- **Stop** stops the unit and the guard, removes the drop-in, and deletes the trace and the spool + (`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace + within a minute, because its consumer is gone. + +## Cutover to the session runtime (CUT-01) + +Operator decision (2026-09-30): the stream moves to the session runtime only if that runtime +sustains at least 1.0x real time on the release container, otherwise it stays on legacy. Only the +release container can measure that, so the switch is guarded by a **probation**. Claim the +container in the host log first, as for any host work. + +``` +# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy. +# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy) +# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact: +pct exec $CTID -- /opt/fly/bin/fly-shadow-run start +pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass +# 3. Cutover: the shadow's gate, then the switch. One command line: +pct exec $CTID -- sh -c '/opt/fly/bin/fly-shadow-run check && /opt/fly/bin/fly-runtime session' +# 4. Watch the probation (30 minutes after the switch): +pct exec $CTID -- /opt/fly/bin/fly-runtime-probation status +pct exec $CTID -- /opt/fly/bin/fly-runtime status +# 5. Pass, or automatic fallback (below). Nothing to stop: step 3 already stopped the shadow. +# Manual rollback, any time (cancels the probation too): +pct exec $CTID -- /opt/fly/bin/fly-runtime legacy +``` + +- **Step 3 in detail.** `check` refuses unless the verdict, the guard and the release all line + up (Shadow run above). `session` then does what "Switch the runtime" describes (compatibility + check, drop-in, restart, health wait) and, once flysim is healthy on the session runtime, starts + the probation. `session` returns 0 at that point: the probation is judged later, by the timer. + `session` also stops the shadow and its guard (`fly-shadow-run stop`, never + `--restart-flysim`) as soon as flysim is healthy on the session runtime, before the probation + starts. A guard left running would judge the session runtime against the legacy baseline and + restart flysim on a trip (a second start inside the 600 s start-limit window, and a reset + warm-up), and the session writes no trace, so the shadow has nothing to follow. If you stop the + shadow by hand at any time during the probation, do it without `--restart-flysim`. +- **The probation** (`infra/bin/fly-runtime-probation`, `fly-runtime-probation.timer` every 60 s, + root). Each tick takes one sample of flysim's `/metrics` (`fly_realtime_factor` averaged over 10 + one-second reads, `fly_lag_seconds`, `fly_uptime_seconds`; the same sampling as the shadow + guard). It judges the session runtime only: + - *Warm-up.* A flysim process is not judged before it has been up 300 s (connectome load, + restore, first minutes). A restart, a pause or a fly that is not `running` starts the window + again; it is never counted as slow. + - *Failure*, sustained and not one sample: over the judged samples of the last 10 minutes (at + least 8 of them) the **median** realtime factor is below **0.97**, or the lag grew by more than + **30 s** from the window's start to its end (median of the first and of the last three + samples). The median is the robust statistic the shadow guard's baseline uses: one or two + stalled minutes do not fail it, a steady 0.85x does, at the earliest about 13 minutes after the + switch (5 min warm-up, 8 samples). A lag step of more than 30 s inside the window counts as + lag growth. + - *Pass*: 30 minutes since the switch, and the latest window is full and healthy. A probation + that cannot fill a window within 2 h (a fly that never runs) fails as inconclusive: no proof + of 1.0x, no cutover. `FLY_PROBATION_*` variables tune every number (tests and rehearsals only). + - **On failure** it runs `fly-runtime fallback "speed: ..."`, exactly the fallback of "Switch + the runtime": under the same lock, `/run/fly/runtime-fellback.json` with the reason + (`"speed: median realtime factor 0.850 < 0.97 ..."`), the drop-in removed, flysim restarted on + legacy, a `fly-runtime` journal line (`journalctl -t fly-runtime`, + `/var/lib/fly/runtime.log`), and the probation ended (`/var/lib/fly/probation/last.json` + says `passed: false`). If that fallback cannot complete (no executable `flysim`) it is retried + every minute. The container is then on legacy and the decision is "no cutover": do not retry + `session` without a fix (or a new measurement) for the cause. + - **On pass** it writes `/run/fly/runtime-probation.json` (`{"passed": true, "at", "startedAt", + "medianRtf", "lagGrowth", "samples", "detail"}`; also kept in + `/var/lib/fly/probation/last.json` because `/run` is cleared by a reboot) and disables its + timer. **Nothing judges the speed afterwards.** A continuous guard would make a passing + cutover fall back at 03:00 on one noisy hour, on a stream that has proven itself, and the + watchdog already covers a stuck or dead loop. The start-limit fallback also stays as it is. +- **Cancel and resume.** `fly-runtime legacy` cancels the probation, as does every fallback + (including the start-limit one), and a tick that finds the legacy runtime selected ends it + without a verdict. The state is `/var/lib/fly/probation/state.json` and the timer is enabled while + a probation runs (`[Install] WantedBy=timers.target`; nothing else enables it), so a reboot + during the probation resumes it: `OnBootSec=90s` runs the first tick, flysim's new process + starts a new warm-up and window, and the 30 minutes keep counting from the original switch. + `fly-runtime session --no-restart` (05-deploy's refresh of the drop-in) starts no probation; + `fly-runtime session --no-probation` is for rehearsals. A `session` that cannot start the + probation (helper or timer unit missing) falls back: an unguarded cutover is not allowed. +- **Reading the result honestly.** The probation is absolute, as decided: a container on which the + legacy loop itself runs below 0.97x (the release container has been measured at 0.66, and 0.77-0.99 + after its cpuset rebalance) will fail it, and the session runtime was measured at 1.25-1.35x + legacy's time per frame on the dev box. A fallback with reason `speed` therefore means "this box + cannot hold real time on the session runtime", not necessarily "the session runtime is + broken"; compare with `fly-shadow-run`'s baseline (`/srv/fly/shadow/baseline.json`) before + anything else. The `check` before it measures the live fly against itself; this measures it + against the clock. +- **Rehearsal** without a host: `fly-runtime-probation simulate CHECKS.jsonl` runs the rule over + recorded samples (`{t, status, rtMean, lag, uptime}`, one a minute); `infra/tests/lint.sh` drives + the real `fly-runtime` and the probation over synthetic traces (healthy, 0.85x, a stall, lag + growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real + systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume). + ## CPU partition (cpuset) `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit diff --git a/infra/tests/fixtures/shadow-guard/README.md b/infra/tests/fixtures/shadow-guard/README.md new file mode 100644 index 0000000..89c6939 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/README.md @@ -0,0 +1,19 @@ +# Recorded live-fly samples for `fly-shadow-run`'s guard + +These samples come from a real `flysim` (legacy, FAFB, macros mode, at real time) on a shared build +box on 2026-09-30. They are in `fly-shadow-run`'s own format and cadence: + +- `baseline.jsonl` holds 60 samples 10 s apart; +- `checks.jsonl` holds 20 samples a minute apart, after the same flysim restart that `start` does. + +`lint.sh` runs `fly-shadow-run simulate` over each case and holds it to `expect`: + +| Case | Setup | Expect | +| --- | --- | --- | +| `slow-alone` | 1 cpu, 1 thread; no shadow | pass | +| `slow-shadow-same` | the same fly, with a real `fly-shadow` following it at normal priority on the same cpu. The live fly dropped from 0.66 to 0.44-0.60 | trip | +| `fast-shadow-idle` | 3 cpus, 3 threads; a real `fly-shadow` at `SCHED_IDLE` on other cpus. The box was already loaded, and the fly ran at 0.4-0.85 | pass | +| `fast-alone` | 3 cpus, 3 threads; no shadow | pass | + +The box's own load moved the fly between 0.4 and 1.0 during some baselines. Those steps are why +the baseline is robust: the median, and the spread taken as the MAD. diff --git a/infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl b/infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl new file mode 100644 index 0000000..dc279df --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-alone/baseline.jsonl @@ -0,0 +1,60 @@ +{"t": 1790738128.362942, "status": "running", "rtMean": 0.7588339770286441, "lag": 33.479, "uptime": 71.223399881} +{"t": 1790738138.4285393, "status": "running", "rtMean": 1.0036906365382738, "lag": 33.479, "uptime": 81.293069051} +{"t": 1790738148.4962938, "status": "running", "rtMean": 0.9970303099114692, "lag": 33.479, "uptime": 91.408291997} +{"t": 1790738158.5748143, "status": "running", "rtMean": 0.9957513747669762, "lag": 33.479, "uptime": 101.483131764} +{"t": 1790738168.9591897, "status": "running", "rtMean": 0.819013893871745, "lag": 35.496, "uptime": 111.869185712} +{"t": 1790738179.0497794, "status": "running", "rtMean": 0.955720505211804, "lag": 35.496, "uptime": 121.957242118} +{"t": 1790738189.13739, "status": "running", "rtMean": 0.8799930137133124, "lag": 36.498, "uptime": 132.018380479} +{"t": 1790738199.2148638, "status": "running", "rtMean": 0.8902680060117365, "lag": 37.521, "uptime": 142.113434378} +{"t": 1790738209.3021023, "status": "running", "rtMean": 0.8803874146669992, "lag": 38.524, "uptime": 152.181022738} +{"t": 1790738219.3764796, "status": "running", "rtMean": 0.8658710279839296, "lag": 40.54, "uptime": 162.284831945} +{"t": 1790738229.4663715, "status": "running", "rtMean": 0.8894453486450183, "lag": 41.541, "uptime": 172.367967371} +{"t": 1790738239.553954, "status": "running", "rtMean": 0.9052554309116678, "lag": 42.543, "uptime": 182.460932044} +{"t": 1790738249.6388013, "status": "running", "rtMean": 0.9129316585556161, "lag": 43.544, "uptime": 192.526870399} +{"t": 1790738259.7050216, "status": "running", "rtMean": 0.9999965689074697, "lag": 43.544, "uptime": 202.609470103} +{"t": 1790738269.7767544, "status": "running", "rtMean": 0.9378600900744024, "lag": 43.544, "uptime": 212.690426315} +{"t": 1790738279.8516681, "status": "running", "rtMean": 0.7973579434723355, "lag": 45.556, "uptime": 222.761268128} +{"t": 1790738289.9210968, "status": "running", "rtMean": 0.9352522067409303, "lag": 46.571, "uptime": 232.836669514} +{"t": 1790738300.0552127, "status": "running", "rtMean": 0.7150556877963433, "lag": 49.584, "uptime": 242.963564523} +{"t": 1790738310.2007082, "status": "running", "rtMean": 1.0059437251512073, "lag": 49.584, "uptime": 253.109498917} +{"t": 1790738320.2790272, "status": "running", "rtMean": 1.00373183915971, "lag": 49.584, "uptime": 263.195154054} +{"t": 1790738330.3444412, "status": "running", "rtMean": 0.9972521469939926, "lag": 49.584, "uptime": 273.255265175} +{"t": 1790738340.4204133, "status": "running", "rtMean": 0.8495939168264007, "lag": 50.586, "uptime": 283.330032566} +{"t": 1790738350.5301325, "status": "running", "rtMean": 0.7839208383476353, "lag": 52.599, "uptime": 293.439062795} +{"t": 1790738360.6693776, "status": "running", "rtMean": 0.9653471893141468, "lag": 53.6, "uptime": 303.576346295} +{"t": 1790738370.8137631, "status": "running", "rtMean": 0.6241158180206947, "lag": 57.623, "uptime": 313.699656832} +{"t": 1790738380.9961703, "status": "running", "rtMean": 0.5687473149333804, "lag": 61.68, "uptime": 323.912074763} +{"t": 1790738391.089262, "status": "running", "rtMean": 0.5804323097526403, "lag": 65.706, "uptime": 333.967914558} +{"t": 1790738401.19394, "status": "running", "rtMean": 0.5362910197658861, "lag": 70.779, "uptime": 344.048343544} +{"t": 1790738411.3023837, "status": "running", "rtMean": 0.5510464052357773, "lag": 74.845, "uptime": 354.205680506} +{"t": 1790738421.4007213, "status": "running", "rtMean": 0.5652293538813947, "lag": 79.905, "uptime": 364.315364667} +{"t": 1790738431.503473, "status": "running", "rtMean": 0.57359026862898, "lag": 83.964, "uptime": 374.377908576} +{"t": 1790738441.6479023, "status": "running", "rtMean": 0.5540343187796515, "lag": 87.999, "uptime": 384.55919851} +{"t": 1790738451.7651033, "status": "running", "rtMean": 0.6037429716311573, "lag": 92.018, "uptime": 394.673360423} +{"t": 1790738461.8663146, "status": "running", "rtMean": 0.6985130182613225, "lag": 95.095, "uptime": 404.755070174} +{"t": 1790738471.9642298, "status": "running", "rtMean": 0.7594984860121092, "lag": 98.14, "uptime": 414.851205955} +{"t": 1790738482.0506132, "status": "running", "rtMean": 0.8166532570546075, "lag": 99.145, "uptime": 424.958463239} +{"t": 1790738492.1384304, "status": "running", "rtMean": 0.8807780226062987, "lag": 100.145, "uptime": 434.992925627} +{"t": 1790738502.2033277, "status": "running", "rtMean": 1.0802703218851182, "lag": 100.145, "uptime": 445.108112717} +{"t": 1790738512.273309, "status": "running", "rtMean": 0.9857221768324773, "lag": 100.145, "uptime": 455.179728346} +{"t": 1790738522.3412535, "status": "running", "rtMean": 1.0008941796078314, "lag": 100.145, "uptime": 465.243065017} +{"t": 1790738532.4065015, "status": "running", "rtMean": 1.0144037951650158, "lag": 100.145, "uptime": 475.316217749} +{"t": 1790738542.4878814, "status": "running", "rtMean": 0.995240358864496, "lag": 100.145, "uptime": 485.400446119} +{"t": 1790738552.5522985, "status": "running", "rtMean": 0.9958695819760208, "lag": 100.145, "uptime": 495.331048011} +{"t": 1790738562.6135433, "status": "running", "rtMean": 0.9990484834746928, "lag": 100.145, "uptime": 505.518260558} +{"t": 1790738572.6848962, "status": "running", "rtMean": 0.9999101070487516, "lag": 100.145, "uptime": 515.603359756} +{"t": 1790738582.7517495, "status": "running", "rtMean": 1.0067915374872096, "lag": 100.145, "uptime": 525.63843004} +{"t": 1790738592.8203006, "status": "running", "rtMean": 0.9933226593909843, "lag": 100.145, "uptime": 535.714625602} +{"t": 1790738602.8871908, "status": "running", "rtMean": 0.9997146956682066, "lag": 100.145, "uptime": 545.76592055} +{"t": 1790738612.9580173, "status": "running", "rtMean": 0.9995574815559497, "lag": 100.145, "uptime": 555.842376949} +{"t": 1790738623.0309892, "status": "running", "rtMean": 1.0009077839472587, "lag": 100.145, "uptime": 565.932440918} +{"t": 1790738633.1058488, "status": "running", "rtMean": 0.905700103566834, "lag": 101.148, "uptime": 576.014824329} +{"t": 1790738643.2241693, "status": "running", "rtMean": 0.9002632818253182, "lag": 102.159, "uptime": 586.12547679} +{"t": 1790738653.3037221, "status": "running", "rtMean": 1.001384402969126, "lag": 102.159, "uptime": 596.212798092} +{"t": 1790738663.377194, "status": "running", "rtMean": 1.0025847949946505, "lag": 102.159, "uptime": 606.291720522} +{"t": 1790738673.450081, "status": "running", "rtMean": 0.9982495351402143, "lag": 102.159, "uptime": 616.368169968} +{"t": 1790738683.5147092, "status": "running", "rtMean": 1.000470259093377, "lag": 102.159, "uptime": 626.427550974} +{"t": 1790738693.5863135, "status": "running", "rtMean": 0.9966639708181871, "lag": 102.159, "uptime": 636.458204371} +{"t": 1790738703.651422, "status": "running", "rtMean": 0.9994712074317433, "lag": 102.159, "uptime": 646.54138456} +{"t": 1790738713.7201247, "status": "running", "rtMean": 0.9965700494189607, "lag": 102.159, "uptime": 656.631814013} +{"t": 1790738723.7912498, "status": "running", "rtMean": 1.0007973265331749, "lag": 102.159, "uptime": 666.694264297} diff --git a/infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl b/infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl new file mode 100644 index 0000000..a7feb68 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-alone/checks.jsonl @@ -0,0 +1,20 @@ +{"t": 1790738735.0354905, "status": "running", "rtMean": 0.999484237762719, "lag": 0.0, "uptime": 11.07355663} +{"t": 1790738795.1101537, "status": "running", "rtMean": 0.998153021033785, "lag": 0.0, "uptime": 71.129215866} +{"t": 1790738855.1800184, "status": "running", "rtMean": 0.9926228160612285, "lag": 0.0, "uptime": 131.202241399} +{"t": 1790738915.249556, "status": "running", "rtMean": 0.9992177109183569, "lag": 0.0, "uptime": 191.273914994} +{"t": 1790738975.3090174, "status": "running", "rtMean": 1.0004807207169564, "lag": 0.0, "uptime": 251.312728385} +{"t": 1790739035.3770518, "status": "running", "rtMean": 0.99729025135176, "lag": 0.0, "uptime": 311.41256314} +{"t": 1790739095.4512274, "status": "running", "rtMean": 0.9963104110487839, "lag": 0.0, "uptime": 371.442377297} +{"t": 1790739155.5106263, "status": "running", "rtMean": 0.9986795197502222, "lag": 0.0, "uptime": 431.514951288} +{"t": 1790739215.5753255, "status": "running", "rtMean": 0.998777006263299, "lag": 0.0, "uptime": 491.615126509} +{"t": 1790739275.6377265, "status": "running", "rtMean": 0.9993828850549406, "lag": 0.0, "uptime": 551.643819315} +{"t": 1790739335.6982403, "status": "running", "rtMean": 0.9998689452246822, "lag": 0.0, "uptime": 611.710123532} +{"t": 1790739395.7690253, "status": "running", "rtMean": 1.0066090326463777, "lag": 0.0, "uptime": 671.806084883} +{"t": 1790739455.8361878, "status": "running", "rtMean": 0.9991477060779191, "lag": 0.0, "uptime": 731.837495033} +{"t": 1790739515.8999934, "status": "running", "rtMean": 0.9968497132252894, "lag": 0.0, "uptime": 791.918687829} +{"t": 1790739575.9599848, "status": "running", "rtMean": 0.9993416499626159, "lag": 0.0, "uptime": 851.966694729} +{"t": 1790739636.031231, "status": "running", "rtMean": 0.9997509681411471, "lag": 0.0, "uptime": 912.047324838} +{"t": 1790739696.1082256, "status": "running", "rtMean": 0.9993880587210896, "lag": 0.0, "uptime": 972.143571488} +{"t": 1790739756.1715124, "status": "running", "rtMean": 0.9978257533955007, "lag": 0.0, "uptime": 1032.192931507} +{"t": 1790739816.2371426, "status": "running", "rtMean": 1.0003866207887322, "lag": 0.0, "uptime": 1092.269950437} +{"t": 1790739876.297765, "status": "running", "rtMean": 0.9997339122145353, "lag": 0.0, "uptime": 1152.311864977} diff --git a/infra/tests/fixtures/shadow-guard/fast-alone/expect b/infra/tests/fixtures/shadow-guard/fast-alone/expect new file mode 100644 index 0000000..2ae2839 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-alone/expect @@ -0,0 +1 @@ +pass diff --git a/infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl new file mode 100644 index 0000000..fb279f7 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/baseline.jsonl @@ -0,0 +1,60 @@ +{"t": 1790736255.1832466, "status": "running", "rtMean": 0.44899475378270337, "lag": 40.531, "uptime": 71.111642723} +{"t": 1790736265.3486006, "status": "running", "rtMean": 0.40737226174421837, "lag": 46.58, "uptime": 81.296028671} +{"t": 1790736275.462523, "status": "running", "rtMean": 0.43926524622884744, "lag": 51.607, "uptime": 91.41614284} +{"t": 1790736285.5483737, "status": "running", "rtMean": 0.4992672422167786, "lag": 57.668, "uptime": 101.49334599} +{"t": 1790736295.691844, "status": "running", "rtMean": 0.4722833612045654, "lag": 62.729, "uptime": 111.631919513} +{"t": 1790736305.8359153, "status": "running", "rtMean": 0.49364414852989763, "lag": 67.756, "uptime": 121.766530366} +{"t": 1790736316.0044537, "status": "running", "rtMean": 0.4592358802945983, "lag": 72.814, "uptime": 131.934151579} +{"t": 1790736326.1091528, "status": "running", "rtMean": 0.4414601438247983, "lag": 78.84, "uptime": 142.0534588} +{"t": 1790736336.2525842, "status": "running", "rtMean": 0.4540765983005316, "lag": 83.88, "uptime": 152.198379259} +{"t": 1790736346.4600585, "status": "running", "rtMean": 0.4173426800525677, "lag": 89.957, "uptime": 162.413446602} +{"t": 1790736356.5611305, "status": "running", "rtMean": 0.4606621035712305, "lag": 96.016, "uptime": 172.491203687} +{"t": 1790736366.7702422, "status": "running", "rtMean": 0.46203321509514217, "lag": 101.071, "uptime": 182.696019242} +{"t": 1790736376.9394329, "status": "running", "rtMean": 0.4863329297033063, "lag": 106.126, "uptime": 192.889038592} +{"t": 1790736387.0649624, "status": "running", "rtMean": 0.4495199219435465, "lag": 112.232, "uptime": 203.013465866} +{"t": 1790736397.1682742, "status": "running", "rtMean": 0.42863654848005284, "lag": 118.286, "uptime": 213.12621802} +{"t": 1790736407.2758026, "status": "running", "rtMean": 0.4139101392220675, "lag": 123.367, "uptime": 223.208709667} +{"t": 1790736417.43286, "status": "running", "rtMean": 0.43302060621434524, "lag": 129.445, "uptime": 233.357393123} +{"t": 1790736427.5712192, "status": "running", "rtMean": 0.43801120859089393, "lag": 135.505, "uptime": 243.507406013} +{"t": 1790736437.7151752, "status": "running", "rtMean": 0.4402615997407782, "lag": 140.554, "uptime": 253.661724645} +{"t": 1790736447.85799, "status": "running", "rtMean": 0.48112727487436235, "lag": 146.635, "uptime": 263.813400946} +{"t": 1790736458.0452223, "status": "running", "rtMean": 0.4318712743090674, "lag": 151.707, "uptime": 273.954505321} +{"t": 1790736468.1886797, "status": "running", "rtMean": 0.42247469989908265, "lag": 157.751, "uptime": 284.121781118} +{"t": 1790736478.3070867, "status": "running", "rtMean": 0.414255858741203, "lag": 163.851, "uptime": 294.242313229} +{"t": 1790736488.4334955, "status": "running", "rtMean": 0.42798509497809467, "lag": 169.928, "uptime": 304.374179381} +{"t": 1790736498.598869, "status": "running", "rtMean": 0.6973435620918129, "lag": 171.95, "uptime": 314.520569518} +{"t": 1790736508.6862988, "status": "running", "rtMean": 0.8506385364177339, "lag": 173.964, "uptime": 324.645689838} +{"t": 1790736518.7639382, "status": "running", "rtMean": 0.6393757799420648, "lag": 176.98, "uptime": 334.702167477} +{"t": 1790736528.8444629, "status": "running", "rtMean": 0.7563780548037421, "lag": 179.995, "uptime": 344.767409573} +{"t": 1790736538.9335213, "status": "running", "rtMean": 0.7299449362518324, "lag": 183.099, "uptime": 354.892773648} +{"t": 1790736549.0587013, "status": "running", "rtMean": 0.7495898580324455, "lag": 185.1, "uptime": 365.018206452} +{"t": 1790736559.125795, "status": "running", "rtMean": 0.7466250548943967, "lag": 188.191, "uptime": 375.072270628} +{"t": 1790736569.2290745, "status": "running", "rtMean": 0.7135159366386999, "lag": 191.217, "uptime": 385.16395309} +{"t": 1790736579.3221574, "status": "running", "rtMean": 0.6444057032246826, "lag": 194.311, "uptime": 395.24551542} +{"t": 1790736589.387774, "status": "running", "rtMean": 0.7078500629057103, "lag": 197.356, "uptime": 405.328315223} +{"t": 1790736599.457208, "status": "running", "rtMean": 0.7724222621426244, "lag": 199.41, "uptime": 415.395630334} +{"t": 1790736609.5669358, "status": "running", "rtMean": 0.7238637707089501, "lag": 202.432, "uptime": 425.523861591} +{"t": 1790736619.667222, "status": "running", "rtMean": 0.636988015566429, "lag": 206.491, "uptime": 435.596000401} +{"t": 1790736629.7565455, "status": "running", "rtMean": 0.6846194839249449, "lag": 209.511, "uptime": 445.705233095} +{"t": 1790736639.9320571, "status": "running", "rtMean": 0.5775285955158141, "lag": 213.527, "uptime": 455.875805326} +{"t": 1790736650.1127295, "status": "running", "rtMean": 0.6874672985502784, "lag": 216.574, "uptime": 466.047794887} +{"t": 1790736660.23605, "status": "running", "rtMean": 0.7980788454806589, "lag": 218.599, "uptime": 476.191578571} +{"t": 1790736670.3181207, "status": "running", "rtMean": 0.8373465907575423, "lag": 220.629, "uptime": 486.259561672} +{"t": 1790736680.5240602, "status": "running", "rtMean": 0.5739965775984952, "lag": 224.72, "uptime": 496.479775337} +{"t": 1790736690.6629243, "status": "running", "rtMean": 0.5286072075517942, "lag": 229.778, "uptime": 506.594493598} +{"t": 1790736700.8302114, "status": "running", "rtMean": 0.6743407053708753, "lag": 232.792, "uptime": 516.784837195} +{"t": 1790736710.9810565, "status": "running", "rtMean": 0.4833175202797613, "lag": 237.843, "uptime": 526.927338551} +{"t": 1790736721.1076307, "status": "running", "rtMean": 0.5049205359243616, "lag": 242.912, "uptime": 537.054603691} +{"t": 1790736731.2034523, "status": "running", "rtMean": 0.4861911891792873, "lag": 248.95, "uptime": 547.101045326} +{"t": 1790736741.3109553, "status": "running", "rtMean": 0.4845765517462596, "lag": 254.061, "uptime": 557.246782973} +{"t": 1790736751.4774404, "status": "running", "rtMean": 0.5333230355802153, "lag": 258.103, "uptime": 567.418066384} +{"t": 1790736761.652144, "status": "running", "rtMean": 0.49627891829609305, "lag": 264.173, "uptime": 577.572329582} +{"t": 1790736771.8544915, "status": "running", "rtMean": 0.5215276573927089, "lag": 268.2, "uptime": 587.79709649} +{"t": 1790736781.9649491, "status": "running", "rtMean": 0.5216891717973449, "lag": 273.234, "uptime": 597.898939598} +{"t": 1790736792.0599647, "status": "running", "rtMean": 0.5310205891816586, "lag": 278.266, "uptime": 607.982986102} +{"t": 1790736802.1870968, "status": "running", "rtMean": 0.49618279364312484, "lag": 283.316, "uptime": 618.117053029} +{"t": 1790736812.290842, "status": "running", "rtMean": 0.49072671618430486, "lag": 288.404, "uptime": 628.23818419} +{"t": 1790736822.4333866, "status": "running", "rtMean": 0.5402747673446865, "lag": 292.418, "uptime": 638.367153256} +{"t": 1790736832.613669, "status": "running", "rtMean": 0.8329938906374317, "lag": 294.42, "uptime": 648.537882771} +{"t": 1790736842.6835933, "status": "running", "rtMean": 0.7430173560600793, "lag": 297.448, "uptime": 658.629022047} +{"t": 1790736852.755823, "status": "running", "rtMean": 0.8578215877131159, "lag": 298.448, "uptime": 668.694834509} diff --git a/infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl new file mode 100644 index 0000000..3196d53 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/checks.jsonl @@ -0,0 +1,20 @@ +{"t": 1790736864.4256852, "status": "running", "rtMean": 0.6099898319965826, "lag": 3.091, "uptime": 11.07909019} +{"t": 1790736924.501681, "status": "running", "rtMean": 0.5411932741082821, "lag": 20.265, "uptime": 71.155545456} +{"t": 1790736984.5807962, "status": "running", "rtMean": 0.7295306018507262, "lag": 35.328, "uptime": 131.199399778} +{"t": 1790737044.6489198, "status": "running", "rtMean": 0.8067884564857175, "lag": 46.47, "uptime": 191.29805351} +{"t": 1790737104.7270966, "status": "running", "rtMean": 0.8192565712279218, "lag": 58.542, "uptime": 251.37716607} +{"t": 1790737164.7932363, "status": "running", "rtMean": 0.8487114702728498, "lag": 69.618, "uptime": 311.44889619} +{"t": 1790737224.91049, "status": "running", "rtMean": 0.42516908835738415, "lag": 101.107, "uptime": 371.522769005} +{"t": 1790737285.0996652, "status": "running", "rtMean": 0.41299332249218484, "lag": 136.493, "uptime": 431.719907398} +{"t": 1790737345.3437996, "status": "running", "rtMean": 0.4410892921905215, "lag": 171.04, "uptime": 491.980527036} +{"t": 1790737405.5281327, "status": "running", "rtMean": 0.4454430216668691, "lag": 204.353, "uptime": 552.14783058} +{"t": 1790737465.838257, "status": "running", "rtMean": 0.5991416565682315, "lag": 227.769, "uptime": 612.473422449} +{"t": 1790737525.9655414, "status": "running", "rtMean": 0.6857160494879407, "lag": 246.844, "uptime": 672.619024119} +{"t": 1790737586.045057, "status": "running", "rtMean": 0.6537634570200577, "lag": 265.963, "uptime": 732.678449214} +{"t": 1790737646.1301575, "status": "running", "rtMean": 0.6473194011694912, "lag": 290.309, "uptime": 792.775859726} +{"t": 1790737706.2470899, "status": "running", "rtMean": 0.474484017045933, "lag": 319.566, "uptime": 852.890865845} +{"t": 1790737766.4071772, "status": "running", "rtMean": 0.5316840402693012, "lag": 349.947, "uptime": 913.037081082} +{"t": 1790737826.488124, "status": "running", "rtMean": 0.7651768950839182, "lag": 371.253, "uptime": 973.141837869} +{"t": 1790737886.652113, "status": "running", "rtMean": 0.4461005912444415, "lag": 403.681, "uptime": 1033.302886448} +{"t": 1790737946.764796, "status": "running", "rtMean": 0.4610048048396617, "lag": 438.093, "uptime": 1093.383696514} +{"t": 1790738006.857649, "status": "running", "rtMean": 0.44882468186134916, "lag": 471.382, "uptime": 1153.477095415} diff --git a/infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect new file mode 100644 index 0000000..2ae2839 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/fast-shadow-idle/expect @@ -0,0 +1 @@ +pass diff --git a/infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl b/infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl new file mode 100644 index 0000000..d0b13ef --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-alone/baseline.jsonl @@ -0,0 +1,60 @@ +{"t": 1790732513.9182734, "status": "running", "rtMean": 0.8924521636213212, "lag": 14.055, "uptime": 71.036299234} +{"t": 1790732524.0150237, "status": "running", "rtMean": 0.8353274823796196, "lag": 16.062, "uptime": 81.13323077} +{"t": 1790732534.1210978, "status": "running", "rtMean": 0.8500748093099013, "lag": 17.063, "uptime": 91.228242756} +{"t": 1790732544.215337, "status": "running", "rtMean": 0.8468167790642429, "lag": 19.065, "uptime": 101.324762382} +{"t": 1790732554.322073, "status": "running", "rtMean": 0.8195776032071418, "lag": 21.069, "uptime": 111.432768959} +{"t": 1790732564.4171112, "status": "running", "rtMean": 0.8132396801449534, "lag": 23.128, "uptime": 121.51184336} +{"t": 1790732574.6153316, "status": "running", "rtMean": 0.7620145427014579, "lag": 25.169, "uptime": 131.725135168} +{"t": 1790732584.921327, "status": "running", "rtMean": 0.8332397110903376, "lag": 27.171, "uptime": 142.033873438} +{"t": 1790732595.01128, "status": "running", "rtMean": 0.870312035539666, "lag": 28.172, "uptime": 152.095917692} +{"t": 1790732605.1342888, "status": "running", "rtMean": 0.8533222405905535, "lag": 29.174, "uptime": 162.233917268} +{"t": 1790732615.2172267, "status": "running", "rtMean": 0.8613640091999233, "lag": 31.183, "uptime": 172.332574842} +{"t": 1790732625.292268, "status": "running", "rtMean": 0.8522988744218247, "lag": 32.186, "uptime": 182.413805105} +{"t": 1790732635.3641157, "status": "running", "rtMean": 0.9357131448898743, "lag": 33.188, "uptime": 192.485818904} +{"t": 1790732645.4261112, "status": "running", "rtMean": 1.0206119648139633, "lag": 33.188, "uptime": 202.528181723} +{"t": 1790732655.4861393, "status": "running", "rtMean": 0.9996233335893017, "lag": 33.188, "uptime": 212.597230658} +{"t": 1790732665.5481722, "status": "running", "rtMean": 0.9988689561123472, "lag": 33.188, "uptime": 222.643138786} +{"t": 1790732675.6082208, "status": "running", "rtMean": 0.9720518244342236, "lag": 33.188, "uptime": 232.688977534} +{"t": 1790732685.6701753, "status": "running", "rtMean": 0.9535516201508779, "lag": 33.188, "uptime": 242.776975854} +{"t": 1790732695.7341325, "status": "running", "rtMean": 1.0629078918872632, "lag": 33.188, "uptime": 252.850174728} +{"t": 1790732705.8101525, "status": "running", "rtMean": 0.9727389888242601, "lag": 33.188, "uptime": 262.903659566} +{"t": 1790732715.8741817, "status": "running", "rtMean": 1.0273735099933976, "lag": 33.188, "uptime": 272.974337275} +{"t": 1790732725.938133, "status": "running", "rtMean": 1.0004052294537187, "lag": 33.188, "uptime": 283.049608446} +{"t": 1790732735.998134, "status": "running", "rtMean": 0.9949238477466771, "lag": 33.188, "uptime": 293.095921712} +{"t": 1790732746.058181, "status": "running", "rtMean": 1.001717860791771, "lag": 33.188, "uptime": 303.168958273} +{"t": 1790732756.1181643, "status": "running", "rtMean": 0.9904886517209306, "lag": 33.188, "uptime": 313.212038344} +{"t": 1790732766.1781104, "status": "running", "rtMean": 1.0019464588045806, "lag": 33.188, "uptime": 323.27335596} +{"t": 1790732776.2361557, "status": "running", "rtMean": 0.9964762908263903, "lag": 33.188, "uptime": 333.345377532} +{"t": 1790732786.2971303, "status": "running", "rtMean": 0.9919143606076284, "lag": 33.188, "uptime": 343.415231522} +{"t": 1790732796.356171, "status": "running", "rtMean": 0.9987406877370043, "lag": 33.188, "uptime": 353.453194803} +{"t": 1790732806.4211473, "status": "running", "rtMean": 0.9606955955830612, "lag": 33.188, "uptime": 363.51066889} +{"t": 1790732816.4811146, "status": "running", "rtMean": 1.0365607476649523, "lag": 33.188, "uptime": 373.577335699} +{"t": 1790732826.5412261, "status": "running", "rtMean": 0.9998410565989371, "lag": 33.188, "uptime": 383.641038325} +{"t": 1790732836.6022642, "status": "running", "rtMean": 1.0000077033831407, "lag": 33.188, "uptime": 393.71493795} +{"t": 1790732846.66412, "status": "running", "rtMean": 1.000194713414025, "lag": 33.188, "uptime": 403.778353067} +{"t": 1790732856.7631304, "status": "running", "rtMean": 0.9963137515722961, "lag": 33.188, "uptime": 413.843209009} +{"t": 1790732866.8251379, "status": "running", "rtMean": 1.0024279700647742, "lag": 33.188, "uptime": 423.939536235} +{"t": 1790732876.8881218, "status": "running", "rtMean": 0.9998292141625301, "lag": 33.188, "uptime": 434.00196051} +{"t": 1790732886.9481704, "status": "running", "rtMean": 1.000376047514638, "lag": 33.188, "uptime": 444.041568588} +{"t": 1790732897.0131807, "status": "running", "rtMean": 0.9650577242433412, "lag": 33.188, "uptime": 454.116318252} +{"t": 1790732907.0751567, "status": "running", "rtMean": 1.0144244685102852, "lag": 33.188, "uptime": 464.167010558} +{"t": 1790732917.135163, "status": "running", "rtMean": 1.0205380747863821, "lag": 33.188, "uptime": 474.251702386} +{"t": 1790732927.2051454, "status": "running", "rtMean": 1.0000612465292147, "lag": 33.188, "uptime": 484.315901269} +{"t": 1790732937.2681184, "status": "running", "rtMean": 0.9994207833538337, "lag": 33.188, "uptime": 494.376673004} +{"t": 1790732947.3331046, "status": "running", "rtMean": 1.000304521129079, "lag": 33.188, "uptime": 504.439961234} +{"t": 1790732957.3971682, "status": "running", "rtMean": 1.0002162260543621, "lag": 33.188, "uptime": 514.506681195} +{"t": 1790732967.4561813, "status": "running", "rtMean": 0.9940778699094166, "lag": 33.188, "uptime": 524.546264956} +{"t": 1790732977.5141263, "status": "running", "rtMean": 0.9996073475880696, "lag": 33.188, "uptime": 534.609522709} +{"t": 1790732987.574194, "status": "running", "rtMean": 1.0002335793712973, "lag": 33.188, "uptime": 544.681525736} +{"t": 1790732997.63819, "status": "running", "rtMean": 0.9719075938039292, "lag": 33.188, "uptime": 554.746296519} +{"t": 1790733007.6981711, "status": "running", "rtMean": 0.9642994644579728, "lag": 33.188, "uptime": 564.819180783} +{"t": 1790733017.758178, "status": "running", "rtMean": 1.018785781616432, "lag": 33.188, "uptime": 574.863920385} +{"t": 1790733027.8201568, "status": "running", "rtMean": 1.0126053016171566, "lag": 33.188, "uptime": 584.931657624} +{"t": 1790733037.8801777, "status": "running", "rtMean": 1.0288813388578921, "lag": 33.188, "uptime": 595.000913192} +{"t": 1790733047.9401584, "status": "running", "rtMean": 0.9993726786826045, "lag": 33.188, "uptime": 605.062362454} +{"t": 1790733058.0032334, "status": "running", "rtMean": 1.0003288362459641, "lag": 33.188, "uptime": 615.100685166} +{"t": 1790733068.0701303, "status": "running", "rtMean": 0.996323054395049, "lag": 33.188, "uptime": 625.182391179} +{"t": 1790733078.1311688, "status": "running", "rtMean": 0.9986121232113987, "lag": 33.188, "uptime": 635.237969741} +{"t": 1790733088.194169, "status": "running", "rtMean": 0.9998456257825143, "lag": 33.188, "uptime": 645.294446623} +{"t": 1790733098.254364, "status": "running", "rtMean": 0.9990527607429407, "lag": 33.188, "uptime": 655.371233565} +{"t": 1790733108.3171723, "status": "running", "rtMean": 0.9801059046785113, "lag": 33.188, "uptime": 665.424268239} diff --git a/infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl b/infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl new file mode 100644 index 0000000..1a8f2b7 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-alone/checks.jsonl @@ -0,0 +1,20 @@ +{"t": 1790733119.441622, "status": "running", "rtMean": 0.999626145847037, "lag": 0.0, "uptime": 11.03453719} +{"t": 1790733179.5021126, "status": "running", "rtMean": 0.996429238965645, "lag": 0.0, "uptime": 71.109465871} +{"t": 1790733239.563163, "status": "running", "rtMean": 1.0001344530283525, "lag": 0.0, "uptime": 131.161767319} +{"t": 1790733299.6230712, "status": "running", "rtMean": 1.0051819085367752, "lag": 0.0, "uptime": 191.213566544} +{"t": 1790733359.684059, "status": "running", "rtMean": 0.9994857841966536, "lag": 0.0, "uptime": 251.305985353} +{"t": 1790733419.744106, "status": "running", "rtMean": 0.9309339263307287, "lag": 1.016, "uptime": 311.343539702} +{"t": 1790733479.8072605, "status": "running", "rtMean": 0.9914113663325995, "lag": 1.016, "uptime": 371.420558771} +{"t": 1790733539.874109, "status": "running", "rtMean": 1.0150616406858766, "lag": 1.016, "uptime": 431.469758515} +{"t": 1790733599.934255, "status": "running", "rtMean": 0.9990854925925501, "lag": 1.016, "uptime": 491.554715659} +{"t": 1790733659.998115, "status": "running", "rtMean": 0.9992033155394792, "lag": 1.016, "uptime": 551.614612008} +{"t": 1790733720.0581028, "status": "running", "rtMean": 1.0002394824346315, "lag": 1.016, "uptime": 611.653389874} +{"t": 1790733780.121188, "status": "running", "rtMean": 1.002487894172868, "lag": 1.016, "uptime": 671.727773294} +{"t": 1790733840.1851053, "status": "running", "rtMean": 1.000530724113054, "lag": 1.016, "uptime": 731.80678409} +{"t": 1790733900.2461364, "status": "running", "rtMean": 1.000644782810976, "lag": 1.016, "uptime": 791.842628622} +{"t": 1790733960.3072183, "status": "running", "rtMean": 0.999652205983927, "lag": 1.016, "uptime": 851.922688196} +{"t": 1790734020.3681173, "status": "running", "rtMean": 0.9946548155046125, "lag": 1.016, "uptime": 911.968050417} +{"t": 1790734080.4291067, "status": "running", "rtMean": 1.0009058823044212, "lag": 1.016, "uptime": 972.041325345} +{"t": 1790734140.4912531, "status": "running", "rtMean": 0.9902809817215064, "lag": 1.016, "uptime": 1032.085088126} +{"t": 1790734200.550132, "status": "running", "rtMean": 1.0136589528338944, "lag": 1.016, "uptime": 1092.153292688} +{"t": 1790734260.6101415, "status": "running", "rtMean": 0.997751864835789, "lag": 1.016, "uptime": 1152.230885469} diff --git a/infra/tests/fixtures/shadow-guard/slow-alone/expect b/infra/tests/fixtures/shadow-guard/slow-alone/expect new file mode 100644 index 0000000..2ae2839 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-alone/expect @@ -0,0 +1 @@ +pass diff --git a/infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl b/infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl new file mode 100644 index 0000000..90822eb --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-shadow-same/baseline.jsonl @@ -0,0 +1,60 @@ +{"t": 1790734381.7911441, "status": "running", "rtMean": 0.9991690302798031, "lag": 0.0, "uptime": 71.04094778} +{"t": 1790734391.863173, "status": "running", "rtMean": 0.9995511232186312, "lag": 0.0, "uptime": 81.137648009} +{"t": 1790734401.9251318, "status": "running", "rtMean": 1.004411393451764, "lag": 0.0, "uptime": 91.179846024} +{"t": 1790734411.9851615, "status": "running", "rtMean": 1.0061548832920237, "lag": 0.0, "uptime": 101.244880286} +{"t": 1790734422.045158, "status": "running", "rtMean": 1.0009389826422062, "lag": 0.0, "uptime": 111.322533823} +{"t": 1790734432.1231213, "status": "running", "rtMean": 0.9994054188236428, "lag": 0.0, "uptime": 121.386590467} +{"t": 1790734442.1821327, "status": "running", "rtMean": 1.0019091973172163, "lag": 0.0, "uptime": 131.434675409} +{"t": 1790734452.2411315, "status": "running", "rtMean": 1.0003511147658264, "lag": 0.0, "uptime": 141.510042108} +{"t": 1790734462.3011394, "status": "running", "rtMean": 0.9998128330113216, "lag": 0.0, "uptime": 151.571854176} +{"t": 1790734472.3611345, "status": "running", "rtMean": 0.9995342276541852, "lag": 0.0, "uptime": 161.611024691} +{"t": 1790734482.435045, "status": "running", "rtMean": 0.9922858838781137, "lag": 0.0, "uptime": 171.712414098} +{"t": 1790734492.4924283, "status": "running", "rtMean": 1.0077000502536002, "lag": 0.0, "uptime": 181.768296008} +{"t": 1790734502.590251, "status": "running", "rtMean": 0.688659978029653, "lag": 3.02, "uptime": 191.845836083} +{"t": 1790734512.7063384, "status": "running", "rtMean": 0.6918570039489707, "lag": 6.031, "uptime": 201.972741056} +{"t": 1790734522.8416302, "status": "running", "rtMean": 0.6636996350321189, "lag": 9.061, "uptime": 212.118463031} +{"t": 1790734532.9413493, "status": "running", "rtMean": 0.677691555064422, "lag": 13.117, "uptime": 222.217638708} +{"t": 1790734543.0511246, "status": "running", "rtMean": 0.6687714298956552, "lag": 16.132, "uptime": 232.330293687} +{"t": 1790734553.214297, "status": "running", "rtMean": 0.6610843395024606, "lag": 19.139, "uptime": 242.48895228} +{"t": 1790734563.3515842, "status": "running", "rtMean": 0.652060892547814, "lag": 23.162, "uptime": 252.608110328} +{"t": 1790734573.4900045, "status": "running", "rtMean": 0.6695512645097088, "lag": 26.172, "uptime": 262.753496555} +{"t": 1790734583.676419, "status": "running", "rtMean": 0.672729094430949, "lag": 30.189, "uptime": 272.933415929} +{"t": 1790734593.8542893, "status": "running", "rtMean": 0.6751609713074462, "lag": 33.199, "uptime": 283.119763313} +{"t": 1790734603.9855552, "status": "running", "rtMean": 0.6532184360045333, "lag": 36.247, "uptime": 293.24006575} +{"t": 1790734614.107205, "status": "running", "rtMean": 0.6660828397073446, "lag": 40.264, "uptime": 303.373977854} +{"t": 1790734624.218526, "status": "running", "rtMean": 0.6077386619823459, "lag": 44.344, "uptime": 313.467368475} +{"t": 1790734634.3447165, "status": "running", "rtMean": 0.6539609074261248, "lag": 47.354, "uptime": 323.602496592} +{"t": 1790734644.4728997, "status": "running", "rtMean": 0.6660933740022716, "lag": 50.368, "uptime": 333.740179276} +{"t": 1790734654.5995867, "status": "running", "rtMean": 0.6500636748816758, "lag": 54.395, "uptime": 343.847346535} +{"t": 1790734664.7299855, "status": "running", "rtMean": 0.6705859566600052, "lag": 57.409, "uptime": 354.005911843} +{"t": 1790734674.917639, "status": "running", "rtMean": 0.6740430368306463, "lag": 61.419, "uptime": 364.191797413} +{"t": 1790734685.0660818, "status": "running", "rtMean": 0.6643961460479318, "lag": 64.428, "uptime": 374.341795785} +{"t": 1790734695.265925, "status": "running", "rtMean": 0.6579653102367324, "lag": 68.437, "uptime": 384.519988281} +{"t": 1790734705.472841, "status": "running", "rtMean": 0.6547900490878023, "lag": 71.446, "uptime": 394.730676243} +{"t": 1790734715.6600814, "status": "running", "rtMean": 0.6530533406133286, "lag": 75.466, "uptime": 404.896364288} +{"t": 1790734725.7730033, "status": "running", "rtMean": 0.6672820515708326, "lag": 78.47, "uptime": 415.037219103} +{"t": 1790734735.8823855, "status": "running", "rtMean": 0.6604279690960906, "lag": 81.507, "uptime": 425.141484166} +{"t": 1790734746.0059605, "status": "running", "rtMean": 0.669876056664904, "lag": 85.525, "uptime": 435.241624797} +{"t": 1790734756.16065, "status": "running", "rtMean": 0.6669554325713298, "lag": 88.532, "uptime": 445.424510067} +{"t": 1790734766.2961965, "status": "running", "rtMean": 0.6789691324390087, "lag": 91.546, "uptime": 455.562624387} +{"t": 1790734776.4270732, "status": "running", "rtMean": 0.6764526659523141, "lag": 95.567, "uptime": 465.699227051} +{"t": 1790734786.5895793, "status": "running", "rtMean": 0.6530891711548452, "lag": 98.603, "uptime": 475.850685381} +{"t": 1790734796.7317367, "status": "running", "rtMean": 0.6406146952722656, "lag": 102.675, "uptime": 486.00189116} +{"t": 1790734806.8721528, "status": "running", "rtMean": 0.6453060329257198, "lag": 105.69, "uptime": 496.149729812} +{"t": 1790734817.0070937, "status": "running", "rtMean": 0.6454966448957478, "lag": 109.706, "uptime": 506.283307741} +{"t": 1790734827.1343982, "status": "running", "rtMean": 0.6448485469528062, "lag": 112.72, "uptime": 516.409124389} +{"t": 1790734837.2881198, "status": "running", "rtMean": 0.6535926679887758, "lag": 116.748, "uptime": 526.560442848} +{"t": 1790734847.4209673, "status": "running", "rtMean": 0.6425044322629614, "lag": 119.784, "uptime": 536.693837434} +{"t": 1790734857.5829508, "status": "running", "rtMean": 0.6452458464522223, "lag": 123.802, "uptime": 546.8305001} +{"t": 1790734867.7133708, "status": "running", "rtMean": 0.6302281366614498, "lag": 127.82, "uptime": 556.984448186} +{"t": 1790734877.8158286, "status": "running", "rtMean": 0.6629500748501092, "lag": 130.844, "uptime": 567.072718764} +{"t": 1790734887.943275, "status": "running", "rtMean": 0.6648674424022735, "lag": 133.854, "uptime": 577.200347159} +{"t": 1790734898.06847, "status": "running", "rtMean": 0.6593429199106378, "lag": 137.876, "uptime": 587.328798352} +{"t": 1790734908.210695, "status": "running", "rtMean": 0.662979366140112, "lag": 140.891, "uptime": 597.465073525} +{"t": 1790734918.3496716, "status": "running", "rtMean": 0.6614754105222075, "lag": 144.914, "uptime": 607.619842905} +{"t": 1790734928.486646, "status": "running", "rtMean": 0.6692348242211306, "lag": 147.924, "uptime": 617.724273337} +{"t": 1790734938.6051722, "status": "running", "rtMean": 0.6733974004623173, "lag": 150.942, "uptime": 627.874978882} +{"t": 1790734948.703509, "status": "running", "rtMean": 0.6484292959854895, "lag": 154.965, "uptime": 637.96851242} +{"t": 1790734958.9605355, "status": "running", "rtMean": 0.6326829212607562, "lag": 158.977, "uptime": 648.224285288} +{"t": 1790734969.0924904, "status": "running", "rtMean": 0.6743317584475094, "lag": 162.001, "uptime": 658.352731683} +{"t": 1790734979.512936, "status": "running", "rtMean": 0.66105927868997, "lag": 165.016, "uptime": 668.754929041} diff --git a/infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl b/infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl new file mode 100644 index 0000000..d4f8935 --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-shadow-same/checks.jsonl @@ -0,0 +1,20 @@ +{"t": 1790734991.7640753, "status": "running", "rtMean": 0.6359105463426694, "lag": 3.008, "uptime": 11.070042764} +{"t": 1790735051.931584, "status": "running", "rtMean": 0.4413866438713924, "lag": 31.225, "uptime": 71.270223818} +{"t": 1790735112.0636158, "status": "running", "rtMean": 0.528275325797771, "lag": 56.478, "uptime": 131.388274947} +{"t": 1790735172.2191246, "status": "running", "rtMean": 0.5653650170639056, "lag": 85.705, "uptime": 191.513860632} +{"t": 1790735232.3440776, "status": "running", "rtMean": 0.598275320104138, "lag": 110.037, "uptime": 251.674657096} +{"t": 1790735292.5060995, "status": "running", "rtMean": 0.6030301486902879, "lag": 134.326, "uptime": 311.836161733} +{"t": 1790735352.646486, "status": "running", "rtMean": 0.6475849197046364, "lag": 156.459, "uptime": 371.966818709} +{"t": 1790735412.780515, "status": "running", "rtMean": 0.5770778494664259, "lag": 179.892, "uptime": 432.08998512} +{"t": 1790735472.8577662, "status": "running", "rtMean": 0.6886656579593289, "lag": 198.051, "uptime": 492.201636495} +{"t": 1790735532.9329088, "status": "running", "rtMean": 0.7616039578620443, "lag": 210.17, "uptime": 552.275859184} +{"t": 1790735592.995646, "status": "running", "rtMean": 0.8492741277663118, "lag": 225.508, "uptime": 612.316843322} +{"t": 1790735653.0601382, "status": "running", "rtMean": 0.8233088403353765, "lag": 232.541, "uptime": 672.386139571} +{"t": 1790735713.1299574, "status": "running", "rtMean": 0.8821898469526929, "lag": 239.649, "uptime": 732.468014006} +{"t": 1790735773.1924357, "status": "running", "rtMean": 0.9074726134753647, "lag": 243.655, "uptime": 792.527038261} +{"t": 1790735833.2571187, "status": "running", "rtMean": 0.899453016514728, "lag": 250.877, "uptime": 852.593245225} +{"t": 1790735893.3221343, "status": "running", "rtMean": 0.6620087337657867, "lag": 258.043, "uptime": 912.634830266} +{"t": 1790735953.5102656, "status": "running", "rtMean": 0.4740061480416233, "lag": 290.508, "uptime": 972.827598732} +{"t": 1790736013.6372716, "status": "running", "rtMean": 0.552244625226687, "lag": 321.774, "uptime": 1032.942900792} +{"t": 1790736073.7192469, "status": "running", "rtMean": 0.5496939405024359, "lag": 348.997, "uptime": 1093.015463153} +{"t": 1790736133.779931, "status": "running", "rtMean": 0.8831947829035597, "lag": 362.15, "uptime": 1153.096169148} diff --git a/infra/tests/fixtures/shadow-guard/slow-shadow-same/expect b/infra/tests/fixtures/shadow-guard/slow-shadow-same/expect new file mode 100644 index 0000000..8bcd2ae --- /dev/null +++ b/infra/tests/fixtures/shadow-guard/slow-shadow-same/expect @@ -0,0 +1 @@ +trip diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index ef42b50..7b2240a 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -510,6 +510,212 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR else pass "07-enable.sh and verify.sh leave flyedge.service alone" fi +# --------------------------------------------------------------------------- +# 3b3. The shadow run (SHADOW-01, infra/units/flyshadow.service). +# +# Report-only and off by default. What would break it is statically visible: the unit ending up +# in a target or 07-enable's list; being bound to flysim (every flysim restart would take the +# shadow with it, and it must follow restarts, not die of them); restarting after a divergence +# (the verdict must stay); losing its idle scheduling (it must never take a live cycle); or +# landing on flysim's cpuset. +# --------------------------------------------------------------------------- +echo "--- flyshadow.service: off by default, report-only, idle, never bound to flysim ---" +SHADOW_UNIT="$INFRA_DIR/units/flyshadow.service" +if [ ! -f "$SHADOW_UNIT" ]; then + fail "units/flyshadow.service is missing" +else + grep -qE '^ExecStart=/opt/fly/current/fly-shadow run$' "$SHADOW_UNIT" \ + && pass "flyshadow.service runs the release's fly-shadow" \ + || fail "flyshadow.service ExecStart must be /opt/fly/current/fly-shadow run" + grep -qE '^ConditionPathExists=/opt/fly/current/fly-shadow$' "$SHADOW_UNIT" \ + && pass "flyshadow.service stays inactive on a release without fly-shadow" \ + || fail "flyshadow.service needs ConditionPathExists=/opt/fly/current/fly-shadow" + if grep -qE '^(Requires|BindsTo|PartOf|Requisite)=.*flysim' "$SHADOW_UNIT"; then + fail "flyshadow.service must not be bound to flysim.service: it follows flysim's restarts" + else + pass "flyshadow.service outlives flysim restarts (not bound to flysim.service)" + fi + grep -qE '^RestartPreventExitStatus=3$' "$SHADOW_UNIT" \ + && pass "flyshadow.service stays stopped after a divergence (exit 3)" \ + || fail "flyshadow.service needs RestartPreventExitStatus=3 so a diverged verdict stays" + grep -qE '^CPUSchedulingPolicy=idle$' "$SHADOW_UNIT" \ + && pass "flyshadow.service runs SCHED_IDLE" \ + || fail "flyshadow.service must be CPUSchedulingPolicy=idle: it may only use idle CPU" + grep -qE '^\[Install\]' "$SHADOW_UNIT" \ + && fail "flyshadow.service has an [Install] section; it is started by fly-shadow-run only" \ + || pass "flyshadow.service has no [Install] section (never enabled)" +fi +if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flyshadow.service'; then + fail "fly.target pulls flyshadow.service in; it must stay off until fly-shadow-run starts it" +else + pass "fly.target does not pull flyshadow.service in" +fi +if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flyshadow'; then + fail "07-enable.sh or verify.sh lists flyshadow.service as always-on" +else + pass "07-enable.sh and verify.sh leave flyshadow.service alone" +fi +for u in flyshadow-guard.timer flyshadow-guard.service; do + if [ ! -f "$INFRA_DIR/units/$u" ]; then + fail "units/$u is missing" + elif grep -qE '^\[Install\]' "$INFRA_DIR/units/$u"; then + fail "$u has an [Install] section; fly-shadow-run starts and stops it" + else + pass "$u is never enabled (started by fly-shadow-run only)" + fi +done +# The guard's rule, driven for real (python3 is on every container this repo provisions) over +# RTF traces: synthetic ones shaped on the release CT's own numbers (tests/shadow_guard_traces.py) +# and ones recorded from a real flysim with and without a shadow (tests/fixtures/shadow-guard/). +# A fly that was already below real time must never trip it; a genuine degradation must. +if command -v python3 >/dev/null 2>&1; then + g_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-guard.XXXXXX")" + guard_trace() { # name, dir with baseline.jsonl and checks.jsonl, expect (pass|trip) + local out rc=0 + out="$("$INFRA_DIR/bin/fly-shadow-run" simulate "$2/baseline.jsonl" "$2/checks.jsonl")" || rc=$? + if { [ "$3" = pass ] && [ "$rc" = 0 ]; } || { [ "$3" = trip ] && [ "$rc" = 1 ]; }; then + pass "fly-shadow-run guard, $1: ${out%% (baseline*}" + else + fail "fly-shadow-run guard, $1: expected $3, got exit $rc: $out" + fi + } + while read -r name expect; do + guard_trace "$name" "$g_tmp/$name" "$expect" + done < <(python3 "$INFRA_DIR/tests/shadow_guard_traces.py" "$g_tmp") + for d in "$INFRA_DIR"/tests/fixtures/shadow-guard/*/; do + [ -f "$d/expect" ] || continue + guard_trace "recorded $(basename "$d")" "$d" "$(cat "$d/expect")" + done + # The guard's lifecycle and `check`'s preconditions (review round 3, G1-a), with a fake systemctl + # (`show` answers FAKE_SHADOW_STATE; the timer is active when FAKE_TIMER_ACTIVE=yes), a fake `id` + # (root) and a metrics URL nobody listens on (a live guard then reports "not judged" and stays). + gl_bin="$g_tmp/lifecycle-bin"; gl_dir="$g_tmp/lifecycle-shadow" + mkdir -p "$gl_bin" "$gl_dir" + cat > "$gl_bin/systemctl" <<'GLSYSTEMCTL' +#!/bin/sh +echo "$*" >> "$FAKE_SYSTEMCTL_LOG" +case "$1" in + show) printf 'ActiveState=%s\nSubState=x\n' "$FAKE_SHADOW_STATE" ;; + is-active) + case "$3" in + flyshadow.service) [ "$FAKE_SHADOW_STATE" = active ]; exit $? ;; + flyshadow-guard.timer) [ "$FAKE_TIMER_ACTIVE" = yes ]; exit $? ;; + *) exit 3 ;; + esac ;; +esac +exit 0 +GLSYSTEMCTL + cat > "$gl_bin/id" <<'GLID' +#!/bin/sh +[ "$1" = -u ] && { echo 0; exit 0; } +exec /usr/bin/id "$@" +GLID + chmod +x "$gl_bin/systemctl" "$gl_bin/id" + gl_run() { # args to fly-shadow-run; env FAKE_SHADOW_STATE, FAKE_TIMER_ACTIVE from the caller + : > "$g_tmp/systemctl.log" + PATH="$gl_bin:$PATH" FAKE_SYSTEMCTL_LOG="$g_tmp/systemctl.log" FLY_SHADOW_DIR="$gl_dir" \ + FLY_METRICS_URL=http://127.0.0.1:1 FLY_SHADOW_BIN="$g_tmp/none" \ + "$INFRA_DIR/bin/fly-shadow-run" "$@" 2>&1 + } + printf '{"rtfMean":0.66,"rtfSd":0.01,"lagRate":0.3,"samples":60,"margin":0.05}\n' > "$gl_dir/baseline.json" + printf '{}\n' > "$gl_dir/guard-state.json" + for st in activating deactivating; do + FAKE_SHADOW_STATE=$st FAKE_TIMER_ACTIVE=yes gl_run guard > "$g_tmp/out" || true + if grep -q 'stop flyshadow-guard.timer' "$g_tmp/systemctl.log"; then + fail "fly-shadow-run guard stopped its timer while flyshadow was $st (auto-restart): $(cat "$g_tmp/out")" + else + pass "fly-shadow-run guard keeps running while flyshadow is $st (crash-restart delay)" + fi + done + for st in inactive failed; do + FAKE_SHADOW_STATE=$st FAKE_TIMER_ACTIVE=yes gl_run guard > "$g_tmp/out" || true + if grep -q 'stop flyshadow-guard.timer' "$g_tmp/systemctl.log"; then + pass "fly-shadow-run guard stops its timer when flyshadow is $st" + else + fail "fly-shadow-run guard kept running with flyshadow $st: $(cat "$g_tmp/out")" + fi + done + gl_check() { # name, expected (refused|passes-gates), then the env + local out rc=0 + out="$(gl_run check)" || rc=$? + case "$2:$rc" in + refused:1) pass "fly-shadow-run check, $1: ${out%%(*}" ;; + passes-gates:2) pass "fly-shadow-run check, $1: past the guard preconditions" ;; + *) fail "fly-shadow-run check, $1: expected $2, got exit $rc: $out" ;; + esac + } + FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "guarded run" passes-gates + FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=no gl_check "guard timer not active" refused + FAKE_SHADOW_STATE=activating FAKE_TIMER_ACTIVE=yes gl_check "shadow restarting" refused + mv "$gl_dir/baseline.json" "$gl_dir/baseline.json.off" + FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "no baseline.json" refused + mv "$gl_dir/baseline.json.off" "$gl_dir/baseline.json" + echo '{}' > "$gl_dir/guard-tripped.json" + FAKE_SHADOW_STATE=active FAKE_TIMER_ACTIVE=yes gl_check "guard tripped" refused + rm -rf "$g_tmp" +else + fail "python3 is needed to test fly-shadow-run's guard rule" +fi +# N2: `start` refuses, starting nothing, unless the cpuset drop-in exists and is disjoint from flysim's. +cs_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-cpuset.XXXXXX")" +mkdir -p "$cs_tmp/bin" "$cs_tmp/shadow" +cat > "$cs_tmp/bin/systemctl" <<'CSSTUB' +#!/bin/sh +echo "$*" >> "$CS_DIR/systemctl.log" +case "$1" in + is-active) exit 3 ;; + show) case "$5" in + flyshadow.service) echo "$CS_SHADOW_CPUS" ;; + flysim.service) echo "$CS_SIM_CPUS" ;; + esac ;; +esac +exit 0 +CSSTUB +printf '#!/bin/sh\n[ "$1" = -u ] && { echo 0; exit 0; }\nexec /usr/bin/id "$@"\n' > "$cs_tmp/bin/id" +printf '#!/bin/sh\nexit 0\n' > "$cs_tmp/fly-shadow" +printf '#!/bin/sh\necho "stub install reached"\nexit 1\n' > "$cs_tmp/bin/install" +chmod +x "$cs_tmp/bin/install" "$cs_tmp/bin/systemctl" "$cs_tmp/bin/id" "$cs_tmp/fly-shadow" +cs_start() { # name, expect (refuse|proceed), shadow cpus, sim cpus, drop-in (yes|no) + local rc=0 out + : > "$cs_tmp/systemctl.log" + rm -f "$cs_tmp/dropin.conf" + [ "$5" = yes ] && : > "$cs_tmp/dropin.conf" + out="$(PATH="$cs_tmp/bin:$PATH" CS_DIR="$cs_tmp" CS_SHADOW_CPUS="$3" CS_SIM_CPUS="$4" \ + FLY_SHADOW_DIR="$cs_tmp/shadow" FLY_SHADOW_BIN="$cs_tmp/fly-shadow" \ + FLY_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_BASELINE_SECONDS=1 \ + FLY_METRICS_URL=http://127.0.0.1:1 "$INFRA_DIR/bin/fly-shadow-run" start 2>&1)" || rc=$? + case "$2" in + refuse) + if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \ + && [ ! -d "$cs_tmp/shadow/trace" ] && echo "$out" | grep -q 'nothing started'; then + pass "fly-shadow-run start refuses, $1" + else + fail "fly-shadow-run start must refuse and start nothing, $1 (rc=$rc): $out" + fi ;; + proceed) + # past the cpuset check it goes on to install -d (stubbed to stop there) + if echo "$out" | grep -q 'stub install reached'; then + pass "fly-shadow-run start proceeds, $1" + else + fail "fly-shadow-run start must pass the cpuset check, $1 (rc=$rc): $out" + fi ;; + esac +} +if command -v python3 >/dev/null 2>&1; then + cs_start "no cpuset drop-in" refuse "0-7" "1,3,5,7" no + cs_start "AllowedCPUs overlapping flysim's" refuse "0 2 3" "1 3 5 7" yes + cs_start "AllowedCPUs empty" refuse "" "1 3 5 7" yes + cs_start "AllowedCPUs disjoint (ranges)" proceed "0 2 4 6" "1 3 5 7" yes + cs_start "AllowedCPUs disjoint (range syntax)" proceed "0-2" "3-7" yes +else + fail "python3 is needed to test fly-shadow-run's cpuset check" +fi +rm -rf "$cs_tmp" +if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then + pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs" +else + fail "05-deploy.sh must give flyshadow.service the page and encoder CPUs, never flysim's" +fi if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \ && grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value" @@ -536,6 +742,530 @@ 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 --bin fly-shadow --bin fly-session' "$INFRA_DIR/build/build-flysim.sh" \ + && grep -qE 'for extra in flysim-session fly-shadow fly-session' "$INFRA_DIR/build/package-release.sh" \ + && pass "build-flysim.sh builds flysim-session and package-release.sh ships it (with fly-shadow)" \ + || 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" +if [ "$1" = is-active ]; then + case "$3" in flyshadow.service|flyshadow-guard.timer) [ "${RT_SHADOW_ACTIVE:-0}" = 1 ]; exit $? ;; esac +fi +RTSTUB +cat > "$rt_dir/release/fly-shadow-run" <<'RTSTUB' +#!/usr/bin/env bash +echo "$*" >> "$RT_DIR/shadow-run.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" \ + FLY_SHADOW_RUN_BIN="$rt_dir/release/fly-shadow-run" \ + FLY_PROBATION_DIR="$rt_dir/probation" FLY_PROBATION_RESULT="$rt_dir/run/runtime-probation.json" \ + "$@" bash "$INFRA_DIR/bin/fly-runtime" "${RT_ARGS[@]}" >/dev/null 2>&1 +} +rt_dropin="$rt_dir/systemd/flysim.service.d/10-runtime.conf" +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 +# N1: a running shadow and guard are stopped by `session`, without restarting flysim; none running: untouched. +[ ! -e "$rt_dir/shadow-run.log" ] \ + && pass "fly-runtime session leaves fly-shadow-run alone when no shadow is running" \ + || fail "fly-runtime session called fly-shadow-run with no shadow running" +RT_ARGS=(legacy); fly_runtime || true +RT_ARGS=(session) +rm -f "$rt_dir/shadow-run.log" +if fly_runtime RT_SHADOW_ACTIVE=1 && [ "$(cat "$rt_dir/shadow-run.log" 2>/dev/null)" = stop ]; then + pass "fly-runtime session stops the running shadow and guard (fly-shadow-run stop, no --restart-flysim)" +else + fail "fly-runtime session must run exactly 'fly-shadow-run stop' when a shadow is running ($(cat "$rt_dir/shadow-run.log" 2>/dev/null))" +fi +rm -f "$rt_dir/shadow-run.log" +RT_ARGS=(session --no-restart) +fly_runtime RT_SHADOW_ACTIVE=1 || true +[ ! -e "$rt_dir/shadow-run.log" ] \ + && pass "fly-runtime session --no-restart (deploy refresh) does not touch the shadow" \ + || fail "fly-runtime session --no-restart must not stop the shadow" +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 +mv "$rt_dir/flysim-session.away" "$rt_dir/release/flysim-session" + +# CUT-01's speed probation (fly-runtime-probation), driven end to end with the real fly-runtime +# against the stubs above: `session` starts it, `tick --sample-json` feeds one recorded sample a +# minute (the sample times are synthetic, so 30 "minutes" take a second), and the outcome is read +# from the drop-in, the fallback reason file, the result file and the stubbed systemctl. +echo "--- the speed probation ---" +PROBATION="$INFRA_DIR/bin/fly-runtime-probation" +pr_state="$rt_dir/probation/state.json" +pr_result="$rt_dir/run/runtime-probation.json" +pr_fellback="$rt_dir/run/runtime-fellback.json" +pr_env() { + env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_RELEASE_DIR="$rt_dir/release" \ + FLY_ENV_FILE="$rt_dir/fly.env" FLY_SYSTEMD_DIR="$rt_dir/systemd" \ + FLY_RUNTIME_LOG="$rt_dir/runtime.log" FLY_RUNTIME_HEALTH_TIMEOUT=4 \ + FLY_RUNTIME_FELLBACK="$pr_fellback" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \ + FLY_PROBATION_DIR="$rt_dir/probation" FLY_PROBATION_RESULT="$pr_result" "$@" +} +pr_reset() { + rm -rf "$rt_dir/probation" "$pr_result" "$pr_fellback" "$rt_dir/systemd/flysim.service.d" + : > "$rt_dir/systemctl.log" +} +pr_traces() { # case, n, t0 -> JSON samples, one a minute: {t,status,rtMean,lag,uptime} + python3 - "$1" "$2" "$3" <<'PRPY' +import json, sys +case, n, t0 = sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) +lag, up = 2.0, 3600.0 +for i in range(1, n + 1): + rtf, status = 1.0 + (0.008 if i % 2 else -0.008), "running" + if case == "slow": # a steady 0.85x + rtf = 0.85 + (0.01 if i % 2 else -0.01); lag += 0.15 * 60 + elif case == "stall" and i in (12, 13): # two stalled minutes (a GC, a disk hiccup): 18 s of lag + rtf = 0.1; lag += 18 if i == 12 else 0 + elif case == "lag": # at real time on average, but 5 s more behind each minute + lag += 5 + elif case == "warmup": # a slow restore: the first 5 samples are before the warm-up + up = 30.0 + 60 * i if i <= 5 else 3600.0 + 60 * i + if i <= 5: + rtf = 0.2 + elif case == "restart" and i == 10: # flysim restarted (uptime goes backwards), then a warm-up again + up, lag = 20.0, 2.0 + if case in ("slow", "stall", "lag", "healthy"): + up = 3600.0 + 60 * i + elif case == "restart": + up = up + 60 if i != 10 else up + print(json.dumps({"t": t0 + 60 * i, "status": status, "rtMean": rtf, "lag": lag, "uptime": up})) +PRPY +} +pr_ticks() { # case, n: feed n samples to tick; leaves the last exit code in pr_rc + local t0 line + t0="$(date +%s)" + pr_rc=0 + while IFS= read -r line; do + pr_env bash "$PROBATION" tick --sample-json "$line" >/dev/null 2>&1 || pr_rc=$? + [ -f "$pr_state" ] || break + done < <(pr_traces "$1" "$2" "$t0") +} +pr_session() { pr_reset; rm -f "$rt_dir/systemd/flysim.service.d/10-runtime.conf"; RT_ARGS=(session); fly_runtime; } +pr_case() { # name, case, samples, expect: pass|fallback-speed|fallback-lag|no-verdict + pr_session || { fail "probation $1: fly-runtime session failed"; return; } + if [ ! -f "$pr_state" ] || ! grep -qx 'enable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + fail "probation $1: fly-runtime session did not start the probation (state file, timer)" + return + fi + pr_ticks "$2" "$3" + case "$4" in + pass) + if [ -f "$pr_result" ] && grep -q '"passed": true' "$pr_result" && [ -f "$rt_dropin" ] \ + && [ ! -f "$pr_fellback" ] && [ ! -f "$pr_state" ] \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "probation $1: passes, writes runtime-probation.json, stops its timer, stays on session" + else + fail "probation $1: expected a pass with the session drop-in kept (result: $(cat "$pr_result" 2>/dev/null))" + fi ;; + fallback-*) + if [ ! -f "$rt_dropin" ] && [ ! -f "$pr_result" ] && [ ! -f "$pr_state" ] \ + && grep -q '"reason":"speed: ' "$pr_fellback" 2>/dev/null \ + && grep -q "${4#fallback-}" "$pr_fellback" \ + && grep -q 'legacy (automatic fallback: speed: ' "$rt_dir/runtime.log" \ + && grep -q '"passed": false' "$rt_dir/probation/last.json" \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "probation $1: falls back to legacy with reason speed (reason file, journal line, timer off)" + else + fail "probation $1: expected a speed fallback ($(cat "$pr_fellback" 2>/dev/null), drop-in $([ -f "$rt_dropin" ] && echo present || echo gone))" + fi ;; + no-verdict) + if [ -f "$rt_dropin" ] && [ -f "$pr_state" ] && [ ! -f "$pr_fellback" ] && [ ! -f "$pr_result" ]; then + pass "probation $1: no verdict yet, still on probation, no fallback" + else + fail "probation $1: expected it to be running undecided" + fi ;; + esac +} +pr_case "healthy session at 1.0x" healthy 32 pass +pr_case "a session at 0.85x, sustained" slow 40 fallback-speed +pr_case "a transient stall (2 stalled minutes, 18 s of lag)" stall 32 pass +pr_case "lag growth at real time (5 s a minute)" lag 40 fallback-lag +pr_case "a slow restore before the warm-up ends is not judged" warmup 36 pass +pr_case "a flysim restart inside the window starts it again" restart 50 pass +pr_case "a healthy session before 30 minutes" healthy 20 no-verdict +# A probation that has not finished is still there, with its state on disk, after a "reboot": a +# new process reads state.json and goes on (the timer stays enabled; nothing is held in memory). +pr_session && pr_ticks healthy 12 +if [ -f "$pr_state" ] && [ "$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["history"]))' "$pr_state")" -ge 8 ]; then + pass "probation state is persisted on disk between ticks (a reboot resumes it)" +else + fail "probation state was not persisted" +fi +# fly-runtime legacy cancels a probation in progress. +RT_ARGS=(legacy) +if fly_runtime && [ ! -f "$pr_state" ] && [ ! -f "$rt_dropin" ] \ + && grep -qx 'disable --now fly-runtime-probation.timer' "$rt_dir/systemctl.log"; then + pass "fly-runtime legacy cancels the probation (state gone, timer disabled)" +else + fail "fly-runtime legacy must cancel the probation" +fi +# A tick with the legacy runtime selected ends a leftover probation and judges nothing. +pr_session && rm -f "$rt_dropin" +pr_env bash "$PROBATION" tick --sample-json '{"t":1,"status":"running","rtMean":0.1,"lag":1,"uptime":9999}' >/dev/null 2>&1 || true +if [ ! -f "$pr_state" ] && [ ! -f "$pr_fellback" ]; then + pass "probation tick with the legacy runtime selected cancels itself, no fallback" +else + fail "probation tick must end when the legacy runtime is selected" +fi +# A switch without a restart (05-deploy's refresh) or with --no-probation starts none. +pr_reset +RT_ARGS=(session --no-restart); fly_runtime +if [ ! -f "$pr_state" ]; then pass "fly-runtime session --no-restart starts no probation"; else fail "session --no-restart must not start a probation"; fi +pr_reset +rm -f "$rt_dropin" +RT_ARGS=(session --no-probation); fly_runtime +if [ ! -f "$pr_state" ] && [ -f "$rt_dropin" ]; then pass "fly-runtime session --no-probation starts no probation"; else fail "session --no-probation must not start a probation"; fi +# No probation helper, no cutover: an unguarded switch falls back. +pr_reset +rm -f "$rt_dropin" +RT_ARGS=(session) +if ! fly_runtime FLY_PROBATION_BIN="$rt_dir/none" && [ ! -f "$rt_dropin" ] && grep -q 'probation could not be started' "$pr_fellback"; then + pass "fly-runtime session falls back when the probation cannot be started" +else + fail "fly-runtime session must not leave an unguarded session runtime" +fi +# The rule over recorded traces, the way fly-shadow-run simulate does it. +pr_sim="$rt_dir/sim.jsonl" +pr_traces slow 40 1790000000 > "$pr_sim" +pr_out="$(bash "$PROBATION" simulate "$pr_sim" 2>&1)" && pr_rc=0 || pr_rc=$? +if [ "$pr_rc" = 1 ]; then pass "probation simulate: ${pr_out%%:*}, a steady 0.85x: ${pr_out#*: }"; else fail "probation simulate: slow trace: rc $pr_rc: $pr_out"; fi +pr_traces healthy 35 1790000000 > "$pr_sim" +pr_out="$(bash "$PROBATION" simulate "$pr_sim" 2>&1)" && pr_rc=0 || pr_rc=$? +if [ "$pr_rc" = 0 ]; then pass "probation simulate: healthy trace passes"; else fail "probation simulate: healthy trace: rc $pr_rc: $pr_out"; fi +# The unit files. +for u in fly-runtime-probation.service fly-runtime-probation.timer; do + [ -f "$INFRA_DIR/units/$u" ] || fail "units/$u is missing" +done +if grep -qx 'ExecStart=/opt/fly/bin/fly-runtime-probation tick' "$INFRA_DIR/units/fly-runtime-probation.service" \ + && grep -qx 'OnUnitActiveSec=60s' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && grep -qx 'OnBootSec=90s' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && grep -qx 'WantedBy=timers.target' "$INFRA_DIR/units/fly-runtime-probation.timer" \ + && ! grep -q 'fly-runtime-probation' "$INFRA_DIR/units/fly.target" "$INFRA_DIR/07-enable.sh"; then + pass "fly-runtime-probation units: a 60 s timer, enabled only by fly-runtime-probation start (boot resumes it)" +else + fail "fly-runtime-probation units are wrong" +fi +if grep -qE 'for name in .*\bfly-runtime-probation\b.*; do$' "$INFRA_DIR/05-deploy.sh"; then + pass "05-deploy.sh installs fly-runtime-probation" +else + fail "05-deploy.sh must converge bin/fly-runtime-probation to /opt/fly/bin" +fi +rm -rf "$rt_dir" + echo "--- fly-watchdog check 2: the feed counters follow FLY_FEED_VIA ---" 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/tests/shadow_guard_traces.py b/infra/tests/shadow_guard_traces.py new file mode 100644 index 0000000..7fe5d6b --- /dev/null +++ b/infra/tests/shadow_guard_traces.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Synthetic live-fly RTF traces for fly-shadow-run's guard (SHADOW-01 review round 2, G1). + + shadow_guard_traces.py OUTDIR + +Writes /baseline.jsonl and /checks.jsonl in fly-shadow-run's sample format +({t, status, rtMean, lag, uptime}) and prints one line per case: ` `, where + is `pass` (the guard must not trip) or `trip` (it must). The baseline is 60 samples 10 s +apart (start's 10 minutes); the checks are one sample a minute for the given length. + +The lag follows flysim's pacer: a fly behind real time owes (1 - rtf) seconds per second, and the +pacer books it as lag only in chunks of more than a second (`pacing::MAX_CATCHUP`). + +The cases come from the release container's own numbers (the coordinator's samples, agents.log +2026-09-30 00:08Z): a flat 0.66 before the cpuset rebalance, 0.77-0.99 noisy after it, plus a fly +at real time; each alone (must pass), and each with a genuine degradation after the start (must +trip). +""" +import json +import os +import random +import sys + + +class Fly: + def __init__(self, seed): + self.rng = random.Random(seed) + self.t, self.uptime, self.lag, self.debt = 1_790_000_000.0, 3600.0, 12.0, 0.0 + + def run(self, seconds, rtf_of): + """Advances `seconds` of wall time at the realtime factors `rtf_of()` gives per second.""" + rtfs = [] + for _ in range(int(seconds)): + rtf = rtf_of(self.rng) + rtfs.append(rtf) + self.debt += max(0.0, 1.0 - rtf) + if self.debt > 1.0: + self.lag += self.debt + self.debt = 0.0 + self.t += 1 + self.uptime += 1 + return rtfs + + def sample(self, rtf_of, status="running"): + rtfs = self.run(10, rtf_of) + return {"t": self.t, "status": status, "rtMean": sum(rtfs) / len(rtfs), + "lag": round(self.lag, 3), "uptime": self.uptime} + + def restart(self): + self.uptime, self.lag, self.debt = 5.0, 0.0, 0.0 + + +def flat(v, jitter=0.01): + return lambda rng: v + rng.uniform(-jitter, jitter) + + +def noisy(lo, hi): + return lambda rng: rng.uniform(lo, hi) + + +def noisy_windows(lo, hi): + """Noise at the sample level: each 10 s holds one value in [lo, hi], so the 10-s means the + guard reads spread over the whole range (the coordinator's samples).""" + state = {"n": 0, "v": None} + + def pace(rng): + if state["n"] % 10 == 0: + state["v"] = rng.uniform(lo, hi) + state["n"] += 1 + return state["v"] + + return pace + + +def realtime(rng): + return min(1.0, 1.0 + rng.uniform(-0.004, 0.002)) + + +def case(seed, before, after, checks=180, degrade_at=None, events=None): + fly = Fly(seed) + baseline = [fly.sample(before) for _ in range(60)] + fly.restart() # start's own flysim restart + rows = [] + for n in range(checks): + pace = after if degrade_at is not None and n >= degrade_at else before + status = "running" + if events and n in events: + kind = events[n] + if kind == "restart": + fly.restart() + elif kind == "paused": + status = "paused" + elif kind == "hiccup": + fly.lag += 1.3 # one pacing shortfall of 1.3 s, nothing more + rows.append(fly.sample(pace, status)) + fly.run(50, pace) + return baseline, rows + + +CASES = { + # The release CT before the rebalance: a flat 0.66, 3 hours, with a restart and a pause. + "ct-flat-0.66": (case(1, flat(0.66), None, events={40: "restart", 90: "paused", 91: "paused"}), "pass"), + # After the rebalance: 0.77-0.99 noisy, 3 hours, a restart. + "ct-noisy-0.77-0.99": (case(2, noisy(0.77, 0.99), None, events={120: "restart"}), "pass"), + "ct-noisy-0.77-0.99-seed3": (case(3, noisy(0.77, 0.99), None), "pass"), + # The same spread at the level of the 10-s samples themselves, the harder case. + "ct-samples-0.77-0.99": (case(8, noisy_windows(0.77, 0.99), None, events={60: "restart"}), "pass"), + "ct-samples-0.77-0.99-seed9": (case(9, noisy_windows(0.77, 0.99), None), "pass"), + "ct-samples-0.77-0.99-seed10": (case(10, noisy_windows(0.77, 0.99), None), "pass"), + # At real time, with single pacing hiccups: never a trip. + "realtime-hiccups": (case(4, realtime, None, events={30: "hiccup", 100: "hiccup", 150: "hiccup"}), "pass"), + # A shadow that costs the fly real time. + "ct-flat-0.66-then-0.55": (case(5, flat(0.66), flat(0.55), checks=40, degrade_at=15), "trip"), + "ct-noisy-then-0.60-0.75": (case(6, noisy(0.77, 0.99), noisy(0.60, 0.75), checks=40, degrade_at=15), "trip"), + "realtime-then-0.90": (case(7, realtime, flat(0.90), checks=40, degrade_at=15), "trip"), + "ct-samples-then-0.55-0.75": ( + case(11, noisy_windows(0.77, 0.99), noisy_windows(0.55, 0.75), checks=40, degrade_at=15), + "trip", + ), +} + + +def main(): + out = sys.argv[1] + for name, ((baseline, checks), expect) in CASES.items(): + d = os.path.join(out, name) + os.makedirs(d, exist_ok=True) + for fname, rows in (("baseline.jsonl", baseline), ("checks.jsonl", checks)): + with open(os.path.join(d, fname), "w") as f: + for r in rows: + f.write(json.dumps(r) + "\n") + print(name, expect) + + +if __name__ == "__main__": + main() diff --git a/infra/units/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/fly-runtime-probation.service b/infra/units/fly-runtime-probation.service new file mode 100644 index 0000000..f1d628b --- /dev/null +++ b/infra/units/fly-runtime-probation.service @@ -0,0 +1,13 @@ +# infra/units/fly-runtime-probation.service -- triggered by fly-runtime-probation.timer. +# +# One sample (10 s of flysim's /metrics) and one decision of CUT-01's speed probation: see +# infra/bin/fly-runtime-probation. On a sustained speed failure it runs `fly-runtime fallback +# "speed: ..."`. With no probation running it disables its own timer. Root: the fallback removes a +# drop-in in /etc/systemd and restarts flysim. +[Unit] +Description=fly-runtime-probation: is the session runtime at real time? (CUT-01) + +[Service] +Type=oneshot +ExecStart=/opt/fly/bin/fly-runtime-probation tick +TimeoutStartSec=240 diff --git a/infra/units/fly-runtime-probation.timer b/infra/units/fly-runtime-probation.timer new file mode 100644 index 0000000..0f809b9 --- /dev/null +++ b/infra/units/fly-runtime-probation.timer @@ -0,0 +1,18 @@ +# infra/units/fly-runtime-probation.timer -- CUT-01's speed probation, every 60 s. +# +# Not enabled by provisioning or deploy. `fly-runtime session` runs `fly-runtime-probation start` +# (systemctl enable --now), which is why this unit has an [Install] section: the enablement is +# what makes a probation survive a reboot (OnBootSec= then runs the first tick). The probation +# disables the timer when it passes, fails over to legacy, or is cancelled (`fly-runtime legacy`). +[Unit] +Description=fly-runtime-probation: the session runtime's speed probation, every minute (CUT-01) + +[Timer] +OnBootSec=90s +OnActiveSec=60s +OnUnitActiveSec=60s +AccuracySec=5s +Unit=fly-runtime-probation.service + +[Install] +WantedBy=timers.target diff --git a/infra/units/flyshadow-guard.service b/infra/units/flyshadow-guard.service new file mode 100644 index 0000000..2873fcc --- /dev/null +++ b/infra/units/flyshadow-guard.service @@ -0,0 +1,15 @@ +# infra/units/flyshadow-guard.service — triggered by flyshadow-guard.timer. +# +# `fly-shadow-run guard` compares the live fly with the 10-minute baseline `fly-shadow-run start` +# recorded before it started the shadow: on a sustained degradation of the realtime factor or the +# lag growth rate against that baseline (3 checks in a row, 5-sample windows), it stops +# flyshadow.service, removes the trace drop-in and restarts flysim without the trace. The live +# stream never pays for the shadow. It stops itself when the shadow is not running. Root, because it installs no file but +# removes one in /etc/systemd and restarts flysim. +[Unit] +Description=fly-shadow-run guard: the live-impact check of the shadow run (SHADOW-01) +ConditionPathExists=/srv/fly/shadow/baseline.json + +[Service] +Type=oneshot +ExecStart=/opt/fly/bin/fly-shadow-run guard diff --git a/infra/units/flyshadow-guard.timer b/infra/units/flyshadow-guard.timer new file mode 100644 index 0000000..ed263a8 --- /dev/null +++ b/infra/units/flyshadow-guard.timer @@ -0,0 +1,11 @@ +# infra/units/flyshadow-guard.timer — SHADOW-01's live-impact guard, every 60 s while a shadow +# runs. Started by `fly-shadow-run start`, stopped by `fly-shadow-run stop` and by the guard +# itself when it trips. No [Install]: it is never enabled, so a reboot does not start it. +[Unit] +Description=Stop the shadow run if the live fly pays for it (SHADOW-01) + +[Timer] +OnActiveSec=60s +OnUnitActiveSec=60s +AccuracySec=5s +Unit=flyshadow-guard.service diff --git a/infra/units/flyshadow.service b/infra/units/flyshadow.service new file mode 100644 index 0000000..a0c9f82 --- /dev/null +++ b/infra/units/flyshadow.service @@ -0,0 +1,66 @@ +# infra/units/flyshadow.service — pushed to /etc/systemd/system/flyshadow.service. +# +# SHADOW-01 (docs/design/session-framework/legacy-gameboy-v1.md section 18): the +# session runtime run beside the live fly. REPORT-ONLY: it presses no button, +# serves no port, and only READS flysim's stores and trace; it writes nothing +# but /srv/fly/shadow (verdict.json, divergence.json, its spool) and its +# runtime directory. DISABLED BY DEFAULT: in no target's Wants=/Requires=, +# not in 07-enable.sh. `fly-shadow-run start` (infra/bin) starts it, turns +# flysim's trace on and restarts flysim once so the shadow follows a process +# from its first frame; `fly-shadow-run stop` undoes both. +# +# Deliberately NOT bound to flysim (no Requires=/BindsTo=/PartOf=): every +# flysim restart (the unstick rule, the watchdog, fly-loop-recover, a +# milestone reset) is a new trace file the shadow follows on its own, so the +# shadow must outlive them. It stops itself on the first divergence with exit +# status 3 and a `diverged` verdict; RestartPreventExitStatus keeps it +# stopped so the verdict stays for the coordinator to read. +# +# Resources (the SHADOW-01 report, "resource plan"): a second whole brain, +# about the live fly's own CPU per frame. It must never take a cycle the live +# fly, the page or the encoder wants, so it runs SCHED_IDLE (it only gets CPU +# nobody else is using), off flysim's cpuset (05-deploy.sh writes +# AllowedCPUs= for it from the page and encoder groups). It pauses for a minute +# while flysim's lag grows faster than its pre-start baseline rate (and stops +# pausing when that does not help: then it is not the cause). +# flyshadow-guard.timer (fly-shadow-run guard) stops it and restarts flysim +# without the trace on a sustained degradation against that baseline. It is lag-tolerant: the trace and the +# spool are on disk, so running behind real time only delays the verdict (the +# 512 MiB spool covers about 15 minutes of lag for hot saves). +# +# Its heartbeat (/consumer, every 30 s, removed when it stops) is +# what keeps flysim tracing: a stopped, diverged or crashed shadow turns the +# live trace off within a minute of a stale heartbeat, with no root action. +[Unit] +Description=flyshadow: the session runtime shadowing the live fly (SHADOW-01, report only) +After=flysim.service +# A release that predates SHADOW-01 has no binary; stay cleanly inactive. +ConditionPathExists=/opt/fly/current/fly-shadow + +[Service] +Type=simple +User=fly +# The live service's configuration, read the way flysim reads it: the +# cartridge, the dataset, the macro mode, the speed. The store paths and the +# metrics listener are flysim.service's own Environment= lines, repeated. +EnvironmentFile=/etc/fly/fly.env +Environment=FLY_STATE_HOT=/run/fly/state +Environment=FLY_STATE=/srv/fly/state +Environment=FLY_METRICS_ADDR=0.0.0.0:9101 +# What flysim writes with the shadow's drop-in (fly-shadow-run), and where the +# verdict goes. The session's sockets and artifacts live on tmpfs. +Environment=FLY_TRACE_DIR=/srv/fly/shadow/trace +Environment=FLY_SHADOW_DIR=/srv/fly/shadow +Environment=FLY_SHADOW_WORK=/run/fly-shadow +RuntimeDirectory=fly-shadow +# The shadow agent's sweep threads (the report's measurements). +Environment=FLY_SHADOW_THREADS=2 +ExecStart=/opt/fly/current/fly-shadow run +Restart=on-failure +RestartSec=10 +RestartPreventExitStatus=3 +CPUSchedulingPolicy=idle +Nice=19 +CPUWeight=1 +IOSchedulingClass=idle +MemoryMax=3G 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 3c6e925..f52e37c 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -435,6 +435,29 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +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]] name = "fly-session" version = "0.1.1" diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index 2673363..d98e038 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -2,6 +2,7 @@ resolver = "3" members = [ "crates/fly-edge", + "crates/fly-legacy-session", "crates/fly-session", "crates/fly-session-types", "crates/flybrain-core", diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml new file mode 100644 index 0000000..803adaf --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "fly-legacy-session" +version.workspace = true +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, 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" + +# SHADOW-01: the session runtime run beside the live fly (`infra/units/flyshadow.service`). +[[bin]] +name = "fly-shadow" +path = "src/bin/fly-shadow.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. 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", "signal"] } +# 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/reward_bearing.rs b/services/flysim/crates/fly-legacy-session/examples/reward_bearing.rs new file mode 100644 index 0000000..166b292 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/examples/reward_bearing.rs @@ -0,0 +1,39 @@ +//! `reward_bearing IN OUT`: a copy of a FLYSIM01 checkpoint with its adapter ledger thinned so the +//! real brain earns rewards where the fly already stands -- the current map unvisited (an `AREA` +//! payout on the first sample), its exits unfound (`boundary`), its ground unwalked +//! (`exploration`), no wild win a replay (`battle`). TASK-01's brain arm +//! (`tests/session_trace.rs`), as a file for SHADOW-01's rehearsal (`tools/shadow-rehearsal.sh`), +//! where the real service restores it. A test fixture, never a stream checkpoint. + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let [input, output] = args.as_slice() else { + eprintln!("usage: reward_bearing IN OUT"); + std::process::exit(2); + }; + let bytes = std::fs::read(input).expect("the checkpoint reads"); + 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"] = serde_json::json!({}); + reward["replayBlocked"] = serde_json::json!([]); + let out = flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes"); + std::fs::write(output, out).expect("the copy writes"); + eprintln!("thinned map {map}: {output}"); +} 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/admission.rs b/services/flysim/crates/fly-legacy-session/src/admission.rs new file mode 100644 index 0000000..c17ebeb --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/admission.rs @@ -0,0 +1,126 @@ +//! Sugar, admitted by the legacy rules onto the coordinator's admission queue, and the operator +//! reward pulse, refused (`legacy-gameboy-v1` section 15 and its amendment of 2026-09-29). +//! +//! The rules are flysim's own, unchanged: `flysim::ratelimit::RateLimiter` (the per-minute limit +//! and "no overlap with an active pulse") and the duration clamp to `[1, sugar_max_ms]`. What +//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed +//! commit** ([`AdmissionQueue::stimulus_remaining_ms`]), which the operator accepted as one commit +//! stale. Until the first commit of an epoch it is unknown, and a request is refused with a retry. +//! A sugar admitted and not yet reported on by a commit counts as active from its admission, as +//! the legacy loop's `stimulate` makes it active at once, so two sugars between two commits are +//! one admission and one `PulseActive` refusal, exactly as the legacy drain answers them. +//! +//! The operator's `POST /reward` pulse is refused. The legacy loop refuses it too unless an +//! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new +//! runtime has no counterpart to turn on, and says so rather than approximating one -- a +//! reinforcement outside `Agent.Commit` is not a session-framework operation. + +use flysim::ratelimit::{RateLimiter, Refusal}; + +use fly_session::coordinator::{Admission, AdmissionQueue}; +use fly_session::fly_session_types::gameboy::STIMULUS_REWARD_PULSE; +use fly_session::types::*; + +/// Why `POST /reward` is refused (`legacy-gameboy-v1` section 15, amendment of 2026-09-29). +pub const OPERATOR_REWARD_REFUSED: &str = "the operator reward pulse is not available on the session runtime (legacy-gameboy-v1 section 15)"; + +/// Retry advice while the pulse is unknown: one frame, rounded up. +pub const UNKNOWN_PULSE_RETRY_MS: u64 = 17; + +/// The edge-side admission of the legacy composition. +pub struct LegacyAdmission { + queue: AdmissionQueue, + agent_id: Id, + limiter: RateLimiter, + default_ms: f64, + max_ms: f64, + serial: u64, +} + +impl LegacyAdmission { + /// flysim's defaults: 6 per minute, 400 ms by default, at most 1000 ms. + pub fn new(queue: AdmissionQueue, agent_id: Id) -> LegacyAdmission { + let control = flysim::config::Config::default().control; + LegacyAdmission::with_limits( + queue, + agent_id, + control.sugar_per_minute, + control.sugar_default_ms, + control.sugar_max_ms, + ) + } + + pub fn with_limits( + queue: AdmissionQueue, + agent_id: Id, + per_minute: usize, + default_ms: f64, + max_ms: f64, + ) -> LegacyAdmission { + LegacyAdmission { + queue, + agent_id, + limiter: RateLimiter::new(per_minute), + default_ms, + max_ms, + serial: 0, + } + } + + fn next_id(&mut self, kind: &str) -> Id { + self.serial += 1; + id(&format!("{kind}-{}", self.serial)) + } + + /// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is + /// queued for the next Prepare; the result is its interaction id and the clamped duration. + pub fn sugar(&mut self, now_ms: u64, duration_ms: Option) -> Result<(Id, f64), Refusal> { + // Read the pulse, decide and queue under one lock, so a commit cannot land between the + // reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by + // a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs: + // a second request before the next commit is refused (`PulseActive`), not admitted + // into a pulse that would take the max and add nothing (review N1). + let agent_id = self.agent_id.clone(); + let interaction_id = self.next_id("sugar"); + let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms); + let admission = self.queue.admit_with(&agent_id, |remaining, pending| { + let Some(remaining) = remaining else { + return Err(Refusal::PulseActive { + retry_after_ms: UNKNOWN_PULSE_RETRY_MS, + }); + }; + limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?; + let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms); + Ok(Admission::Stimulus { + agent_id: agent_id.clone(), + interaction_id: interaction_id.clone(), + kind_id: id(STIMULUS_REWARD_PULSE), + duration_ms: duration, + }) + }); + if admission.is_err() { + // A refusal spends no id. + self.serial -= 1; + } + let Admission::Stimulus { duration_ms: duration, .. } = admission?; + Ok((interaction_id, duration)) + } + + /// `POST /reward`: refused, always (the legacy default, `control.allow_reward = false`). + pub fn reward(&mut self, _value: f64) -> Result { + Err(OPERATOR_REWARD_REFUSED) + } + + /// Admits exactly this sugar, bypassing the rules: a parity run replays the legacy loop's + /// admitted inputs, it does not re-decide them. + pub fn replay_sugar(&mut self, duration_ms: f64) -> Id { + let interaction_id = self.next_id("sugar"); + self.queue.admit(Admission::Stimulus { + agent_id: self.agent_id.clone(), + interaction_id: interaction_id.clone(), + kind_id: id(STIMULUS_REWARD_PULSE), + duration_ms, + }); + interaction_id + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs new file mode 100644 index 0000000..f669945 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/bin/fly-shadow.rs @@ -0,0 +1,350 @@ +//! `fly-shadow`: SHADOW-01, the session runtime run beside the live fly. +//! +//! ```text +//! fly-shadow run [options] follow the live trace, compare, write the verdict (the unit) +//! fly-shadow check [options] exit 0 only if the verdict allows the cutover (CUT-01's hook) +//! ``` +//! +//! `run` reads the live service's own configuration the way flysim does (`/etc/fly/fly.env` through +//! the unit's `EnvironmentFile`, `FLY_STATE`, `FLY_STATE_HOT`, ...): the cartridge, the dataset, the +//! stores (read only), the macro mode, the speed and the metrics listener. Options: +//! +//! | Option | Default | +//! | --- | --- | +//! | `--trace-dir DIR` | `$FLY_TRACE_DIR` | +//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` | +//! | `--spool DIR` | `/spool` | +//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `/work`: sockets and artifact stores | +//! | `--mode in-process\|thread\|process` | `in-process` | +//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads | +//! | `--required-brain-seconds S` | 10800 | +//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) | +//! | `--metrics HOST:PORT` | the live metrics listener | +//! | `--spool-max-mib N` | 512 | +//! | `--context N` | 30 transition pairs before a divergence | +//! | `--all-files` | follow every trace file present, oldest first (a rehearsal) | +//! | `--keep-traces` | keep compared trace files | +//! | `--keep-spool` | keep every spooled live checkpoint (a rehearsal replays them) | +//! | `--exit-on-pass` | exit once the verdict is `pass` | +//! | `--max-transitions N` | stop after N compared transitions | +//! +//! Exit status: 0 passed or stopped, 3 diverged, 2 the shadow's own error. +//! +//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING] +//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current` +//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for +//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the +//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`, +//! SERVE-01's service). `--compatibility` defaults to this build's legacy compatibility string. + +use std::path::PathBuf; +use std::time::Duration; + +use fly_legacy_session::shadow::{self, LagGuard, ShadowConfig, StopFlag, verdict}; +use fly_session::ExecutionMode; + +fn usage() -> ! { + eprintln!("usage: fly-shadow run [options] | fly-shadow check --verdict FILE [options]"); + std::process::exit(2); +} + +fn die(message: impl std::fmt::Display) -> ! { + eprintln!("fly-shadow: {message}"); + std::process::exit(2); +} + +struct Args(Vec); + +impl Args { + fn flag(&mut self, name: &str) -> bool { + match self.0.iter().position(|a| a == name) { + Some(i) => { + self.0.remove(i); + true + } + None => false, + } + } + + fn value(&mut self, name: &str) -> Option { + let i = self.0.iter().position(|a| a == name)?; + if i + 1 >= self.0.len() { + die(format!("{name} needs a value")); + } + let value = self.0.remove(i + 1); + self.0.remove(i); + Some(value) + } + + fn parsed(&mut self, name: &str) -> Option { + self.value(name).map(|v| { + v.parse() + .unwrap_or_else(|_| die(format!("{name}: cannot parse {v:?}"))) + }) + } + + fn done(self) { + if !self.0.is_empty() { + die(format!("unknown arguments: {:?}", self.0)); + } + } +} + +fn env_path(name: &str) -> Option { + std::env::var_os(name) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + +fn file_sha256(path: &std::path::Path) -> String { + let bytes = std::fs::read(path).unwrap_or_else(|e| die(format!("{}: {e}", path.display()))); + shadow::sha256_hex(&bytes) +} + +fn this_binary() -> PathBuf { + std::env::current_exe().unwrap_or_else(|e| die(format!("current_exe: {e}"))) +} + +/// The release binaries a verdict vouches for: SERVE-01's service (`flysim-session`, what CUT-01 +/// switches to), its worker program, the shadow itself, the legacy service and the edge. +const RELEASE_BINARIES: [&str; 5] = [ + "flysim-session", + "fly-session", + "fly-shadow", + "flysim", + "fly-edge", +]; + +/// SHA-256 of the release binaries in `dir`, by name. +fn binaries_in(dir: &std::path::Path) -> std::collections::BTreeMap { + RELEASE_BINARIES + .iter() + .filter_map(|name| { + let path = dir.join(name); + path.is_file() + .then(|| ((*name).to_owned(), file_sha256(&path))) + }) + .collect() +} + +/// The resolved directory of this binary: the release it runs from. +fn this_release() -> PathBuf { + this_binary() + .parent() + .and_then(|d| d.canonicalize().ok()) + .unwrap_or_default() +} + +fn main() { + let mut argv: Vec = std::env::args().skip(1).collect(); + if argv.is_empty() { + usage(); + } + let command = argv.remove(0); + let mut args = Args(argv); + match command.as_str() { + "run" => run(args), + "check" => { + let verdict_path: PathBuf = args + .value("--verdict") + .map(PathBuf::from) + .unwrap_or_else(|| usage()); + // The release CUT-01 switches into (what `/opt/fly/current` resolves to now), and the + // binary in it that it switches to: SERVE-01's service. + let current = args + .value("--current") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/opt/fly/current")); + let binary = args + .value("--binary") + .unwrap_or_else(|| "flysim-session".to_owned()); + let compatibility = args.value("--compatibility"); + let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300); + args.done(); + let compatibility = compatibility.unwrap_or_else(|| { + let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e)); + flysim::simloop::compatibility_string(&config).unwrap_or_else(|e| die(e)) + }); + let text = std::fs::read_to_string(&verdict_path) + .unwrap_or_else(|e| die(format!("{}: {e}", verdict_path.display()))); + let value: serde_json::Value = + serde_json::from_str(&text).unwrap_or_else(|e| die(format!("verdict: {e}"))); + let now = verdict::parse_iso(&verdict::now_iso()).expect("now parses"); + let dir = current + .canonicalize() + .unwrap_or_else(|e| die(format!("{}: {e}", current.display()))); + let binaries = binaries_in(&dir); + let dir_text = dir.display().to_string(); + let release = verdict::Release { + dir: &dir_text, + binaries: &binaries, + }; + match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) { + Ok(()) => println!("cutover allowed: {}", value["reason"]), + Err(reason) => { + println!("cutover refused: {reason}"); + std::process::exit(1); + } + } + } + _ => usage(), + } +} + +fn run(mut args: Args) { + let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(format!("{e:#}"))); + let out_dir = args + .value("--out") + .map(PathBuf::from) + .or_else(|| env_path("FLY_SHADOW_DIR")) + .unwrap_or_else(|| die("--out or FLY_SHADOW_DIR is required")); + let trace_dir = args + .value("--trace-dir") + .map(PathBuf::from) + .or_else(|| env_path(flysim::trace::DIR_ENV)) + .unwrap_or_else(|| die("--trace-dir or FLY_TRACE_DIR is required")); + let spool_dir = args + .value("--spool") + .map(PathBuf::from) + .unwrap_or_else(|| out_dir.join("spool")); + let work_dir = args + .value("--work") + .map(PathBuf::from) + .or_else(|| env_path("FLY_SHADOW_WORK")) + .unwrap_or_else(|| out_dir.join("work")); + let mode = match args.value("--mode").as_deref() { + None | Some("in-process") => ExecutionMode::InProcess, + Some("thread") => ExecutionMode::Thread, + Some("process") => ExecutionMode::Process, + Some(other) => die(format!("--mode {other:?}")), + }; + let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| { + std::env::var("FLY_SHADOW_THREADS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(2) + }); + let required: f64 = args + .parsed("--required-brain-seconds") + .unwrap_or(shadow::REQUIRED_BRAIN_SECONDS); + let lag_margin: f64 = args.parsed("--lag-guard-margin").unwrap_or(0.05); + let metrics = args.value("--metrics").or_else(|| { + config.control.metrics_bind.map(|addr| { + if addr.ip().is_unspecified() { + format!("127.0.0.1:{}", addr.port()) + } else { + addr.to_string() + } + }) + }); + let spool_mib: u64 = args.parsed("--spool-max-mib").unwrap_or(512); + let context_lines: usize = args.parsed("--context").unwrap_or(30); + let all_files = args.flag("--all-files"); + let keep_traces = args.flag("--keep-traces"); + let keep_spool = args.flag("--keep-spool"); + let exit_on_pass = args.flag("--exit-on-pass"); + let max_transitions: Option = args.parsed("--max-transitions"); + // Undocumented: the toy connectome, for tests only. + let profile = match args.value("--profile") { + None => fly_session::legacy_agent::LegacyProfileKind::Production, + Some(p) => { + fly_session::legacy_agent::LegacyProfileKind::parse(&p).unwrap_or_else(|e| die(e)) + } + }; + args.done(); + + if config.loop_.game != "pokemon-red" { + die(format!( + "the legacy composition is Pokémon Red, not {:?}", + config.loop_.game + )); + } + if u64::from(config.feed.audio_hz) != fly_session::legacy_env::DEFAULT_AUDIO_RATE { + die(format!( + "the live service's audio rate {} is not the legacy environment's {}", + config.feed.audio_hz, + fly_session::legacy_env::DEFAULT_AUDIO_RATE + )); + } + let baseline_file = out_dir.join("baseline.json"); + let lag_guard = (lag_margin > 0.0) + .then_some(()) + .and(metrics) + .map(|metrics_addr| LagGuard { + metrics_addr, + baseline_file: Some(baseline_file), + margin: lag_margin, + window: Duration::from_secs(60), + back_off: Duration::from_secs(60), + suppress: Duration::from_secs(600), + }); + let shadow_config = ShadowConfig { + trace_dir, + hot_dir: config.paths.hot_dir.clone(), + durable_dir: config.paths.save_dir.clone(), + out_dir, + spool_dir, + work_dir, + rom_path: config.paths.rom.clone(), + dataset_dir: config.paths.dataset.clone(), + profile, + macro_mode: config.macros.mode, + speed: config.loop_.speed, + mode, + agent_threads, + required_brain_seconds: required, + all_files, + keep_traces, + keep_spool, + exit_on_pass, + max_transitions, + spool_max_bytes: spool_mib << 20, + context_lines, + poll: Duration::from_millis(100), + lag_guard, + binary_sha256: file_sha256(&this_binary()), + binaries: binaries_in(&this_release()), + release: this_release().display().to_string(), + }; + eprintln!( + "fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)", + mode.label(), + agent_threads, + shadow_config.trace_dir.display(), + shadow_config.hot_dir.display(), + shadow_config.durable_dir.display() + ); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap_or_else(|e| die(format!("tokio: {e}"))); + let stop = StopFlag::default(); + let ended = runtime.block_on(async { + let signals = stop.clone(); + tokio::spawn(async move { + use tokio::signal::unix::{SignalKind, signal}; + let mut term = signal(SignalKind::terminate()).expect("SIGTERM"); + let mut int = signal(SignalKind::interrupt()).expect("SIGINT"); + tokio::select! { + _ = term.recv() => {} + _ = int.recv() => {} + } + eprintln!("fly-shadow: stopping"); + signals.request(); + }); + shadow::run(shadow_config, stop).await + }); + match ended { + Ok((shadow::Ended::Diverged, _)) => std::process::exit(3), + Ok((ended, verdict)) => { + eprintln!( + "fly-shadow: {ended:?}; {} transitions ({:.1} brain s) identical, verdict {}", + verdict.agreement.transitions, + verdict.brain_seconds(), + verdict.status.as_str() + ); + } + Err(e) => die(e), + } +} 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 new file mode 100644 index 0000000..ae0148e --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -0,0 +1,806 @@ +//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the +//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the +//! coordinator, over one router, in any of the launcher's execution modes. +//! +//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01 +//! export (STATE-02): what CUT-01's shadow runs beside the legacy service. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use flybus::{Grants, Pattern, Policy, RouterConfig}; + +use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport}; +use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; +use fly_session::fly_session_types::gameboy; +use fly_session::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, + ThreadBudget, Via, +}; +use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT}; +use fly_session::legacy_env::BackendConfig; +use fly_session::task::ActionExecutor; +use fly_session::types::*; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flysim::snapshot::MacroMode; + +use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; +use fly_session::legacy_checkpoint::{ + AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, + SaveReport, SaveTicket, TaskHalf, now_wall_ms, +}; +use flysim::store::Checkpoint; +use std::time::Instant; + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz). +const HISTORY: usize = 4096; + +/// A service session's committed-snapshot cadence on the session topic: once a second of frames +/// (every 60th boundary), plus every boundary with task events or boundary actions, which the +/// coordinator always publishes. The live presentation is the legacy feed (`docs/feed-protocol.md`, +/// 30 Hz, built by the service host from the committed boundary), not this topic, which nothing +/// in the release subscribes to; each snapshot attaches a sealed copy of the frame and the audio +/// chunk, so publishing it every other frame cost about 0.7 ms a frame on the release CPU +/// (PERF-01; was 2). +const SNAPSHOT_EVERY: u64 = 60; + +const COORDINATOR_CLIENT: &str = "coordinator"; +const ENV_CLIENT: &str = "legacy-world"; +const ENV_SERVICE: &str = "env.world"; +const ENV_WORKER: &str = "world"; +const AGENT_CLIENT: &str = "legacy-fly"; + +/// How one legacy session is composed. +#[derive(Clone, Debug)] +pub struct LegacyConfig { + pub mode: ExecutionMode, + pub rom_path: PathBuf, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + pub macro_mode: MacroMode, + pub agent_id: Id, + pub agent_threads: usize, + /// Record the step details and the task records (a parity run). + pub record: bool, +} + +/// `FLY_SESSION_LOCAL_LANE=0` keeps in-process participants on the bus: a measurement knob, +/// so the local lane can be compared with the bus path in one build. On by default. +pub const LOCAL_LANE_ENV: &str = "FLY_SESSION_LOCAL_LANE"; + +fn local_lane_enabled() -> bool { + std::env::var(LOCAL_LANE_ENV).map_or(true, |v| v != "0") +} + +/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds. +pub fn channels_and_hold(mode: MacroMode) -> (Vec, f64) { + let channels: Vec<&str> = if mode.dealt() { + flybrain_gb::macro_channels(crate::task::GAME) + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .map_or(0.0, |group| group.hold_ms); + (channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms) +} + +/// A running legacy session: its launcher, its coordinator and the task object. +pub struct LegacySession { + pub coordinator: Coordinator, + pub task: PokeredTask, + pub launcher: Launcher, + pub rom: Vec, + pub config: LegacyConfig, + session_id: Id, + backend: BackendConfig, + /// Which generation of the world is running: 1 is the one the session started. + world_generation: u32, + /// The legacy store policy, once attached ([`LegacySession::attach_store`]). + checkpointer: Option, + saves: u64, + /// Saves on the writer thread whose outcome has not been collected. + pending_saves: Vec, + /// Captures sent and not yet collected ([`LegacySession::begin_save`]). + pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>, + /// The feed event log's watermark the saves record: the restored file's, carried over (the + /// session runtime has no feed event log of its own before EDGE-01). + last_event_id: u64, +} + +/// Where the legacy store lives and how often it is written (the service's `[paths]` and +/// `[loop]`). +#[derive(Clone, Debug)] +pub struct StoreConfig { + pub hot_dir: PathBuf, + pub durable_dir: PathBuf, + pub keep_generations: usize, + pub hot_seconds: f64, + pub checkpoint_seconds: f64, + pub speed: f64, +} + +/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the +/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is +/// the restore gate and what every save records (`legacy-gameboy-v1` section 12). +pub fn compatibility_of(config: &LegacyConfig) -> String { + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let profile = config.profile.profile(); + flybrain_gb::Compatibility { + neural_kernel_version: gameboy::KERNEL_VERSION, + adapter: flybrain_gb::GameAdapter::id(&adapter), + dataset_fingerprint: &profile.dataset_fingerprint, + plasticity_version: gameboy::PLASTICITY_VERSION, + pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter), + } + .string() +} + +/// How a session came up. +#[derive(Debug)] +pub enum Boot { + /// No checkpoint in either store: a fresh fly, warmed up. + Fresh, + /// A candidate restored, after `skipped` were refused. + Restored { + candidate: flysim::store::Candidate, + skipped: Vec<(flysim::store::Candidate, String)>, + migrated_from: Option, + imported: crate::import::Imported, + }, +} + +/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order +/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each +/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision +/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or +/// refused by a participant's `State.StageRestore` or the task. A refused install fences its +/// session, so each attempt runs on a session of its own (a directory under `root` each). No +/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop +/// refuses to start a fresh fly over them. Either way the store is attached and the startup +/// durable save is written, and the intervals run from then. +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); + let candidates = flysim::store::restore_order(&hot, &durable); + let rom = std::fs::read(&config.rom_path) + .map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?; + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let gate = fly_session::legacy_checkpoint::RestoreGate::from_env( + &sha256_hex(&rom), + &compatibility_of(&config), + flybrain_gb::GameAdapter::migrates_from(&adapter), + ); + let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new(); + let mut outcome = None; + for (attempt, candidate) in candidates.iter().enumerate() { + let checkpoint = match flysim::store::load(&candidate.path) { + Ok(checkpoint) => checkpoint, + Err(e) => { + skipped.push((candidate.clone(), format!("{e:#}"))); + continue; + } + }; + let migrated_from = match gate.check(&checkpoint) { + Ok(from) => from, + Err(reason) => { + skipped.push((candidate.clone(), reason)); + continue; + } + }; + let mut session = + LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?; + let installed = match session.bootstrap().await { + Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await, + Err(e) => Err(e), + }; + match installed { + Ok(imported) => { + let rank = session.task.rank(); + session.attach_store(store)?; + session + .checkpointer_mut() + .expect("attached") + .restored(rank, imported.rank_since_ms); + outcome = Some(( + session, + Boot::Restored { + candidate: candidate.clone(), + skipped: std::mem::take(&mut skipped), + migrated_from, + imported, + }, + )); + break; + } + Err(reason) => { + session.stop().await; + skipped.push((candidate.clone(), reason)); + } + } + } + let (session, boot) = match outcome { + Some(pair) => pair, + None if candidates.is_empty() => { + let mut session = LegacySession::start(&root.join("fresh"), config).await?; + session.bootstrap().await?; + session.attach_store(store)?; + (session, Boot::Fresh) + } + None => { + let reasons: Vec = skipped + .iter() + .map(|(candidate, reason)| format!("{}: {reason}", candidate.origin)) + .collect(); + return Err(format!( + "every one of the {} checkpoint candidates failed to load; refusing to start a \ + fresh run over them:\n{}", + candidates.len(), + reasons.join("\n") + )); + } + }; + Ok((session, boot)) +} + +/// A save [`LegacySession::advance`] queued at the boundary it reached. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SaveQueued { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, +} + +/// One transition as a parity run sees it. +pub struct Step { + pub report: StepReport, + pub details: Option, + pub records: Vec, +} + +impl LegacySession { + /// Builds the router, launches the world and the fly, and builds the coordinator with the task + /// object's two faces. Nothing has been initialized yet. + pub async fn start(root: &Path, config: LegacyConfig) -> Result { + let rom = std::fs::read(&config.rom_path) + .map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?; + let rom_digest = sha256_hex(&rom); + let session_id = id("legacy"); + let epoch = id("e1"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let agent_service = format!("agent.{}", config.agent_id); + let policy = Policy::closed() + .client( + COORDINATOR_CLIENT, + grants(|g| { + g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]; + g.publish = vec![Pattern::prefix("session.")]; + g.manage_topics = vec![Pattern::prefix("session.")]; + g.register = vec![Pattern::prefix("session.")]; + }), + ) + // The launcher's supervisor: health checks and shutdown, never a registration. + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]), + ) + .client( + ENV_CLIENT, + grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]), + ) + .client( + &format!("{ENV_CLIENT}-r2"), + grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]), + ) + .client( + AGENT_CLIENT, + grants(|g| g.register = vec![Pattern::exact(&agent_service)]), + ); + let mut router_config = RouterConfig::new(&store_root); + router_config.policy = policy; + let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?; + let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?; + let mut launcher = Launcher::start( + router, + config.mode, + // In-process participants reach the router in memory: no socket between two tasks + // of one process (a separate process always uses the socket). They are called over + // the local lane: the same worker shell, no bus message and no store file per + // artifact (PERF-01, `workers-v1` amendment). + if local_lane_enabled() { Via::Local } else { Via::Memory }, + &store_root, + &sockets, + budget, + ) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + + let mut backend = BackendConfig::legacy(&rom_digest); + backend.slots = vec![id(crate::task::SLOT)]; + launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: session_id.clone(), + worker_id: id(ENV_WORKER), + incarnation_id: id("world-inc-1"), + worker_threads: 1, + rom_path: config.rom_path.clone(), + backend: backend.clone(), + client_id: ENV_CLIENT.to_owned(), + service: ENV_SERVICE.to_owned(), + }) + .await + .map_err(|e| format!("the world: {}", e.message))?; + let environment = launcher + .worker(&id(ENV_WORKER)) + .expect("launched") + .worker_ref(); + + let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode); + let identity = launcher + .launch_legacy_agent(LegacyAgentLaunch { + session_id: session_id.clone(), + agent_id: config.agent_id.clone(), + port_id: id(fly_session::legacy_env::DEFAULT_PORT), + incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?, + worker_threads: config.agent_threads, + dataset_dir: config.dataset_dir.clone(), + profile: config.profile, + macro_channels: macro_channels.clone(), + client_id: AGENT_CLIENT.to_owned(), + service: agent_service, + }) + .await + .map_err(|e| format!("the fly: {}", e.message))?; + let agent_ref = launcher + .worker(&config.agent_id) + .expect("launched") + .worker_ref(); + let mut slot = AgentSlot::new( + agent_ref, + config.agent_id.clone(), + id(fly_session::legacy_env::DEFAULT_PORT), + config.profile.profile().asset, + fly_session::legacy_parity::LEGACY_SEED, + ); + slot.worker_threads = identity.worker_threads as u64; + slot.model_version = gameboy::KERNEL_VERSION.to_owned(); + slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned(); + + let task = PokeredTask::new( + PokeredConfig { + agent_id: config.agent_id.clone(), + port_id: id(fly_session::legacy_env::DEFAULT_PORT), + mode: config.macro_mode, + macro_channels, + hold_ms, + record: config.record, + }, + &rom, + &rom_digest, + &epoch, + )?; + let client = launcher + .connect(COORDINATOR_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let executors: BTreeMap> = + BTreeMap::from([(config.agent_id.clone(), task.executor())]); + let mut coordinator = Coordinator::new( + client, + session_id.clone(), + epoch, + id("ep1"), + environment, + vec![slot], + task.task(), + executors, + ); + coordinator.set_environment_config( + backend.asset_ref(), + fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID), + ); + coordinator.set_media( + &[gameboy::VIEW_ID], + &[fly_session::legacy_env::AUDIO_STREAM_ID], + ); + coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID); + coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref()); + coordinator + .declare_rollback_policy(ROLLBACK_POLICY) + .map_err(|e| e.message)?; + // The legacy loop runs as fast as its brain allows when measured, and the service paces + // itself; a parity run is a measurement. + if config.record { + coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]); + } else { + // A service session runs indefinitely: its in-memory history stays bounded. + coordinator.bound_history(HISTORY); + // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. + coordinator.snapshot_every(SNAPSHOT_EVERY); + } + Ok(LegacySession { + coordinator, + task, + launcher, + rom, + config, + session_id, + backend, + world_generation: 1, + checkpointer: None, + saves: 0, + pending_saves: Vec::new(), + pending_captures: Vec::new(), + last_event_id: 0, + }) + } + + /// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0], + /// `Agent.Initialize` (the warm-up): `Ready(0)`. + pub async fn bootstrap(&mut self) -> Result<(), String> { + self.coordinator + .bootstrap() + .await + .map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?; + if self.config.record { + self.coordinator.disable_pacing(); + } + Ok(()) + } + + /// The agent's identity as an import stamps it. + pub fn agent_import(&self) -> AgentImport { + let (macro_channels, _) = channels_and_hold(self.config.macro_mode); + AgentImport { + agent_id: self.config.agent_id.clone(), + profile: self.config.profile.profile().asset, + seed: fly_session::legacy_parity::LEGACY_SEED, + macro_channels, + } + } + + /// This build's legacy compatibility string ([`compatibility_of`]). + pub fn compatibility(&self) -> String { + compatibility_of(&self.config) + } + + /// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`], + /// before any transition): the world is replaced by a fresh one (the environment stages a + /// restore only on a replacement, as every group restore does), then [`crate::import`] runs + /// the group install and the session resumes at the checkpoint's boundary. + pub async fn import_checkpoint( + &mut self, + checkpoint: &Checkpoint, + epoch: &Id, + ) -> Result { + if self.world_generation != 1 { + return Err("this session has already replaced its world".to_owned()); + } + self.launcher.reap(&id(ENV_WORKER), &id("import")).await; + self.world_generation = 2; + self.launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: self.session_id.clone(), + worker_id: id(ENV_WORKER), + incarnation_id: id("world-inc-2"), + worker_threads: 1, + rom_path: self.config.rom_path.clone(), + backend: self.backend.clone(), + client_id: format!("{ENV_CLIENT}-r2"), + service: ENV_SERVICE.to_owned(), + }) + .await + .map_err(|e| format!("the replacement world: {}", e.message))?; + let world = self + .launcher + .worker(&id(ENV_WORKER)) + .expect("launched") + .worker_ref(); + self.coordinator + .replace_participant(&id(ENV_WORKER), world) + .map_err(|e| format!("replacing the world: {}", e.error.message))?; + let rom = self.rom.clone(); + let agent = self.agent_import(); + let imported = crate::import::import_flysim01( + &mut self.coordinator, + &self.task, + checkpoint, + &rom, + &agent, + self.backend.audio_sample_rate, + epoch, + ) + .await?; + if self.config.record { + self.coordinator.disable_pacing(); + } + self.last_event_id = checkpoint.runtime.last_event_id; + Ok(imported) + } + + /// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]). + pub async fn import_flysim01( + &mut self, + bytes: &[u8], + epoch: &Id, + ) -> Result { + let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?; + self.import_checkpoint(&checkpoint, epoch).await + } + + // -- the store (STATE-02) ------------------------------------------------------------------ + + /// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot + /// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from + /// here on, so a milestone capture lands between the boundary's slot save and its rollback. + pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> { + let checkpointer = LegacyCheckpointer::open(CheckpointerConfig { + hot_dir: store.hot_dir.clone(), + durable_dir: store.durable_dir.clone(), + keep_generations: store.keep_generations, + hot_seconds: store.hot_seconds, + checkpoint_seconds: store.checkpoint_seconds, + compatibility: self.compatibility(), + speed: store.speed, + slot_id: id(crate::task::SLOT), + })?; + self.checkpointer = Some(checkpointer); + self.coordinator.defer_rollbacks(true); + Ok(()) + } + + pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> { + self.checkpointer.as_ref() + } + + pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> { + 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. + pub async fn save(&mut self, kind: SaveKind) -> Result { + let ticket = self.queue_save(kind).await?; + ticket + .reply + .await + .map_err(|_| "the checkpoint writer stopped".to_owned())? + } + + /// One save of the committed boundary, queued: the participants capture now (the boundary's + /// state) and the encoding and fsync run on the checkpointer's writer thread while the loop + /// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The + /// outcome is collected by [`LegacySession::completed_saves`]. + pub async fn queue_save(&mut self, kind: SaveKind) -> Result { + self.begin_save(kind).await?; + let mut tickets = self.finish_captures().await?; + let last = tickets + .pop() + .ok_or_else(|| "no save was begun".to_owned())?; + self.pending_saves.extend(tickets); + Ok(last) + } + + /// Begins one save of the committed boundary: every participant's `State.Capture` is sent + /// (each takes its state now) and the task's half is taken now; the session may step on + /// while the agent encodes and seals its payload off its lock + /// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`] + /// hands it to the writer. + pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> { + self.saves += 1; + let capture = self + .coordinator + .begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let (task, _slot_filled) = self.task.task_half(); + self.pending_captures.push((capture, kind, task)); + Ok(()) + } + + /// Collects every begun capture, in order, and queues it to the checkpointer's writer. + pub async fn finish_captures(&mut self) -> Result, String> { + let mut tickets = Vec::new(); + for (capture, kind, task) in std::mem::take(&mut self.pending_captures) { + let (boundary, world, agents) = self + .coordinator + .finish_capture(capture) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let [(_, agent)] = <[(Id, Vec); 1]>::try_from(agents) + .map_err(|_| "the legacy composition has exactly one agent".to_owned())?; + let capture = LegacyCapture { + boundary, + agent_payload: agent, + world_payload: world, + task, + }; + let last_event_id = self.last_event_id; + let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; + tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?); + } + Ok(tickets) + } + + /// The saves queued so far that have committed (or failed), without waiting; with `wait`, + /// every queued save's outcome. Every outcome is reported, a failed save as its own `Err` + /// beside the others (TASK-01 review R2-2): the caller decides. + pub async fn completed_saves(&mut self, wait: bool) -> Vec> { + let mut done = Vec::new(); + let mut still = Vec::new(); + for mut ticket in std::mem::take(&mut self.pending_saves) { + let stopped = || Err("the checkpoint writer stopped".to_owned()); + if wait { + done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped())); + } else { + match ticket.reply.try_recv() { + Ok(result) => done.push(result), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket), + Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()), + } + } + } + self.pending_saves = still; + done + } + + /// Hands every begun capture to the writer now and reports what was queued. `advance` does + /// this after the next step so the agent's sealing overlaps it; a step that fails does it + /// before returning the error, and a caller that pauses (or is about to stop stepping) calls + /// this so a save begun at the last boundary reaches the writer as the legacy loop's + /// immediate hand-off would have (TASK-01 review R2-1). + pub async fn flush_captures(&mut self) -> Result, String> { + let mut saves = Vec::new(); + for ticket in self.finish_captures().await? { + saves.push(SaveQueued { + generation: ticket.generation, + durable: ticket.durable, + archive_rank: ticket.archive_rank, + }); + self.pending_saves.push(ticket); + } + Ok(saves) + } + + /// One transition and what the legacy loop does at the boundary it reaches, in the declared + /// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the + /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save + /// after it, then the interval saves (`checkpoint_if_due`). + pub async fn advance(&mut self) -> Result<(Step, Vec), String> { + let report = match self.coordinator.step().await { + Ok(report) => report, + Err(e) => { + // The legacy writer already has the saves of the earlier boundaries: hand the + // begun captures over before reporting the failure (TASK-01 review R2-1). + let flushed = self.flush_captures().await.err(); + let mut message = + format!("step ({} at {}): {}", e.detail, e.phase, e.error.message); + if let Some(flush) = flushed { + message.push_str(&format!("; and the pending saves: {flush}")); + } + return Err(message); + } + }; + // The captures begun at the last boundary: the agent sealed its payload while this + // transition's Prepare ticked. + let saves = self.flush_captures().await?; + if self.checkpointer.is_some() { + let rank = self.task.rank(); + let ms = self.task.brain_ms(); + let change = self + .checkpointer + .as_mut() + .expect("attached") + .observe_rank(rank, ms); + if let Some(RankChange::Climbed(rank)) = change { + self.begin_save(SaveKind::Milestone(rank)).await?; + } + } + let rolled_back = self + .coordinator + .apply_pending_rollback() + .await + .map_err(|e| { + format!( + "rollback ({} at {}): {}", + e.detail, e.phase, e.error.message + ) + })?; + if self.checkpointer.is_some() { + if rolled_back { + self.begin_save(SaveKind::Durable).await?; + } + let due = self + .checkpointer + .as_mut() + .expect("attached") + .due(Instant::now()); + if let Some(kind) = due { + self.begin_save(kind).await?; + } + } + Ok(( + Step { + report, + details: self.coordinator.take_details(), + records: self.task.take_records(), + }, + saves, + )) + } + + /// One transition, with its details when recorded ([`LegacySession::advance`] without the + /// saves it reports). + pub async fn step(&mut self) -> Result { + self.advance().await.map(|(step, _)| step) + } + + /// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed. + pub async fn shutdown_save(&mut self) -> Result, String> { + if self.checkpointer.is_none() { + return Ok(None); + } + self.flush_captures().await?; + let report = self.save(SaveKind::Durable).await?; + let outcomes = self.completed_saves(true).await; + if let Some(checkpointer) = self.checkpointer.as_mut() { + checkpointer.close(); + } + // Every queued save has been waited for; the first failure is the shutdown's. + for outcome in outcomes { + outcome?; + } + Ok(Some(report)) + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/driver.rs b/services/flysim/crates/fly-legacy-session/src/driver.rs new file mode 100644 index 0000000..89c2c82 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/driver.rs @@ -0,0 +1,79 @@ +//! A stub readout for parity runs that must earn real rewards: the rotation driver of flysim's ROM +//! tests (`tests/rom_catch.rs`, `tests/rom_macros_mode.rs`) -- a decoder of its own, fed rates +//! that lean on one macro population at a time, rotating every [`BURST_FRAMES`] frames. +//! +//! The brain still ticks and decodes exactly as it would; the driver only replaces the decision +//! the executor is handed, at the one point the legacy loop lets a harness do that +//! (`flysim::frame::FrameObserver::readout`). A session run hands the same driver the same +//! `(ms, bound)` in its executor ([`crate::task::PokeredTask::set_driver`]), so both arms press the +//! same macros and the rewards those macros earn reach `Agent.Commit`. Not a service path. + +use flybrain_core::decoder::PopulationDecoder; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::ordered::NumberMap; + +/// Frames the stub leans on one channel before the rotation moves on (`rom_catch.rs`). +pub const BURST_FRAMES: u32 = 24; +/// The hot population's rate, and every other one's (`rom_catch.rs`). +const HOT: f64 = 16.0; +const REST: f64 = 10.0; + +/// Replaces a decision, given the brain clock and the scene's bound channels. +pub trait DecisionDriver: Send { + fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec); +} + +/// The rotation: one macro population hot at a time, in channel order. +pub struct RotationDriver { + decoder: PopulationDecoder, + channels: Vec<&'static str>, + frame: u32, +} + +impl Default for RotationDriver { + fn default() -> Self { + Self::new() + } +} + +impl RotationDriver { + pub fn new() -> RotationDriver { + let channels = flybrain_gb::macro_channels(crate::task::GAME); + let mut decoder = PopulationDecoder::new(gameboy_decoder_config_with_macros(&channels)) + .expect("the preset is well formed"); + decoder.calibrate(&rates(&channels, None)); + RotationDriver { + decoder, + channels, + frame: 0, + } + } +} + +fn rates(channels: &[&str], hot: Option<&str>) -> NumberMap { + let mut rates = NumberMap::new(); + for channel in channels { + rates.set(channel, REST); + } + for bucket in 0..8 { + rates.set(&format!("command_{bucket}"), REST); + } + if let Some(channel) = hot { + rates.set(channel, HOT); + } + rates +} + +impl DecisionDriver for RotationDriver { + fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec) { + let hot = self.channels[(self.frame / BURST_FRAMES) as usize % self.channels.len()]; + self.frame += 1; + *active = self.decoder.decode_bound( + &rates(&self.channels, Some(hot)), + ms, + false, + None, + Some(bound), + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/import.rs b/services/flysim/crates/fly-legacy-session/src/import.rs new file mode 100644 index 0000000..d5c1284 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/import.rs @@ -0,0 +1,143 @@ +//! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new +//! runtime through the ordinary group restore (`Coordinator::import`). +//! +//! The halves are STATE-02's (`fly_session::legacy_checkpoint`): the world as ENV-01's `FLYENV01` +//! payload at `k = emulatorFrame - 1` with the ratchet's snapshot as slot `best`; the agent as its +//! `FLYAGT01` payload with the file's reinforcement count and the file's framebuffer as the next +//! input, as `LegacyFrame::restore` installs it; the task as `{reward, ratchet, slotFilled}`. The ids +//! come from the file (`flysim01-g`, source scope `(session, legacy, k)`). +//! +//! The rest is `restore: legacy-transient-reset` (`legacy-gameboy-v1` section 14): the executor +//! starts fresh and observes the restored boundary, and the agent's readout transient starts as a +//! fresh process has it. The decision context the agent resumes with is computed here, from the +//! task's ledger and the checkpoint's own memory image. After the install the coordinator holds the +//! task to it: `Task::restored` re-observes the restored world and must derive the same context. + +use std::collections::BTreeMap; + +use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent}; +use fly_session::legacy_agent::legacy_remainder_to_rational; +use fly_session::legacy_checkpoint::{ + AgentImport, agent_payload, halves, import_checkpoint_id, legacy_source_scope, world_payload, +}; +use fly_session::types::*; +use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage}; +use flysim::store::Checkpoint; + +use crate::task::PokeredTask; + +/// What an import installed. +#[derive(Clone, Debug)] +pub struct Imported { + pub boundary: u64, + pub epoch: Id, + pub brain_ticks: u64, + pub checkpoint_id: Id, + /// The file's `rankSinceMs` and generation, for the host's rank tracking and store. + pub rank_since_ms: f64, + pub generation: u64, +} + +/// The checkpoint's memory image at its boundary, read as the environment reads it after an +/// import: the emulator state imported into a stopped emulator, then MEM-01's one bulk read. +pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result { + let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .map_err(|e| format!("the cartridge: {e}"))?; + emulator + .import_state(emulator_state) + .map_err(|e| format!("the emulator state: {e}"))?; + Ok(emulator.read_memory_image()) +} + +/// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no +/// transition, onto a replacement world. `task` is the composition's task object. +pub async fn import_flysim01( + coordinator: &mut Coordinator, + task: &PokeredTask, + checkpoint: &Checkpoint, + rom: &[u8], + agent: &AgentImport, + audio_sample_rate: u64, + new_epoch: &Id, +) -> Result { + let descriptor = coordinator + .descriptor() + .cloned() + .ok_or("the session never bootstrapped")?; + let halves = halves( + checkpoint, + coordinator.episode_id(), + &id(crate::task::SLOT), + audio_sample_rate, + )?; + let boundary = halves.world.boundary; + let checkpoint_id = import_checkpoint_id(halves.host.generation); + let scope = legacy_source_scope(coordinator.session_id(), boundary); + let world = world_payload( + &halves.world, + &coordinator.environment_ref().worker_id, + &checkpoint_id, + &scope, + &descriptor.configuration_digest, + ); + + // The task's ledger, and from it and the restored image the context the agent resumes with. + let (ledger, task_attachments) = + PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty()) + .map_err(|e| format!("the task ledger: {}", e.message))?; + let brain_ms = halves.agent.network.ms; + // `Sim::boot` seeds the palette from the restored brain's RNG state. + task.set_palette_seed(halves.agent.network.rng as u32); + let image = image_of(rom, &halves.world.emulator)?; + let context = task.preview_context(&ledger, &task_attachments, &image, brain_ms)?; + let payload = agent_payload( + &halves.agent, + halves.reinforcements, + &checkpoint.runtime.framebuffer, + agent, + &checkpoint_id, + &scope, + &context, + )?; + let remainder = legacy_remainder_to_rational(halves.agent.remainder) + .map_err(|e| format!("the remainder: {e}"))?; + let audio_positions: BTreeMap = descriptor + .audio + .iter() + .map(|stream| (stream.stream_id.clone(), halves.world.audio_next_sample)) + .collect(); + let spec = ImportSpec { + checkpoint_id: checkpoint_id.clone(), + source_scope: scope, + boundary, + world_payload: world, + agents: vec![ImportedAgent { + agent_id: agent.agent_id.clone(), + payload, + brain_ticks: brain_ms as u64, + remainder, + context, + }], + task_ledger: ledger, + task_attachments, + audio_positions, + }; + coordinator + .import(spec, new_epoch) + .await + .map_err(|e| format!("the import ({}): {}", e.detail, e.error.message))?; + 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(), + brain_ticks: brain_ms as u64, + checkpoint_id, + rank_since_ms: halves.host.rank_since_ms, + generation: halves.host.generation, + }) +} diff --git a/services/flysim/crates/fly-legacy-session/src/lib.rs b/services/flysim/crates/fly-legacy-session/src/lib.rs new file mode 100644 index 0000000..c4b1075 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/lib.rs @@ -0,0 +1,25 @@ +//! The live fly on the session framework (TASK-01). +//! +//! - [`task`]: `pokered-macros-v1`, the Pokémon Red task and its action executor as one object, +//! running the legacy macro engine and reward adapter unchanged over the boundary memory image. +//! - [`composition`]: the legacy agent, the legacy environment and the task under one coordinator. +//! - [`import`]: a FLYSIM01 checkpoint as the session's start. +//! - [`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. +//! - [`shadow`]: SHADOW-01, the session runtime following the live fly's trace, the comparator and +//! the verdict CUT-01 reads. +//! +//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md` +//! TASK-01 the record. + +pub mod admission; +pub mod composition; +pub mod driver; +pub mod import; +pub mod service; +pub mod shadow; +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/shadow/checkpoint.rs b/services/flysim/crates/fly-legacy-session/src/shadow/checkpoint.rs new file mode 100644 index 0000000..3baaae6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/checkpoint.rs @@ -0,0 +1,169 @@ +//! Checkpoint bytes at a live save: the shadow's own export of the same boundary, byte for byte +//! against the file the live service wrote, after the named substitutions. +//! +//! The shadow never writes to the live stores. At a boundary where the live trace records a +//! capture `g`, the shadow takes its own participant-coherent capture of that boundary (in the +//! position the live one had: before or after that boundary's rollback), exports it as FLYSIM01 +//! through the one encoder both runtimes share (STATE-02), and compares the bytes with the live +//! file. The host fields the shadow cannot own are the live file's: `generation`, `wallMs` and +//! `lastEventId` (declared `host-fields`). `compatibility` and `speed` are the shadow's own +//! configuration and `rankSinceMs` its own rank tracking, so a difference in any of them is a +//! divergence. A legacy milestone archive taken before that boundary's slot save +//! (`afterActions` 0 ahead of a `save-slot`) holds the pre-capture ratchet and slot: the live +//! file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's there (declared +//! `archive-order`) and everything else must still be identical. + +use fly_session::legacy_checkpoint::{self, HostHalf, TaskHalf}; +use fly_session::types::id; +use flysim::store; + +/// The shadow's capture of one boundary. +#[derive(Clone, Debug)] +pub struct ShadowCapture { + pub boundary: u64, + pub world_payload: Vec, + pub agent_payload: Vec, + pub task: TaskHalf, + /// The shadow's `rankSinceMs` at the capture. + pub rank_since_ms: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + Identical, + /// Identical after a declared difference. + Declared, +} + +/// A checkpoint that differs: the explanation and the shadow's export, kept for the review. +#[derive(Debug)] +pub struct Mismatch { + pub detail: String, + pub shadow_bytes: Vec, +} + +/// Compares the live file's bytes with the shadow's export of the same boundary. +pub fn compare( + live: &[u8], + capture: &ShadowCapture, + compatibility: &str, + speed: f64, + archive_order: bool, +) -> Result> { + let fail = |detail: String| { + Box::new(Mismatch { + detail, + shadow_bytes: Vec::new(), + }) + }; + let live_checkpoint = store::decode(live).map_err(|e| fail(format!("the live file: {e:#}")))?; + let host = HostHalf { + generation: live_checkpoint.runtime.generation, + wall_ms: live_checkpoint.runtime.wall_ms, + compatibility: compatibility.to_owned(), + speed, + rank_since_ms: capture.rank_since_ms, + last_event_id: live_checkpoint.runtime.last_event_id, + }; + let mut bytes = legacy_checkpoint::export( + &capture.agent_payload, + &capture.world_payload, + &id(crate::task::SLOT), + &capture.task, + &host, + ) + .map_err(fail)?; + if archive_order { + let mut shadow = + store::decode(&bytes).map_err(|e| fail(format!("the shadow export: {e:#}")))?; + shadow.runtime.ratchet = live_checkpoint.runtime.ratchet; + shadow.runtime.ratchet_game = live_checkpoint.runtime.ratchet_game.clone(); + shadow.runtime.ratchet_frame = live_checkpoint.runtime.ratchet_frame.clone(); + bytes = + store::encode(&shadow.agent, &shadow.runtime).map_err(|e| fail(format!("{e:#}")))?; + } + if bytes == live { + return Ok(if archive_order { + Outcome::Declared + } else { + Outcome::Identical + }); + } + Err(Box::new(Mismatch { + detail: explain(&live_checkpoint, &bytes), + shadow_bytes: bytes, + })) +} + +/// Which members differ, for the divergence report. +fn explain(live: &store::Checkpoint, shadow_bytes: &[u8]) -> String { + let shadow = match store::decode(shadow_bytes) { + Ok(shadow) => shadow, + Err(e) => return format!("the shadow export does not decode: {e:#}"), + }; + let (l, s) = (&live.runtime, &shadow.runtime); + let mut fields = Vec::new(); + macro_rules! field { + ($name:literal, $a:expr, $b:expr) => { + if $a != $b { + fields.push($name); + } + }; + } + field!("romSha256", l.rom_sha256, s.rom_sha256); + field!("emulatorFrame", l.emulator_frame, s.emulator_frame); + field!("compatibility", l.compatibility, s.compatibility); + field!("speed", l.speed, s.speed); + field!("buttons", l.buttons, s.buttons); + field!("rankSinceMs", l.rank_since_ms, s.rank_since_ms); + field!("reward", l.reward, s.reward); + field!("ratchet", l.ratchet, s.ratchet); + field!("reinforcements", l.reinforcements, s.reinforcements); + field!("emulator", l.emulator, s.emulator); + field!("framebuffer", l.framebuffer, s.framebuffer); + field!("ratchetGame", l.ratchet_game, s.ratchet_game); + field!("ratchetFrame", l.ratchet_frame, s.ratchet_frame); + let agent_same = store::encode(&shadow.agent, &live.runtime) + .ok() + .zip(store::encode(&live.agent, &live.runtime).ok()) + .is_some_and(|(a, b)| a == b); + if !agent_same { + fields.push("agent"); + } + let mut detail = format!( + "generation {}: the shadow's export differs from the live file in {}", + live.runtime.generation, + if fields.is_empty() { + "the encoding only".to_owned() + } else { + fields.join(", ") + } + ); + if fields.contains(&"rankSinceMs") { + detail.push_str(&format!( + " (rankSinceMs live {} shadow {})", + l.rank_since_ms, s.rank_since_ms + )); + } + if fields.contains(&"emulator") { + let first = l.emulator.iter().zip(&s.emulator).position(|(a, b)| a != b); + let count = l + .emulator + .iter() + .zip(&s.emulator) + .filter(|(a, b)| a != b) + .count(); + detail.push_str(&format!( + " (emulator: {} vs {} bytes, {count} differ, first at {first:?})", + l.emulator.len(), + s.emulator.len() + )); + } + if fields.contains(&"ratchet") { + detail.push_str(&format!( + " (ratchet live {:?} shadow {:?})", + l.ratchet, s.ratchet + )); + } + detail +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs b/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs new file mode 100644 index 0000000..b355ebb --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/follow.rs @@ -0,0 +1,154 @@ +//! Following the live service's `FLY_TRACE_DIR`: one file per flysim process, named +//! `trace--.jsonl`, so the names sort in start order. A file is a *segment*: +//! the process that wrote it restored one checkpoint (its startup save names it), ran, and ended +//! where the next file begins. +//! +//! The live recorder buffers about a megabyte, so lines arrive in bursts some seconds late and the +//! last line of a file may be incomplete until the next burst. A reader therefore hands out only +//! complete lines. A file has ended when it has no more complete lines *and* a newer file exists: +//! systemd starts the next process only after the previous one exited, and a process flushes its +//! trace on the way out. A process killed hard loses its unflushed tail; those transitions are +//! simply not compared. + +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; + +/// The trace files in `dir`, in start order. +pub fn trace_files(dir: &Path) -> std::io::Result> { + let mut files: Vec = std::fs::read_dir(dir)? + .filter_map(|entry| entry.ok().map(|e| e.path())) + .filter(|path| { + path.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("trace-") && n.ends_with(".jsonl")) + }) + .collect(); + files.sort(); + Ok(files) +} + +/// The first trace file in `dir` that sorts after `after` (or the first of all). +pub fn next_file(dir: &Path, after: Option<&Path>) -> std::io::Result> { + Ok(trace_files(dir)? + .into_iter() + .find(|path| after.is_none_or(|after| path.file_name() > after.file_name()))) +} + +/// Whether a file newer than `path` exists in its directory. +pub fn superseded(path: &Path) -> bool { + let Some(dir) = path.parent() else { + return false; + }; + matches!(next_file(dir, Some(path)), Ok(Some(_))) +} + +/// About how many live transitions are written but not yet compared: the bytes beyond `consumed` +/// in `path` and every byte of the newer files, over the mean line length read so far. +pub fn backlog(path: &Path, consumed: u64, lines: u64) -> u64 { + if lines == 0 { + return 0; + } + let mean = (consumed / lines).max(1); + let here = std::fs::metadata(path) + .map(|m| m.len()) + .unwrap_or(consumed) + .saturating_sub(consumed); + let newer: u64 = path + .parent() + .and_then(|dir| trace_files(dir).ok()) + .into_iter() + .flatten() + .filter(|p| p.file_name() > path.file_name()) + .filter_map(|p| std::fs::metadata(p).ok().map(|m| m.len())) + .sum(); + (here + newer) / mean +} + +/// A reader of one growing file that returns complete lines only. +pub struct Follower { + path: PathBuf, + reader: BufReader, + partial: Vec, + pub lines: u64, + /// Bytes of complete lines handed out. + pub consumed: u64, +} + +impl Follower { + pub fn open(path: &Path) -> std::io::Result { + Ok(Follower { + path: path.to_owned(), + reader: BufReader::with_capacity(1 << 20, File::open(path)?), + partial: Vec::new(), + lines: 0, + consumed: 0, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// The next complete line, if one has been written; `None` when the reader is at the end of + /// what exists so far (an incomplete last line is kept for the next call). + pub fn next_line(&mut self) -> std::io::Result> { + let read = self.reader.read_until(b'\n', &mut self.partial)?; + if read == 0 || self.partial.last() != Some(&b'\n') { + return Ok(None); + } + self.consumed += self.partial.len() as u64; + self.partial.pop(); + let line = String::from_utf8(std::mem::take(&mut self.partial)) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + self.lines += 1; + Ok(Some(line)) + } + + /// Bytes of an incomplete last line held back. + pub fn pending_bytes(&self) -> usize { + self.partial.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn complete_lines_only_and_files_in_start_order() { + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("trace-0000000000100-7.jsonl"); + let b = dir.path().join("trace-0000000000200-9.jsonl"); + std::fs::write(dir.path().join("other.txt"), b"x").unwrap(); + let mut file = File::create(&a).unwrap(); + file.write_all(b"{\"format\":1}\n{\"half").unwrap(); + file.flush().unwrap(); + let mut follower = Follower::open(&a).unwrap(); + assert_eq!( + follower.next_line().unwrap().as_deref(), + Some("{\"format\":1}") + ); + assert_eq!(follower.next_line().unwrap(), None); + assert_eq!(follower.pending_bytes(), 6); + assert!(!superseded(&a)); + file.write_all(b"\":2}\n").unwrap(); + file.flush().unwrap(); + assert_eq!( + follower.next_line().unwrap().as_deref(), + Some("{\"half\":2}") + ); + assert_eq!(follower.next_line().unwrap(), None); + std::fs::write(&b, b"").unwrap(); + assert!(superseded(&a)); + assert!(!superseded(&b)); + assert_eq!(trace_files(dir.path()).unwrap(), vec![a.clone(), b.clone()]); + assert_eq!(next_file(dir.path(), None).unwrap(), Some(a.clone())); + assert_eq!(next_file(dir.path(), Some(&a)).unwrap(), Some(b.clone())); + assert_eq!(next_file(dir.path(), Some(&b)).unwrap(), None); + // The backlog counts what is left here and everything in newer files. + std::fs::write(&b, b"01234567890\n01234567890\n").unwrap(); + assert_eq!(backlog(&a, follower.consumed, follower.lines), 2); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs new file mode 100644 index 0000000..e48f662 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/mod.rs @@ -0,0 +1,1401 @@ +//! SHADOW-01: the session runtime run beside the live legacy fly, transition by transition, as +//! the gate for the automatic cutover (CUT-01). `docs/design/session-framework/legacy-gameboy-v1.md` +//! section 18 is the contract; this module is its implementation. +//! +//! **What "the same inputs" means.** The legacy loop is deterministic given its start state and +//! the admissions applied at the top of each frame. Everything nondeterministic it consumes +//! reaches the fly through exactly two doors: +//! +//! 1. *The start state.* Each flysim process restores a checkpoint with +//! `legacy-transient-reset` (or warms up a fresh fly) and writes a durable startup save of the +//! state it starts from. The trace's boundary line names that save (`g`). A restart, a +//! watchdog kill, `fly-loop-recover` and `fly-reset-to-milestone` are all a new process, so a +//! new file and a new start. +//! 2. *Admissions.* Sugar (the rate limiter and the pulse rule run on wall time and the live +//! pulse) and an operator reward pulse are applied at the top of a frame, and each lands in that +//! transition's `admissions`. +//! +//! Wall time reaches nothing else the fly does: pacing, the publish rate, the checkpoint +//! intervals, chat (a caption track) and pause (no frames run) change no transition. The per-frame +//! trace records which checkpoints were taken where, so the shadow reproduces those too. +//! +//! So the shadow follows the live trace (`FLY_TRACE_DIR`): for each process file it boots a new +//! session from that process's own startup save through the ordinary FLYSIM01 import, replays each +//! transition's admissions into the admission queue, runs the transition, and compares its own +//! trace line with the live one field by field -- ticks, clock, remainder, rates, spikes, +//! decision, pad, macro events, frame, work RAM, rewards, rank, slot saves and rollbacks -- plus +//! the ledger digest where the live trace carries one (`FLY_TRACE_LEDGERS`), and the FLYSIM01 bytes +//! of every live save it can still read ([`checkpoint`]). The first difference stops the shadow +//! with a `diverged` verdict and the context around it. + +pub mod checkpoint; +pub mod follow; +pub mod spool; +pub mod verdict; + +use std::collections::VecDeque; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::types::{id, parse_id}; +use flysim::snapshot::MacroMode; + +use crate::admission::LegacyAdmission; +use crate::composition::{LegacyConfig, LegacySession}; +use crate::trace::{self, Agreement, Difference}; +use checkpoint::ShadowCapture; +use follow::Follower; +use spool::Spool; +use verdict::{Checkpoints, Cost, Divergence, Skipped, Status, Verdict}; + +/// Lowercase hex SHA-256. +pub fn sha256_hex(bytes: &[u8]) -> String { + flysim::trace::sha256_hex(bytes) +} + +/// 3 hours of live brain time: the operator's decision of 2026-09-23. +pub const REQUIRED_BRAIN_SECONDS: f64 = 10_800.0; + +/// How the shadow runs. +#[derive(Clone, Debug)] +pub struct ShadowConfig { + /// The live service's `FLY_TRACE_DIR`. + pub trace_dir: PathBuf, + /// The live stores, read only (`FLY_STATE_HOT`, `FLY_STATE`). + pub hot_dir: PathBuf, + pub durable_dir: PathBuf, + /// `verdict.json`, `divergence.json`. + pub out_dir: PathBuf, + pub spool_dir: PathBuf, + /// The session's sockets and artifact stores, one directory per segment. + pub work_dir: PathBuf, + pub rom_path: PathBuf, + pub dataset_dir: PathBuf, + /// The agent profile: the production one on the stream; the toy connectome in tests. + pub profile: LegacyProfileKind, + /// The live service's configuration that a save records or the composition needs. + pub macro_mode: MacroMode, + pub speed: f64, + pub mode: ExecutionMode, + pub agent_threads: usize, + pub required_brain_seconds: f64, + /// Follow every trace file present at start, oldest first (a rehearsal), rather than only the + /// newest. + pub all_files: bool, + /// Keep trace files of finished segments (default: delete them once compared). + pub keep_traces: bool, + /// Keep every spooled checkpoint (a rehearsal replays them afterwards). + pub keep_spool: bool, + pub exit_on_pass: bool, + /// Stop after this many compared transitions (a bounded rehearsal); `None` runs on. + pub max_transitions: Option, + pub spool_max_bytes: u64, + pub context_lines: usize, + pub poll: Duration, + /// Stay behind a live fly that is behind real time. + pub lag_guard: Option, + /// The sha256 of the shadow binary (the candidate), for the verdict. + pub binary_sha256: String, + /// The release binaries beside it, by name, and their directory (the verdict's `candidate`). + pub binaries: std::collections::BTreeMap, + pub release: String, +} + +/// The back-off that keeps the shadow from costing the live fly real time, judged against the +/// live fly's own pace before the shadow existed (SHADOW-01 review round 2, G1). +/// +/// flysim's `fly_lag_seconds` is the accumulated pacing shortfall of the process: it grows, in +/// chunks of more than a second, whenever the loop runs behind real time, and a fly that runs at a +/// realtime factor of 0.7 grows it by about 0.3 s every second whatever the shadow does. So the +/// signal is the lag *growth rate* against the baseline rate `fly-shadow-run start` measured +/// before the shadow started (`baseline.json`: `lagRate`, `margin`; 0 and `margin` when there is +/// none). See [`LagJudge`] for the rule, which lifts the back-off when pausing the shadow does not +/// help: then the shadow is not the cause, and the host guard (`fly-shadow-run guard`) is what +/// acts on a lasting degradation. A metrics listener that cannot be read never pauses the shadow. +#[derive(Clone, Debug)] +pub struct LagGuard { + /// `host:port` of the live metrics listener. + pub metrics_addr: String, + /// `fly-shadow-run`'s baseline, re-read every poll when it exists. + pub baseline_file: Option, + /// The allowed rise of the lag growth rate (s/s) when no baseline gives one. + pub margin: f64, + /// The span the growth rate is measured over. + pub window: Duration, + pub back_off: Duration, + /// How long back-offs stay off after one that did not help. + pub suppress: Duration, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum JudgeMode { + Normal, + /// Paused until `until`; the lag and time when the pause began. + BackingOff { + until: Instant, + from: (Instant, f64), + }, + Suppressed { + until: Instant, + }, +} + +/// The in-shadow back-off rule, fed `(now, fly_lag_seconds)` every poll: +/// +/// - *Normal*: when the lag has grown faster than `base_rate + margin` over the last `window`, +/// pause the shadow for `back_off`. +/// - *At the end of a pause*: if the live lag kept growing faster than that while the shadow was +/// paused, the shadow is not the cause: no back-off for `suppress`. Otherwise back to normal, +/// with a fresh window. +/// - A new flysim process (the lag falls) starts the window again. +#[derive(Clone, Debug)] +pub struct LagJudge { + pub base_rate: f64, + pub margin: f64, + window: Duration, + back_off: Duration, + suppress: Duration, + samples: VecDeque<(Instant, f64)>, + mode: JudgeMode, +} + +impl LagJudge { + pub fn new( + base_rate: f64, + margin: f64, + window: Duration, + back_off: Duration, + suppress: Duration, + ) -> LagJudge { + LagJudge { + base_rate, + margin, + window, + back_off, + suppress, + samples: VecDeque::new(), + mode: JudgeMode::Normal, + } + } + + fn limit(&self) -> f64 { + self.base_rate + self.margin + } + + /// The growth rate over the last `window`, once the samples span it. + fn rate(&self) -> Option { + let &(newest_at, newest) = self.samples.back()?; + let &(oldest_at, oldest) = self + .samples + .iter() + .rev() + .find(|(at, _)| newest_at.duration_since(*at) >= self.window)?; + let dt = newest_at.duration_since(oldest_at).as_secs_f64(); + (dt > 0.0).then(|| (newest - oldest) / dt) + } + + /// Whether the shadow should be paused now. + pub fn observe(&mut self, now: Instant, lag: f64) -> bool { + if self.samples.back().is_some_and(|&(_, last)| lag < last) { + self.samples.clear(); + if let JudgeMode::BackingOff { until, .. } = self.mode { + self.mode = JudgeMode::BackingOff { + until, + from: (now, lag), + }; + } + } + self.samples.push_back((now, lag)); + while self + .samples + .front() + .is_some_and(|&(at, _)| now.duration_since(at) > self.window * 3) + { + self.samples.pop_front(); + } + match self.mode { + JudgeMode::Normal => { + if self.rate().is_some_and(|rate| rate > self.limit()) { + self.mode = JudgeMode::BackingOff { + until: now + self.back_off, + from: (now, lag), + }; + return true; + } + false + } + JudgeMode::BackingOff { until, from } => { + if now < until { + return true; + } + let dt = now.duration_since(from.0).as_secs_f64(); + let during = if dt > 0.0 { (lag - from.1) / dt } else { 0.0 }; + self.mode = if during > self.limit() { + JudgeMode::Suppressed { + until: now + self.suppress, + } + } else { + JudgeMode::Normal + }; + self.samples.clear(); + self.samples.push_back((now, lag)); + false + } + JudgeMode::Suppressed { until } => { + if now >= until { + self.mode = JudgeMode::Normal; + self.samples.clear(); + self.samples.push_back((now, lag)); + } + false + } + } + } +} + +/// `fly-shadow-run`'s baseline: `(lagRate, margin)`. +pub fn read_baseline(path: &Path) -> Option<(f64, f64)> { + let v: Value = serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?; + Some((v["lagRate"].as_f64()?, v["margin"].as_f64()?)) +} + +/// What the poller shares: the last lag read (ms, `u64::MAX` unknown) and whether to back off. +pub struct LagState { + pub lag_ms: AtomicU64, + pub back_off: AtomicBool, +} + +/// How a run ended. +#[derive(Debug, PartialEq, Eq)] +pub enum Ended { + Pass, + Diverged, + Stopped, + Limit, +} + +/// Why a segment ended. +enum SegmentEnd { + /// The process's file ended (the next one began). + Completed, + /// Nothing more could be compared in it, for a reason outside the session runtime: the + /// kind (one of [`verdict::SKIP_KINDS`] or `trace-malformed`) and what happened. + Skipped(&'static str, String), + Diverged(Box), + Stop(Ended), +} + +/// A stop request (SIGTERM or SIGINT), checked between frames. +#[derive(Clone, Default)] +pub struct StopFlag(Arc); + +impl StopFlag { + pub fn request(&self) { + self.0.store(true, Ordering::Relaxed); + } + + pub fn requested(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + +/// Polls the live `fly_lag_seconds` every two seconds and applies [`LagJudge`]. +fn spawn_lag_poller(guard: &LagGuard, stop: StopFlag) -> Arc { + let state = Arc::new(LagState { + lag_ms: AtomicU64::new(u64::MAX), + back_off: AtomicBool::new(false), + }); + let out = Arc::clone(&state); + let guard = guard.clone(); + std::thread::Builder::new() + .name("fly-shadow-lag".to_owned()) + .spawn(move || { + let mut judge = LagJudge::new( + 0.0, + guard.margin, + guard.window, + guard.back_off, + guard.suppress, + ); + while !stop.requested() { + if let Some((rate, margin)) = guard.baseline_file.as_deref().and_then(read_baseline) + { + judge.base_rate = rate; + judge.margin = margin; + } + let back_off = match read_lag_seconds(&guard.metrics_addr) { + Some(lag) => { + out.lag_ms.store((lag * 1000.0) as u64, Ordering::Relaxed); + judge.observe(Instant::now(), lag) + } + None => { + out.lag_ms.store(u64::MAX, Ordering::Relaxed); + false + } + }; + out.back_off.store(back_off, Ordering::Relaxed); + std::thread::sleep(Duration::from_secs(2)); + } + }) + .expect("the lag poller starts"); + state +} + +/// `GET /metrics` over plain HTTP/1.0, the `fly_lag_seconds` sample. +pub fn read_lag_seconds(addr: &str) -> Option { + use std::io::{Read, Write}; + let mut stream = std::net::TcpStream::connect(addr).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(2))).ok()?; + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .ok()?; + write!(stream, "GET /metrics HTTP/1.0\r\nHost: {addr}\r\n\r\n").ok()?; + let mut body = String::new(); + stream.read_to_string(&mut body).ok()?; + parse_lag_seconds(&body) +} + +pub fn parse_lag_seconds(text: &str) -> Option { + text.lines() + .filter(|line| !line.starts_with('#')) + .find_map(|line| { + let mut parts = line.split_whitespace(); + (parts.next()? == "fly_lag_seconds").then(|| parts.next()?.parse().ok())? + }) +} + +/// Unix milliseconds now. +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) +} + +/// The start wall ms a trace file's name carries (`trace--.jsonl`). +pub fn trace_start_ms(path: &Path) -> Option { + path.file_name()? + .to_str()? + .strip_prefix("trace-")? + .split('-') + .next()? + .parse() + .ok() +} + +/// The live processes that booted after `since` and have no trace file, in the sugar journal's +/// boot headers (every flysim process writes one, traced or not) against the trace files seen. +/// A process's trace file is created during its boot, after the previous process's boot header +/// and before its own, so each boot owns the trace files started in that interval. Returns the +/// untraced boots' headers; `checked` collects the boots matched, so each is judged once. +pub fn untraced_boots( + boots: &[Value], + traces_seen: &std::collections::BTreeSet, + since: u64, + checked: &mut std::collections::BTreeSet, +) -> Vec { + let mut walls: Vec<(u64, &Value)> = boots + .iter() + .filter(|b| b["runtime"] == "flysim") + .filter_map(|b| Some((b["wallMs"].as_u64()?, b))) + .collect(); + walls.sort_by_key(|(w, _)| *w); + walls.dedup_by_key(|(w, _)| *w); + let mut untraced = Vec::new(); + let mut previous = 0u64; + for (wall, boot) in walls { + if wall > since && !checked.contains(&wall) { + if traces_seen.range(previous + 1..=wall).next().is_some() { + checked.insert(wall); + } else { + untraced.push(boot.clone()); + } + } + previous = wall; + } + untraced +} + +/// Writes the heartbeat file (its modification time is what counts). +fn touch(path: &Path) { + if let Err(e) = std::fs::write(path, verdict::now_iso()) { + eprintln!("fly-shadow: could not write {}: {e}", path.display()); + } +} + +/// The live trace's capture ids: `g`. +fn generation_of_capture(capture: &Value) -> Option { + capture["checkpointId"] + .as_str()? + .strip_prefix('g')? + .parse() + .ok() +} + +/// Runs the shadow until it passes (with `exit_on_pass`), diverges, is stopped, or reaches +/// `max_transitions`. +pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict), String> { + for dir in [&config.out_dir, &config.work_dir, &config.trace_dir] { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + let session_config = LegacyConfig { + mode: config.mode, + rom_path: config.rom_path.clone(), + dataset_dir: config.dataset_dir.clone(), + profile: config.profile, + macro_mode: config.macro_mode, + agent_id: id("fly"), + agent_threads: config.agent_threads, + record: true, + }; + let compatibility = crate::composition::compatibility_of(&session_config); + let mut spool = Spool::new( + &config.spool_dir, + vec![config.hot_dir.clone(), config.durable_dir.clone()], + config.spool_max_bytes, + ) + .map_err(|e| format!("the spool: {e}"))?; + if config.keep_spool { + spool = spool.keep_all(); + } + let spool_thread = spool.spawn(Duration::from_millis(250), Duration::from_secs(3 * 3600)); + // The consumer heartbeat the live recorder needs to keep tracing (flysim `trace`): written + // now, before the live service is (re)started, and every 30 s; removed when the shadow stops, + // so a stopped, diverged or dead shadow turns the live trace off by itself. + let heartbeat = config.trace_dir.join(flysim::trace::CONSUMER_FILE); + touch(&heartbeat); + let beating = Arc::new(AtomicBool::new(true)); + let heartbeat_thread = { + let (path, beating) = (heartbeat.clone(), Arc::clone(&beating)); + std::thread::Builder::new() + .name("fly-shadow-heartbeat".to_owned()) + .spawn(move || { + let mut last = Instant::now(); + while beating.load(Ordering::Relaxed) { + if last.elapsed() >= Duration::from_secs(30) { + touch(&path); + last = Instant::now(); + } + std::thread::sleep(Duration::from_millis(200)); + } + }) + .expect("the heartbeat thread starts") + }; + let lag = config + .lag_guard + .as_ref() + .map(|guard| spawn_lag_poller(guard, stop.clone())); + let mut shadow = Shadow { + verdict: Verdict { + status: Status::Running, + reason: "following the live trace".to_owned(), + binary_sha256: config.binary_sha256.clone(), + binaries: config.binaries.clone(), + release: config.release.clone(), + compatibility: compatibility.clone(), + execution_mode: config.mode.label().to_owned(), + agent_threads: config.agent_threads, + required_brain_seconds: config.required_brain_seconds, + agreement: Agreement::default(), + brain_ms: 0.0, + ledger_checks: 0, + checkpoints: Checkpoints::default(), + segments_compared: 0, + skipped: Vec::new(), + divergence: None, + started_at: verdict::now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + }, + config, + session_config, + compatibility, + spool, + lag, + stop, + last_write: Instant::now() - Duration::from_secs(60), + following: None, + started_wall_ms: now_ms(), + traces_seen: Default::default(), + boots_checked: Default::default(), + last_coverage: Instant::now() - Duration::from_secs(60), + }; + shadow.write(); + let ended = shadow.follow().await; + beating.store(false, Ordering::Relaxed); + let _ = heartbeat_thread.join(); + let _ = std::fs::remove_file(&heartbeat); + shadow.spool.stop(); + let _ = spool_thread.join(); + let ended = ended?; + match ended { + Ended::Diverged => {} + Ended::Pass => {} + Ended::Stopped | Ended::Limit => { + if shadow.verdict.status == Status::Running { + shadow.verdict.status = Status::Stopped; + shadow.verdict.reason = match ended { + Ended::Limit => "stopped at the transition limit".to_owned(), + _ => "stopped before the window was complete".to_owned(), + }; + } + } + } + shadow.write(); + if shadow.verdict.status != Status::Diverged { + shadow.spool.clear(); + } + Ok((ended, shadow.verdict)) +} + +struct Shadow { + config: ShadowConfig, + session_config: LegacyConfig, + compatibility: String, + spool: Spool, + lag: Option>, + stop: StopFlag, + verdict: Verdict, + last_write: Instant, + /// The file being compared, the bytes and lines of it compared so far. + following: Option<(PathBuf, u64, u64)>, + /// Coverage: when this shadow started (Unix ms), every trace file it has seen (start ms), + /// the live boots already matched to one, and when it last looked. + started_wall_ms: u64, + traces_seen: std::collections::BTreeSet, + boots_checked: std::collections::BTreeSet, + last_coverage: Instant, +} + +impl Shadow { + fn write(&mut self) { + self.verdict.spool_evicted = self.spool.evicted(); + // Refreshed on every write, backed off or not, so the verdict's catch-up bound is current. + if let Some((path, consumed, lines)) = &self.following { + self.verdict.lag_transitions = follow::backlog(path, *consumed, *lines); + } + self.verdict.live_lag_seconds = self.lag.as_ref().and_then(|lag| { + let ms = lag.lag_ms.load(Ordering::Relaxed); + (ms != u64::MAX).then(|| ms as f64 / 1000.0) + }); + let path = self.config.out_dir.join("verdict.json"); + if let Err(e) = verdict::write_json(&path, &self.verdict.to_json()) { + eprintln!("fly-shadow: could not write {}: {e}", path.display()); + } + self.last_write = Instant::now(); + } + + /// Every live process since the shadow started must have left a trace: one that ran untraced + /// (its trace could not be created, or its consumer check failed) can never be compared, so + /// it fails the verdict as a `coverage` divergence rather than letting the window pass on the + /// processes that were traced. Looked at every 5 s. + fn coverage(&mut self) -> Option { + if self.last_coverage.elapsed() < Duration::from_secs(5) { + return None; + } + self.last_coverage = Instant::now(); + if let Ok(files) = follow::trace_files(&self.config.trace_dir) { + self.traces_seen + .extend(files.iter().filter_map(|f| trace_start_ms(f))); + } + let segments = flysim::journal::read_segments(&self.config.hot_dir).ok()?; + let boots: Vec = segments.into_iter().filter_map(|s| s.boot).collect(); + let untraced = untraced_boots( + &boots, + &self.traces_seen, + self.started_wall_ms, + &mut self.boots_checked, + ); + let boot = untraced.first()?; + Some(Divergence { + kind: "coverage".to_owned(), + trace: String::new(), + step: boot["startFrame"].as_str().and_then(|s| s.parse().ok()), + difference: None, + detail: format!( + "a live flysim process booted at {} ({}, frame {}) left no trace while the shadow \ + was running: its transitions can never be compared", + verdict::iso(boot["wallMs"].as_i64().unwrap_or(0)), + boot["origin"].as_str().unwrap_or("?"), + boot["startFrame"].as_str().unwrap_or("?"), + ), + context: Vec::new(), + }) + } + + fn write_if_due(&mut self) { + if self.last_write.elapsed() >= Duration::from_secs(5) { + self.write(); + } + } + + fn diverged(&mut self, divergence: Divergence) { + eprintln!( + "fly-shadow: DIVERGED ({}) in {} at step {:?}: {}", + divergence.kind, + divergence.trace, + divergence.step, + divergence + .difference + .as_ref() + .map_or(divergence.detail.clone(), |d| d.to_string()) + ); + let path = self.config.out_dir.join("divergence.json"); + if let Err(e) = verdict::write_json(&path, &divergence.to_json()) { + eprintln!("fly-shadow: could not write {}: {e}", path.display()); + } + self.verdict.status = Status::Diverged; + self.verdict.passed_at = None; + self.verdict.reason = format!("diverged: {}", divergence.kind); + self.verdict.divergence = Some(divergence); + self.write(); + } + + /// The segment loop: each process file in start order. + async fn follow(&mut self) -> Result { + let dir = self.config.trace_dir.clone(); + let mut current: Option = if self.config.all_files { + None + } else { + // Only the newest file present at start: older processes are history whose startup + // saves are gone, and are pruned. + let files = follow::trace_files(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + if !self.config.keep_traces && files.len() > 1 { + for old in &files[..files.len() - 1] { + let _ = std::fs::remove_file(old); + } + } + files.into_iter().rev().nth(1) + }; + loop { + let next = loop { + if self.stop.requested() { + return Ok(Ended::Stopped); + } + match follow::next_file(&dir, current.as_deref()) { + Ok(Some(path)) => break path, + Ok(None) => {} + Err(e) => return Err(format!("{}: {e}", dir.display())), + } + if let Some(divergence) = self.coverage() { + self.diverged(divergence); + return Ok(Ended::Diverged); + } + self.write_if_due(); + tokio::time::sleep(self.config.poll).await; + }; + let name = next + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + eprintln!("fly-shadow: following {name}"); + self.traces_seen.extend(trace_start_ms(&next)); + self.verdict.current_trace = Some(name.clone()); + let compared_before = self.verdict.agreement.transitions; + let end = self.segment(&next).await; + let compared = self.verdict.agreement.transitions - compared_before; + match end { + SegmentEnd::Completed => { + eprintln!("fly-shadow: {name} ended; {compared} transitions identical"); + if !self.config.keep_traces { + let _ = std::fs::remove_file(&next); + } + } + SegmentEnd::Skipped(kind, reason) => { + eprintln!( + "fly-shadow: {name} skipped ({kind}) after {compared} transitions: {reason}" + ); + self.verdict.skipped.push(Skipped { + trace: name, + transitions_compared: compared, + kind: kind.to_owned(), + reason, + }); + if !self.config.keep_traces { + let _ = std::fs::remove_file(&next); + } + } + SegmentEnd::Diverged(divergence) => { + self.diverged(*divergence); + return Ok(Ended::Diverged); + } + SegmentEnd::Stop(ended) => return Ok(ended), + } + self.write(); + current = Some(next); + } + } + + /// Waits for the next complete line of a segment; `None` when the segment has ended. + async fn next_line(&mut self, follower: &mut Follower) -> Result, SegmentEnd> { + loop { + match follower.next_line() { + Ok(Some(line)) => return Ok(Some(line)), + Ok(None) => {} + Err(e) => { + return Err(SegmentEnd::Skipped( + "trace-malformed", + format!("reading the trace: {e}"), + )); + } + } + if self.stop.requested() { + return Err(SegmentEnd::Stop(Ended::Stopped)); + } + if follow::superseded(follower.path()) { + // The next process exists, so this one has exited and flushed: one more read for + // a final flush racing the directory listing, then the segment is over. + tokio::time::sleep(Duration::from_millis(500)).await; + return match follower.next_line() { + Ok(line) => Ok(line), + Err(e) => Err(SegmentEnd::Skipped( + "trace-malformed", + format!("reading the trace: {e}"), + )), + }; + } + if let Some(divergence) = self.coverage() { + return Err(SegmentEnd::Diverged(Box::new(divergence))); + } + self.write_if_due(); + tokio::time::sleep(self.config.poll).await; + } + } + + async fn segment(&mut self, path: &Path) -> SegmentEnd { + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut follower = match Follower::open(path) { + Ok(f) => f, + Err(e) => return SegmentEnd::Skipped("trace-malformed", format!("open: {e}")), + }; + // The header. + let header: Value = match self.next_line(&mut follower).await { + Ok(Some(line)) => match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => return SegmentEnd::Skipped("trace-malformed", format!("header: {e}")), + }, + Ok(None) => return SegmentEnd::Skipped("no-transition", "an empty trace".to_owned()), + Err(end) => return end, + }; + if header["format"] != trace::FORMAT { + return SegmentEnd::Skipped( + "trace-malformed", + format!("not {}: {}", trace::FORMAT, header["format"]), + ); + } + // The start boundary and its startup save. + let start: Value = match self.next_line(&mut follower).await { + Ok(Some(line)) => match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => { + return SegmentEnd::Skipped("trace-malformed", format!("start line: {e}")); + } + }, + Ok(None) => { + return SegmentEnd::Skipped( + "no-transition", + "the process ran no transition".to_owned(), + ); + } + Err(end) => return end, + }; + let Some(startup) = start["operational"]["captures"] + .as_array() + .and_then(|c| c.first()) + .and_then(generation_of_capture) + .filter(|_| start.get("boundary").is_some()) + else { + return SegmentEnd::Skipped( + "trace-malformed", + "no startup save at the start boundary".to_owned(), + ); + }; + let bytes = { + let mut waited = Duration::ZERO; + loop { + if let Some(bytes) = self.spool.read(startup) { + break bytes; + } + if waited >= Duration::from_secs(30) { + return SegmentEnd::Skipped( + "startup-save-gone", + format!( + "the startup save g{startup} is no longer in the stores or the spool" + ), + ); + } + tokio::time::sleep(Duration::from_millis(500)).await; + waited += Duration::from_millis(500); + } + }; + let checkpoint = match flysim::store::decode(&bytes) { + Ok(c) => c, + Err(e) => { + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("the startup save g{startup} does not decode: {e:#}"), + ))); + } + }; + // The legacy gate, as the live process applied it to its own save. + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let gate = fly_session::legacy_checkpoint::RestoreGate::from_env( + &checkpoint.runtime.rom_sha256, + &self.compatibility, + flybrain_gb::GameAdapter::migrates_from(&adapter), + ); + if let Err(reason) = gate.check(&checkpoint) { + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!( + "the live process's startup save g{startup} is refused by this candidate's \ + restore gate ({reason}): is the shadow the build the live service runs?" + ), + ))); + } + let segment_dir = self.config.work_dir.join(format!("segment-{startup}")); + let _ = std::fs::remove_dir_all(&segment_dir); + let started = Instant::now(); + let mut session = + match LegacySession::start(&segment_dir, self.session_config.clone()).await { + Ok(s) => s, + Err(e) => { + return SegmentEnd::Diverged(Box::new( + self.boot_failure(&name, format!("the session did not start: {e}")), + )); + } + }; + // A fresh start (the stores were empty): the live process ran the one-frame scaffold and + // the warm-up from power-on, and the shadow does the same (`Environment.Initialize`, + // `Agent.Initialize`) rather than import the startup save. An import would not be the + // same emulator: binjgb's audio resampler phase is not in its exported state, so an + // imported emulator's channel accumulators drift from a powered-on one's (found by + // `tests/shadow.rs`). Every other start is a restore on both sides, and the same. + let fresh = checkpoint.runtime.emulator_frame == 1; + let booted: Result = match session.bootstrap().await { + Ok(()) if fresh => Ok(0.0), + Ok(()) => session + .import_checkpoint(&checkpoint, &id("e2")) + .await + .map(|imported| imported.rank_since_ms), + Err(e) => Err(e), + }; + let rank_since_ms = match booted { + Ok(ms) => ms, + Err(e) => { + session.stop().await; + let _ = std::fs::remove_dir_all(&segment_dir); + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("the session runtime could not restore the live save g{startup}: {e}"), + ))); + } + }; + if fresh { + // The fresh fly's startup save must be the shadow's own boundary 0, byte for byte. + let outcome = match session + .coordinator + .capture_payloads(&id("shadow-fresh")) + .await + { + Ok((boundary, world_payload, agents)) => match agents.into_iter().next() { + Some((_, agent_payload)) => checkpoint::compare( + &bytes, + &ShadowCapture { + boundary, + world_payload, + agent_payload, + task: session.task.task_half().0, + rank_since_ms, + }, + &self.compatibility, + self.config.speed, + false, + ) + .map_err(|m| m.detail), + None => Err("a capture with no agent".to_owned()), + }, + Err(e) => Err(format!("capture: {}", e.error.message)), + }; + match outcome { + Ok(_) => self.verdict.checkpoints.identical += 1, + Err(detail) => { + session.stop().await; + return SegmentEnd::Diverged(Box::new(self.boot_failure( + &name, + format!("a fresh start: the startup save g{startup} is not the shadow's boundary 0: {detail}"), + ))); + } + } + } + eprintln!( + "fly-shadow: {name}: {} g{startup} (boundary {}) in {:?}", + if fresh { "fresh start, as" } else { "restored" }, + checkpoint.runtime.emulator_frame.saturating_sub(1), + started.elapsed() + ); + self.spool.set_floor(startup + 1); + self.verdict.segments_compared += 1; + // Rollbacks wait for the boundary's captures, as the host orders them (section 16). + session.coordinator.defer_rollbacks(true); + // A segment can run for days: keep the coordinator's in-memory history bounded. + session.coordinator.bound_history(4096); + let end = self + .run_segment(&name, &mut follower, &mut session, rank_since_ms) + .await; + session.stop().await; + let _ = std::fs::remove_dir_all(&segment_dir); + end + } + + fn boot_failure(&self, name: &str, detail: String) -> Divergence { + Divergence { + kind: "boot".to_owned(), + trace: name.to_owned(), + step: None, + difference: None, + detail, + context: Vec::new(), + } + } + + async fn run_segment( + &mut self, + name: &str, + follower: &mut Follower, + session: &mut LegacySession, + rank_since_ms: f64, + ) -> SegmentEnd { + let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly")); + let mut rank = session.task.rank(); + let mut rank_since_ms = rank_since_ms; + let mut context: VecDeque<(Value, Value)> = VecDeque::new(); + let mut captures_taken: u64 = 0; + loop { + let line = match self.next_line(follower).await { + Ok(Some(line)) => line, + Ok(None) => return SegmentEnd::Completed, + Err(end) => return end, + }; + let live: Value = match serde_json::from_str(&line) { + Ok(v) => v, + Err(e) => { + return SegmentEnd::Skipped("trace-malformed", format!("a trace line: {e}")); + } + }; + if live.get("truncated").is_some() { + return SegmentEnd::Skipped( + "trace-cap", + format!("the live trace stopped ({})", live["reason"]), + ); + } + let Some(behaviour) = live.get("behaviour").cloned() else { + continue; + }; + let step: Option = behaviour["step"].as_str().and_then(|s| s.parse().ok()); + // The admissions of this transition, replayed as the live loop applied them. + for admission_line in behaviour["admissions"].as_array().into_iter().flatten() { + match admission_line["kind"].as_str() { + Some("sugar") => { + let Some(duration) = admission_line["durationMs"].as_f64() else { + return SegmentEnd::Skipped( + "trace-malformed", + "a sugar with no duration".to_owned(), + ); + }; + admission.replay_sugar(duration); + } + Some("reward") => { + return SegmentEnd::Skipped( + "operator-reward-pulse", + format!( + "an operator reward pulse at step {step:?} (declared \ + operator-reward-pulse: not available on the session runtime)" + ), + ); + } + other => { + return SegmentEnd::Skipped( + "trace-malformed", + format!("an unknown admission {other:?}"), + ); + } + } + } + // Back off while the live fly is losing real time ([`LagGuard`]). + if let Some(lag) = self.lag.clone() { + let throttle = Instant::now(); + while lag.back_off.load(Ordering::Relaxed) { + if self.stop.requested() { + return SegmentEnd::Stop(Ended::Stopped); + } + self.write_if_due(); + tokio::time::sleep(Duration::from_millis(200)).await; + } + self.verdict.cost.throttled_ms += throttle.elapsed().as_secs_f64() * 1000.0; + } + let t0 = Instant::now(); + if let Err(e) = session.coordinator.step().await { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!("step ({} at {}): {}", e.detail, e.phase, e.error.message), + context: context.into_iter().collect(), + })); + } + // `Sim::track_rank`, before the boundary's captures. + let now_rank = session.task.rank(); + if now_rank != rank { + rank = now_rank; + rank_since_ms = session.task.brain_ms(); + } + // The live captures at this boundary, each where the live loop took it: before the + // rollback (a milestone archive), or after it. + let actions: Vec = behaviour["boundaryActions"] + .as_array() + .into_iter() + .flatten() + .map(|a| a["kind"].as_str().unwrap_or("").to_owned()) + .collect(); + let rollback_at = actions.iter().position(|k| k == "rollback"); + let live_captures: Vec<(u64, usize)> = live["operational"]["captures"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| { + Some(( + generation_of_capture(c)?, + c["afterActions"].as_u64()? as usize, + )) + }) + .collect(); + let mut taken: Vec<(u64, usize, ShadowCapture)> = Vec::new(); + for pass in [false, true] { + if pass && let Err(e) = session.coordinator.apply_pending_rollback().await { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!( + "rollback ({} at {}): {}", + e.detail, e.phase, e.error.message + ), + context: context.into_iter().collect(), + })); + } + for (generation, after) in &live_captures { + let after_rollback = rollback_at.is_some_and(|r| *after > r); + if after_rollback != pass { + continue; + } + captures_taken += 1; + let checkpoint_id = + parse_id(&format!("shadow-{captures_taken}")).expect("a valid id"); + match session.coordinator.capture_payloads(&checkpoint_id).await { + Ok((boundary, world_payload, agents)) => { + let Some((_, agent_payload)) = agents.into_iter().next() else { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: "a capture with no agent".to_owned(), + context: context.into_iter().collect(), + })); + }; + taken.push(( + *generation, + *after, + ShadowCapture { + boundary, + world_payload, + agent_payload, + task: session.task.task_half().0, + rank_since_ms, + }, + )); + } + Err(e) => { + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail: format!( + "capture ({} at {}): {}", + e.detail, e.phase, e.error.message + ), + context: context.into_iter().collect(), + })); + } + } + } + } + let details = session.coordinator.take_details(); + let records = session.task.take_records(); + let elapsed = t0.elapsed().as_secs_f64() * 1000.0; + self.verdict.cost.record(elapsed); + let session_error = |detail: String, context: VecDeque<(Value, Value)>| { + SegmentEnd::Diverged(Box::new(Divergence { + kind: "session-error".to_owned(), + trace: name.to_owned(), + step, + difference: None, + detail, + context: context.into_iter().collect(), + })) + }; + let (Some(details), [record]) = (details, records.as_slice()) else { + return session_error( + format!( + "the session recorded no transition ({} task records)", + records.len() + ), + context, + ); + }; + let mut shadow_line = match trace::line(&details, record) { + Ok(line) => line["behaviour"].clone(), + Err(e) => return session_error(format!("the shadow's trace line: {e}"), context), + }; + if behaviour.get("ledgersDigest").is_some() { + shadow_line["ledgersDigest"] = Value::String(sha256_hex(record.ledgers.as_bytes())); + self.verdict.ledger_checks += 1; + } + context.push_back((behaviour.clone(), shadow_line.clone())); + while context.len() > self.config.context_lines { + context.pop_front(); + } + if let Err(difference) = trace::compare_line(&behaviour, &shadow_line, &record.bound) { + let kind = if difference.field == "ledgersDigest" { + "ledgers" + } else { + "transition" + }; + let detail = if kind == "ledgers" { + format!( + "the shadow's ledgers after the boundary: {}", + record.ledgers + ) + } else { + String::new() + }; + return SegmentEnd::Diverged(Box::new(Divergence { + kind: kind.to_owned(), + trace: name.to_owned(), + step, + difference: Some(*difference), + detail, + context: context.into_iter().collect(), + })); + } + // The live saves at this boundary, byte for byte. + let save_slots_before = |after: usize| { + actions[..after.min(actions.len())] + .iter() + .filter(|k| *k == "save-slot") + .count() + }; + let total_save_slots = actions.iter().filter(|k| *k == "save-slot").count(); + for (generation, after, capture) in &taken { + let Some(live_bytes) = self.spool.read(*generation) else { + self.verdict.checkpoints.unavailable += 1; + continue; + }; + let archive_order = save_slots_before(*after) < total_save_slots; + match checkpoint::compare( + &live_bytes, + capture, + &self.compatibility, + self.config.speed, + archive_order, + ) { + Ok(checkpoint::Outcome::Identical) => self.verdict.checkpoints.identical += 1, + Ok(checkpoint::Outcome::Declared) => self.verdict.checkpoints.declared += 1, + Err(mismatch) => { + // Both files, for the review. + let out = &self.config.out_dir; + let _ = std::fs::write( + out.join(format!("divergence-live-g{generation}.checkpoint")), + &live_bytes, + ); + let _ = std::fs::write( + out.join(format!("divergence-shadow-g{generation}.checkpoint")), + &mismatch.shadow_bytes, + ); + return SegmentEnd::Diverged(Box::new(Divergence { + kind: "checkpoint".to_owned(), + trace: name.to_owned(), + step, + difference: Some(Difference { + field: format!("checkpoint g{generation}"), + legacy: Value::String(sha256_hex(&live_bytes)), + session: Value::String(format!("boundary {}", capture.boundary)), + }), + detail: mismatch.detail, + context: context.into_iter().collect(), + })); + } + } + self.spool.set_floor(*generation + 1); + } + self.verdict.agreement.count(&behaviour); + self.following = Some(( + follower.path().to_owned(), + follower.consumed, + follower.lines, + )); + self.verdict.brain_ms += behaviour["ticksAdvanced"] + .as_str() + .and_then(|s| s.parse::().ok()) + .unwrap_or(0.0); + if self.verdict.status == Status::Running + && self.verdict.brain_seconds() >= self.config.required_brain_seconds + && verdict::saves_suffice( + self.verdict.brain_seconds(), + self.verdict.checkpoints.identical + self.verdict.checkpoints.declared, + self.verdict.checkpoints.unavailable, + ) + .is_ok() + { + self.verdict.status = Status::Pass; + self.verdict.passed_at = Some(verdict::now_iso()); + self.verdict.reason = format!( + "{} s of live brain time compared with zero divergence", + self.config.required_brain_seconds + ); + eprintln!("fly-shadow: PASS ({})", self.verdict.reason); + self.write(); + if self.config.exit_on_pass { + return SegmentEnd::Stop(Ended::Pass); + } + } + if self + .config + .max_transitions + .is_some_and(|max| self.verdict.agreement.transitions >= max) + { + return SegmentEnd::Stop(Ended::Limit); + } + if let Some(divergence) = self.coverage() { + return SegmentEnd::Diverged(Box::new(divergence)); + } + self.write_if_due(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_lag_sample_is_read_from_the_exposition() { + let text = "# HELP fly_lag_seconds lag\n# TYPE fly_lag_seconds gauge\nfly_lag_seconds 0.25\nfly_other 3\n"; + assert_eq!(parse_lag_seconds(text), Some(0.25)); + assert_eq!(parse_lag_seconds("fly_lag_seconds_total 3\n"), None); + } + + /// Feeds a judge 2-s polls for `seconds`, the lag growing at `rate(paused)` s/s; returns the + /// fraction of the time the shadow was paused. + fn paused_fraction(judge: &mut LagJudge, seconds: u64, rate: impl Fn(bool) -> f64) -> f64 { + let t0 = Instant::now(); + let (mut lag, mut paused, mut paused_polls) = (5.0, false, 0u64); + for i in 0..seconds / 2 { + lag += 2.0 * rate(paused); + paused = judge.observe(t0 + Duration::from_secs(i * 2), lag); + paused_polls += u64::from(paused); + } + paused_polls as f64 / (seconds / 2) as f64 + } + + fn judge(base_rate: f64) -> LagJudge { + LagJudge::new( + base_rate, + 0.05, + Duration::from_secs(60), + Duration::from_secs(60), + Duration::from_secs(600), + ) + } + + #[test] + fn a_fly_below_real_time_is_judged_against_its_own_pace() { + // The release CT at RTF 0.66: 0.34 s of lag every second, before and during the shadow. + let mut j = judge(0.34); + assert_eq!(paused_fraction(&mut j, 3 * 3600, |_| 0.34), 0.0); + // Without a baseline the same fly is paused once, the pause does not help, and the + // back-off lifts: at most one minute in eleven. + let mut j = judge(0.0); + let f = paused_fraction(&mut j, 3 * 3600, |_| 0.34); + assert!(f > 0.0 && f < 0.1, "{f}"); + } + + #[test] + fn a_shadow_that_costs_the_fly_time_stays_paused_while_it_would() { + // The fly keeps real time while the shadow is paused and loses 0.3 s/s while it runs: + // pausing helps, so the judge keeps pausing it, most of the time. + let mut j = judge(0.0); + let f = paused_fraction(&mut j, 3 * 3600, |paused| if paused { 0.0 } else { 0.3 }); + assert!(f > 0.4, "{f}"); + } + + #[test] + fn a_restart_starts_the_window_again() { + let t0 = Instant::now(); + let mut j = judge(0.0); + for i in 0..40u64 { + assert!(!j.observe(t0 + Duration::from_secs(i * 2), 50.0)); + } + // The lag falls to zero (a new process): no rate across the restart. + assert!(!j.observe(t0 + Duration::from_secs(82), 0.0)); + assert!(!j.observe(t0 + Duration::from_secs(84), 0.0)); + } + + #[test] + fn every_boot_after_the_start_owns_a_trace() { + let boot = |wall: u64| serde_json::json!({"runtime": "flysim", "wallMs": wall, "startFrame": "1", "origin": "x"}); + let boots = vec![boot(1_000), boot(2_000), boot(3_000), boot(4_000)]; + let mut checked = Default::default(); + // Traces created during boots 2 and 4 (the one at 1,000 predates the shadow). + let traces: std::collections::BTreeSet = [1_950, 3_990].into(); + let untraced = untraced_boots(&boots, &traces, 1_500, &mut checked); + assert_eq!(untraced.len(), 1); + assert_eq!(untraced[0]["wallMs"], 3_000); + assert_eq!(checked, [2_000u64, 4_000].into()); + // A session-runtime boot is not this shadow's to follow; a boot before the start neither. + let other = vec![serde_json::json!({"runtime": "fly-session", "wallMs": 5_000})]; + assert!(untraced_boots(&other, &traces, 1_500, &mut checked).is_empty()); + assert_eq!( + trace_start_ms(Path::new("/x/trace-0001790741297310-444741.jsonl")), + Some(1_790_741_297_310) + ); + } + + #[test] + fn capture_ids() { + assert_eq!( + generation_of_capture(&serde_json::json!({"checkpointId": "g42", "afterActions": 0})), + Some(42) + ); + assert_eq!( + generation_of_capture(&serde_json::json!({"checkpointId": "x"})), + None + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs b/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs new file mode 100644 index 0000000..5258ed6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/spool.rs @@ -0,0 +1,251 @@ +//! The spool: copies of the live stores' checkpoint generations, taken as they appear. +//! +//! The live service keeps two generations per store (`keep_generations`) and writes a hot one +//! every five seconds, so a hot file lives about ten seconds, while the trace line that names it +//! arrives some seconds after the capture (the recorder buffers) and the shadow may be further +//! behind still. The spool thread therefore polls both store directories and copies every new +//! `.checkpoint` into the spool at once. Store commits write `.checkpoint.tmp` and rename +//! it, so a file under its final name is complete; one rotated away mid-copy is skipped. +//! +//! The spool is bounded: generations below the shadow's floor (already compared, or of a finished +//! segment) are deleted, and above `max_bytes` the oldest pending ones go first; a capture whose +//! file is gone is reported as unavailable, never as a divergence. The spool only reads the live +//! stores; it never writes, renames or deletes anything in them. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, SystemTime}; + +/// The generation of a store file name, `.checkpoint`. +pub fn generation_of(name: &str) -> Option { + name.strip_suffix(".checkpoint")?.parse().ok() +} + +fn spool_name(generation: u64) -> String { + format!("g{generation}.checkpoint") +} + +/// Shared between the copying thread and the shadow. +#[derive(Clone)] +pub struct Spool { + dir: PathBuf, + sources: Vec, + max_bytes: u64, + floor: Arc, + stop: Arc, + evicted: Arc, + /// Keep every copy (a rehearsal that replays the run again afterwards): no floor, no bound. + keep: bool, +} + +impl Spool { + pub fn new(dir: &Path, sources: Vec, max_bytes: u64) -> std::io::Result { + std::fs::create_dir_all(dir)?; + Ok(Spool { + dir: dir.to_owned(), + sources, + max_bytes, + floor: Arc::new(AtomicU64::new(0)), + stop: Arc::new(AtomicBool::new(false)), + evicted: Arc::new(AtomicU64::new(0)), + keep: false, + }) + } + + /// Keep every copy: the floor and the byte bound delete nothing. + pub fn keep_all(mut self) -> Spool { + self.keep = true; + self + } + + /// Generations below `floor` are no longer needed. + pub fn set_floor(&self, floor: u64) { + self.floor.fetch_max(floor, Ordering::Relaxed); + } + + /// Pending generations dropped for space. + pub fn evicted(&self) -> u64 { + self.evicted.load(Ordering::Relaxed) + } + + /// Where generation `generation` can be read: the spool's copy, else a live store's file. + pub fn path(&self, generation: u64) -> Option { + let spooled = self.dir.join(spool_name(generation)); + if spooled.is_file() { + return Some(spooled); + } + self.sources + .iter() + .map(|dir| dir.join(format!("{generation}.checkpoint"))) + .find(|path| path.is_file()) + } + + /// Reads generation `generation`, from the spool or a live store (a file rotated away between + /// the lookup and the read is `None`). + pub fn read(&self, generation: u64) -> Option> { + let spooled = self.dir.join(spool_name(generation)); + if let Ok(bytes) = std::fs::read(&spooled) { + return Some(bytes); + } + self.sources + .iter() + .find_map(|dir| std::fs::read(dir.join(format!("{generation}.checkpoint"))).ok()) + } + + pub fn stop(&self) { + self.stop.store(true, Ordering::Relaxed); + } + + /// Starts the copying thread. The first scan copies only files modified within `window` + /// (the stores' permanent milestone archives are old and not needed); later scans copy every + /// new generation. + pub fn spawn(&self, period: Duration, window: Duration) -> std::thread::JoinHandle<()> { + let spool = self.clone(); + std::thread::Builder::new() + .name("fly-shadow-spool".to_owned()) + .spawn(move || { + let mut state = ScanState::default(); + let mut first = true; + while !spool.stop.load(Ordering::Relaxed) { + spool.scan(&mut state, first.then_some(window)); + first = false; + std::thread::sleep(period); + } + }) + .expect("the spool thread starts") + } + + /// One pass: copy what is new, delete what is below the floor, keep within the byte bound. + pub fn scan(&self, state: &mut ScanState, only_newer_than: Option) { + let floor = self.floor.load(Ordering::Relaxed); + let now = SystemTime::now(); + for source in &self.sources { + let Ok(entries) = std::fs::read_dir(source) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(generation) = name.to_str().and_then(generation_of) else { + continue; + }; + if (generation < floor && !self.keep) || state.seen.contains(&generation) { + continue; + } + if let Some(window) = only_newer_than { + let recent = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| now.duration_since(t).ok()) + .is_some_and(|age| age <= window); + if !recent { + state.seen.insert(generation); + continue; + } + } + let target = self.dir.join(spool_name(generation)); + let tmp = self.dir.join(format!("{}.tmp", spool_name(generation))); + match std::fs::copy(entry.path(), &tmp) { + Ok(bytes) => { + if std::fs::rename(&tmp, &target).is_ok() { + state.held.insert(generation, bytes); + } + state.seen.insert(generation); + } + // Rotated away mid-copy: gone for good; the next scan will not see it either. + Err(_) => { + let _ = std::fs::remove_file(&tmp); + } + } + } + } + if self.keep { + return; + } + let below: Vec = state.held.range(..floor).map(|(g, _)| *g).collect(); + for generation in below { + let _ = std::fs::remove_file(self.dir.join(spool_name(generation))); + state.held.remove(&generation); + } + while state.held.values().sum::() > self.max_bytes { + let Some((&generation, _)) = state.held.iter().next() else { + break; + }; + let _ = std::fs::remove_file(self.dir.join(spool_name(generation))); + state.held.remove(&generation); + self.evicted.fetch_add(1, Ordering::Relaxed); + } + } + + /// Removes every spooled file (the shadow is done). + pub fn clear(&self) { + if self.keep { + return; + } + if let Ok(entries) = std::fs::read_dir(&self.dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + if name + .to_str() + .is_some_and(|n| n.starts_with('g') && n.contains(".checkpoint")) + { + let _ = std::fs::remove_file(entry.path()); + } + } + } + } +} + +/// What one spool thread has copied and seen. +#[derive(Default)] +pub struct ScanState { + seen: BTreeSet, + held: BTreeMap, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copies_new_generations_releases_below_the_floor_and_stays_bounded() { + let live = tempfile::tempdir().unwrap(); + let hot = live.path().join("hot"); + let durable = live.path().join("durable"); + std::fs::create_dir_all(&hot).unwrap(); + std::fs::create_dir_all(&durable).unwrap(); + let spool_dir = live.path().join("spool"); + let spool = Spool::new(&spool_dir, vec![hot.clone(), durable.clone()], 25).unwrap(); + std::fs::write(hot.join("5.checkpoint"), [1u8; 10]).unwrap(); + std::fs::write(durable.join("6.checkpoint"), [2u8; 10]).unwrap(); + std::fs::write(durable.join("manifest.json"), b"{}").unwrap(); + std::fs::write(hot.join("7.checkpoint.tmp"), [3u8; 10]).unwrap(); + let mut state = ScanState::default(); + spool.scan(&mut state, Some(Duration::from_secs(3600))); + assert!(spool_dir.join("g5.checkpoint").is_file()); + assert!(spool_dir.join("g6.checkpoint").is_file()); + assert!(!spool_dir.join("g7.checkpoint").exists()); + // The live store rotates 5 away: the spool still has it. + std::fs::remove_file(hot.join("5.checkpoint")).unwrap(); + assert_eq!(spool.read(5), Some(vec![1u8; 10])); + // A third file overflows the 25-byte bound: the oldest pending goes. + std::fs::write(hot.join("8.checkpoint"), [4u8; 10]).unwrap(); + spool.scan(&mut state, None); + assert_eq!(spool.evicted(), 1); + assert_eq!(spool.read(5), None); + assert!(spool.path(8).is_some()); + // Below the floor is released. + spool.set_floor(8); + spool.scan(&mut state, None); + assert!(!spool_dir.join("g6.checkpoint").exists()); + // Still readable from the live store while it is there. + assert_eq!(spool.read(6), Some(vec![2u8; 10])); + // The live stores were never touched. + assert!(durable.join("manifest.json").is_file()); + assert!(hot.join("8.checkpoint").is_file()); + spool.clear(); + assert!(!spool_dir.join("g8.checkpoint").exists()); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs new file mode 100644 index 0000000..a1923d7 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/shadow/verdict.rs @@ -0,0 +1,601 @@ +//! The verdict file, `fly-shadow-verdict-v1`: the contract CUT-01's automatic cutover reads. +//! +//! The shadow rewrites `verdict.json` in its output directory atomically (temporary file, rename) +//! every few seconds and at every change of status. The fields CUT-01 relies on: +//! +//! | Field | Meaning | +//! | --- | --- | +//! | `format` | `fly-shadow-verdict-v1` | +//! | `status` | `running`, `pass`, `diverged`, `stopped` or `error` | +//! | `candidate` | what was shadowed: `binarySha256` of the shadow binary; `binaries`, the SHA-256 of every release binary beside it by name (`fly-shadow`, `fly-session`, `flysim`, `fly-edge`: the session-runtime service CUT-01 switches to is built from the same tree in the same release); `release`, that directory; `compatibility` and its `compatibilitySha256`; `executionMode`; `agentThreads` | +//! | `required.brainSeconds` | the window the decision names: 10,800 s (3 h) of live brain time | +//! | `compared.brainSeconds`, `compared.transitions` | how much of the live fly was compared, transition by transition, with zero divergence | +//! | `passedAt` | when `compared.brainSeconds` first reached `required.brainSeconds` with no divergence | +//! | `firstDivergence` | `null`, or the first difference with its context (also `divergence.json`) | +//! | `declaredDifferences` | the named exclusions the comparison applied | +//! +//! `pass` is sticky only while nothing diverges: a shadow that keeps running after it passed and +//! then finds a difference turns the verdict to `diverged`. `stopped` is a shadow that exited +//! before it passed (a `pass` stays `pass` when the shadow stops). `error` is the shadow's own +//! failure (it could not read its inputs), which proves nothing either way. +//! +//! **The cutover rule (for CUT-01), [`allows_cutover`].** Cut over only if, read at the moment of +//! cutting over, every one of these holds; anything else keeps the legacy fly: +//! +//! - `format` is `fly-shadow-verdict-v1`, `status` is `pass`, `firstDivergence` is `null`, and +//! `compared.brainSeconds` reaches `required.brainSeconds` and never less than the operator's +//! 10,800 s (`REQUIRED_BRAIN_SECONDS`), whatever window the shadow was run with; +//! - *the release*: `candidate.release` is the directory `/opt/fly/current` resolves to now, +//! every binary in `candidate.binaries` still has its recorded SHA-256 there, and the binary +//! being switched to (`flysim-session`, SERVE-01's service) is one of them -- the shadow +//! vouches for the release it ran in and nothing else; +//! - `candidate.compatibility` is the live service's `--print-compatibility`; +//! - *saves were compared*: at least one live save per [`BRAIN_SECONDS_PER_SAVE`] brain seconds +//! compared byte for byte, and no more than [`MAX_UNAVAILABLE_FRACTION`] of the saves the trace +//! named were unavailable (a shadow starved past its spool must not pass on transitions alone); +//! - *nothing was skipped for a reason inside the session runtime*: every `skipped` entry's `kind` +//! is one of [`SKIP_KINDS`] (the live side's own events); a session-side failure is a +//! divergence, never a skip; +//! - *the shadow is caught up and alive*: `updatedAt` is no older than `max_age_s`, and +//! `lagTransitions` is at most [`MAX_LAG_TRANSITIONS`]. + +use std::path::Path; + +use serde_json::{Value, json}; + +use crate::trace::{Agreement, Difference}; + +pub const FORMAT: &str = "fly-shadow-verdict-v1"; + +/// Skips that are the live side's own events, not the session runtime's failures: the operator +/// reward pulse (declared), a startup save rotated away before the shadow reached it, a trace +/// stopped at its byte cap or for want of a consumer, and a process that ran no transition. +pub const SKIP_KINDS: [&str; 4] = [ + "operator-reward-pulse", + "startup-save-gone", + "trace-cap", + "no-transition", +]; + +/// At least one live save compared byte for byte per this many brain seconds (the live loop +/// saves every 5 s; 600 leaves room for a lagging shadow's spool evictions). +pub const BRAIN_SECONDS_PER_SAVE: f64 = 600.0; + +/// At most this fraction of the saves the trace named may have been unavailable. +pub const MAX_UNAVAILABLE_FRACTION: f64 = 0.1; + +/// The shadow at most about a minute behind the live trace. +pub const MAX_LAG_TRANSITIONS: u64 = 3_600; + +/// The declared differences the comparison applies, by name (`legacy-gameboy-v1`). +pub const DECLARED: [(&str, &str); 5] = [ + ( + "archive-order", + "a legacy milestone archive holds the pre-capture ratchet and slot (sections 4, 16): the \ + live file's ratchet, ratchetGame and ratchetFrame stand in for the shadow's in that capture", + ), + ( + "decision-list-order", + "the decision is compared as gameboy-channels-v1: buttons down and the first bound channel \ + held (section 6)", + ), + ( + "host-fields", + "generation, wallMs and lastEventId are the live file's: the session runtime has no feed \ + event log before EDGE-01 and allocates no generations as a shadow", + ), + ( + "admission-replay", + "sugar is replayed from the live trace's admissions, not re-decided: admission reads a \ + one-commit-stale pulse by the operator's decision (section 15)", + ), + ( + "operator-reward-pulse", + "a live POST /reward pulse cannot be reproduced (section 15 amendment): the rest of that \ + segment is reported uncompared, not diverged", + ), +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Running, + Pass, + Diverged, + Stopped, + Error, +} + +impl Status { + pub fn as_str(self) -> &'static str { + match self { + Status::Running => "running", + Status::Pass => "pass", + Status::Diverged => "diverged", + Status::Stopped => "stopped", + Status::Error => "error", + } + } +} + +/// What the checkpoint comparisons found. +#[derive(Clone, Debug, Default)] +pub struct Checkpoints { + /// Byte-identical after the host fields. + pub identical: u64, + /// Byte-identical after the host fields and a declared difference. + pub declared: u64, + /// Named in the trace but rotated away before the spool copied it. + pub unavailable: u64, +} + +/// A segment the shadow did not (fully) compare, and why. +#[derive(Clone, Debug)] +pub struct Skipped { + pub trace: String, + pub transitions_compared: u64, + /// One of [`SKIP_KINDS`], or `trace-malformed`. + pub kind: String, + pub reason: String, +} + +/// The first divergence and its context. +#[derive(Clone, Debug)] +pub struct Divergence { + /// `transition`, `ledgers`, `checkpoint`, `boot` or `session-error`. + pub kind: String, + pub trace: String, + pub step: Option, + pub difference: Option, + pub detail: String, + /// The last transition lines before it, live and shadow, oldest first. + pub context: Vec<(Value, Value)>, +} + +impl Divergence { + pub fn to_json(&self) -> Value { + json!({ + "kind": self.kind, + "trace": self.trace, + "step": self.step.map(|s| s.to_string()), + "field": self.difference.as_ref().map(|d| d.field.clone()), + "live": self.difference.as_ref().map(|d| d.legacy.clone()), + "shadow": self.difference.as_ref().map(|d| d.session.clone()), + "detail": self.detail, + "context": self.context.iter().map(|(live, shadow)| json!({"live": live, "shadow": shadow})).collect::>(), + }) + } +} + +/// The per-frame cost of the shadow, wall time. +#[derive(Clone, Debug, Default)] +pub struct Cost { + samples: Vec, + pub total_ms: f64, + pub frames: u64, + pub throttled_ms: f64, +} + +impl Cost { + /// Keeps the last 36,000 frames (10 minutes) for the percentiles. + pub fn record(&mut self, ms: f64) { + self.total_ms += ms; + self.frames += 1; + if self.samples.len() == 36_000 { + self.samples.remove(0); + } + self.samples.push(ms); + } + + pub fn to_json(&self) -> Value { + let mut sorted = self.samples.clone(); + sorted.sort_by(f64::total_cmp); + let pct = |p: f64| { + if sorted.is_empty() { + return Value::Null; + } + let i = ((sorted.len() - 1) as f64 * p).round() as usize; + json!((sorted[i] * 1000.0).round() / 1000.0) + }; + json!({ + "framesTimed": self.frames, + "msPerFrameMean": if self.frames == 0 { Value::Null } else { json!(((self.total_ms / self.frames as f64) * 1000.0).round() / 1000.0) }, + "msPerFrameP50": pct(0.5), + "msPerFrameP99": pct(0.99), + "throttledSeconds": (self.throttled_ms / 1000.0).round(), + }) + } +} + +/// Everything the verdict file says. +#[derive(Clone, Debug)] +pub struct Verdict { + pub status: Status, + pub reason: String, + pub binary_sha256: String, + /// SHA-256 of the release binaries beside the shadow, by file name. + pub binaries: std::collections::BTreeMap, + /// The directory they are in. + pub release: String, + pub compatibility: String, + pub execution_mode: String, + pub agent_threads: usize, + pub required_brain_seconds: f64, + pub agreement: Agreement, + pub brain_ms: f64, + pub ledger_checks: u64, + pub checkpoints: Checkpoints, + pub segments_compared: u64, + pub skipped: Vec, + pub divergence: Option, + pub started_at: String, + pub passed_at: Option, + pub current_trace: Option, + /// Complete live lines not yet compared in the current segment, when known. + pub lag_transitions: u64, + pub live_lag_seconds: Option, + pub spool_evicted: u64, + pub cost: Cost, +} + +pub fn now_iso() -> String { + let ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64); + iso(ms) +} + +/// UTC `YYYY-MM-DDTHH:MM:SS.mmmZ` from Unix milliseconds (civil-from-days). +pub fn iso(ms: i64) -> String { + let secs = ms.div_euclid(1000); + let millis = ms.rem_euclid(1000); + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{millis:03}Z", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} + +impl Verdict { + pub fn brain_seconds(&self) -> f64 { + self.brain_ms / 1000.0 + } + + pub fn to_json(&self) -> Value { + let a = &self.agreement; + json!({ + "format": FORMAT, + "status": self.status.as_str(), + "reason": self.reason, + "candidate": { + "binarySha256": self.binary_sha256, + "binaries": self.binaries, + "release": self.release, + "compatibility": self.compatibility, + "compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()), + "executionMode": self.execution_mode, + "agentThreads": self.agent_threads, + }, + "required": {"brainSeconds": self.required_brain_seconds}, + "compared": { + "brainSeconds": (self.brain_seconds() * 1000.0).round() / 1000.0, + "transitions": a.transitions, + "segments": self.segments_compared, + "sugar": a.sugar, + "rewards": a.rewards, + "rewardKinds": a.reward_kinds, + "macroEvents": a.macro_events, + "pressed": a.pressed, + "slotSaves": a.saves, + "rollbacks": a.rollbacks, + "spikes": a.spikes, + "ledgerChecks": self.ledger_checks, + "checkpoints": { + "identical": self.checkpoints.identical, + "declared": self.checkpoints.declared, + "unavailable": self.checkpoints.unavailable, + }, + }, + "skipped": self.skipped.iter().map(|s| json!({ + "trace": s.trace, "transitionsCompared": s.transitions_compared, "kind": s.kind, "reason": s.reason, + })).collect::>(), + "declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::>(), + "firstDivergence": self.divergence.as_ref().map(|d| { + let mut v = d.to_json(); + if let Some(o) = v.as_object_mut() { o.remove("context"); } + v + }), + "startedAt": self.started_at, + "updatedAt": now_iso(), + "passedAt": self.passed_at, + "currentTrace": self.current_trace, + "lagTransitions": self.lag_transitions, + "liveLagSeconds": self.live_lag_seconds, + "spoolEvicted": self.spool_evicted, + "cost": self.cost.to_json(), + }) + } +} + +/// Writes `value` to `path` atomically. +pub fn write_json(path: &Path, value: &Value) -> std::io::Result<()> { + let tmp = path.with_extension("json.tmp"); + let mut text = serde_json::to_string_pretty(value).expect("JSON serializes"); + text.push('\n'); + std::fs::write(&tmp, text)?; + std::fs::rename(&tmp, path) +} + +/// Whether the saves compared are enough for the brain time compared ([`BRAIN_SECONDS_PER_SAVE`], +/// [`MAX_UNAVAILABLE_FRACTION`]). +pub fn saves_suffice(brain_seconds: f64, compared: u64, unavailable: u64) -> Result<(), String> { + let needed = (brain_seconds / BRAIN_SECONDS_PER_SAVE).floor().max(1.0) as u64; + if compared < needed { + return Err(format!( + "{compared} live saves compared over {brain_seconds:.0} brain s; {needed} needed" + )); + } + if unavailable as f64 > MAX_UNAVAILABLE_FRACTION * (compared + unavailable) as f64 { + return Err(format!( + "{unavailable} of {} live saves were unavailable to compare", + compared + unavailable + )); + } + Ok(()) +} + +/// The release the cutover would switch into: its resolved directory and the SHA-256 of the +/// binaries in it, by file name. +pub struct Release<'a> { + pub dir: &'a str, + pub binaries: &'a std::collections::BTreeMap, +} + +/// How far ahead of the clock a verdict's `updatedAt` may be before it is refused. +const MAX_CLOCK_SKEW_S: i64 = 60; + +/// Reads a verdict file and says whether it allows the cutover, by the rule in the module notes. +/// `binary` is the file name of the session-runtime binary CUT-01 switches to, inside `release` +/// (what `/opt/fly/current` resolves to now), and `compatibility` the live service's; +/// `max_age_s` bounds `updatedAt`. +pub fn allows_cutover( + verdict: &Value, + binary: &str, + release: &Release<'_>, + compatibility: &str, + now_ms: i64, + max_age_s: i64, +) -> Result<(), String> { + if verdict["format"] != FORMAT { + return Err(format!("not {FORMAT}")); + } + if verdict["status"] != "pass" { + return Err(format!("status is {}", verdict["status"])); + } + if !verdict["firstDivergence"].is_null() { + return Err("a divergence is recorded".to_owned()); + } + let candidate = &verdict["candidate"]; + if candidate["release"] != release.dir { + return Err(format!( + "the verdict is for the release {}, not {}", + candidate["release"], release.dir + )); + } + let shadowed = candidate["binaries"] + .as_object() + .ok_or("the verdict names no binaries")?; + if !shadowed.contains_key(binary) { + return Err(format!("{binary} was not in the shadowed release")); + } + for (name, sha) in shadowed { + if release.binaries.get(name).map(String::as_str) != sha.as_str() { + return Err(format!( + "{name} in {} is not the binary the shadow ran beside", + release.dir + )); + } + } + if candidate["compatibility"] != compatibility { + return Err("the verdict is for another compatibility string".to_owned()); + } + let compared = verdict["compared"]["brainSeconds"].as_f64().unwrap_or(0.0); + // The operator's window is a floor the verdict cannot lower: a shadow run with a shorter + // `--required-brain-seconds` (a rehearsal, a test) never arms the cutover. + let required = verdict["required"]["brainSeconds"] + .as_f64() + .unwrap_or(f64::INFINITY) + .max(crate::shadow::REQUIRED_BRAIN_SECONDS); + if compared < required { + return Err(format!("{compared} of {required} brain seconds compared")); + } + let saves = &verdict["compared"]["checkpoints"]; + saves_suffice( + compared, + saves["identical"].as_u64().unwrap_or(0) + saves["declared"].as_u64().unwrap_or(0), + saves["unavailable"].as_u64().unwrap_or(u64::MAX / 2), + )?; + for skip in verdict["skipped"].as_array().into_iter().flatten() { + let kind = skip["kind"].as_str().unwrap_or(""); + if !SKIP_KINDS.contains(&kind) { + return Err(format!( + "a segment was skipped for {kind:?}: {}", + skip["reason"] + )); + } + } + let lag = verdict["lagTransitions"].as_u64().unwrap_or(u64::MAX); + if lag > MAX_LAG_TRANSITIONS { + return Err(format!( + "the shadow is {lag} transitions behind the live trace" + )); + } + let updated = verdict["updatedAt"] + .as_str() + .and_then(parse_iso) + .ok_or("no updatedAt")?; + // A verdict from the future (beyond a small skew) is refused: after a backward clock step an + // old pass would otherwise stay "fresh" for the size of the step plus `max_age_s`. + if updated - now_ms > MAX_CLOCK_SKEW_S * 1000 { + return Err(format!( + "the verdict is dated {} s in the future", + (updated - now_ms) / 1000 + )); + } + if now_ms - updated > max_age_s * 1000 { + return Err(format!( + "the verdict is {} s old", + (now_ms - updated) / 1000 + )); + } + Ok(()) +} + +/// Parses [`iso`]'s format back to Unix milliseconds. +pub fn parse_iso(text: &str) -> Option { + let b = text.as_bytes(); + if b.len() != 24 || b[23] != b'Z' { + return None; + } + let n = |r: std::ops::Range| -> Option { text.get(r)?.parse().ok() }; + let (y, m, d) = (n(0..4)?, n(5..7)?, n(8..10)?); + let (hh, mm, ss, ms) = (n(11..13)?, n(14..16)?, n(17..19)?, n(20..23)?); + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = if m > 2 { m - 3 } else { m + 9 }; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(((days * 86_400 + hh * 3600 + mm * 60 + ss) * 1000) + ms) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_round_trips() { + for ms in [0i64, 951_782_400_123, 1_790_000_000_999, 4_102_444_800_000] { + assert_eq!(parse_iso(&iso(ms)), Some(ms), "{}", iso(ms)); + } + assert_eq!(iso(0), "1970-01-01T00:00:00.000Z"); + assert_eq!(iso(951_782_400_123), "2000-02-29T00:00:00.123Z"); + } + + fn verdict(status: Status, brain_ms: f64) -> Value { + Verdict { + status, + reason: String::new(), + binary_sha256: "b".repeat(64), + binaries: [("flysim-session".to_owned(), "b".repeat(64))].into(), + release: "/opt/fly/releases/test".to_owned(), + compatibility: "c".to_owned(), + execution_mode: "in-process".to_owned(), + agent_threads: 2, + required_brain_seconds: 10_800.0, + agreement: Agreement::default(), + brain_ms, + ledger_checks: 0, + checkpoints: Checkpoints { + identical: 2_000, + declared: 1, + unavailable: 5, + }, + segments_compared: 1, + skipped: Vec::new(), + divergence: None, + started_at: now_iso(), + passed_at: None, + current_trace: None, + lag_transitions: 0, + live_lag_seconds: None, + spool_evicted: 0, + cost: Cost::default(), + } + .to_json() + } + + #[test] + fn the_cutover_rule() { + let now = parse_iso(&now_iso()).unwrap(); + let binaries: std::collections::BTreeMap = + [("flysim-session".to_owned(), "b".repeat(64))].into(); + let release = Release { + dir: "/opt/fly/releases/test", + binaries: &binaries, + }; + let ok = |v: &Value| allows_cutover(v, "flysim-session", &release, "c", now, 300); + let pass = verdict(Status::Pass, 10_800_000.0); + assert_eq!(ok(&pass), Ok(())); + // Another binary, another release, a changed file in it. + assert!(allows_cutover(&pass, "fly-other", &release, "c", now, 300).is_err()); + let moved = Release { + dir: "/opt/fly/releases/other", + binaries: &binaries, + }; + assert!(allows_cutover(&pass, "flysim-session", &moved, "c", now, 300).is_err()); + let changed: std::collections::BTreeMap = + [("flysim-session".to_owned(), "a".repeat(64))].into(); + let rebuilt = Release { + dir: "/opt/fly/releases/test", + binaries: &changed, + }; + assert!(allows_cutover(&pass, "flysim-session", &rebuilt, "c", now, 300).is_err()); + assert!(allows_cutover(&pass, "flysim-session", &release, "other", now, 300).is_err()); + assert!( + allows_cutover(&pass, "flysim-session", &release, "c", now + 301_000, 300).is_err() + ); + // A clock stepped back: a verdict dated well ahead of now is refused, a small skew is not. + assert!( + allows_cutover(&pass, "flysim-session", &release, "c", now - 120_000, 300).is_err() + ); + assert!(allows_cutover(&pass, "flysim-session", &release, "c", now - 30_000, 300).is_ok()); + assert!(ok(&verdict(Status::Pass, 10_799_000.0)).is_err()); + // A verdict that asked for less than the operator's 3 h never passes the check. + let mut short_window = verdict(Status::Pass, 67_000.0); + short_window["required"]["brainSeconds"] = json!(60.0); + assert!(ok(&short_window).is_err()); + for status in [ + Status::Running, + Status::Diverged, + Status::Stopped, + Status::Error, + ] { + assert!(ok(&verdict(status, 10_800_000.0)).is_err()); + } + let mut diverged = pass.clone(); + diverged["firstDivergence"] = json!({"kind": "transition"}); + assert!(ok(&diverged).is_err()); + // Saves: none compared, or too many unavailable. + let mut starved = pass.clone(); + starved["compared"]["checkpoints"] = + json!({"identical": 0, "declared": 0, "unavailable": 0}); + assert!(ok(&starved).is_err()); + starved["compared"]["checkpoints"] = + json!({"identical": 100, "declared": 0, "unavailable": 50}); + assert!(ok(&starved).is_err()); + // Skips: the live side's own are fine, anything else is not. + let mut skipped = pass.clone(); + skipped["skipped"] = json!([{"kind": "startup-save-gone", "reason": "x"}]); + assert_eq!(ok(&skipped), Ok(())); + skipped["skipped"] = json!([{"kind": "trace-malformed", "reason": "x"}]); + assert!(ok(&skipped).is_err()); + // Behind the live trace. + let mut behind = pass.clone(); + behind["lagTransitions"] = json!(MAX_LAG_TRANSITIONS + 1); + assert!(ok(&behind).is_err()); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs new file mode 100644 index 0000000..f85694e --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -0,0 +1,1046 @@ +//! `pokered-macros-v1`: the Pokémon Red task and its action executor, one object +//! (`legacy-gameboy-v1` section 10, `workers-v1` section 4 amendment of 2026-09-23). +//! +//! Nothing here is a port of a rule. The reward adapter (`PokemonRedReward`), the ratchet, and the +//! macro layer (`flysim::macros::MacroLayer` over `flybrain-gb`'s palette, executor and `PokeState`) +//! are the very types the legacy loop runs, called in `flysim::frame::LegacyFrame`'s order. What +//! changed is what they read: a boundary's 64 KiB memory image and the cartridge, through +//! `flybrain_gb::ImageReader` (MEM-01), instead of a live emulator. +//! +//! | legacy frame | here | +//! | --- | --- | +//! | `execute`: `MacroLayer::decide` over the emulator | Phase B, [`ActionExecutor::apply`] over `ImageReader(O[k])` | +//! | `evaluate`: `adapter.sample`, `MacroLayer::observe`, location, progress | Phase C, [`Task::evaluate_transition`] over `ImageReader(O[k+1])` | +//! | `boundary`: the ratchet's capture and decision | Phase C too: a slot save and a rollback request, applied by the coordinator at `Ready(k+1)` | +//! | `rollback`: `recover_game`'s `clear_transient`, `cancel`, `observe` | [`Task::rollback`] over `ImageReader(O'[k+1])` | +//! +//! The ratchet keeps its ledger here; its *slot* lives in the environment (`gameboy-slots-v1`). +//! The ratchet only needs to know a slot exists (its budget test is `snapshot.is_none()`), so it +//! holds a marker [`Snapshot`] in place of the bytes. +//! +//! `restore: legacy-transient-reset` (section 14): a restore installs the adapter and the ratchet, +//! and the executor starts as a fresh process has it -- a new macro layer with empty ledgers and +//! nothing running, which observes the restored boundary before it decides anything. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +use serde_json::{Value, json}; + +use fly_session::fly_session_types::gameboy::{ + self, ChannelsDecision, Location, MemoryInspection, ReadoutContext, RollbackRequest, +}; +use fly_session::legacy_checkpoint::TaskHalf; +use fly_session::task::{ + ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task, +}; +use fly_session::types::*; +use flybrain_core::decoder::gameboy::to_button_mask; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::emulator::FRAMEBUFFER_LEN; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::{Ratchet, Snapshot}; +use flybrain_gb::{AdapterLedger, Cartridge, ImageReader, MemoryImage}; +use flysim::config::Config; +use flysim::macros::{MacroEvent, MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +/// The attachment the image travels under (ENV-01's `legacy_env::MEMORY_ATTACHMENT`). +pub const MEMORY_ATTACHMENT: &str = fly_session::legacy_env::MEMORY_ATTACHMENT; +/// The composition's one slot, which is the ratchet's. +pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT; +/// The game id the adapter and the palette are chosen by. +pub const GAME: &str = "pokemon-red"; +/// The palette seed of a fresh start. The legacy loop seeds the palette from the brain's RNG +/// state after the warm-up (`Sim::boot`: `rng_state() as u32`), which the task cannot read: the +/// agent does not publish it. It is also never read: `MacroMachine`'s generator is written and +/// never consulted (no macro has a random step), which `tests/palette_seed.rs` holds on the +/// cartridge, so a fresh start's constant presses exactly what the legacy seed presses. A +/// restore uses the legacy seed itself, the imported agent state's RNG +/// ([`PokeredTask::set_palette_seed`]). +pub const PALETTE_SEED: u32 = 0; + +fn schema(name: &str) -> SchemaRef { + let digest = digest_of_bytes(format!("fly-legacy-session-schema-v1\n{name}\n1\n").as_bytes()); + SchemaRef::new(name, 1, &digest).expect("a task-local schema reference is valid") +} + +/// The task ledger's schema: STATE-02's `TaskHalf` ledger `{reward, ratchet, slotFilled}` -- +/// FLYSIM01's `reward` and `ratchet`, and whether the environment's slot `best` holds the +/// ratchet's snapshot. Nothing else: the executor's ledgers and the adapter's transient +/// observations are not captured (`legacy-transient-reset`). +pub fn ledger_schema() -> SchemaRef { + schema("pokered-task-ledger-v1") +} +/// The attachment the task ledger's adapter state travels as (its JSON). +pub const REWARD_ATTACHMENT: &str = "reward"; + +/// The executor's capture: a marker only, because its state is transient (section 10, "Capture"). +pub fn executor_schema() -> SchemaRef { + schema("pokered.executor.v1") +} +pub fn progress_schema() -> SchemaRef { + schema("pokered.progress.v1") +} +pub fn event_schema() -> SchemaRef { + schema("pokered.event.v1") +} + +fn state_error(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +/// The ratchet's stand-in for a slot it knows the environment holds. +fn slot_marker() -> Snapshot { + Snapshot { + game: format!("slot:{SLOT}").into_bytes(), + frame: vec![0; FRAMEBUFFER_LEN], + } +} + +/// The legacy trace's JSON of one macro event (`flysim::trace::macro_json`). +pub fn macro_json(phase: &str, event: &MacroEvent) -> Value { + json!({ + "phase": phase, + "slot": event.slot, + "name": event.name, + "outcome": event.outcome.map(|outcome| outcome.as_str()), + }) +} + +/// What the object did in one transition, for the trace and the ledger comparison: the fields of +/// `flysim-legacy-frame-trace-v1` that are the task's and the executor's. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TaskRecord { + /// The boundary the transition started from. + pub boundary: u64, + /// The decision as the executor was given it, as the legacy active set (buttons, then the + /// macro channel). + pub decision: Vec, + /// The bound channels the decision was masked to (the context of this transition's Prepare). + pub bound: Vec, + pub mask: u32, + /// `macroEvents`, phases `execute`, `evaluate` and `rollback`, in order. + pub macro_events: Vec, + /// SHA-256 of work RAM, `$C000-$DFFF`, of O[k+1]. + pub wram_digest: String, + /// `rewards`: `{kind, value, stimulationMs}` in adapter order. + pub rewards: Vec, + pub rank: u32, + /// The ratchet asked for a slot save at `Ready(k+1)`. + pub saved: bool, + /// The ratchet asked for a rollback at `Ready(k+1)`, and it ran. + pub rolled_back: bool, + /// The ledgers after the boundary: adapter, ratchet and executor, as one canonical string. + pub ledgers: String, +} + +/// The ledgers as one canonical string: the adapter's export (its lifetime ledgers), the +/// ratchet's state and whether it holds a slot, and the executor's observable state -- scene, +/// bound channels, running macro, outcome counts, "nearer the objective". A legacy loop computes +/// the same string from its own parts, which is how a parity run compares ledgers frame by frame. +pub fn ledgers_of( + adapter: &PokemonRedReward, + ratchet: &Ratchet, + macros: Option<&MacroLayer>, +) -> String { + flysim::frame::ledgers_string(adapter, ratchet, macros) +} + +/// 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 { + pub agent_id: Id, + pub port_id: Id, + pub mode: MacroMode, + /// `executor.macroChannels`, composition order; empty in raw mode. + pub macro_channels: Vec, + /// The macro group's `holdMs` from the decoder configuration. + pub hold_ms: f64, + /// Record a [`TaskRecord`] per transition (a parity run); off in service. + pub record: bool, +} + +struct Inner { + config: PokeredConfig, + cartridge: Cartridge, + adapter: PokemonRedReward, + ratchet: Ratchet, + macros: Option, + epoch: Id, + /// O[k]: the image the executor reads in Phase B and the task reads as "old" in Phase C. + current: Option<(u64, MemoryImage)>, + /// The brain clock of the transition in flight (Phase B's clock), in ms. + ms: f64, + evaluations: u64, + issued: u64, + last_source_step: u64, + open: Option, + records: Vec, + /// A parity run's stub readout ([`crate::driver`]); never set in service. + 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, +} + +/// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the +/// coordinator holds each where it expects a task and an executor, and both reach the same state. +#[derive(Clone)] +pub struct PokeredTask { + inner: Arc>, +} + +impl PokeredTask { + /// A fresh object over the cartridge. `rom_digest` is the environment's `contentDigest`: a + /// cartridge that is not it is refused (`legacy-gameboy-v1` section 8). + pub fn new( + config: PokeredConfig, + rom: &[u8], + rom_digest: &str, + epoch: &Id, + ) -> Result { + let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?; + let adapter = PokemonRedReward::new(); + let ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let macros = fresh_layer(&config, PALETTE_SEED); + Ok(Self { + inner: Arc::new(Mutex::new(Inner { + config, + cartridge, + adapter, + ratchet, + macros, + epoch: epoch.clone(), + current: None, + ms: 0.0, + evaluations: 0, + issued: 0, + last_source_step: 0, + open: None, + records: Vec::new(), + driver: None, + uncaptured: std::collections::BTreeSet::new(), + feed: FeedRecord::default(), + mask: 0, + rollback_game_over: false, + palette_seed: PALETTE_SEED, + })), + }) + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The task face. + pub fn task(&self) -> Box { + Box::new(TaskFace(self.clone())) + } + + /// The executor face. + pub fn executor(&self) -> Box { + Box::new(ExecutorFace(self.clone())) + } + + /// Replace every decision the executor is handed by `driver`'s, as a legacy harness does + /// through `FrameObserver::readout`. A parity run's tool; the service never sets one. + pub fn set_driver(&self, driver: Box) { + self.lock().driver = Some(driver); + } + + /// Every address the engine has read that the image does not capture. Empty is the contract + /// (`legacy-gameboy-v1` section 8): a register window reads `$FF` in the image. + pub fn uncaptured_reads(&self) -> Vec { + 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) { + self.lock().palette_seed = seed; + } + + /// The records since the last call. + pub fn take_records(&self) -> Vec { + std::mem::take(&mut self.lock().records) + } + + /// The ledgers as one canonical string: the adapter's export, the ratchet's state, and the + /// executor's observable state (scene, bound channels, running macro, outcome counts). + pub fn ledgers(&self) -> String { + self.lock().ledgers() + } + + /// The ledger of a task half (STATE-02's `TaskHalf`, FLYSIM01's `reward` and `ratchet`), with + /// whether the ratchet holds a snapshot (which the environment's slot `best` now holds). + /// + /// The adapter's lifetime ledger grows with play and is past the 32 KiB `TypedValue` bound on + /// the live fly (42-46 KB at rank 12-15), so it is artifact-backed (`workers-v1` section 1): + /// the typed value is `{reward: {digest, byteLength}, ratchet, slotFilled}` and the reward's + /// JSON travels as the attachment [`REWARD_ATTACHMENT`]. + pub fn ledger_of( + half: &TaskHalf, + slot_filled: bool, + ) -> DomainResult<(TypedValue, BTreeMap>)> { + // The adapter's own JSON, exactly as FLYSIM01's `reward` member holds it. + let reward = serde_json::to_vec(&half.reward) + .map_err(|e| state_error(format!("the adapter ledger: {e}")))?; + let value = json!({ + "reward": {"digest": digest_of_bytes(&reward), "byteLength": reward.len().to_string()}, + "ratchet": serde_json::to_value(half.ratchet) + .map_err(|e| state_error(format!("the ratchet: {e}")))?, + "slotFilled": slot_filled, + }); + let typed = TypedValue::new(ledger_schema(), value).map_err(|e| state_error(e.0))?; + Ok(( + typed, + BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), reward)]), + )) + } + + /// The task's half of a FLYSIM01 export at the committed boundary, and whether the slot is + /// filled. + pub fn task_half(&self) -> (TaskHalf, bool) { + let inner = self.lock(); + ( + TaskHalf { + reward: inner.adapter.export_state(), + ratchet: inner.ratchet.state, + }, + inner.ratchet.snapshot.is_some(), + ) + } + + /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. + pub fn brain_ms(&self) -> f64 { + self.lock().ms + } + + /// The adapter's ladder rank now (`Sim::track_rank` reads it after each transition). + pub fn rank(&self) -> u32 { + self.lock().adapter.progress().rank + } + + /// The context a restore of `ledger` onto the boundary `image` shows at brain time `ms`: what + /// [`Task::restored`] will compute after the install, computed before it so the agent's + /// payload can carry it. Changes nothing. + pub fn preview_context( + &self, + ledger: &TypedValue, + attachments: &BTreeMap>, + image: &MemoryImage, + ms: f64, + ) -> Result { + let inner = self.lock(); + let (adapter, _ratchet) = + parse_ledger(&inner, ledger, attachments).map_err(|e| e.message)?; + let mut layer = fresh_layer(&inner.config, inner.palette_seed); + if let Some(layer) = layer.as_mut() { + let mut reader = ImageReader::new(image, &inner.cartridge); + let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms); + } + Ok(ReadoutContext { + boot: adapter.boot(), + bound: layer + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(), + location: adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } + .to_typed()) + } + + /// The readout context the task would hand the decoder now. + pub fn context(&self) -> ReadoutContext { + self.lock().context() + } +} + +/// `Sim::boot`'s layer: the configuration's palette at the macro group's hold. +fn fresh_layer(config: &PokeredConfig, seed: u32) -> Option { + let mut service = Config::default(); + service.loop_.game = GAME.to_owned(); + service.macros.mode = config.mode; + macro_layer(&service, config.hold_ms, seed) +} + +/// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked +/// for that the image does not capture (`legacy-gameboy-v1` section 8, MEM-01 amendment). Such a +/// read answers `$FF` where the live emulator would answer the register, so the engine and the +/// legacy loop could disagree; the record makes that visible rather than silent. +struct Watched<'a> { + reader: ImageReader<'a>, + uncaptured: &'a mut std::collections::BTreeSet, +} + +impl flybrain_gb::adapter::MemoryReader for Watched<'_> { + fn read8(&mut self, address: u16) -> u8 { + if !flybrain_gb::captured(address) { + self.uncaptured.insert(address); + } + self.reader.read8(address) + } + + fn read_rom(&mut self, bank: u8, address: u16) -> Option { + self.reader.read_rom(bank, address) + } +} + +fn decision_active(decision: &ChannelsDecision) -> Vec { + let mut active: Vec = gameboy::GAMEBOY_BUTTONS + .iter() + .zip(decision.buttons) + .filter(|(_, down)| *down) + .map(|(name, _)| (*name).to_owned()) + .collect(); + if let Some(channel) = &decision.macro_channel { + active.push(channel.clone()); + } + active +} + +fn intent_of(mask: u32) -> ControllerIntent { + let control = fly_session::legacy_env::control_of("p1", mask as u8); + ControllerIntent { + buttons: control.buttons, + axes: control.axes, + } +} + +impl Inner { + fn image_of(&self, inspection: &Inspection) -> DomainResult { + let typed = MemoryInspection::from_typed(&inspection.value) + .map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?; + if typed.rom_digest != self.cartridge.sha256_hex() { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the inspection's romDigest is not the executor's cartridge", + )); + } + let bytes = inspection + .attachments + .get(MEMORY_ATTACHMENT) + .ok_or_else(|| { + DomainError::new( + ErrorCode::BufferInvalid, + format!( + "boundary {} has no {MEMORY_ATTACHMENT}", + inspection.boundary + ), + MutationCertainty::Unknown, + ) + })?; + MemoryImage::from_bytes(bytes).map_err(|e| { + DomainError::new( + ErrorCode::BufferInvalid, + e.to_string(), + MutationCertainty::Unknown, + ) + }) + } + + fn context(&self) -> ReadoutContext { + ReadoutContext { + boot: self.adapter.boot(), + bound: self + .macros + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(), + location: self + .adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } + } + + fn contexts(&self) -> BTreeMap { + BTreeMap::from([(self.config.agent_id.clone(), self.context().to_typed())]) + } + + fn progress_value(&self) -> TypedValue { + let progress = self.adapter.progress(); + TypedValue::new( + progress_schema(), + json!({ + "rank": progress.rank, + "uniqueLocations": progress.unique_locations, + "rewardTotal": progress.reward_total, + "best": self.ratchet.state.best, + "recoveries": self.ratchet.state.recoveries, + }), + ) + .expect("progress fits the contract") + } + + fn ledgers(&self) -> String { + ledgers_of(&self.adapter, &self.ratchet, self.macros.as_ref()) + } + + fn observe(&mut self, image: &MemoryImage, ms: f64) -> Vec { + let cartridge = self.cartridge.clone(); + let Inner { + macros, + adapter, + uncaptured, + .. + } = self; + let mut reader = Watched { + reader: ImageReader::new(image, &cartridge), + uncaptured, + }; + match macros.as_mut() { + Some(layer) => layer.observe(&mut reader, &AdapterLedger(&*adapter), ms), + None => Vec::new(), + } + } + + fn event( + &mut self, + source_step: u64, + rule: &str, + ordinal: u32, + kind: &str, + payload: Value, + ) -> TaskEvent { + self.issued += 1; + TaskEvent { + id: event_id(&self.epoch, source_step, rule, ordinal), + kind_id: id(kind), + source_step, + agent_id: Some(self.config.agent_id.clone()), + payload: TypedValue::new(event_schema(), payload).expect("an event payload fits"), + } + } + + fn close(&mut self) { + if let Some(mut record) = self.open.take() { + record.ledgers = self.ledgers(); + self.records.push(record); + } + } +} + +struct TaskFace(PokeredTask); +struct ExecutorFace(PokeredTask); + +impl Task for TaskFace { + fn schema(&self) -> SchemaRef { + progress_schema() + } + + fn inspection_attachments(&self) -> Vec { + vec![MEMORY_ATTACHMENT.to_owned()] + } + + fn bootstrap( + &mut self, + initial: &Inspection, + bindings: &[PortBinding], + ) -> DomainResult { + let mut inner = self.0.lock(); + if bindings.len() != 1 + || bindings[0].agent_id != inner.config.agent_id + || bindings[0].port_id != inner.config.port_id + { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "pokered-macros-v1 serves exactly one agent on its one port", + )); + } + let image = inner.image_of(initial)?; + // `Sim::boot` on a fresh start: the layer observes O[0] once, at the warm-up's end. The + // agent is initialized after this, but its warm-up is the profile's constant, so the + // brain time the legacy loop observes at is known: exactly `warmupMs`. + let ms = gameboy::WARMUP_MS as f64; + inner.ms = ms; + inner.observe(&image, ms); + inner.current = Some((initial.boundary, image)); + Ok(Bootstrap { + contexts: inner.contexts(), + progress: inner.progress_value(), + events: Vec::new(), + }) + } + + fn evaluate_transition( + &mut self, + scope: &Scope, + old: &Inspection, + new: &Inspection, + _applied_controls: &[PortControl], + ) -> DomainResult { + let mut inner = self.0.lock(); + match &inner.current { + Some((boundary, _)) if *boundary == old.boundary && old.boundary == scope.step => {} + _ => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "the task evaluates the transition from the boundary it last observed", + )); + } + } + let span = fly_session::profile::span("task.image"); + let image = inner.image_of(new)?; + drop(span); + let ms = inner.ms; + let k1 = scope.step + 1; + inner.evaluations += 1; + inner.last_source_step = k1; + + // `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the + // location (the agent's, from the context), then the rank. + let span = fly_session::profile::span("task.sample"); + let cartridge = inner.cartridge.clone(); + let rewards = { + let Inner { + adapter, + uncaptured, + .. + } = &mut *inner; + let mut reader = Watched { + reader: ImageReader::new(&image, &cartridge), + uncaptured, + }; + adapter.sample(&mut reader, ms) + }; + 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(); + + // `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above + // its best -- a slot save at `Ready(k+1)` -- and says whether to roll back. + let safe = inner.adapter.safe_for_snapshot(); + let nearer = inner + .macros + .as_ref() + .is_some_and(MacroLayer::nearer_the_objective); + let game_over = inner.adapter.game_over(); + let mut saved = false; + let recover = inner.ratchet.observe_with_progress( + safe, + u64::from(progress.rank), + progress.unique_locations as u64, + ms as u64, + game_over, + nearer, + || { + saved = true; + slot_marker() + }, + ); + + drop(span); + let span = fly_session::profile::span("task.outcome"); + let mut outcome = AgentOutcome::default(); + let mut events = Vec::new(); + for (n, event) in rewards.iter().enumerate() { + let ordinal = n as u32; + let task_event = inner.event( + k1, + "reward", + ordinal, + "pokered.reward", + json!({"kind": event.kind, "label": event.label, "value": event.value}), + ); + outcome.rewards.push(Reward { + event_id: task_event.id.clone(), + rule_id: id(event.kind), + value: event.value, + }); + // `Stimulus.durationMs` is positive: an event that drives no pulse is a Reward alone, + // as the legacy `stimulate(0)` changes nothing. + if event.stimulation_ms > 0 { + outcome.stimulations.push(Stimulus { + id: task_event.id.clone(), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: f64::from(event.stimulation_ms), + }); + } + 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" }), + outcome: RollbackRequest { + slot_id: SLOT.to_owned(), + trigger: if game_over { "game-over" } else { "stall" }.to_owned(), + } + .to_typed(), + }); + + if let Some(record) = inner.open.as_mut() { + record + .macro_events + .extend(abandoned.iter().map(|e| macro_json("evaluate", e))); + record.wram_digest = sha256_hex(&image.as_bytes()[0xc000..=0xdfff]); + record.rewards = rewards + .iter() + .map(|e| json!({"kind": e.kind, "value": e.value, "stimulationMs": e.stimulation_ms})) + .collect(); + record.rank = progress.rank; + record.saved = saved; + } + drop(span); + let span = fly_session::profile::span("task.contexts"); + let next_contexts = inner.contexts(); + let progress_value = inner.progress_value(); + drop(span); + inner.current = Some((new.boundary, image)); + if !recover { + inner.close(); + } + Ok(Evaluation { + outcomes: BTreeMap::from([(inner.config.agent_id.clone(), outcome)]), + next_contexts, + progress: progress_value, + events, + episode, + slot_saves: if saved { vec![id(SLOT)] } else { Vec::new() }, + }) + } + + fn rollback( + &mut self, + scope: &Scope, + restored: &Inspection, + ) -> DomainResult { + let mut inner = self.0.lock(); + let image = inner.image_of(restored)?; + let ms = inner.ms; + inner.epoch = scope.epoch.clone(); + // `recover_game`'s task half: the adapter's transient observations; then the executor + // cancels and observes the restored game (`LegacyFrame::rollback`). + inner.adapter.clear_transient(); + let mut events = match inner.macros.as_mut() { + Some(layer) => layer.cancel(ms), + 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 + .macro_events + .extend(events.iter().map(|e| macro_json("rollback", e))); + } + inner.current = Some((restored.boundary, image)); + inner.close(); + Ok(RollbackEvaluation { + next_contexts: inner.contexts(), + events: Vec::new(), + }) + } + + fn restored( + &mut self, + scope: &Scope, + restored: &Inspection, + clock: &RationalNs, + ) -> DomainResult>> { + let mut inner = self.0.lock(); + let image = inner.image_of(restored)?; + let ms = clock_ms(clock)?; + inner.epoch = scope.epoch.clone(); + inner.ms = ms; + // `Sim::boot` after a restore: a fresh layer (installed by `install_restore`) observes the + // restored game once, at the restored brain time, before the first frame decides. + inner.observe(&image, ms); + inner.current = Some((restored.boundary, image)); + Ok(Some(inner.contexts())) + } + + fn progress(&self) -> TypedValue { + self.0.lock().progress_value() + } + + fn evaluations(&self) -> u64 { + self.0.lock().evaluations + } + + fn capture(&self) -> DomainResult { + let (half, slot_filled) = self.0.task_half(); + PokeredTask::ledger_of(&half, slot_filled).map(|(typed, _)| typed) + } + + fn capture_attachments(&self) -> DomainResult>> { + let (half, slot_filled) = self.0.task_half(); + PokeredTask::ledger_of(&half, slot_filled).map(|(_, attachments)| attachments) + } + + fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { + self.validate_restore_with(state, &BTreeMap::new()) + } + + fn validate_restore_with( + &self, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let inner = self.0.lock(); + parse_ledger(&inner, state, attachments).map(|_| ()) + } + + fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> { + self.install_restore_with(epoch, state, &BTreeMap::new()) + } + + fn install_restore_with( + &mut self, + epoch: &Id, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let mut inner = self.0.lock(); + let (adapter, ratchet) = parse_ledger(&inner, state, attachments)?; + inner.adapter = adapter; + inner.ratchet = ratchet; + // `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers. + 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; + inner.last_source_step = 0; + Ok(()) + } + + fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult> { + Err(DomainError::before( + ErrorCode::Unsupported, + "pokered-macros-v1 compares runs by FLY_TRACE, not by rebased event ids", + )) + } + + fn event_watermarks(&self) -> (u64, u64) { + let inner = self.0.lock(); + (inner.last_source_step, inner.issued) + } +} + +fn parse_ledger( + inner: &Inner, + state: &TypedValue, + attachments: &BTreeMap>, +) -> DomainResult<(PokemonRedReward, Ratchet)> { + if state.schema != ledger_schema() { + return Err(state_error( + "the captured ledger is not a pokered-macros-v1 ledger", + )); + } + let bytes = attachments + .get(REWARD_ATTACHMENT) + .ok_or_else(|| state_error("the ledger's reward attachment is missing"))?; + let declared = &state.value["reward"]; + if declared["digest"].as_str() != Some(digest_of_bytes(bytes).as_str()) + || declared["byteLength"].as_str() != Some(bytes.len().to_string().as_str()) + { + return Err(state_error( + "the reward attachment is not the one the ledger names", + )); + } + let reward: Value = serde_json::from_slice(bytes) + .map_err(|e| state_error(format!("the reward attachment is not JSON: {e}")))?; + let mut value = state.value.clone(); + value["reward"] = reward; + let half = TaskHalf::from_ledger(&value).map_err(state_error)?; + let slot_filled = state + .value + .get("slotFilled") + .and_then(Value::as_bool) + .ok_or_else(|| state_error("the ledger has no slotFilled"))?; + // `LegacyFrame::restore`'s order: the adapter (unless the file has none), then the ratchet + // bounded by the adapter's ladder. + let mut adapter = PokemonRedReward::new(); + if !half.reward.is_null() { + adapter + .import_state(&half.reward) + .map_err(|e| state_error(format!("adapter: {e}")))?; + } + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + ratchet + .import( + Some(half.ratchet), + slot_filled.then(slot_marker), + adapter.rank_ladder().len(), + ) + .map_err(|e| state_error(format!("ratchet: {e}")))?; + let _ = inner; + Ok((adapter, ratchet)) +} + +impl ActionExecutor for ExecutorFace { + fn apply( + &mut self, + scope: &Scope, + decision: &TypedValue, + current: &Inspection, + _progress: &TypedValue, + clock: &RationalNs, + ) -> DomainResult<(ControllerIntent, Vec)> { + let mut inner = self.0.lock(); + let decision = ChannelsDecision::from_typed(decision) + .map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?; + let image = match &inner.current { + Some((boundary, image)) if *boundary == current.boundary && *boundary == scope.step => { + image.clone() + } + _ => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "the executor reads the boundary the task last observed", + )); + } + }; + // The clock is the brain time after Prepare, whole milliseconds (the legacy + // `network.ms`), which is what the macro layer's windows read. + let ms = clock_ms(clock)?; + inner.ms = ms; + let mut active = decision_active(&decision); + let bound = inner + .macros + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(); + if let Some(driver) = inner.driver.as_mut() { + driver.readout(ms, &bound, &mut active); + } + let raw = to_button_mask(&active); + let cartridge = inner.cartridge.clone(); + let (mask, events) = { + let Inner { + macros, + adapter, + uncaptured, + .. + } = &mut *inner; + match macros.as_mut() { + Some(layer) => { + let mut reader = Watched { + reader: ImageReader::new(&image, &cartridge), + uncaptured, + }; + let decided = + layer.decide(&active, raw, ms, &mut reader, &AdapterLedger(&*adapter)); + (decided.mask, decided.events) + } + 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, + decision: active, + bound, + mask, + macro_events: events.iter().map(|e| macro_json("execute", e)).collect(), + ..TaskRecord::default() + }); + } + Ok((intent_of(mask), Vec::new())) + } + + fn capture(&self) -> DomainResult { + TypedValue::new(executor_schema(), json!({"executor": gameboy::EXECUTOR_ID})) + .map_err(|e| DomainError::invalid(e.0)) + } + + fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { + if state.schema != executor_schema() + || state.value.get("executor").and_then(Value::as_str) != Some(gameboy::EXECUTOR_ID) + { + return Err(state_error( + "the captured executor is not pokered-macros-v1", + )); + } + Ok(()) + } + + /// Nothing to install: the executor's state is transient (`legacy-transient-reset`), and + /// the task's install already gave it a fresh layer. + fn install_restore(&mut self, state: &TypedValue) -> DomainResult<()> { + self.validate_restore(state) + } +} + +/// Brain time in ms from the executor's clock: exact whole nanoseconds of whole milliseconds. +pub fn clock_ms(clock: &RationalNs) -> DomainResult { + if clock.denominator != 1 || !clock.numerator.is_multiple_of(1_000_000) { + return Err(DomainError::invalid( + "the executor clock is not a whole number of milliseconds", + )); + } + Ok((clock.numerator / 1_000_000) as f64) +} diff --git a/services/flysim/crates/fly-legacy-session/src/trace.rs b/services/flysim/crates/fly-legacy-session/src/trace.rs new file mode 100644 index 0000000..dea7a22 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/trace.rs @@ -0,0 +1,280 @@ +//! The session's own `FLY_TRACE`: the legacy loop's trace format (`flysim-legacy-frame-trace-v1`, +//! FND-01) written from a session-framework run, and the comparison of two of them. +//! +//! FND-01's trace is what the running service does, frame by frame, as digests. A new-runtime +//! session driven from the same checkpoint with the same admissions must write the same lines. So +//! the session trace is assembled from exactly what crosses the session's boundaries -- +//! `Agent.Prepare` (ticks, clock, remainder, decision), `Agent.Commit` (rates, spike bitset), the +//! executor's joypad batch, `Environment.Advance`'s view, the task's image-derived fields, and the +//! boundary actions -- and compared as JSON, with one declared exclusion: the decision is compared +//! as `gameboy-channels-v1` sees it ([`channels`]): the buttons down, and the first channel of the +//! context's bound set the decode holds. The decoder's list order is not in the decision schema, +//! and a macro channel the macro group still holds after its scene unbound it (the legacy `active` +//! can carry one) reaches nothing: the macro layer starts only a bound channel, and the joypad mask +//! is the buttons'. The mask, the macro events and every other field are compared as they are. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use fly_session::coordinator::StepDetails; +use fly_session::fly_session_types::gameboy::GAMEBOY_BUTTONS; +use fly_session::legacy_parity::trace_rates_digest; +use fly_session::types::*; + +use crate::task::TaskRecord; + +pub const FORMAT: &str = "flysim-legacy-frame-trace-v1"; + +/// flysim's `remainder_ns`: the exact rational nanoseconds of the frame remainder. +fn remainder_json(remainder: &RationalNs) -> Value { + json!({"numerator": remainder.numerator.to_string(), "denominator": remainder.denominator.to_string()}) +} + +fn popcount(bytes: &[u8]) -> u64 { + bytes.iter().map(|b| u64::from(b.count_ones())).sum() +} + +/// One transition line of the session's trace, built from the coordinator's details of the +/// transition and the task's record of it. +pub fn line(details: &StepDetails, record: &TaskRecord) -> Result { + let [(agent_id, prepared)] = details.prepared.as_slice() else { + return Err("the legacy composition has exactly one agent".to_owned()); + }; + let commit = details + .commits + .iter() + .find(|(id, _)| id == agent_id) + .map(|(_, result)| result) + .ok_or("no commit for the agent")?; + let spikes = details + .commit_attachments + .iter() + .find(|(id, name, _)| { + id == agent_id && name == fly_session::legacy_agent::SPIKES_ATTACHMENT + }) + .map(|(_, _, bytes)| bytes) + .ok_or("the commit carried no spike bitset")?; + let step: u64 = details + .engine_frame + .as_deref() + .ok_or("O[k] has no engineFrame")? + .parse() + .map_err(|_| "engineFrame is not a U64")?; + let admissions: Vec = details + .admissions + .iter() + .map(|admission| match admission { + fly_session::coordinator::Admission::Stimulus { duration_ms, .. } => { + json!({"kind": "sugar", "durationMs": duration_ms}) + } + }) + .collect(); + let framebuffer = details + .view_digests + .iter() + .find(|(view, _)| view == "lcd") + .map(|(_, digest)| digest.clone()) + .ok_or("O[k+1] has no lcd view")?; + let boundary_actions: Vec = details + .boundary_actions + .iter() + .map(|action| { + json!({ + "kind": action.kind.as_str(), + "slotId": action.slot_id, + "stateDigest": action.state_digest, + }) + }) + .collect(); + Ok(json!({ + "behaviour": { + "step": step.to_string(), + "admissions": admissions, + "ticksAdvanced": prepared.ticks_advanced.to_string(), + "brainTicks": prepared.brain_ticks.to_string(), + "remainder": remainder_json(&prepared.remainder), + "ratesDigest": trace_rates_digest(&commit.telemetry)?, + "spikesDigest": sha256_hex(spikes), + "spikeCount": popcount(spikes), + "decision": record.decision, + "mask": record.mask, + "macroEvents": record.macro_events, + "framebufferDigest": framebuffer, + "wramDigest": record.wram_digest, + "rewards": record.rewards, + "rank": record.rank, + "acknowledgedBoundary": (step + 1).to_string(), + "boundaryActions": boundary_actions, + } + })) +} + +/// The decision as `gameboy-channels-v1` sees it, given the bound channels it was masked to: the +/// buttons down, and the first bound channel the active set holds (AGENT-01's rule). +pub fn channels(decision: &Value, bound: &[String]) -> (BTreeSet, Option) { + let active: Vec<&str> = decision + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let buttons = active + .iter() + .filter(|name| GAMEBOY_BUTTONS.contains(name)) + .map(|name| (*name).to_owned()) + .collect(); + let macro_channel = bound + .iter() + .find(|channel| active.contains(&channel.as_str())) + .cloned(); + (buttons, macro_channel) +} + +/// Reads a trace file's transition lines (`behaviour` only), skipping the header and the start +/// boundary line. +pub fn behaviours(text: &str) -> Result, String> { + let mut lines = text.lines().filter(|l| !l.trim().is_empty()); + let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?) + .map_err(|e| format!("header: {e}"))?; + if header["format"] != FORMAT { + return Err(format!("not {FORMAT}: {}", header["format"])); + } + let mut out = Vec::new(); + for line in lines { + let value: Value = serde_json::from_str(line).map_err(|e| format!("line: {e}"))?; + if let Some(behaviour) = value.get("behaviour") { + out.push(behaviour.clone()); + } + } + Ok(out) +} + +/// What a comparison found, for the report. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Agreement { + pub transitions: u64, + pub sugar: u64, + pub reward_pulses: u64, + pub rewards: u64, + pub reward_kinds: Vec, + pub macro_events: u64, + pub pressed: u64, + pub saves: u64, + pub rollbacks: u64, + pub spikes: u64, +} + +/// The first field two transition lines disagree on, with both values. +#[derive(Clone, Debug, PartialEq)] +pub struct Difference { + pub field: String, + pub legacy: Value, + pub session: Value, +} + +impl std::fmt::Display for Difference { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}:\n legacy {}\n session {}", + self.field, self.legacy, self.session + ) + } +} + +/// One transition, field by field over the union of both lines' keys, the decision as +/// [`channels`] of the session's bound set for that transition. +pub fn compare_line( + legacy: &Value, + session: &Value, + bound: &[String], +) -> Result<(), Box> { + let (Some(a_map), Some(b_map)) = (legacy.as_object(), session.as_object()) else { + return Err(Box::new(Difference { + field: "(line)".to_owned(), + legacy: legacy.clone(), + session: session.clone(), + })); + }; + let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect(); + for key in keys { + let (x, y) = (&legacy[key.as_str()], &session[key.as_str()]); + let same = if key == "decision" { + channels(x, bound) == channels(y, bound) + } else { + x == y + }; + if !same { + return Err(Box::new(Difference { + field: key.clone(), + legacy: x.clone(), + session: y.clone(), + })); + } + } + Ok(()) +} + +impl Agreement { + /// Counts one agreed transition line. + pub fn count(&mut self, line: &Value) { + self.transitions += 1; + for admission in line["admissions"].as_array().into_iter().flatten() { + match admission["kind"].as_str() { + Some("sugar") => self.sugar += 1, + Some("reward") => self.reward_pulses += 1, + _ => {} + } + } + for reward in line["rewards"].as_array().into_iter().flatten() { + self.rewards += 1; + if let Some(kind) = reward["kind"].as_str() + && !self.reward_kinds.iter().any(|k| k == kind) + { + self.reward_kinds.push(kind.to_owned()); + } + } + self.macro_events += line["macroEvents"].as_array().map_or(0, |v| v.len() as u64); + if line["mask"].as_u64().unwrap_or(0) != 0 { + self.pressed += 1; + } + for action in line["boundaryActions"].as_array().into_iter().flatten() { + match action["kind"].as_str() { + Some("save-slot") => self.saves += 1, + Some("rollback") => self.rollbacks += 1, + _ => {} + } + } + self.spikes += line["spikeCount"].as_u64().unwrap_or(0); + } +} + +/// Every transition identical, field by field; the decision as [`channels`] of the session's bound +/// set for that transition. The first difference is the error, with both values. +pub fn compare( + legacy: &[Value], + session: &[Value], + bounds: &[Vec], +) -> Result { + if bounds.len() != session.len() { + return Err("one bound set per session transition".to_owned()); + } + if legacy.len() != session.len() { + return Err(format!( + "the legacy trace has {} transitions, the session's {}", + legacy.len(), + session.len() + )); + } + let mut agreement = Agreement::default(); + for (n, (a, b)) in legacy.iter().zip(session).enumerate() { + compare_line(a, b, &bounds[n]) + .map_err(|d| format!("transition {n} (step {}) {d}", a["step"]))?; + agreement.count(a); + } + Ok(agreement) +} + +/// `GAMEBOY_BUTTONS`, re-exported for the decision reconstruction's tests. +pub const BUTTONS: [&str; 8] = GAMEBOY_BUTTONS; 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/ledger_size.rs b/services/flysim/crates/fly-legacy-session/tests/ledger_size.rs new file mode 100644 index 0000000..57538c2 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/ledger_size.rs @@ -0,0 +1,130 @@ +//! The task ledger is not bounded by the 32 KiB `TypedValue` limit (TASK-01 review B1). +//! +//! The adapter's lifetime ledger grows with play (42-46 KB on the live fly at rank 12-15). The +//! pokered-macros-v1 ledger keeps it as an attachment beside a small typed value, so a ledger of +//! any size captures, validates and installs, and a malformed one is an error, never a panic. +//! ROM-free: the cartridge is ENV-01's toy one, which the task never reads here. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use fly_legacy_session::task::{PokeredConfig, PokeredTask, REWARD_ATTACHMENT}; +use fly_session::fly_session_types::gameboy::ReadoutContext; +use fly_session::legacy_checkpoint::TaskHalf; +use fly_session::legacy_env_parity::toy_cart; +use fly_session::types::*; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flysim::snapshot::MacroMode; + +fn task() -> PokeredTask { + let rom = toy_cart::rom(0); + PokeredTask::new( + PokeredConfig { + agent_id: id("fly"), + port_id: id("p1"), + mode: MacroMode::Raw, + macro_channels: Vec::new(), + hold_ms: 0.0, + record: false, + }, + &rom, + &digest_of_bytes(&rom), + &id("e1"), + ) + .expect("the object") +} + +/// A real adapter state grown past 64 KB: thousands of walked tiles, as a long life has. +fn big_reward() -> Value { + let mut reward = PokemonRedReward::new().export_state(); + let tiles: Vec = (0..12_000) + .map(|n| json!(format!("{}:{}:{}", n % 200, n / 200 % 64, n / 12_800))) + .collect(); + reward["tiles"] = Value::Array(tiles); + reward +} + +#[test] +fn a_ledger_past_32_kib_captures_validates_and_installs() { + let reward = big_reward(); + let bytes = serde_json::to_vec(&reward).unwrap(); + assert!(bytes.len() > 64 * 1024, "{} bytes", bytes.len()); + // The adapter itself takes it, so it is a real ledger and not just a large JSON value. + PokemonRedReward::new() + .import_state(&reward) + .expect("an adapter state"); + + let half = TaskHalf { + reward, + ratchet: Default::default(), + }; + let (typed, attachments) = PokeredTask::ledger_of(&half, false).expect("any size"); + assert!( + typed.to_json().to_string().len() < 1024, + "the typed value stays small" + ); + assert_eq!(attachments[REWARD_ATTACHMENT], bytes); + + let object = task(); + let mut face = object.task(); + face.validate_restore_with(&typed, &attachments) + .expect("validates"); + face.install_restore_with(&id("e2"), &typed, &attachments) + .expect("installs"); + let (restored, slot) = object.task_half(); + assert!(!slot); + let mut direct = PokemonRedReward::new(); + direct.import_state(&half.reward).unwrap(); + assert_eq!( + restored.reward, + direct.export_state(), + "the installed adapter is the imported one" + ); + // And what it captures back is a ledger of the same kind, which installs again. + let (again, again_attachments) = (face.capture().unwrap(), face.capture_attachments().unwrap()); + assert!(again_attachments[REWARD_ATTACHMENT].len() > 32 * 1024); + face.validate_restore_with(&again, &again_attachments) + .expect("re-validates"); + + // The context preview reads it too. + let image = flybrain_gb::MemoryImage::zeroed(); + let context = object + .preview_context(&typed, &attachments, &image, 1_000.0) + .expect("previews"); + assert!(ReadoutContext::from_typed(&context).is_ok()); +} + +#[test] +fn a_bad_ledger_is_an_error_not_a_panic() { + let half = TaskHalf { + reward: big_reward(), + ratchet: Default::default(), + }; + let (typed, attachments) = PokeredTask::ledger_of(&half, false).unwrap(); + let face = task().task(); + for (what, attachments) in [ + ("missing", BTreeMap::new()), + ( + "another", + BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), b"{}".to_vec())]), + ), + ( + "truncated", + BTreeMap::from([( + REWARD_ATTACHMENT.to_owned(), + attachments[REWARD_ATTACHMENT][..100].to_vec(), + )]), + ), + ] { + let err = face + .validate_restore_with(&typed, &attachments) + .unwrap_err(); + assert_eq!( + err.code, + ErrorCode::IncompatibleState, + "{what}: {}", + err.message + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs b/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs new file mode 100644 index 0000000..115f008 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs @@ -0,0 +1,79 @@ +//! The palette seed is never read (TASK-01 review N3). +//! +//! The legacy loop seeds the macro palette with the brain's RNG state after boot; a fresh session +//! start cannot see it and uses `PALETTE_SEED`. That is equivalent only while no macro reads its +//! generator. This holds it on the cartridge: two macro layers seeded differently, handed the same +//! decisions (the ROM tests' rotation driver) over the same frames, press the same buttons and +//! report the same events, frame by frame. A macro that ever draws from its generator breaks it +//! here rather than in a shadow run. +//! +//! ROM job: `FLY_ROM` and `FLY_DOOR_CHECKPOINT` (the operator's rom env script). + +use fly_legacy_session::composition::channels_and_hold; +use fly_legacy_session::driver::{DecisionDriver, RotationDriver}; +use flybrain_core::decoder::gameboy::to_button_mask; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::macros::macro_layer; +use flysim::snapshot::MacroMode; + +#[test] +fn two_palette_seeds_press_the_same_buttons() { + let (Some(rom), Some(path)) = ( + std::env::var_os("FLY_ROM"), + std::env::var_os("FLY_DOOR_CHECKPOINT"), + ) else { + eprintln!("skipping: FLY_ROM or FLY_DOOR_CHECKPOINT is not set"); + return; + }; + let rom = std::fs::read(rom).expect("the cartridge"); + let checkpoint = flysim::store::load(std::path::Path::new(&path)).expect("FLYSIM01"); + let mut emulator = + Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb"); + emulator + .import_state(&checkpoint.runtime.emulator) + .expect("the emulator state"); + let mut adapter = PokemonRedReward::new(); + adapter + .import_state(&checkpoint.runtime.reward) + .expect("the adapter state"); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_owned(); + config.macros.mode = MacroMode::Macros; + let (_, hold_ms) = channels_and_hold(MacroMode::Macros); + let mut a = macro_layer(&config, hold_ms, 0).expect("a layer"); + let mut b = macro_layer(&config, hold_ms, 0xdead_beef).expect("a layer"); + let mut driver = RotationDriver::new(); + let mut ms = checkpoint.agent.network.ms; + let frames = std::env::var("FLY_TASK01_SEED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(3000); + let mut macros = 0; + for frame in 0..frames { + assert_eq!( + a.bound_channels(), + b.bound_channels(), + "frame {frame}: bound" + ); + let mut active = Vec::new(); + driver.readout(ms, &a.bound_channels(), &mut active); + let raw = to_button_mask(&active); + let da = a.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter)); + let db = b.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter)); + assert_eq!(da.mask, db.mask, "frame {frame}: mask"); + assert_eq!(da.events, db.events, "frame {frame}: events"); + macros += da.events.iter().filter(|e| e.outcome.is_none()).count(); + emulator.set_buttons(da.mask as u8); + emulator.run_frame().expect("a frame"); + let _ = emulator.take_audio_u8(); + ms += 17.0; + let _ = adapter.sample(&mut emulator, ms); + let ea = a.observe(&mut emulator, &AdapterLedger(&adapter), ms); + let eb = b.observe(&mut emulator, &AdapterLedger(&adapter), ms); + assert_eq!(ea, eb, "frame {frame}: observe"); + } + assert!(macros > 10, "the driver started macros ({macros})"); + eprintln!("{frames} frames, {macros} macros started: two seeds, the same presses"); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs new file mode 100644 index 0000000..0a46beb --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs @@ -0,0 +1,537 @@ +//! The coordinator's boundary actions on the legacy workers, without a ROM: ENV-01's toy +//! cartridge, AGENT-01's toy connectome, and a scripted task that asks for a slot save at +//! boundary 3, a reward at 4 and a rollback onto the slot at 6. +//! +//! What it holds, in-process and as processes: +//! +//! - the rollback runs `Ready(e, 6) -> RollingBack(6) -> Ready(e', 6)`, in the policy's order +//! (`RestoreSlot`, the task's part, `Agent.Rollback`), and the session steps on in `e'`; +//! - the restored boundary is the saved one: the task reads O'[6]'s memory image and it is O[3]'s; +//! - the step details record the save's state digest and the rollback, and the trace carries them +//! as boundary actions, saves first; +//! - admitted sugar is cut into the next Prepare and reported applied at the boundary it committed. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +use serde_json::json; + +use flybus::{Grants, Pattern, Policy, RouterConfig}; + +use fly_session::coordinator::{AdmissionEnd, AgentSlot, Coordinator}; +use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; +use fly_session::fly_session_types::gameboy::{ + self, ChannelsDecision, ReadoutContext, RollbackRequest, +}; +use fly_session::fly_session_types::trace::BoundaryActionKind; +use fly_session::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, + ThreadBudget, Via, +}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_env::{BackendConfig, MEMORY_ATTACHMENT, STATE_FORMAT_ID}; +use fly_session::legacy_env_parity::toy_cart; +use fly_session::task::{ + ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task, +}; +use fly_session::types::*; + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +fn schema(name: &str) -> SchemaRef { + SchemaRef::new(name, 1, &digest_of_bytes(name.as_bytes())).unwrap() +} + +/// What the scripted task saw. +#[derive(Default)] +struct Seen { + /// Boundary -> the image digest the task read for it (the last reading wins). + images: BTreeMap, + restored: Option<(u64, String)>, +} + +struct Scripted { + agent: Id, + seen: Arc>, + evaluations: u64, +} + +fn context() -> TypedValue { + ReadoutContext { + boot: false, + bound: Vec::new(), + location: None, + } + .to_typed() +} + +fn image_digest(inspection: &Inspection) -> DomainResult { + let bytes = inspection + .attachments + .get(MEMORY_ATTACHMENT) + .ok_or_else(|| DomainError::invalid("no image"))?; + assert_eq!(bytes.len(), 65_536); + Ok(digest_of_bytes(bytes)) +} + +impl Task for Scripted { + fn schema(&self) -> SchemaRef { + schema("scripted.progress") + } + + fn inspection_attachments(&self) -> Vec { + vec![MEMORY_ATTACHMENT.to_owned()] + } + + fn bootstrap( + &mut self, + initial: &Inspection, + _bindings: &[PortBinding], + ) -> DomainResult { + let digest = image_digest(initial)?; + self.seen + .lock() + .unwrap() + .images + .insert(initial.boundary, digest); + Ok(Bootstrap { + contexts: BTreeMap::from([(self.agent.clone(), context())]), + progress: self.progress(), + events: Vec::new(), + }) + } + + fn evaluate_transition( + &mut self, + scope: &Scope, + old: &Inspection, + new: &Inspection, + _controls: &[PortControl], + ) -> DomainResult { + assert_eq!(old.boundary, scope.step, "O[k] is the old inspection"); + assert_eq!(new.boundary, scope.step + 1, "O[k+1] is the new one"); + self.evaluations += 1; + let k1 = scope.step + 1; + self.seen + .lock() + .unwrap() + .images + .insert(k1, image_digest(new)?); + let mut outcome = AgentOutcome::default(); + let mut events = Vec::new(); + if k1 == 4 { + let event = TaskEvent { + id: event_id(&scope.epoch, k1, "scripted", 0), + kind_id: id("scripted.reward"), + source_step: k1, + agent_id: Some(self.agent.clone()), + payload: TypedValue::new(schema("scripted.event"), json!({})).unwrap(), + }; + outcome.rewards.push(Reward { + event_id: event.id.clone(), + rule_id: id("scripted"), + value: 0.5, + }); + outcome.stimulations.push(Stimulus { + id: event.id.clone(), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: 100.0, + }); + events.push(event); + } + Ok(Evaluation { + outcomes: BTreeMap::from([(self.agent.clone(), outcome)]), + next_contexts: BTreeMap::from([(self.agent.clone(), context())]), + progress: self.progress(), + events, + episode: (k1 == 6).then(|| EpisodeRequest { + kind: EpisodeRequestKind::Rollback, + reason: id("stall"), + outcome: RollbackRequest { + slot_id: "best".into(), + trigger: "stall".into(), + } + .to_typed(), + }), + slot_saves: if k1 == 3 { + vec![id("best")] + } else { + Vec::new() + }, + }) + } + + fn rollback( + &mut self, + scope: &Scope, + restored: &Inspection, + ) -> DomainResult { + assert_eq!(restored.boundary, scope.step); + self.seen.lock().unwrap().restored = Some((restored.boundary, image_digest(restored)?)); + Ok(RollbackEvaluation { + next_contexts: BTreeMap::from([(self.agent.clone(), context())]), + events: Vec::new(), + }) + } + + fn progress(&self) -> TypedValue { + TypedValue::new( + schema("scripted.progress"), + json!({"evaluations": self.evaluations}), + ) + .unwrap() + } + + fn evaluations(&self) -> u64 { + self.evaluations + } + + fn capture(&self) -> DomainResult { + Ok(self.progress()) + } + + fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn install_restore(&mut self, _epoch: &Id, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult> { + Ok(BTreeMap::new()) + } + + fn event_watermarks(&self) -> (u64, u64) { + (0, 0) + } +} + +/// The joypad the decision's buttons ask for. +struct Buttons; + +impl ActionExecutor for Buttons { + fn apply( + &mut self, + _scope: &Scope, + decision: &TypedValue, + _current: &Inspection, + _progress: &TypedValue, + _clock: &RationalNs, + ) -> DomainResult<(ControllerIntent, Vec)> { + let decision = + ChannelsDecision::from_typed(decision).map_err(|e| DomainError::invalid(e.0))?; + let control = fly_session::legacy_env::control_of("p1", decision.mask()); + Ok(( + ControllerIntent { + buttons: control.buttons, + axes: control.axes, + }, + Vec::new(), + )) + } + + fn capture(&self) -> DomainResult { + Ok(TypedValue::new(schema("buttons"), json!({})).unwrap()) + } + + fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn install_restore(&mut self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } +} + +async fn run(mode: ExecutionMode) { + let root = tempfile::tempdir().unwrap(); + let rom = toy_cart::rom(0); + let rom_path = root.path().join("toy.gb"); + std::fs::write(&rom_path, &rom).unwrap(); + let store = root.path().join("store"); + let sockets = root.path().join("sockets"); + std::fs::create_dir_all(&sockets).unwrap(); + let policy = Policy::closed() + .client( + "coordinator", + grants(|g| { + g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]; + g.publish = vec![Pattern::prefix("session.")]; + g.manage_topics = vec![Pattern::prefix("session.")]; + g.register = vec![Pattern::prefix("session.")]; + }), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]), + ) + .client( + "world", + grants(|g| g.register = vec![Pattern::exact("env.world")]), + ) + .client( + "fly", + grants(|g| g.register = vec![Pattern::exact("agent.fly")]), + ); + let mut config = RouterConfig::new(&store); + config.policy = policy; + let router = flybus::Router::new(config).unwrap(); + let mut launcher = Launcher::start( + router, + mode, + Via::Unix, + &store, + &sockets, + ThreadBudget::new(3, 1).unwrap(), + ) + .await + .unwrap(); + let mut backend = BackendConfig::legacy(&digest_of_bytes(&rom)); + backend.slots = vec![id("best")]; + launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: id("s"), + worker_id: id("world"), + incarnation_id: id("world-1"), + worker_threads: 1, + rom_path, + backend: backend.clone(), + client_id: "world".into(), + service: "env.world".into(), + }) + .await + .unwrap(); + launcher + .launch_legacy_agent(LegacyAgentLaunch { + session_id: id("s"), + agent_id: id("fly"), + port_id: id("p1"), + incarnation_id: id("fly-1"), + worker_threads: 1, + dataset_dir: fly_session::legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_channels: Vec::new(), + client_id: "fly".into(), + service: "agent.fly".into(), + }) + .await + .unwrap(); + let mut slot = AgentSlot::new( + launcher.worker(&id("fly")).unwrap().worker_ref(), + id("fly"), + id("p1"), + LegacyProfileKind::Toy.profile().asset, + fly_session::legacy_parity::LEGACY_SEED, + ); + slot.model_version = gameboy::KERNEL_VERSION.into(); + slot.plasticity_version = gameboy::PLASTICITY_VERSION.into(); + let seen = Arc::new(Mutex::new(Seen::default())); + let task = Scripted { + agent: id("fly"), + seen: seen.clone(), + evaluations: 0, + }; + let executors: BTreeMap> = + BTreeMap::from([(id("fly"), Box::new(Buttons) as Box)]); + let mut coordinator = Coordinator::new( + launcher.connect("coordinator").await.unwrap(), + id("s"), + id("e1"), + id("ep1"), + launcher.worker(&id("world")).unwrap().worker_ref(), + vec![slot], + Box::new(task), + executors, + ); + coordinator.set_environment_config( + backend.asset_ref(), + fly_session::environment::synthetic_asset("scripted", "scripted-v1"), + ); + coordinator.set_media( + &[gameboy::VIEW_ID], + &[fly_session::legacy_env::AUDIO_STREAM_ID], + ); + coordinator.set_state_format(STATE_FORMAT_ID); + coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref()); + coordinator + .declare_rollback_policy(ROLLBACK_POLICY) + .unwrap(); + coordinator.record_details(true); + coordinator + .bootstrap() + .await + .unwrap_or_else(|e| panic!("bootstrap: {}", e.error.message)); + coordinator.disable_pacing(); + let admissions = coordinator.admissions(); + assert_eq!( + admissions.stimulus_remaining_ms(&id("fly")), + None, + "no commit yet" + ); + + let mut actions = Vec::new(); + for k in 0..9u64 { + if k == 2 { + // Two sugars before the next commit: the legacy drain admits the first and refuses + // the second (its pulse is already active), and so does the session's admission. + let mut legacy = flysim::ratelimit::RateLimiter::new(6); + let mut remaining = admissions + .stimulus_remaining_ms(&id("fly")) + .expect("committed"); + let legacy_answers: Vec<_> = [300.0, 250.0] + .iter() + .map(|duration: &f64| { + let answer = legacy.admit(1_000, remaining); + if answer.is_ok() { + remaining = remaining.max(*duration); + } + answer + }) + .collect(); + let mut sugar = + fly_legacy_session::admission::LegacyAdmission::new(admissions.clone(), id("fly")); + let first = sugar.sugar(1_000, Some(300.0)).map(|(_, d)| d); + let second = sugar.sugar(1_000, Some(250.0)).map(|(_, d)| d); + assert_eq!(first, Ok(300.0)); + assert_eq!(legacy_answers[0], Ok(())); + assert_eq!( + second.err(), + legacy_answers[1].err(), + "the second is refused as legacy refuses it" + ); + assert_eq!(admissions.queued(), 1); + } + let report = coordinator.step().await.unwrap_or_else(|e| { + panic!( + "{} step {k}: {} ({})", + mode.label(), + e.error.message, + e.detail + ) + }); + assert_eq!(report.boundary, k + 1); + assert!( + !report.paused && !report.terminal, + "a rollback is not an episode end" + ); + let details = coordinator.take_details().unwrap(); + if k == 2 { + assert_eq!( + details.admissions.len(), + 1, + "the sugar is cut into Prepare(2)" + ); + } + for action in &details.boundary_actions { + actions.push((k + 1, action.kind, action.state_digest.clone())); + } + if k + 1 == 6 { + let rollback = details.rollback.as_ref().expect("the rollback's details"); + assert_eq!(rollback.epoch, id("e1.rb1")); + assert_eq!(rollback.observation.boundary, 6); + assert!( + rollback.observation.audio.is_empty(), + "a restore plays no interval" + ); + assert_eq!(rollback.agents.len(), 1); + } + } + assert_eq!( + coordinator.epoch(), + &id("e1.rb1"), + "the session steps on in the new epoch" + ); + assert_eq!(actions.len(), 2); + assert_eq!( + (actions[0].0, actions[0].1), + (3, BoundaryActionKind::SaveSlot) + ); + assert!( + actions[0].2.is_some(), + "a save records the saved state's digest" + ); + assert_eq!( + (actions[1].0, actions[1].1, actions[1].2.clone()), + (6, BoundaryActionKind::Rollback, None) + ); + let phases: Vec = coordinator + .trace + .phases + .iter() + .map(|p| format!("{}->{}", p.from, p.to)) + .collect(); + assert!( + phases.contains(&"Ready(6)->RollingBack(6)".to_owned()), + "{phases:?}" + ); + assert!( + phases.contains(&"RollingBack(6)->Ready(6)".to_owned()), + "{phases:?}" + ); + let traced: Vec<(u64, usize)> = coordinator + .trace + .transitions + .iter() + .map(|t| { + ( + t.behaviour.acknowledged_boundary, + t.behaviour.boundary_actions.len(), + ) + }) + .filter(|(_, n)| *n > 0) + .collect(); + assert_eq!( + traced, + vec![(3, 1), (6, 1)], + "the trace carries the boundary actions" + ); + let seen = std::mem::take(&mut *seen.lock().unwrap()); + let (boundary, restored) = seen.restored.clone().expect("the task rolled back"); + assert_eq!(boundary, 6); + assert_eq!( + restored, seen.images[&3], + "O'[6] is the world saved at boundary 3" + ); + assert_ne!( + restored, seen.images[&6], + "and not the one the rollback threw away" + ); + let ended = admissions.take_ended(); + assert_eq!(ended.len(), 1); + assert_eq!(ended[0].1, AdmissionEnd::Applied { boundary: 3 }); + assert_eq!( + admissions.pending_stimulus_ms(&id("fly")), + None, + "nothing pending once committed" + ); + assert!(admissions.stimulus_remaining_ms(&id("fly")).is_some()); + let audit = coordinator.audit.join(" "); + for needle in [ + "save-slot:best@3", + "restore-slot:best@6", + "agent-rollback:fly@6", + "rolled-back:best@6", + ] { + assert!(audit.contains(needle), "{needle} in {audit}"); + } + launcher.reap_all(&id("done")).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_save_then_a_rollback_in_process() { + run(ExecutionMode::InProcess).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_save_then_a_rollback_as_processes() { + if !fly_session::launcher::default_worker_program().is_file() { + eprintln!("process mode skipped: no worker program"); + return; + } + run(ExecutionMode::Process).await; +} diff --git a/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs new file mode 100644 index 0000000..859c39d --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs @@ -0,0 +1,126 @@ +//! TASK-01 round-2 review notes R2-1 and R2-2 on the session's save hand-off. The toy raw +//! composition from power-on (`FLY_ROM`; a build without it skips): +//! +//! - R2-1: a save begun at boundary k reaches the writer even when the step after it fails, and +//! `flush_captures` hands it over while the loop idles (a pause), as the legacy loop's writer +//! thread has it from the boundary on. +//! - R2-2: `completed_saves` reports every queued save's outcome, a failed one beside the rest. + +use std::path::PathBuf; + +use fly_legacy_session::composition::{ + LegacyConfig, LegacySession, StoreConfig, +}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_checkpoint::SaveKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flysim::snapshot::MacroMode; + +async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)> { + let Some(rom_path) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + let config = LegacyConfig { + mode: ExecutionMode::InProcess, + rom_path, + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + let mut session = LegacySession::start(&root.join("run"), config) + .await + .expect("the session starts"); + session.bootstrap().await.expect("Ready(0)"); + let store = StoreConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("durable"), + keep_generations: 4, + // Saves only when asked. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + session.attach_store(&store).expect("the store attaches"); + Some((session, store)) +} + +/// One step, then the interval save it began (the first boundary is due for a durable one) +/// written and collected, so a test starts with nothing queued. +async fn warm_up(session: &mut LegacySession) { + session.advance().await.expect("a step"); + session.flush_captures().await.expect("the flush"); + for outcome in session.completed_saves(true).await { + outcome.expect("the first save"); + } +} + +fn files_in(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir) + .map(|entries| entries.filter_map(Result::ok).count()) + .unwrap_or(0) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_begun_save_reaches_the_writer_when_the_next_step_fails() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, _)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + for _ in 0..2 { + session.advance().await.expect("a step"); + } + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + // The next transition fails at its commit. + session.coordinator.injections.at_step = 3; + session.coordinator.injections.undeclared_stimulus = true; + let error = session.advance().await.err().expect("the step fails"); + assert!(error.starts_with("step ("), "{error}"); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1, "the save begun before the failed step was written"); + let report = outcomes.into_iter().next().unwrap().expect("and it committed"); + assert!(!report.durable); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_pause_flushes_the_begun_save() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + let before = files_in(&store.hot_dir); + let queued = session.flush_captures().await.expect("the flush"); + assert_eq!(queued.len(), 1); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1); + assert!(outcomes[0].is_ok()); + assert!(files_in(&store.hot_dir) > before, "the hot generation is on disk"); + assert!( + session.flush_captures().await.expect("a second flush").is_empty(), + "nothing is held twice" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn every_save_outcome_is_reported_after_a_failure() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + // The store's hot directory goes away under the writer: every save after it fails. The + // first failure must not hide the outcomes behind it. + std::fs::remove_dir_all(&store.hot_dir).expect("remove hot"); + std::fs::write(&store.hot_dir, b"not a directory").expect("block hot"); + let mut expected = 0; + for _ in 0..3 { + session.begin_save(SaveKind::Hot).await.expect("begin"); + session.flush_captures().await.expect("flush"); + expected += 1; + } + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), expected, "one outcome per queued save: {outcomes:?}"); + assert!(outcomes.iter().all(Result::is_err), "the writes failed: {outcomes:?}"); +} 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-legacy-session/tests/session_trace.rs b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs new file mode 100644 index 0000000..cee9fc6 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs @@ -0,0 +1,835 @@ +//! TASK-01's pre-shadow proof: a whole new-runtime session -- the legacy agent worker (AGENT-01), +//! the legacy environment worker (ENV-01) and the `pokered-macros-v1` task and executor in the +//! coordinator -- reproduces the legacy loop's `FLY_TRACE` (FND-01) frame by frame: ticks, clock, +//! remainder, rates, spikes, decision, joypad mask, macro events, frame, work RAM, rewards, rank, +//! slot saves and rollbacks. Where the legacy side is a host run in this process, the ledgers +//! (adapter, ratchet, executor) are compared after every boundary too. +//! +//! Every run is an explicit ROM job (the operator's rom env script, never a download): +//! +//! - `toy_raw_from_power_on` (`FLY_ROM`): the committed toy connectome in raw mode from power-on, +//! with sugar admitted through the coordinator's admission queue. +//! - `fafb_service_trace_checkpoints` (`FLY_TASK01_FAFB=1`, `FLY_ENV01_TRACE_DIR`, +//! `FLY_DOOR_CHECKPOINT`): the checkpoints of the service's own traces (the FND-01 review's +//! `rollback`, `climb` and `r58`: a ratchet rollback, a slot save, two real rewards), for each +//! trace's length, against today's legacy loop; the session imported from the same FLYSIM01 +//! files. `FLY_TASK01_TRACE_LIMIT` caps each. +//! - `fafb_reward_segments` (`FLY_TASK01_FAFB=1`): host runs of `LegacyFrame` from stream +//! checkpoints, with sugar, in two arms. The brain arm: the adapter ledger thinned so rewards +//! fire where the fly already is (new area, exits, new ground, wild wins). The driver arm: the +//! brain ticks and decodes as always but the executor is handed the ROM tests' rotation driver's +//! decision (`fly_legacy_session::driver`), which walks, talks, fights and picks up, so real +//! rewards reach `Agent.Commit`. `FLY_TASK01_SEGMENTS` picks the checkpoints (`name=path,...`), +//! `FLY_TASK01_FRAMES` the length. +//! +//! Execution modes: in-process, then process (the workspace's `fly-session` binary); a build +//! without it skips process mode and says so. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use serde_json::Value; + +use fly_legacy_session::admission::LegacyAdmission; +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_legacy_session::driver::{DecisionDriver, RotationDriver}; +use fly_legacy_session::task::ledgers_of; +use fly_legacy_session::trace::{self, Agreement}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, 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::{LegacyFrame, Parts}; +use flysim::macros::macro_layer; +use flysim::snapshot::MacroMode; +use flysim::trace::FrameTrace; + +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 + } + } +} + +fn fafb() -> Option { + if std::env::var_os("FLY_TASK01_FAFB").is_none() { + eprintln!("skipping: FLY_TASK01_FAFB is not set"); + return None; + } + let dir = legacy_parity::fafb_dir(); + if dir.is_none() { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + } + dir +} + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +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 +} + +/// What each frame admits at its top, in admission order, and whether the rotation driver hands +/// the executor its decisions. +#[derive(Clone, Debug, Default)] +struct Inputs { + /// `(frame index from 1, duration ms)`. + sugar: Vec<(usize, f64)>, + driver: bool, +} + +/// The legacy loop's one look into a decision: the driver's, when the run has one. +struct Driven(Option); + +impl flysim::frame::FrameObserver for Driven { + fn readout(&mut self, ms: f64, bound: Option<&[String]>, active: &mut Vec) { + if let Some(driver) = self.0.as_mut() { + driver.readout(ms, bound.unwrap_or(&[]), active); + } + } +} + +/// How a run starts. +#[derive(Clone)] +enum Start { + PowerOn, + /// A FLYSIM01 file. + Checkpoint(Vec), +} + +/// The run's `FLY_TRACE` behaviours and, when it has them, the ledgers after every boundary. +struct Run { + behaviours: Vec, + ledgers: Vec, + /// The bound set of each transition's decision (session runs only). + bounds: Vec>, +} + +fn decoder_hold(mode: MacroMode) -> (Vec<&'static str>, f64) { + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let (_, hold) = channels_and_hold(mode); + (channels, hold) +} + +/// The legacy loop in this process: `LegacyFrame` with `FLY_TRACE` on, admitting the inputs at +/// the top of each frame as the service's command drain does, the ledgers read after each +/// boundary. +fn run_legacy( + rom: &[u8], + data: &Arc, + start: &Start, + mode: MacroMode, + frames: usize, + inputs: &Inputs, + trace_path: &Path, +) -> Run { + 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) = decoder_hold(mode); + 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"); + let mut frame = + LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace"))); + match start { + Start::PowerOn => { + frame + .initialize(&mut emulator, &mut agent) + .expect("the first frame and the warm-up"); + } + Start::Checkpoint(bytes) => { + let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01"); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + &checkpoint, + ) + .expect("the checkpoint 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 mut ledgers = Vec::new(); + let mut observer = Driven(inputs.driver.then(RotationDriver::new)); + for k in 1..=frames { + // The command drain: the sugar admitted for this frame, in admission order. + for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) { + agent.network.stimulate(*duration); + if let Some(trace) = frame.trace_mut() { + trace.sugar(*duration); + } + } + 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 observer) + .expect("a frame"); + frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + ledgers.push(ledgers_of(&adapter, &ratchet, macros.as_ref())); + } + frame.finish_trace(); + drop(frame); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + Run { + behaviours: trace::behaviours(&text).expect("a FLY_TRACE"), + ledgers, + bounds: Vec::new(), + } +} + +/// The same run on the session framework. +#[allow(clippy::too_many_arguments)] +async fn run_session( + mode: ExecutionMode, + rom_path: &Path, + dataset_dir: &Path, + profile: LegacyProfileKind, + macro_mode: MacroMode, + start: &Start, + frames: usize, + inputs: &Inputs, +) -> Run { + let root = tempfile::tempdir().expect("tmp"); + let config = LegacyConfig { + mode, + rom_path: rom_path.to_owned(), + dataset_dir: dataset_dir.to_owned(), + profile, + macro_mode, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + let mut session = LegacySession::start(root.path(), config) + .await + .unwrap_or_else(|e| panic!("the session starts: {e}")); + if inputs.driver { + session.task.set_driver(Box::new(RotationDriver::new())); + } + session + .bootstrap() + .await + .unwrap_or_else(|e| panic!("Ready(0): {e}")); + if let Start::Checkpoint(bytes) = start { + session + .import_flysim01(bytes, &id("e2")) + .await + .unwrap_or_else(|e| panic!("the FLYSIM01 import: {e}")); + } + let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly")); + assert!( + admission.reward(1.0).is_err(), + "the operator reward pulse is refused" + ); + let mut behaviours = Vec::new(); + let mut ledgers = Vec::new(); + let mut bounds = Vec::new(); + for k in 1..=frames { + for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) { + admission.replay_sugar(*duration); + } + let step = session + .step() + .await + .unwrap_or_else(|e| panic!("{} frame {k}: {e}", mode.label())); + let details = step.details.expect("details are recorded"); + let [record] = step.records.as_slice() else { + panic!("frame {k}: {} task records", step.records.len()); + }; + behaviours.push( + trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"] + .clone(), + ); + ledgers.push(record.ledgers.clone()); + bounds.push(record.bound.clone()); + } + let ended = session.coordinator.admissions().take_ended(); + assert_eq!( + ended.len(), + inputs.sugar.iter().filter(|(k, _)| *k <= frames).count(), + "every admission ended" + ); + assert!( + ended + .iter() + .all(|(_, end)| matches!(end, fly_session::coordinator::AdmissionEnd::Applied { .. })), + "and every one was applied" + ); + let uncaptured = session.task.uncaptured_reads(); + assert!( + uncaptured.is_empty(), + "the engine read addresses the image does not capture: {:04x?}", + uncaptured + ); + session.stop().await; + Run { + behaviours, + ledgers, + bounds, + } +} + +fn report(what: &str, agreement: &Agreement, elapsed: std::time::Duration) { + eprintln!( + "{what} ({elapsed:?}): {} transitions identical ({} sugar, {} rewards {:?}, \ + {} macro events, {} pressed, {} slot saves, {} rollbacks, {} spikes)", + agreement.transitions, + agreement.sugar, + agreement.rewards, + agreement.reward_kinds, + agreement.macro_events, + agreement.pressed, + agreement.saves, + agreement.rollbacks, + agreement.spikes + ); +} + +fn compare_ledgers(legacy: &[String], session: &[String]) { + assert_eq!(legacy.len(), session.len()); + for (k, (a, b)) in legacy.iter().zip(session).enumerate() { + assert_eq!(a, b, "the ledgers after frame {}", k + 1); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_raw_from_power_on() { + let Some(rom_path) = rom_path() else { return }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(legacy_parity::toy::dir()).expect("the toy")); + let frames = env_usize("FLY_TASK01_TOY_FRAMES", 600); + let inputs = Inputs { + sugar: vec![(40, 300.0), (frames / 2, 500.0)], + driver: false, + }; + let dir = tempfile::tempdir().expect("tmp"); + let legacy = run_legacy( + &rom, + &data, + &Start::PowerOn, + MacroMode::Raw, + frames, + &inputs, + &dir.path().join("trace.jsonl"), + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &legacy_parity::toy::dir(), + LegacyProfileKind::Toy, + MacroMode::Raw, + &Start::PowerOn, + frames, + &inputs, + ) + .await; + let agreement = trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + assert_eq!(agreement.sugar, 2); + report( + &format!("toy raw, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } +} + +/// The checkpoints of the service's own traces (the FND-01 review's `rollback` -- a ratchet +/// rollback on the first boundary, a real `talk` reward -- `climb` -- a ratchet slot save -- and +/// `r58` -- a real `talk` reward -- with their start checkpoints). +/// +/// Those traces were recorded by the service as it stood on 2026-09-23. The macro engine has +/// changed since (loop-review rows 59 to 67), so from some frame on they are not what today's +/// engine does. The reference is therefore FND-01's harness at this tree -- `LegacyFrame` with +/// `FLY_TRACE` on, which FND-01 proved byte-identical to the service's loop -- run here from the +/// same checkpoint for the trace's length; the session must match it frame by frame, ledgers +/// included. How far the recorded service trace agrees with today's legacy loop is reported, not +/// asserted. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_service_trace_checkpoints() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + let Some(dir) = std::env::var_os("FLY_ENV01_TRACE_DIR").map(PathBuf::from) else { + eprintln!("skipping: FLY_ENV01_TRACE_DIR is not set"); + return; + }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let limit = env_usize("FLY_TASK01_TRACE_LIMIT", usize::MAX); + let names: Vec = std::env::var("FLY_TASK01_TRACES") + .map(|v| v.split(',').map(str::to_owned).collect()) + .unwrap_or_else(|_| vec!["rollback".into(), "climb".into(), "r58".into()]); + for name in names { + let checkpoint = if name == "r58" { + std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from) + } else { + Some(dir.join(format!("{name}.checkpoint"))) + }; + let Some(checkpoint) = checkpoint.filter(|c| c.is_file()) else { + eprintln!("skipping {name}: no checkpoint"); + continue; + }; + let text = + std::fs::read_to_string(dir.join(format!("{name}.trace.jsonl"))).expect("the trace"); + let mut service = trace::behaviours(&text).expect("a FLY_TRACE"); + service.truncate(limit); + let frames = service.len(); + let bytes = std::fs::read(&checkpoint).expect("the checkpoint"); + let start = Start::Checkpoint(bytes); + let tmp = tempfile::tempdir().expect("tmp"); + let started = std::time::Instant::now(); + let legacy = run_legacy( + &rom, + &data, + &start, + MacroMode::Macros, + frames, + &Inputs::default(), + &tmp.path().join("trace.jsonl"), + ); + let agreed = legacy + .behaviours + .iter() + .zip(&service) + .take_while(|(today, recorded)| today == recorded) + .count(); + eprintln!( + "legacy loop {name}: {frames} frames in {:?}; the recorded service trace agrees with \ + today's loop for its first {agreed} transitions", + started.elapsed() + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &dataset, + LegacyProfileKind::Production, + MacroMode::Macros, + &start, + frames, + &Inputs::default(), + ) + .await; + let agreement = + trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + report( + &format!("service checkpoint {name}, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } +} + +/// Runs `frames` transitions of a booted session with the store attached, recording the +/// session's `FLY_TRACE` behaviours, ledgers and bound sets, and every save it took. +async fn run_booted( + session: &mut LegacySession, + frames: usize, +) -> (Run, Vec) { + let mut run = Run { + behaviours: Vec::new(), + ledgers: Vec::new(), + bounds: Vec::new(), + }; + let mut saves = Vec::new(); + for k in 1..=frames { + let (step, saved) = session + .advance() + .await + .unwrap_or_else(|e| panic!("frame {k}: {e}")); + saves.extend(saved); + let details = step.details.expect("details are recorded"); + let [record] = step.records.as_slice() else { + panic!("frame {k}: {} task records", step.records.len()); + }; + run.behaviours.push( + trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"] + .clone(), + ); + run.ledgers.push(record.ledgers.clone()); + run.bounds.push(record.bound.clone()); + } + (run, saves) +} + +/// The SHADOW-01 entry gate: the session runtime boots from a live FLYSIM01 store, runs, saves, +/// restarts and restores from its own save, and every segment matches the legacy loop's trace. +/// +/// The store holds one durable generation, a stream checkpoint (the FND-01 review's `rollback` +/// file when `FLY_ENV01_TRACE_DIR` is set: a ratchet rollback on the first boundary, so the +/// after-rollback durable save is exercised; else `FLY_DOOR_CHECKPOINT`). Process one boots from +/// it (the legacy candidate order and gate, `boot`), writes its startup durable save, runs +/// `FLY_TASK01_BOOT_FRAMES` transitions with the legacy boundary saves, and shuts down with a +/// durable save. Process two boots from the same store and so restores process one's shutdown +/// save -- a file the session runtime wrote -- and runs on. The legacy loop runs the first +/// segment from the original file and the second from process one's save, which is also the +/// proof that the legacy loop reads what the session runtime writes. In-process then process. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_boot_run_save_restore() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + // The live fly's checkpoints predate `pokered-unique8-v8` (row 68, v0.6.7), and a boot takes + // an older adapter's file only when the operator asks for its migration, as the v0.6.7 + // deploy does. Both runtimes read the same list, so the comparison is unchanged. + if std::env::var_os("FLY_ACCEPT_ADAPTERS").is_none() { + // SAFETY: set before any runtime or thread of this test reads the environment. + unsafe { + std::env::set_var( + "FLY_ACCEPT_ADAPTERS", + flybrain_gb::pokemon_red::MIGRATES_FROM.join(","), + ); + } + } + // The rollback file (a ratchet rollback on the first boundary), and the live fly's largest + // task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound + // (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`). + let sources: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_BOOT_SOURCES") { + Ok(list) => list + .split(',') + .filter_map(|item| { + item.split_once('=') + .map(|(n, p)| (n.to_owned(), PathBuf::from(p))) + }) + .collect(), + Err(_) => [ + ( + "rollback", + std::env::var_os("FLY_ENV01_TRACE_DIR") + .map(|dir| PathBuf::from(dir).join("rollback.checkpoint")), + ), + ( + "row64", + std::env::var_os("FLY_ROW64_CHECKPOINT").map(PathBuf::from), + ), + ( + "row65-yard", + std::env::var_os("FLY_ROW65_YARD_CHECKPOINT").map(PathBuf::from), + ), + ] + .into_iter() + .filter_map(|(name, path)| path.filter(|p| p.is_file()).map(|p| (name.to_owned(), p))) + .collect(), + }; + if sources.is_empty() { + eprintln!("skipping: no source checkpoint"); + return; + } + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900); + for (name, source) in sources { + let original = std::fs::read(&source).expect("the checkpoint"); + let decoded = flysim::store::decode(&original).expect("FLYSIM01"); + let generation = decoded.runtime.generation; + eprintln!( + "boot source {name}: generation {generation}, task ledger {} bytes of adapter JSON", + serde_json::to_vec(&decoded.runtime.reward) + .map(|v| v.len()) + .unwrap_or(0) + ); + for mode in modes() { + let root = tempfile::tempdir().expect("tmp"); + let store = fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 4, + // The intervals are wall clock; a parity run takes its saves at the boundaries the + // legacy loop names (startup, a climb, a rollback, shutdown) and not on a timer. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + flysim::store::Store::new(&store.durable_dir, store.keep_generations) + .commit(generation, &original, None) + .expect("the seeded store"); + let config = |mode| LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + + // Process one. + let started = std::time::Instant::now(); + let (mut one, boot) = fly_legacy_session::composition::boot( + &root.path().join("p1"), + config(mode), + &store, + ) + .await + .unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label())); + match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(generation), + "the seeded generation" + ); + } + other => panic!("boot one: {other:?}"), + } + let startup = one.checkpointer().expect("attached").next_generation() - 1; + assert!( + startup > generation, + "the startup save takes a generation above the store's" + ); + let (run_one, saves_one) = run_booted(&mut one, frames).await; + let shutdown = one + .shutdown_save() + .await + .expect("the shutdown save") + .expect("a store"); + one.stop().await; + assert!(shutdown.durable); + let legacy_one = run_legacy( + &rom, + &data, + &Start::Checkpoint(original.clone()), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-one.jsonl"), + ); + let agreement = + trace::compare(&legacy_one.behaviours, &run_one.behaviours, &run_one.bounds) + .unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label())); + compare_ledgers(&legacy_one.ledgers, &run_one.ledgers); + report( + &format!("boot {name} segment one, {}", mode.label()), + &agreement, + started.elapsed(), + ); + eprintln!( + " saves: startup g{startup}, during the run {:?}, shutdown g{}", + saves_one + .iter() + .map(|s| (s.generation, s.durable, s.archive_rank)) + .collect::>(), + shutdown.generation + ); + if agreement.rollbacks > 0 { + assert!( + saves_one.iter().any(|s| s.durable), + "a rollback is followed by a durable save" + ); + } + + // Process two: restores process one's shutdown save. + let started = std::time::Instant::now(); + let (mut two, boot) = fly_legacy_session::composition::boot( + &root.path().join("p2"), + config(mode), + &store, + ) + .await + .unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label())); + let restored_path = match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(shutdown.generation), + "the latest save" + ); + candidate.path.clone() + } + other => panic!("boot two: {other:?}"), + }; + let written = std::fs::read(&restored_path).expect("the session's own save"); + let (run_two, _) = run_booted(&mut two, frames).await; + two.stop().await; + let legacy_two = run_legacy( + &rom, + &data, + &Start::Checkpoint(written), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-two.jsonl"), + ); + let agreement = + trace::compare(&legacy_two.behaviours, &run_two.behaviours, &run_two.bounds) + .unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label())); + compare_ledgers(&legacy_two.ledgers, &run_two.ledgers); + report( + &format!("boot {name} segment two, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } +} + +/// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited +/// (an `AREA` payout on the first sample), its exits unfound (`boundary`), its ground unwalked +/// (`exploration`), and no wild win is a replay (`battle`). +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"] = serde_json::json!({}); + reward["replayBlocked"] = serde_json::json!([]); + flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes") +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_reward_segments() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let segments: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_SEGMENTS") { + Ok(list) => list + .split(',') + .filter_map(|item| { + item.split_once('=') + .map(|(n, p)| (n.to_owned(), PathBuf::from(p))) + }) + .collect(), + Err(_) => [ + "FLY_DOOR_CHECKPOINT", + "FLY_CATCH_CHECKPOINT", + "FLY_ENGAGE_CHECKPOINT", + // The live fly's largest task ledgers (42 and 46 KB, TASK-01 review B1). + "FLY_ROW64_CHECKPOINT", + "FLY_ROW65_YARD_CHECKPOINT", + ] + .iter() + .filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p)))) + .collect(), + }; + let frames = env_usize("FLY_TASK01_FRAMES", 1200); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let arms: Vec = std::env::var("FLY_TASK01_ARMS") + .map(|v| v.split(',').map(str::to_owned).collect()) + .unwrap_or_else(|_| vec!["brain".into(), "driver".into()]); + for (segment, path) in segments { + for arm in &arms { + let name = format!("{segment} {arm}"); + let original = std::fs::read(&path).expect("the checkpoint"); + let bytes = if arm == "brain" { + reward_bearing(&original) + } else { + original + }; + let inputs = Inputs { + sugar: vec![(10, 400.0), (frames / 2, 250.0)], + driver: arm == "driver", + }; + let dir = tempfile::tempdir().expect("tmp"); + let started = std::time::Instant::now(); + let start = Start::Checkpoint(bytes); + let legacy = run_legacy( + &rom, + &data, + &start, + MacroMode::Macros, + frames, + &inputs, + &dir.path().join("trace.jsonl"), + ); + eprintln!( + "legacy loop {name}: {frames} frames in {:?}", + started.elapsed() + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &dataset, + LegacyProfileKind::Production, + MacroMode::Macros, + &start, + frames, + &inputs, + ) + .await; + let agreement = + trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + report( + &format!("segment {name}, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/shadow.rs b/services/flysim/crates/fly-legacy-session/tests/shadow.rs new file mode 100644 index 0000000..7378a15 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/shadow.rs @@ -0,0 +1,561 @@ +//! SHADOW-01 end to end, on the committed toy connectome in raw mode (an explicit ROM job: +//! `FLY_ROM`, and the workspace's `flysim` binary beside this test's). +//! +//! The *real* `flysim` service runs with the shadow's trace switches (`FLY_TRACE_DIR`, +//! `FLY_TRACE_LEDGERS=1`, a hot save every second), takes sugar through its control API and is +//! restarted once; the shadow (`fly_legacy_session::shadow::run`) follows it from its first frame. +//! Every transition, ledger digest and live save must agree, across both processes. +//! +//! Then the negative controls, on copies of the same trace and spool: a work-RAM digest flipped, +//! a sugar removed, a ledger digest flipped and a live save's bytes changed must each stop a +//! fresh shadow with a `diverged` verdict naming the right kind, field and step. +//! +//! The FAFB rehearsal of the same pipeline, at stream scale, is `tools/shadow-rehearsal.sh`. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +use fly_legacy_session::shadow::{self, Ended, ShadowConfig, StopFlag, verdict::Status}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use flysim::snapshot::MacroMode; + +/// The `flysim` binary built from *this* tree, in this test's own target directory and profile. +/// +/// `cargo test -p fly-legacy-session` does not build `flysim`'s binary, so a binary found beside the +/// test can be stale -- built from another tree that shared the target directory -- and a stale +/// flysim that predates `FLY_TRACE_DIR` writes no trace at all (the "one trace file per process" +/// failure, 0 files, seen on a build box whose target directory other trees shared). So the test +/// builds it: `cargo build -p flysim --bin flysim` with the same target directory, profile and +/// flags, a no-op when it is current. `None` (skip) only when cargo is not reachable. +fn flysim_binary() -> Option { + let exe = std::env::current_exe().ok()?; + let profile_dir = exe.parent()?.parent()?; // //deps/ + let target = profile_dir.parent()?; + let release = profile_dir.file_name()? == "release"; + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + let mut build = Command::new(cargo); + build + .args(["build", "-p", "flysim", "--bin", "flysim"]) + .env("CARGO_TARGET_DIR", target) + .current_dir(env!("CARGO_MANIFEST_DIR")); + if release { + build.arg("--release"); + } + match build.status() { + Ok(status) => assert!( + status.success(), + "building the flysim binary under test failed" + ), + Err(e) => { + eprintln!("skipping: cargo is not reachable to build flysim ({e})"); + return None; + } + } + let path = profile_dir.join("flysim"); + assert!( + path.is_file(), + "no flysim binary at {} after the build", + path.display() + ); + Some(path) +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .expect("an ephemeral port") + .local_addr() + .expect("its address") + .port() +} + +fn http(port: u16, method: &str, path: &str, body: Option<&str>) -> Option<(u16, String)> { + let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?; + let body = body.unwrap_or(""); + write!( + stream, + "{method} {path} HTTP/1.0\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .ok()?; + let mut text = String::new(); + stream.read_to_string(&mut text).ok()?; + let status = text.split_whitespace().nth(1)?.parse().ok()?; + let body = text + .split_once("\r\n\r\n") + .map_or("", |(_, b)| b) + .to_owned(); + Some((status, body)) +} + +struct Live { + child: Child, + control: u16, +} + +struct LiveDirs { + hot: PathBuf, + durable: PathBuf, + trace: PathBuf, +} + +fn start_live(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path) -> Live { + start_live_traced(binary, rom, dirs, log, true) +} + +/// `traced = false` starts the service with no `FLY_TRACE_DIR`: a live process that leaves no +/// trace, as one whose trace cannot be created would. +fn start_live_traced(binary: &Path, rom: &Path, dirs: &LiveDirs, log: &Path, traced: bool) -> Live { + let trace_dir = if traced { + dirs.trace.clone() + } else { + PathBuf::new() + }; + let control = free_port(); + let child = Command::new(binary) + .env("FLY_ROM", rom) + .env("FLY_DATASET", legacy_parity::toy::dir()) + .env("FLY_STATE", &dirs.durable) + .env("FLY_STATE_HOT", &dirs.hot) + .env("FLY_FEED_BIND", format!("127.0.0.1:{}", free_port())) + .env("FLY_CONTROL_BIND", format!("127.0.0.1:{control}")) + .env("FLY_METRICS_ADDR", format!("127.0.0.1:{}", free_port())) + .env("FLY_MACRO_MODE", "raw") + .env("FLY_CHAT_ENABLED", "false") + .env("FLYSIM_LOOP_GAME", "pokemon-red") + .env("FLYSIM_LOOP_SPEED", "0") + .env("FLYSIM_LOOP_HOT_SECONDS", "1") + .env("FLYSIM_LOOP_CHECKPOINT_SECONDS", "4") + .env("RAYON_NUM_THREADS", "1") + .env("FLY_TRACE_DIR", &trace_dir) + .env("FLY_TRACE_LEDGERS", "1") + .env_remove("FLY_TRACE") + .env_remove("NOTIFY_SOCKET") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(std::fs::File::create(log).expect("a log")) + .spawn() + .expect("flysim starts"); + let live = Live { child, control }; + let deadline = Instant::now() + Duration::from_secs(240); + while live.brain_ms().is_none() { + assert!(Instant::now() < deadline, "flysim never ran"); + std::thread::sleep(Duration::from_millis(200)); + } + live +} + +impl Live { + fn brain_ms(&self) -> Option { + let (status, body) = http(self.control, "GET", "/status", None)?; + let v: Value = serde_json::from_str(&body).ok()?; + (status == 200 && v["status"] == "running").then(|| v["brainMs"].as_f64())? + } + + fn sugar(&self, ms: u32) { + let body = format!(r#"{{"durationMs":{ms},"by":"shadow-test","source":"operator"}}"#); + let (status, text) = + http(self.control, "POST", "/stimulate", Some(&body)).expect("the control API"); + assert!( + (200..300).contains(&status), + "sugar refused: {status} {text}" + ); + } + + fn run_for(&self, brain_ms: f64) { + let start = self.brain_ms().expect("running"); + while self.brain_ms().unwrap_or(start) < start + brain_ms { + std::thread::sleep(Duration::from_millis(100)); + } + } + + fn stop(mut self) { + let _ = Command::new("kill") + .args(["-TERM", &self.child.id().to_string()]) + .status(); + let _ = self.child.wait(); + } +} + +fn config( + rom: &Path, + root: &Path, + trace: &Path, + sources: (&Path, &Path), + spool: &Path, +) -> ShadowConfig { + ShadowConfig { + trace_dir: trace.to_owned(), + hot_dir: sources.0.to_owned(), + durable_dir: sources.1.to_owned(), + out_dir: root.join("out"), + spool_dir: spool.to_owned(), + work_dir: root.join("work"), + rom_path: rom.to_owned(), + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + speed: 0.0, + mode: ExecutionMode::InProcess, + agent_threads: 1, + required_brain_seconds: 30.0, + all_files: true, + keep_traces: true, + keep_spool: true, + exit_on_pass: false, + max_transitions: None, + spool_max_bytes: 1 << 30, + context_lines: 5, + poll: Duration::from_millis(20), + lag_guard: None, + binary_sha256: "test".to_owned(), + binaries: Default::default(), + release: String::new(), + } +} + +fn transitions(trace: &Path) -> Vec<(PathBuf, usize)> { + shadow::follow::trace_files(trace) + .unwrap() + .into_iter() + .map(|path| { + let n = std::fs::read_to_string(&path) + .unwrap() + .lines() + .filter(|l| l.contains("\"behaviour\"")) + .count(); + (path, n) + }) + .collect() +} + +fn verdict_of(out: &Path) -> Value { + std::fs::read_to_string(out.join("verdict.json")) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or(Value::Null) +} + +/// Copies `trace` into a new directory, applying `edit` to the first file's lines. +fn tampered(trace: &Path, to: &Path, edit: impl Fn(usize, &mut Value) -> bool) -> u64 { + std::fs::create_dir_all(to).unwrap(); + let mut step = None; + for (i, (path, _)) in transitions(trace).into_iter().enumerate() { + let text = std::fs::read_to_string(&path).unwrap(); + let mut out = String::new(); + let mut n = 0; + for line in text.lines() { + let mut v: Value = serde_json::from_str(line).unwrap(); + if i == 0 && v.get("behaviour").is_some() { + if step.is_none() && edit(n, &mut v) { + step = v["behaviour"]["step"].as_str().and_then(|s| s.parse().ok()); + } + n += 1; + } + out.push_str(&v.to_string()); + out.push('\n'); + } + std::fs::write(to.join(path.file_name().unwrap()), out).unwrap(); + } + step.expect("the edit applied") +} + +/// The shadow on a thread of its own with its own runtime (the session's future is not `Send`). +fn spawn_shadow( + config: ShadowConfig, + stop: StopFlag, +) -> std::thread::JoinHandle> { + std::thread::spawn(move || { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("a runtime") + .block_on(shadow::run(config, stop)) + }) +} + +fn diverges( + rom: &Path, + root: &Path, + trace: &Path, + spool: &Path, + empty: &Path, +) -> shadow::verdict::Verdict { + diverges_with(rom, root, trace, spool, empty, |_| {}) +} + +fn diverges_with( + rom: &Path, + root: &Path, + trace: &Path, + spool: &Path, + empty: &Path, + edit: impl FnOnce(&mut ShadowConfig), +) -> shadow::verdict::Verdict { + let _ = std::fs::remove_dir_all(root.join("out")); + let mut config = config(rom, root, trace, (empty, empty), spool); + edit(&mut config); + let stop = StopFlag::default(); + let handle = spawn_shadow(config, stop.clone()); + let deadline = Instant::now() + Duration::from_secs(600); + while !handle.is_finished() { + if Instant::now() > deadline { + stop.request(); + } + std::thread::sleep(Duration::from_millis(100)); + } + let (ended, verdict) = handle.join().unwrap().expect("the shadow ran"); + assert_eq!(ended, Ended::Diverged, "{:?}", verdict.reason); + verdict +} + +#[test] +fn the_shadow_follows_the_real_service_and_catches_every_planted_difference() { + let Some(rom) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return; + }; + let Some(binary) = flysim_binary() else { + eprintln!("skipping: no flysim binary beside this test (cargo test --workspace builds it)"); + return; + }; + // `FLY_SHADOW_TEST_DIR` keeps everything for a look afterwards. + let tmp = tempfile::tempdir().unwrap(); + let kept = std::env::var_os("FLY_SHADOW_TEST_DIR").map(PathBuf::from); + if let Some(dir) = &kept { + let _ = std::fs::remove_dir_all(dir); + std::fs::create_dir_all(dir).unwrap(); + } + let root_path = kept.unwrap_or_else(|| tmp.path().to_owned()); + let root = &root_path; + let dirs = LiveDirs { + hot: root.join("live/hot"), + durable: root.join("live/durable"), + trace: root.join("live/trace"), + }; + let spool = root.join("shadow/spool"); + let shadow_root = root.join("shadow"); + let config = config( + &rom, + &shadow_root, + &dirs.trace, + (&dirs.hot, &dirs.durable), + &spool, + ); + let out = config.out_dir.clone(); + let stop = StopFlag::default(); + let handle = spawn_shadow(config, stop.clone()); + // The live recorder starts no trace without the shadow's heartbeat. + let heartbeat = dirs.trace.join(flysim::trace::CONSUMER_FILE); + let deadline = Instant::now() + Duration::from_secs(60); + while !heartbeat.is_file() { + assert!(Instant::now() < deadline, "the shadow wrote no heartbeat"); + std::thread::sleep(Duration::from_millis(50)); + } + + // Process one: a fresh fly (the stores are empty), two sugars, 25 brain seconds. + let live = start_live(&binary, &rom, &dirs, &root.join("flysim-1.log")); + live.sugar(300); + live.run_for(8_000.0); + live.sugar(700); + live.run_for(17_000.0); + live.stop(); + // Process two: restores its own latest save, a sugar, 15 brain seconds. + let live = start_live(&binary, &rom, &dirs, &root.join("flysim-2.log")); + live.run_for(5_000.0); + live.sugar(450); + live.run_for(10_000.0); + live.stop(); + + let files = transitions(&dirs.trace); + assert_eq!( + files.len(), + 2, + "one trace file per process; the shadow's verdict: {}; divergence: {}", + verdict_of(&out), + std::fs::read_to_string(out.join("divergence.json")).unwrap_or_default() + ); + let total: usize = files.iter().map(|(_, n)| n).sum(); + let deadline = Instant::now() + Duration::from_secs(600); + loop { + let v = verdict_of(&out); + if v["compared"]["transitions"].as_u64() == Some(total as u64) || handle.is_finished() { + break; + } + assert!( + Instant::now() < deadline, + "the shadow did not catch up: {v}" + ); + std::thread::sleep(Duration::from_millis(200)); + } + let passed = verdict_of(&out); + eprintln!( + "shadow after both processes: {}", + serde_json::to_string_pretty(&passed).unwrap() + ); + assert_eq!( + passed["status"], "pass", + "40 brain seconds against a 30 s window" + ); + assert!(passed["firstDivergence"].is_null()); + + // Process three runs untraced while the shadow follows: it can never be compared, so the + // shadow must fail its verdict (coverage), not keep a pass built on the traced processes. + let live = start_live_traced(&binary, &rom, &dirs, &root.join("flysim-3.log"), false); + live.run_for(3_000.0); + live.stop(); + let deadline = Instant::now() + Duration::from_secs(120); + while !handle.is_finished() { + if Instant::now() > deadline { + stop.request(); + } + std::thread::sleep(Duration::from_millis(200)); + } + let (ended, verdict) = handle.join().unwrap().expect("the shadow ran"); + assert_eq!( + ended, + Ended::Diverged, + "an untraced live process fails the verdict" + ); + let coverage = verdict.divergence.as_ref().expect("a divergence"); + assert_eq!(coverage.kind, "coverage", "{}", coverage.detail); + assert_eq!(verdict.status, Status::Diverged); + assert_eq!( + transitions(&dirs.trace).len(), + 2, + "process three left no trace" + ); + assert_eq!(verdict.agreement.transitions, total as u64); + assert_eq!(verdict.segments_compared, 2); + assert!(verdict.skipped.is_empty(), "{:?}", verdict.skipped); + assert_eq!(verdict.agreement.sugar, 3); + assert_eq!( + verdict.ledger_checks, total as u64, + "a ledger digest every boundary" + ); + // At least the fresh fly's startup save and both shutdown saves; the hot saves, one a wall + // second, add as many more as the box's speed gives. + assert!( + verdict.checkpoints.identical >= 3, + "live saves compared byte for byte: {:?}", + verdict.checkpoints + ); + + // The negative controls, each on a copy. + let empty = root.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + let neg = root.join("neg"); + + let at = tampered(&dirs.trace, &neg.join("wram/trace"), |n, v| { + (n == 700) + .then(|| v["behaviour"]["wramDigest"] = Value::String("0".repeat(64))) + .is_some() + }); + let got = diverges( + &rom, + &neg.join("wram"), + &neg.join("wram/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("transition", Some(at))); + assert_eq!(d.difference.unwrap().field, "wramDigest"); + assert!(!d.context.is_empty()); + assert_eq!(got.status, Status::Diverged); + + let at = tampered(&dirs.trace, &neg.join("ledgers/trace"), |n, v| { + (n == 900) + .then(|| v["behaviour"]["ledgersDigest"] = Value::String("0".repeat(64))) + .is_some() + }); + let got = diverges( + &rom, + &neg.join("ledgers"), + &neg.join("ledgers/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("ledgers", Some(at))); + + // A sugar the live loop applied, missing from the shadow's inputs: the brain differs from + // that transition on, and the comparison says where. + let at = tampered(&dirs.trace, &neg.join("sugar/trace"), |_, v| { + let had = v["behaviour"]["admissions"] + .as_array() + .is_some_and(|a| !a.is_empty()); + if had { + v["behaviour"]["admissions"] = Value::Array(Vec::new()); + // The admissions field itself would differ first; hold it to the tampered value. + } + had + }); + let got = diverges( + &rom, + &neg.join("sugar"), + &neg.join("sugar/trace"), + &spool, + &empty, + ); + let d = got.divergence.expect("a divergence"); + eprintln!( + "sugar removed at step {at}: diverged at {:?} on {:?}", + d.step, d.difference + ); + assert_eq!(d.kind, "transition"); + assert!(d.step.is_some_and(|s| s >= at)); + + // A live save whose bytes differ (its rankSinceMs moved by one ms). + let copy = neg.join("save/spool"); + std::fs::create_dir_all(©).unwrap(); + for entry in std::fs::read_dir(&spool).unwrap().flatten() { + std::fs::copy(entry.path(), copy.join(entry.file_name())).unwrap(); + } + let (first, _) = transitions(&dirs.trace).remove(0); + let text = std::fs::read_to_string(&first).unwrap(); + let (generation, at) = text + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter(|v| v.get("behaviour").is_some()) + .find_map(|v| { + let capture = v["operational"]["captures"].as_array()?.first()?.clone(); + let generation: u64 = capture["checkpointId"] + .as_str()? + .strip_prefix('g')? + .parse() + .ok()?; + let step: u64 = v["behaviour"]["step"].as_str()?.parse().ok()?; + Some((generation, step)) + }) + .expect("a live save during the run"); + let path = copy.join(format!("g{generation}.checkpoint")); + let mut checkpoint = flysim::store::load(&path).unwrap(); + checkpoint.runtime.rank_since_ms += 1.0; + std::fs::write( + &path, + flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).unwrap(), + ) + .unwrap(); + let got = diverges(&rom, &neg.join("save"), &dirs.trace, ©, &empty); + let d = got.divergence.expect("a divergence"); + assert_eq!((d.kind.as_str(), d.step), ("checkpoint", Some(at))); + assert!(d.detail.contains("rankSinceMs"), "{}", d.detail); + + // A session-side failure is a divergence, never a skip: a candidate whose restore gate + // refuses the live startup save (another dataset profile, so another compatibility string). + let got = diverges_with(&rom, &neg.join("gate"), &dirs.trace, &spool, &empty, |c| { + c.profile = LegacyProfileKind::Production; + }); + let d = got.divergence.expect("a divergence"); + assert_eq!(d.kind, "boot", "{}", d.detail); + assert!(d.detail.contains("restore gate"), "{}", d.detail); + assert!(got.skipped.is_empty()); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/speed.rs b/services/flysim/crates/fly-legacy-session/tests/speed.rs new file mode 100644 index 0000000..a90340b --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/speed.rs @@ -0,0 +1,265 @@ +//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, on the same +//! box, from the same checkpoint, in the service configuration (no trace, no step details). +//! +//! `FLY_TASK01_BENCH=1` (plus rom-env and `data/fafb-v783`): the legacy loop (`LegacyFrame`, the +//! service's frame, trace off) and the session (agent, world and task under the coordinator, +//! details off) each run `FLY_TASK01_BENCH_FRAMES` unpaced frames after a warm-up, with +//! `FLY_TASK01_BENCH_THREADS` sweep threads (the release container runs 3). Reported: ms per frame, +//! the realtime factor at 1x (one frame is 16.74 ms of game time), and the session's per-method +//! latencies from the coordinator's metrics. Then the session runs paced at 1x for the same +//! number of frames and reports the realtime factor it held. + +use std::sync::Arc; +use std::time::Instant; + +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +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_core::lif::SweepPlan; +use flybrain_gb::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::{LegacyFrame, Parts}; +use flysim::macros::macro_layer; +use flysim::snapshot::MacroMode; + +/// The legacy frame's phases, timed through the one hook the stream itself uses. +struct Phases { + last: Instant, + sums: std::collections::BTreeMap<&'static str, f64>, + on: bool, +} + +impl flysim::frame::FrameObserver for Phases { + fn after(&mut self, phase: flysim::frame::FramePhase, _agent: &mut NeuralAgent) { + let now = Instant::now(); + if self.on { + let name = match phase { + flysim::frame::FramePhase::Ticked => "legacy.ticks", + flysim::frame::FramePhase::Executed => "legacy.decode+execute", + flysim::frame::FramePhase::Emulated => "legacy.frame", + flysim::frame::FramePhase::Advanced => "legacy.take_frame", + flysim::frame::FramePhase::Committed => "legacy.evaluate+commit", + }; + *self.sums.entry(name).or_default() += (now - self.last).as_secs_f64() * 1000.0; + } + self.last = now; + } +} + +const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_against_legacy_per_frame() { + if std::env::var_os("FLY_TASK01_BENCH").is_none() { + eprintln!("skipping: FLY_TASK01_BENCH is not set"); + return; + } + let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( + std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), + legacy_parity::fafb_dir(), + std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from), + ) else { + eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing"); + return; + }; + let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1200); + let warmup = env_usize("FLY_TASK01_BENCH_WARMUP", 120); + let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3); + let rom = std::fs::read(&rom_path).unwrap(); + let bytes = std::fs::read(&checkpoint_path).unwrap(); + let checkpoint = flysim::store::decode(&bytes).unwrap(); + + // ---- The legacy loop: the service's frame, trace off. + let data = Arc::new(load_brain_dataset_from_dir(&dataset).unwrap()); + let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap(); + 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 = MacroMode::Macros; + let (channels, hold_ms) = channels_and_hold(MacroMode::Macros); + 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).unwrap(); + if threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap()); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + &checkpoint, + ) + .unwrap(); + 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 mut legacy_ms = 0.0; + let mut phases = Phases { + last: Instant::now(), + sums: Default::default(), + on: false, + }; + let mut boundary_ms = 0.0; + for n in 0..warmup + frames { + let started = Instant::now(); + phases.on = n >= warmup; + phases.last = started; + 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 phases).unwrap(); + let at = Instant::now(); + frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .unwrap(); + if n >= warmup { + boundary_ms += at.elapsed().as_secs_f64() * 1000.0; + } + if n >= warmup { + legacy_ms += started.elapsed().as_secs_f64() * 1000.0; + } + } + // What a legacy checkpoint costs the loop: the agent's export (the writer thread encodes). + let at = Instant::now(); + for _ in 0..10 { + std::hint::black_box(agent.export_state()); + } + let export_ms = at.elapsed().as_secs_f64() * 100.0; + drop(agent); + let legacy_per = legacy_ms / frames as f64; + for (name, sum) in &phases.sums { + eprintln!( + " legacy {name:<24} mean {:>8.0} us", + sum * 1000.0 / frames as f64 + ); + } + eprintln!( + " legacy boundary mean {:>8.0} us", + boundary_ms * 1000.0 / frames as f64 + ); + eprintln!( + " legacy agent.export_state mean {:>8.0} us (per checkpoint)", + export_ms * 1000.0 + ); + eprintln!( + "legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}", + (FRAME_MS / legacy_per).min(1.0) + ); + + // ---- The session, unpaced then paced, in each mode. + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + for paced in [false, true] { + let root = tempfile::tempdir().unwrap(); + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: threads.max(1), + record: false, + }, + ) + .await + .unwrap(); + session.bootstrap().await.unwrap(); + session.import_flysim01(&bytes, &id("e2")).await.unwrap(); + if !paced { + session.coordinator.disable_pacing(); + } + for _ in 0..warmup { + session.step().await.unwrap(); + } + session.coordinator.metrics.clear(); + let _ = fly_session::profile::report(); + let started = Instant::now(); + for _ in 0..frames { + session.step().await.unwrap(); + } + let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64; + if !paced { + // What a save costs the loop: the participants' State.Capture at the boundary. + let root = tempfile::tempdir().unwrap(); + session + .attach_store(&fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 2, + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }) + .unwrap(); + let at = Instant::now(); + for _ in 0..5 { + let ticket = session + .queue_save(fly_session::legacy_checkpoint::SaveKind::Hot) + .await + .unwrap(); + drop(ticket); + } + eprintln!( + " session save (capture on the loop) mean {:>8.0} us", + at.elapsed().as_secs_f64() * 1e6 / 5.0 + ); + } + let factor = FRAME_MS / per; + eprintln!( + "session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)", + mode.label(), + if paced { "paced at 1x" } else { "unpaced" }, + if paced { factor } else { factor.min(1.0) }, + per / legacy_per + ); + if !paced { + for (name, count, mean) in fly_session::profile::report() { + eprintln!( + " span {name:<22} mean {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6 + ); + } + for name in session.coordinator.metrics.names() { + let p = session.coordinator.metrics.percentiles(&name).unwrap(); + eprintln!( + " {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}", + p.p50_us(), + p.p95_us(), + session.coordinator.metrics.count(&name) + ); + } + } + session.stop().await; + } + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs new file mode 100644 index 0000000..db51760 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs @@ -0,0 +1,265 @@ +//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, measured +//! A/B-interleaved on one box so both see the same load: chunks of `FLY_TASK01_AB_CHUNK` frames +//! of the legacy loop (`LegacyFrame`, the service's frame, trace off) alternate with chunks of the +//! session (agent, world and task under the coordinator, service configuration: no details, +//! bounded history, snapshots at 30 Hz), both from the same checkpoint with the same sweep threads. +//! A shared box's load then shifts both arms alike, and the ratio is the comparison. +//! +//! `FLY_TASK01_BENCH=1` plus rom-env and `data/fafb-v783`. Reported per execution mode: mean +//! ms/frame of each arm, the ratio, the fps each sustains unpaced, and the headroom at 1x (one +//! Game Boy frame is 16.74 ms). + +use std::sync::Arc; +use std::time::Instant; + +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +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_core::lif::SweepPlan; +use flybrain_gb::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::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +struct Legacy { + emulator: Emulator, + adapter: PokemonRedReward, + ratchet: Ratchet, + agent: NeuralAgent, + frame: LegacyFrame, + macros: Option, +} + +impl Legacy { + fn new( + rom: &[u8], + dataset: &std::path::Path, + checkpoint: &flysim::store::Checkpoint, + threads: usize, + ) -> Legacy { + let data = Arc::new(load_brain_dataset_from_dir(dataset).unwrap()); + let mut emulator = + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap(); + 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 = MacroMode::Macros; + let (channels, hold_ms) = channels_and_hold(MacroMode::Macros); + 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(data, agent_config).unwrap(); + if threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap()); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .unwrap(); + 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); + } + Legacy { + emulator, + adapter, + ratchet, + agent, + frame, + macros, + } + } + + fn step(&mut self) { + let mut parts = Parts { + agent: &mut self.agent, + emulator: &mut self.emulator, + adapter: &mut self.adapter, + ratchet: &mut self.ratchet, + macros: self.macros.as_mut(), + }; + let transition = self.frame.transition(&mut parts, &mut ()).unwrap(); + self.frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .unwrap(); + } +} + +/// The service's runtime: two Tokio workers (SERVE-01's `flysim-session`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_against_legacy_interleaved() { + run(2).await; +} + +/// PERF-01: the same with one Tokio worker, the coordinator, the router and every in-process +/// participant on one thread beside the brain's sweep pool. `FLY_PERF_WORKERS` picks which of +/// the two runs (default 2). +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn session_against_legacy_interleaved_one_worker() { + run(1).await; +} + +async fn run(workers: usize) { + if std::env::var_os("FLY_TASK01_BENCH").is_none() { + eprintln!("skipping: FLY_TASK01_BENCH is not set"); + return; + } + if env_usize("FLY_PERF_WORKERS", 2) != workers { + return; + } + let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( + std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), + legacy_parity::fafb_dir(), + std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from), + ) else { + eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing"); + return; + }; + let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1800); + let chunk = env_usize("FLY_TASK01_AB_CHUNK", 60); + let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3); + let rom = std::fs::read(&rom_path).unwrap(); + let bytes = std::fs::read(&checkpoint_path).unwrap(); + let checkpoint = flysim::store::decode(&bytes).unwrap(); + // PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-process + // over the local lane, the default in-process path), `bus` (in-process over the bus, + // `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three. + let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned()); + // `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's + // `flysim-session`): the spike bitset of every commit and the audio chunk of every boundary. + let service = std::env::var_os("FLY_PERF_SERVICE").is_some(); + for arm in arms.split(',') { + let mode = match arm { + "local" | "bus" => ExecutionMode::InProcess, + "process" => ExecutionMode::Process, + other => panic!("unknown arm {other}"), + }; + // SAFETY: set before the session's runtime reads it; nothing else reads the variable. + unsafe { + std::env::set_var( + fly_legacy_session::composition::LOCAL_LANE_ENV, + if arm == "bus" { "0" } else { "1" }, + ); + } + let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads); + let root = tempfile::tempdir().unwrap(); + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: threads.max(1), + record: false, + }, + ) + .await + .unwrap(); + session.bootstrap().await.unwrap(); + session.import_flysim01(&bytes, &id("e2")).await.unwrap(); + session.coordinator.disable_pacing(); + if service { + session + .coordinator + .request_commit_attachments(&[fly_session::legacy_agent::SPIKES_ATTACHMENT]); + session.coordinator.digest_views(false); + } + let audio_name = + fly_session::media::audio_attachment(fly_session::legacy_env::AUDIO_STREAM_ID); + // Warm both. + for _ in 0..chunk { + legacy.step(); + session.step().await.unwrap(); + } + session.coordinator.metrics.clear(); + let _ = fly_session::profile::report(); + // The legacy brain's own phase clock, to set its ticks beside the session's + // `agent.ticks` span. + legacy.agent.network.profile = true; + legacy.agent.network.reset_timings(); + let (mut legacy_ms, mut session_ms) = (0.0, 0.0); + let mut done = 0; + while done < frames { + let at = Instant::now(); + for _ in 0..chunk { + legacy.step(); + } + legacy_ms += at.elapsed().as_secs_f64() * 1000.0; + let at = Instant::now(); + for _ in 0..chunk { + session.step().await.unwrap(); + if service { + let _ = session.coordinator.take_details(); + let _ = session.coordinator.media_bytes(&audio_name).await.unwrap(); + } + } + session_ms += at.elapsed().as_secs_f64() * 1000.0; + done += chunk; + } + let (l, s) = (legacy_ms / done as f64, session_ms / done as f64); + eprintln!( + "{} ({arm}{}, {workers} tokio workers): legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)", + mode.label(), + if service { ", service reads" } else { "" }, + 1000.0 / l, + 1000.0 / s, + s / l, + FRAME_MS - l, + FRAME_MS - s + ); + let timings = legacy.agent.network.timings(); + eprintln!( + " legacy ticks (phase clock) mean {:>8.0} us over {done} frames", + timings.total_ns() as f64 / done as f64 / 1000.0 + ); + for (name, count, mean, max) in fly_session::profile::report_with_max() { + eprintln!( + " span {name:<26} mean {:>8.0} us max {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6, + max.as_secs_f64() * 1e6 + ); + } + for name in session.coordinator.metrics.names() { + let p = session.coordinator.metrics.percentiles(&name).unwrap(); + eprintln!( + " {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}", + p.p50_us(), + p.p95_us(), + session.coordinator.metrics.count(&name) + ); + } + session.stop().await; + } +} diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 9d54739..84aa4b7 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -20,7 +20,7 @@ use crate::publish::PublicationOutcome; use crate::metrics::Metrics; use crate::phase::{Phase, PhaseMachine}; use crate::rpc::{self, DomainReply, Serials, WorkerRef}; -use crate::task::{ActionExecutor, Task}; +use crate::task::{ActionExecutor, Inspection, Task}; // `crate::types` is this crate's facade over the shared `fly-session-types` crate; the // glob keeps the contract's own names in sight instead of restating them. use crate::types::*; @@ -237,6 +237,11 @@ pub struct AgentSlot { pub worker_threads: u64, pub tick_duration: RationalNs, pub warmup_ticks: u64, + /// The numerical model and plasticity versions the profile runs, which are part of the + /// agent's compatibility identity. The synthetic fake model's by default; the legacy profile + /// runs `lif-1ms-f64-v2` and `fly-kc-mbon-rstdp-v2`. + pub model_version: String, + pub plasticity_version: String, pub committed_step: u64, /// The graph this fly attested to at `Agent.Initialize`, which is what the published /// descriptor says about it. `None` before initialization. @@ -271,6 +276,8 @@ impl AgentSlot { worker_threads: 1, tick_duration: RationalNs::ZERO, warmup_ticks: 0, + model_version: crate::agent::MODEL_VERSION.to_owned(), + plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), committed_step: 0, graph: None, telemetry: None, @@ -315,6 +322,10 @@ pub struct Coordinator { /// published and never attached to an agent's sensory input. audio: BTreeMap, pending_audio: BTreeMap, + /// Sealed copies of in-memory media being made for this boundary's publication, by the + /// in-memory artifact's id (PERF-01): begun as soon as `Environment.Advance` answers, so the + /// store round trips overlap the task's evaluation and the commits. + promoting: BTreeMap>>, /// One chunk sequence per declared audio stream, for this epoch. timelines: AudioTimelines, /// The attachment names this session's native media travels under. The composition @@ -339,6 +350,46 @@ pub struct Coordinator { /// The rollback policy the composition declares, if any (`legacy-ratchet-rollback-v1` is /// the only one defined). Without one, a task's rollback request is a task failure. rollback_policy: Option, + /// The documents `Environment.Initialize` names. The synthetic arena's by default; a + /// composition with its own backend (the legacy Game Boy) sets them. + backend_config: AssetRef, + task_config: AssetRef, + /// The decision schema every agent's profile registers. + decision_schema: SchemaRef, + /// The inspection attachments the task reads (`Task::inspection_attachments`), and the + /// holds on them: O[k]'s until transition k -> k+1 has been evaluated, O[k+1]'s from the + /// world's result until it becomes the committed boundary's. + inspection_names: Vec, + inspection_held: BTreeMap, + pending_inspection: BTreeMap, + /// O[k]'s inspection with its bytes, as the executor and the task read it. + current_inspection: Option, + /// The environment's advertised capabilities, from `Worker.Hello`. + environment_capabilities: Vec, + /// Agent reply attachments `Agent.Commit` is asked for (`telemetry.spikes`), kept in the + /// step details. None by default. + commit_attachments: Vec, + /// Record [`StepDetails`] for every transition (a parity run). + record_details: bool, + /// Digest every view into the step details (on with them by default; a service that reads + /// the details only for the commit attachments turns it off). + digest_views: bool, + last_details: Option, + /// Audience admissions: queued by the edge, cut into the next Prepare. + admissions: AdmissionQueue, + /// The admissions the transition in flight carries, until it commits or fails. + in_flight_admissions: Vec, + /// How many rollbacks this session has applied, which names the next rollback epoch. + rollbacks: u64, + /// The world's state format, when it is not the synthetic arena's. + state_format_id: Option, + /// Leave a requested rollback for the host to apply (`apply_pending_rollback`). + defer_rollbacks: bool, + pending_rollback: Option<(u64, EpisodeRequest)>, + /// [`Coordinator::bound_history`]. + history_limit: Option, + /// [`Coordinator::snapshot_every`]. + snapshot_every: u64, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -420,6 +471,7 @@ impl Coordinator { pending_views: BTreeMap::new(), audio: BTreeMap::new(), pending_audio: BTreeMap::new(), + promoting: BTreeMap::new(), timelines: AudioTimelines::default(), media_names: vec![ media::view_attachment(crate::environment::VIEW_ID), @@ -435,6 +487,32 @@ impl Coordinator { pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), episode: None, rollback_policy: None, + backend_config: crate::environment::synthetic_asset( + "counter-arena-backend", + "counter-arena-backend-v1", + ), + task_config: crate::environment::synthetic_asset( + "counter-arena-setup", + "counter-arena-setup-v1", + ), + decision_schema: crate::task::decision_schema(), + inspection_names: Vec::new(), + inspection_held: BTreeMap::new(), + pending_inspection: BTreeMap::new(), + current_inspection: None, + environment_capabilities: Vec::new(), + commit_attachments: Vec::new(), + record_details: false, + digest_views: true, + last_details: None, + admissions: AdmissionQueue::default(), + in_flight_admissions: Vec::new(), + rollbacks: 0, + state_format_id: None, + defer_rollbacks: false, + pending_rollback: None, + history_limit: None, + snapshot_every: 1, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -525,15 +603,86 @@ impl Coordinator { .collect() } + /// 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); + }; + artifact + .read_all() + .await + .map(Some) + .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() } /// Declares the composition's rollback policy (`workers-v1` section 4 and `step-v1` section 6, - /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. Until the rollback - /// sequence is wired (TASK-01), a declared rollback request pauses the session at its boundary - /// like a terminal one, which is safe; an undeclared one fails the epoch. + /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. With it declared, a + /// rollback request is applied at the boundary it was asked for (`apply_rollback`, TASK-01), + /// and every agent must advertise the policy at `Worker.Hello`; without it the request fails + /// the epoch. pub fn declare_rollback_policy(&mut self, policy: &str) -> Result<(), DomainError> { if policy != fly_session_types::extensions::ROLLBACK_POLICY { return Err(DomainError::invalid(format!("{policy} is not a defined rollback policy"))); @@ -542,6 +691,253 @@ impl Coordinator { Ok(()) } + /// The documents `Environment.Initialize` names: the backend configuration and the task + /// setup. A composition with its own backend sets them before [`Coordinator::bootstrap`]. + pub fn set_environment_config(&mut self, backend_config: AssetRef, task_config: AssetRef) { + self.backend_config = backend_config; + self.task_config = task_config; + } + + /// The view and audio stream ids this composition's world produces, which name the + /// attachments `Environment.Initialize` is asked for (afterwards they come from its + /// descriptor). The synthetic arena's by default. + pub fn set_media(&mut self, views: &[&str], audio_streams: &[&str]) { + self.media_names = views + .iter() + .map(|v| media::view_attachment(v)) + .chain(audio_streams.iter().map(|a| media::audio_attachment(a))) + .collect(); + } + + /// The state format the world's captures declare (`Compatibility.stateFormatId`): the + /// synthetic arena's by default, `fly-gb-env-v1` for the legacy Game Boy world (ENV-01). + pub fn set_state_format(&mut self, state_format_id: &str) { + self.state_format_id = Some(id(state_format_id)); + } + + /// Bounds the session's in-memory history -- the behaviour trace, the phase log, the audit + /// log and the latency samples -- to the newest `keep` entries each, for a session that runs + /// indefinitely (the live fly). Unbounded by default: a test reads all of it. + pub fn bound_history(&mut self, keep: usize) { + self.history_limit = Some(keep); + } + + /// Publishes the committed snapshot of every `n`-th boundary, and of every boundary with task + /// events or boundary actions. Presentation reads snapshots as latest values + /// (`publishing-v1`), and the legacy feed publishes at `snapshot_hz` (30 Hz) from its 60 Hz + /// loop, so a live composition need not pay a publication on every frame. 1 (every boundary) + /// by default. + pub fn snapshot_every(&mut self, n: u64) { + self.snapshot_every = n.max(1); + } + + fn trim_history(&mut self) { + let Some(keep) = self.history_limit else { return }; + fn trim(items: &mut Vec, keep: usize) { + if items.len() > 2 * keep { + items.drain(..items.len() - keep); + } + } + trim(&mut self.trace.transitions, keep); + trim(&mut self.trace.phases, keep); + trim(&mut self.audit, keep); + trim(&mut self.injection_log, keep); + self.metrics.truncate(keep); + } + + /// Leave a rollback the task asks for pending at its boundary, for the host to apply with + /// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts + /// while one is pending. + pub fn defer_rollbacks(&mut self, on: bool) { + self.defer_rollbacks = on; + } + + /// The boundary a deferred rollback waits at, if one does. + pub fn pending_rollback(&self) -> Option { + self.pending_rollback.as_ref().map(|(k, _)| *k) + } + + /// Applies a deferred rollback (the declared policy, `apply_rollback`), and adds it to the + /// last transition's trace and step details, where an immediate rollback would have been. + /// Returns whether one was pending. + pub async fn apply_pending_rollback(&mut self) -> Outcome { + let Some((boundary, request)) = self.pending_rollback.take() else { + return Ok(false); + }; + let (action, details) = self.apply_rollback(boundary, &request).await?; + if let Some(trace) = self.trace.transitions.last_mut() + && trace.behaviour.acknowledged_boundary == boundary + { + trace.behaviour.boundary_actions.push(action.clone()); + } + if let Some(step) = self.last_details.as_mut() + && step.step + 1 == boundary + { + step.boundary_actions.push(action); + step.rollback = Some(details); + } + Ok(true) + } + + /// One participant-coherent capture of the committed boundary for the legacy store + /// (STATE-02's `LegacyCheckpointer`): every participant's `State.Capture` payload under + /// `Capturing(k)`, released once read. The task's half is the host's to take from the task. + /// Taken after the boundary's slot save and before a pending rollback, as + /// `legacy-gameboy-v1` section 16 orders a milestone capture. + pub async fn capture_payloads( + &mut self, + checkpoint_id: &Id, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let pending = self.begin_capture(checkpoint_id).await?; + self.finish_capture(pending).await + } + + /// Sends every participant's `State.Capture` for the committed boundary and returns without + /// waiting for the replies: the capture off the loop (TASK-01 review N5). + /// + /// Each participant takes its state at the boundary when it handles the request, which it + /// does before any request sent after it (a worker takes its lock in arrival order), and a + /// participant that encodes off its lock (the legacy agent) answers the next Prepare while it + /// seals the payload. The session may step on; [`Coordinator::finish_capture`] collects the + /// payloads, in the order sent, whenever the host is ready for them. + pub async fn begin_capture(&mut self, checkpoint_id: &Id) -> Outcome { + let origin = self.phases.phase(); + let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary()) + else { + return Err(SessionFailure { + error: DomainError::before( + ErrorCode::InvalidPhase, + "a coherent capture is taken at a committed boundary only", + ), + phase: origin.label(), + detail: "capture".to_owned(), + participant: None, + }); + }; + self.transition(Phase::Capturing(boundary))?; + let mut participants = vec![self.environment.clone()]; + participants.extend(self.agents.iter().map(|slot| slot.worker.clone())); + let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json()); + let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; + let scope = self.scope(boundary); + let mut calls = Vec::new(); + for worker in participants { + let request_id = self.serials.next(&worker.service); + let sent = crate::rpc::send( + &self.bus, + &worker, + "State.Capture", + Some(scope.clone()), + params.clone(), + &[], + request_id, + &want, + ) + .await; + match sent { + Ok(sent) => calls.push((worker, sent)), + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + } + } + self.transition(origin)?; + Ok(PendingCapture { checkpoint_id: checkpoint_id.clone(), boundary, scope, calls }) + } + + /// Collects a capture begun with [`Coordinator::begin_capture`]: the world's payload and + /// every agent's, read and released. + pub async fn finish_capture( + &mut self, + pending: PendingCapture, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let PendingCapture { checkpoint_id, boundary, scope, calls } = pending; + let mut payloads = Vec::new(); + for (worker, sent) in calls { + let reply = match sent.finish().await { + Ok(reply) => reply, + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + }; + self.check_reply(&worker, &reply, &Some(scope.clone()), "State.Capture")?; + if let Err(e) = reply.result() { + return Err(self.fail_now(e, "capture")); + } + let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), + "capture", + )); + }; + let span = crate::profile::span("coord.capture.read"); + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") + })?; + drop(span); + self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; + payloads.push((worker.worker_id.clone(), bytes)); + } + let world = payloads.remove(0).1; + self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}")); + Ok((boundary, world, payloads)) + } + + /// The world's compatibility as this composition declares it. + fn world_compatibility(&self, descriptor: &EnvironmentDescriptor) -> crate::state::Compatibility { + let mut compatibility = crate::state::Compatibility::of(descriptor); + if let Some(format) = &self.state_format_id { + compatibility.state_format_id = format.clone(); + } + compatibility + } + + /// The decision schema the agents' profile registers (`gameboy-channels-v1` for the legacy + /// composition). A PreparedDecision carrying another is refused. + pub fn set_decision_schema(&mut self, schema: SchemaRef) { + self.decision_schema = schema; + } + + /// Ask every `Agent.Commit` for these reply attachments and keep their bytes in the step + /// details (the legacy agent's `telemetry.spikes`). Implies [`Coordinator::record_details`]. + pub fn request_commit_attachments(&mut self, names: &[&str]) { + self.commit_attachments = names.iter().map(|n| (*n).to_owned()).collect(); + self.record_details = true; + } + + /// Record [`StepDetails`] for every transition, for a parity run to read. + pub fn record_details(&mut self, on: bool) { + self.record_details = on; + } + + /// Whether recorded step details carry each view's SHA-256 (`StepDetails::view_digests`): + /// on by default; SERVE-01's service host reads the details for the commit attachments only + /// and turns it off, which saves hashing every frame. + pub fn digest_views(&mut self, on: bool) { + self.digest_views = on; + } + + /// The details of the last completed transition, when they are recorded. + pub fn take_details(&mut self) -> Option { + self.last_details.take() + } + + /// The admission queue: the edge's handle for audience and operator inputs. + pub fn admissions(&self) -> AdmissionQueue { + self.admissions.clone() + } + + /// O[k]'s inspection with its bytes, as the task last read it. + pub fn current_inspection(&self) -> Option<&Inspection> { + self.current_inspection.as_ref() + } + + pub fn episode_id(&self) -> &Id { + &self.episode_id + } + pub fn rollback_policy(&self) -> Option<&Id> { self.rollback_policy.as_ref() } @@ -639,6 +1035,13 @@ impl Coordinator { self.pending_views.clear(); self.audio.clear(); self.pending_audio.clear(); + self.inspection_held.clear(); + self.pending_inspection.clear(); + // An admission whose Prepare never committed is aborted, and the edge refunds it + // (`legacy-gameboy-v1` section 15). Queued ones stay queued for the restored epoch. + let aborted = std::mem::take(&mut self.in_flight_admissions); + self.admissions.end(aborted, AdmissionEnd::Aborted); + self.admissions.forget_remaining(); match &participant { Some(who) => self.audit.push(format!("fail:{detail}:{who}")), None => self.audit.push(format!("fail:{detail}")), @@ -717,7 +1120,12 @@ impl Coordinator { Ok(()) } - async fn hello(&mut self, worker: WorkerRef, role: Role, required: &str) -> Outcome { + async fn hello( + &mut self, + worker: WorkerRef, + role: Role, + required: &str, + ) -> Outcome<(Id, Vec)> { let params = HelloParams { session_id: self.session_id.clone(), expected_worker_id: worker.worker_id.clone(), @@ -757,19 +1165,33 @@ impl Coordinator { )); } self.audit.push(format!("hello:{}", worker.worker_id)); - Ok(result.incarnation_id) + Ok((result.incarnation_id, result.capabilities)) } async fn hello_environment(&mut self) -> Outcome<()> { let worker = self.environment.clone(); - let incarnation = self.hello(worker, Role::Environment, "world-step-v1").await?; + let (incarnation, capabilities) = + self.hello(worker, Role::Environment, "world-step-v1").await?; self.environment.domain_incarnation = Some(incarnation); + self.environment_capabilities = capabilities; Ok(()) } async fn hello_agent(&mut self, index: usize) -> Outcome<()> { let worker = self.agents[index].worker.clone(); - let incarnation = self.hello(worker, Role::Agent, "agent-step-v1").await?; + let (incarnation, capabilities) = self.hello(worker, Role::Agent, "agent-step-v1").await?; + if self.rollback_policy.is_some() + && !capabilities.iter().any(|c| c == fly_session_types::extensions::ROLLBACK_CAPABILITY) + { + return Err(self.fail_now( + DomainError::before( + ErrorCode::Unsupported, + "the composition declares a rollback policy and the agent does not answer \ + Agent.Rollback", + ), + "hello", + )); + } self.agents[index].worker.domain_incarnation = Some(incarnation); Ok(()) } @@ -791,20 +1213,15 @@ impl Coordinator { .map(|a| PortBinding { port_id: a.port_id.clone(), agent_id: a.agent_id.clone() }) .collect(); let params = EnvironmentInitializeParams { - backend_config: crate::environment::synthetic_asset( - "counter-arena-backend", - "counter-arena-backend-v1", - ), - task_config: crate::environment::synthetic_asset( - "counter-arena-setup", - "counter-arena-setup-v1", - ), + backend_config: self.backend_config.clone(), + task_config: self.task_config.clone(), episode_id: self.episode_id.clone(), port_bindings: bindings.iter().map(PortBinding::pair).collect(), }; let worker = self.environment.clone(); let scope = self.scope(0); - let want = self.media_names.clone(); + self.inspection_names = self.task.inspection_attachments(); + let want = self.wanted_media(); let reply = self .call( &worker, @@ -845,10 +1262,18 @@ impl Coordinator { "port-assignment", )); } - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); self.views = views; self.audio = audio; self.media_names = media::attachment_names(&result.descriptor); + let inspection = self + .read_inspection(0, &result.observation.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "observation-0"))?; + self.inspection_held = held; + self.current_inspection = Some(inspection); self.timelines = AudioTimelines::fresh(&result.descriptor); if let Err(e) = self.timelines.accept(&result.descriptor, &result.observation) { return Err(self.fail_now(e, "observation-0")); @@ -872,8 +1297,85 @@ impl Coordinator { Ok(()) } + /// SHA-256 of each sensory view's bytes as this session holds them, for the step details. + async fn view_digests( + &mut self, + observation: &WorldObservation, + ) -> Outcome> { + let mut out = Vec::new(); + for view in &observation.sensory_views { + let name = media::view_attachment(&view.view_id); + let Some(artifact) = self.views.get(&name).cloned() else { continue }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + Ok(out) + } + + /// The attachments a world reply is asked for: the declared media, then the inspection + /// attachments the task reads. + fn wanted_media(&self) -> Vec { + let mut want = self.media_names.clone(); + for name in &self.inspection_names { + if !want.contains(name) { + want.push(name.clone()); + } + } + want + } + + /// Takes the inspection attachments out of a world reply's artifacts, leaving the media. + fn take_inspection( + &self, + artifacts: &mut BTreeMap, + ) -> BTreeMap { + self.inspection_names + .iter() + .filter_map(|name| artifacts.remove(name).map(|a| (name.clone(), a))) + .collect() + } + + /// Reads one boundary's inspection attachments into the [`Inspection`] the task and the + /// executor read. Every declared attachment must be there: a boundary whose inspection + /// bytes are missing is refused, never replaced by an older one. + async fn read_inspection( + &self, + boundary: u64, + value: &TypedValue, + held: &BTreeMap, + ) -> DomainResult { + let mut attachments = BTreeMap::new(); + for name in &self.inspection_names { + let artifact = held.get(name).ok_or_else(|| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("boundary {boundary}'s inspection arrived without {name}"), + MutationCertainty::Unknown, + ) + })?; + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Unknown, + ) + })?; + attachments.insert(name.clone(), std::sync::Arc::new(bytes)); + } + Ok(Inspection { boundary, value: value.clone(), attachments }) + } + fn bootstrap_task(&mut self) -> Outcome<()> { - let observation = self.observation.clone().expect("initialized"); + let inspection = self.current_inspection.clone().expect("initialized"); let bindings: Vec = self .agents .iter() @@ -881,7 +1383,7 @@ impl Coordinator { .collect(); let bootstrap = self .task - .bootstrap(&observation.inspection, &bindings) + .bootstrap(&inspection, &bindings) .map_err(|e| self.fail_now(e, "task-bootstrap"))?; for event in &bootstrap.events { if event.source_step != 0 { @@ -1101,6 +1603,253 @@ pub struct StepReport { pub terminal: bool, } +/// One audience input the coordinator admits into a Prepare (`workers-v1` section 5 and its +/// amendment; `legacy-gameboy-v1` section 15). +/// +/// The rules that decide *whether* an input is admitted (a rate limiter, "no overlap with an +/// active pulse") are the composition's and run on the edge side of [`AdmissionQueue`], reading +/// [`AdmissionQueue::stimulus_remaining_ms`]: the last completed commit's value, one commit +/// stale at most. The coordinator only places what was admitted at the next admission cut, in +/// admission order, and reports each one applied or aborted. +#[derive(Clone, Debug, PartialEq)] +pub enum Admission { + /// A profile-supported stimulus in `Prepare.preStepStimulations` (sugar: `reward-pulse`). + Stimulus { agent_id: Id, interaction_id: Id, kind_id: Id, duration_ms: f64 }, +} + +impl Admission { + pub fn agent_id(&self) -> &Id { + match self { + Admission::Stimulus { agent_id, .. } => agent_id, + } + } + + pub fn interaction_id(&self) -> &Id { + match self { + Admission::Stimulus { interaction_id, .. } => interaction_id, + } + } +} + +/// How an admission ended: applied by a Prepare whose transition committed at `boundary`, or +/// aborted because the epoch failed first (the edge refunds it). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AdmissionEnd { + Applied { boundary: u64 }, + Aborted, +} + +#[derive(Debug, Default)] +struct AdmissionState { + queued: Vec, + /// Cut into a Prepare whose transition has not committed yet. + in_flight: Vec, + remaining: BTreeMap, + ended: Vec<(Admission, AdmissionEnd)>, +} + +impl AdmissionState { + fn set_remaining(&mut self, agent_id: &Id, remaining: Option) { + match remaining { + Some(ms) => { + self.remaining.insert(agent_id.clone(), ms); + } + None => { + self.remaining.remove(agent_id); + } + } + } +} + +/// The edge's handle on admission: queue what the composition's rules admitted, read the last +/// commit's stimulus pulse, collect the outcomes. Clone it freely; every clone is the same queue. +#[derive(Clone, Debug, Default)] +pub struct AdmissionQueue(std::sync::Arc>); + +impl AdmissionQueue { + fn lock(&self) -> std::sync::MutexGuard<'_, AdmissionState> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Queue an admitted input for the next admission cut. + pub fn admit(&self, admission: Admission) { + self.lock().queued.push(admission); + } + + /// `stimulusRemainingMs` of the agent's last completed commit (an `Agent.Rollback` reply + /// counts as one). `None` before the first commit of an epoch -- after a restore the pulse + /// is unknown and the legacy rule refuses with a retry (`legacy-gameboy-v1` section 15). + pub fn stimulus_remaining_ms(&self, agent_id: &Id) -> Option { + self.lock().remaining.get(agent_id).copied() + } + + /// Inputs admitted and not yet cut into a Prepare. + pub fn queued(&self) -> usize { + self.lock().queued.len() + } + + /// The longest stimulus admitted for the agent that no commit has reported on yet: queued + /// for the next cut, or cut into a Prepare still in flight. The legacy loop applies a sugar + /// the moment it admits it, so its pulse is active for the next request at once; here it + /// is active from admission too, which is what this reads. `None` when there is none. + pub fn pending_stimulus_ms(&self, agent_id: &Id) -> Option { + let state = self.lock(); + state + .queued + .iter() + .chain(state.in_flight.iter()) + .filter(|a| a.agent_id() == agent_id) + .map(|a| match a { + Admission::Stimulus { duration_ms, .. } => *duration_ms, + }) + .reduce(f64::max) + } + + /// Every admission that has ended since the last call, in the order they ended. + pub fn take_ended(&self) -> Vec<(Admission, AdmissionEnd)> { + std::mem::take(&mut self.lock().ended) + } + + fn cut(&self) -> Vec { + let mut state = self.lock(); + let cut = std::mem::take(&mut state.queued); + state.in_flight.extend(cut.iter().cloned()); + cut + } + + fn end(&self, admissions: Vec, end: AdmissionEnd) { + self.commit(admissions, end, &[]); + } + + /// Ends the admissions and records the commit's pulses under one lock. + fn commit(&self, admissions: Vec, end: AdmissionEnd, pulses: &[(Id, Option)]) { + let mut state = self.lock(); + for admission in admissions { + state + .in_flight + .retain(|a| a.interaction_id() != admission.interaction_id()); + state.ended.push((admission, end.clone())); + } + for (agent_id, remaining) in pulses { + state.set_remaining(agent_id, *remaining); + } + } + + /// Decides and queues one admission under the lock every commit takes: `decide` gets the + /// agent's last reported pulse and the longest pending one, and returns the admission to + /// queue (or a refusal). No commit can interleave between the reads and the push, which is + /// the single-threaded legacy loop's answer (TASK-01 review R2-3). + pub fn admit_with( + &self, + agent_id: &Id, + decide: impl FnOnce(Option, Option) -> Result, + ) -> Result { + let mut state = self.lock(); + let remaining = state.remaining.get(agent_id).copied(); + let pending = state + .queued + .iter() + .chain(state.in_flight.iter()) + .filter(|a| a.agent_id() == agent_id) + .map(|a| match a { + Admission::Stimulus { duration_ms, .. } => *duration_ms, + }) + .reduce(f64::max); + let admission = decide(remaining, pending)?; + state.queued.push(admission.clone()); + Ok(admission) + } + + fn set_remaining(&self, agent_id: &Id, remaining: Option) { + self.lock().set_remaining(agent_id, remaining); + } + + fn forget_remaining(&self) { + self.lock().remaining.clear(); + } +} + +/// Everything one transition exchanged, for a parity run (`Coordinator::record_details`): the +/// fields a legacy `FLY_TRACE` line is assembled from. +#[derive(Clone, Debug)] +pub struct StepDetails { + /// The boundary the transition started from. + pub step: u64, + /// O[k]'s `engineFrame`. + pub engine_frame: Option, + /// The admissions this transition's Prepare applied, in admission order. + pub admissions: Vec, + pub prepared: Vec<(Id, PreparedDecision)>, + pub controls: Vec, + pub commits: Vec<(Id, AgentCommitResult)>, + /// `(agent, attachment, bytes)` for each requested commit reply attachment. + pub commit_attachments: Vec<(Id, String, Vec)>, + /// SHA-256 of each O[k+1] view's bytes, by view id. + pub view_digests: Vec<(String, Digest)>, + pub evaluation: crate::task::Evaluation, + /// The boundary actions applied at `Ready(k+1)`, in order. + pub boundary_actions: Vec, + /// After a rollback: the new epoch, the restored observation and each agent's reply. + pub rollback: Option, +} + +/// What a rollback at a boundary produced. +#[derive(Clone, Debug)] +pub struct RollbackDetails { + pub epoch: Id, + pub observation: WorldObservation, + pub view_digests: Vec<(String, Digest)>, + pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>, +} + +/// A capture sent to every participant and not yet collected ([`Coordinator::begin_capture`]). +pub struct PendingCapture { + checkpoint_id: Id, + boundary: u64, + scope: Scope, + calls: Vec<(WorkerRef, crate::rpc::SentCall)>, +} + +impl PendingCapture { + /// The committed boundary the capture is of. + pub fn boundary(&self) -> u64 { + self.boundary + } +} + +/// A checkpoint of another format, assembled by an importer in each participant's own capture +/// format, to install as a session's start ([`Coordinator::import`]). +#[derive(Clone, Debug)] +pub struct ImportSpec { + pub checkpoint_id: Id, + /// The scope the payloads record as their source (for a FLYSIM01 file, + /// `legacy_checkpoint::legacy_source_scope`: the session, epoch `legacy`, the boundary). + pub source_scope: Scope, + /// The boundary the checkpoint is at. + pub boundary: u64, + /// The environment's `State.Capture` payload. + pub world_payload: Vec, + /// Every agent, in sorted agent-id order. + pub agents: Vec, + pub task_ledger: TypedValue, + /// The ledger's attachments (`Task::capture_attachments`), by name. + pub task_attachments: BTreeMap>, + /// Each declared audio stream's next sample. + pub audio_positions: BTreeMap, +} + +/// One agent of an [`ImportSpec`]. +#[derive(Clone, Debug)] +pub struct ImportedAgent { + pub agent_id: Id, + /// The agent's `State.Capture` payload. + pub payload: Vec, + pub brain_ticks: u64, + pub remainder: RationalNs, + /// The decision context the payload retains. + pub context: TypedValue, +} + /// One per-agent bus call, ready to dispatch. struct Job { agent_id: Id, @@ -1110,6 +1859,8 @@ struct Job { params: Map, attachments: Vec<(String, flybus::Artifact)>, request_id: DomainRequestId, + /// Reply attachments to extract. + want: Vec, } /// Issues one domain call with owned arguments, so it can run in its own task. @@ -1546,7 +2297,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1563,6 +2314,34 @@ impl Coordinator { }); } } + // One job has nothing to run beside it: it is called in place, not spawned. + DispatchOrder::Concurrent if jobs.len() == 1 => { + let job = jobs.into_iter().next().expect("one job"); + let started = Instant::now(); + let outcome = call_owned( + self.bus.clone(), + job.worker.clone(), + job.method, + job.scope.clone(), + job.params.clone(), + job.attachments.clone(), + job.request_id.clone(), + job.want.clone(), + deadline, + ) + .await; + out.push(JobResult { + agent_id: job.agent_id, + outcome, + scope: job.scope, + worker: job.worker, + method: job.method, + request_id: job.request_id, + params: job.params, + attachments: job.attachments, + elapsed: started.elapsed(), + }); + } DispatchOrder::Concurrent => { let mut tasks = Vec::new(); for job in jobs { @@ -1581,7 +2360,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1642,6 +2421,16 @@ impl Coordinator { "step", )); }; + if let Some((boundary, _)) = &self.pending_rollback { + let boundary = *boundary; + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + format!("the rollback asked for at boundary {boundary} has not been applied"), + ), + "step", + )); + } if self.episode.is_some() { return Err(self.fail_now( DomainError::before( @@ -1670,26 +2459,42 @@ impl Coordinator { // ---- Phase A: prepare all agents concurrently self.transition(Phase::Preparing(k))?; + let span = crate::profile::span("coord.prepare"); let prepared = self.prepare_all(k, descriptor.step_duration).await?; + drop(span); // ---- Phase B: build and apply one complete batch self.transition(Phase::Applying(k))?; + let span = crate::profile::span("coord.executor"); let controls = self.build_batch(k, &descriptor, &old_observation)?; + drop(span); let batch_id = self.batch_id(k); + let span = crate::profile::span("coord.advance"); let step_result = self.advance(k, &batch_id, &controls).await?; + drop(span); + if self.snapshot_every <= 1 || (k + 1).is_multiple_of(self.snapshot_every) { + self.begin_promotions(); + } + let span = crate::profile::span("coord.observe"); // ---- Phase C: observe and evaluate the task once self.transition(Phase::Observing(k + 1))?; self.verify_step_result(k, &descriptor, &batch_id, &controls, &old_observation, &step_result)?; let scope = self.scope(k); + let pending_inspection = std::mem::take(&mut self.pending_inspection); + let new_inspection = self + .read_inspection(k + 1, &step_result.observation.inspection, &pending_inspection) + .await + .map_err(|e| self.fail_now(e, "step-result"))?; + let old_inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); + drop(span); + let span = crate::profile::span("coord.evaluate"); let evaluation = self .task - .evaluate_transition( - &scope, - &old_observation.inspection, - &step_result.observation.inspection, - &controls, - ) + .evaluate_transition(&scope, &old_inspection, &new_inspection, &controls) .map_err(|e| { // Task interpretation failed after prepared brains and the world already // changed, so the epoch is failed rather than re-evaluated. @@ -1726,8 +2531,10 @@ impl Coordinator { } } + drop(span); // ---- Phase D: commit all agent outcomes concurrently self.transition(Phase::Committing(k))?; + let commit_span = crate::profile::span("coord.commit"); let new_views: BTreeMap = step_result .observation .sensory_views @@ -1746,10 +2553,12 @@ impl Coordinator { self.pending_audio.get(&name).map(|a| (name, a.clone())) }) .collect(); - let commits = self + let (commits, commit_attachments) = self .commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views) .await?; + drop(commit_span); + let span = crate::profile::span("coord.boundary"); // Only once every commit succeeded does the committed boundary move. self.transition(Phase::Ready(k + 1))?; for index in 0..self.agents.len() { @@ -1786,9 +2595,54 @@ impl Coordinator { self.audio = new_audio; self.pending_views.clear(); self.pending_audio.clear(); + // O[k] has been evaluated, so its inspection is released; O[k+1]'s is the boundary's. + self.inspection_held = pending_inspection; + self.current_inspection = Some(new_inspection); self.observation = Some(step_result.observation.clone()); self.stats.advances += 1; + // The admissions this transition carried are applied: its Prepare committed. + let applied = std::mem::take(&mut self.in_flight_admissions); + // One lock for the end of the in-flight admissions and the new pulse: an edge thread + // never sees the admission gone and the old pulse still standing (TASK-01 review R2-3). + let pulses: Vec<(Id, Option)> = commits + .iter() + .map(|(agent_id, result)| (agent_id.clone(), result.telemetry.stimulus_remaining_ms)) + .collect(); + self.admissions + .commit(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }, &pulses); + let view_digests = if self.record_details && self.digest_views { + self.view_digests(&step_result.observation).await? + } else { + Vec::new() + }; + + // ---- Ready(k+1): the boundary actions the transition asked for, saves first + // (`step-v1` section 6 amendment). + let mut boundary_actions = Vec::new(); + for slot_id in &evaluation.slot_saves { + let action = self.save_slot(k + 1, slot_id).await?; + boundary_actions.push(action); + } + let mut rollback_details = None; + if let Some(request) = &evaluation.episode + && request.kind == EpisodeRequestKind::Rollback + { + let request = request.clone(); + if self.defer_rollbacks { + // The host takes its captures at this boundary first (a milestone archive is + // captured after the slot save and before the rollback, legacy-gameboy-v1 + // section 16), then applies it: `apply_pending_rollback`. + self.pending_rollback = Some((k + 1, request)); + } else { + let (action, details) = self.apply_rollback(k + 1, &request).await?; + boundary_actions.push(action); + rollback_details = Some(details); + } + } + + drop(span); + let span = crate::profile::span("coord.trace_publish"); let event_ids: Vec = evaluation.events.iter().map(|e| e.id.clone()).collect(); let decisions: BTreeMap = prepared .iter() @@ -1803,17 +2657,51 @@ impl Coordinator { &step_result, &outcomes, &event_ids, + &boundary_actions, ); + if self.record_details { + self.last_details = Some(StepDetails { + step: k, + engine_frame: old_observation.engine_frame.clone(), + admissions: applied, + prepared: prepared.clone(), + controls: controls.clone(), + commits: commits.clone(), + commit_attachments, + view_digests, + evaluation: evaluation.clone(), + boundary_actions: boundary_actions.clone(), + rollback: rollback_details, + }); + } // The prepared decisions and their request ids are needed by the trace, so they are // released only after it has been recorded. for slot in &mut self.agents { slot.prepared = None; slot.prepare_request = None; } + let publish_span = crate::profile::span("coord.publish"); + let publishing = Instant::now(); self.publish_events(k + 1, &evaluation.events).await?; - self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).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 + // `snapshot_hz`, 30 Hz, from a 60 Hz loop). + if self.snapshot_every <= 1 + || (k + 1).is_multiple_of(self.snapshot_every) + || !evaluation.events.is_empty() + || !boundary_actions.is_empty() + { + self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + } + drop(publish_span); + self.metrics.record("publish", publishing.elapsed()); - let terminal = evaluation.episode.is_some(); + // A rollback request was applied above and is not an episode end; only a terminal one + // pauses the session for the episode policy. + let terminal = evaluation + .episode + .as_ref() + .is_some_and(|request| request.kind == EpisodeRequestKind::Terminal); if terminal { // A terminal event's final rewards are committed; then the session pauses at this // boundary and the declared episode policy runs. No worker resets itself. @@ -1825,8 +2713,10 @@ impl Coordinator { self.pause.store(false, std::sync::atomic::Ordering::SeqCst); self.audit.push(format!("pause:{}", k + 1)); } + drop(span); // The critical path: one whole transition, pacing sleep included. self.metrics.record("step", step_started.elapsed()); + self.trim_history(); Ok(StepReport { boundary: k + 1, paused, terminal }) } @@ -1844,6 +2734,41 @@ impl Coordinator { Ok(reports) } + /// Starts sealing a bus copy of every in-memory medium the boundary just produced, for its + /// publication ([`Coordinator::publication_handle`]). + fn begin_promotions(&mut self) { + for (_, stale) in std::mem::take(&mut self.promoting) { + stale.abort(); + } + for artifact in self.pending_views.values().chain(self.pending_audio.values()) { + if artifact.is_in_memory() { + let (bus, artifact) = (self.bus.clone(), artifact.clone()); + let id = artifact.reference().artifact_id.clone(); + self.promoting.insert( + id, + tokio::spawn(async move { crate::rpc::promote(&bus, &artifact).await }), + ); + } + } + } + + /// The handle a publication attaches for `artifact`: the handle itself when it is sealed in + /// the router's store, else the sealed copy begun at the Advance, or one made now. + async fn publication_handle( + &mut self, + artifact: &flybus::Artifact, + ) -> DomainResult { + if !artifact.is_in_memory() { + return Ok(artifact.clone()); + } + match self.promoting.remove(&artifact.reference().artifact_id) { + Some(task) => task.await.map_err(|e| { + DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) + })?, + None => crate::rpc::promote(&self.bus, artifact).await, + } + } + fn batch_id(&self, k: u64) -> Id { parse_id(&format!("batch-{}-{k}", self.epoch)).expect("epoch and step make an Id") } @@ -1857,17 +2782,44 @@ impl Coordinator { let scope = self.scope(k); // The task's per-agent decision contexts and the admitted pre-step stimulation list // are frozen here; anything accepted later waits for the next boundary. + let cut = self.admissions.cut(); + let mut admitted = Vec::new(); + for admission in cut { + if self.agent(admission.agent_id()).is_some() { + admitted.push(admission); + } else { + // An input for no configured agent is never applied; the edge refunds it. + self.admissions.end(vec![admission], AdmissionEnd::Aborted); + } + } + self.in_flight_admissions = admitted.clone(); let mut jobs = Vec::new(); let mut bodies = Vec::new(); for index in 0..self.agents.len() { let slot = &self.agents[index]; + let pre_step_stimulations: Vec = admitted + .iter() + .filter_map(|a| match a { + Admission::Stimulus { agent_id, interaction_id, kind_id, duration_ms } + if *agent_id == slot.agent_id => + { + Some(Stimulus { + id: interaction_id.clone(), + kind_id: kind_id.clone(), + duration_ms: *duration_ms, + }) + } + Admission::Stimulus { .. } => None, + }) + .collect(); let params = PrepareParams { agent_id: slot.agent_id.clone(), profile_digest: slot.profile.digest.clone(), interval, decision_context_digest: slot.context_digest.clone(), - // No audience input exists in the first synthetic composition. - pre_step_stimulations: Vec::::new(), + // What the admission cut admitted for this agent, in admission order. The + // synthetic composition has no audience input, so its list is empty. + pre_step_stimulations, }; let params = match params.to_json() { Value::Object(m) => m, @@ -1890,6 +2842,7 @@ impl Coordinator { params, attachments: Vec::new(), request_id, + want: Vec::new(), }); } let results = self.run_jobs(jobs, self.dispatch).await; @@ -1934,7 +2887,7 @@ impl Coordinator { method, )); } - if decision.decision.schema != crate::task::decision_schema() { + if decision.decision.schema != self.decision_schema { return Err(self.fail_now( DomainError::before( ErrorCode::IdentityMismatch, @@ -2009,7 +2962,11 @@ impl Coordinator { ) -> Outcome> { let scope = self.scope(k); let progress = self.task.progress(); - let clock = observation.world_time; + let _ = observation; + let inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); let mut intents: BTreeMap = BTreeMap::new(); // Sorted agent-id order, never completion order. for index in 0..self.agents.len() { @@ -2019,6 +2976,18 @@ impl Coordinator { .prepared .clone() .expect("every agent is Prepared before the batch is built"); + // `step-v1` section 3, Phase B amendment: the clock is the agent's brain time after + // its Prepare -- its executed ticks at its tick duration, exactly. + let tick = self.agents[index].tick_duration; + let clock = RationalNs::reduced( + u128::from(tick.numerator) * u128::from(decision.brain_ticks), + u128::from(tick.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let clock = match clock { + Ok(clock) => clock, + Err(e) => return Err(self.fail_now(e, "executor")), + }; let executor = self.executors.get_mut(&agent_id).ok_or_else(|| { DomainError::before( ErrorCode::IdentityMismatch, @@ -2032,7 +3001,7 @@ impl Coordinator { let applied = executor.apply( &scope, &decision.decision, - &observation.inspection, + &inspection, &progress, &clock, ); @@ -2090,6 +3059,7 @@ impl Coordinator { controls: &[PortControl], ) -> Outcome { let scope = self.scope(k); + let build_span = crate::profile::span("coord.advance.build"); let params = AdvanceParams { batch_id: batch_id.clone(), controls: controls.to_vec(), @@ -2098,10 +3068,11 @@ impl Coordinator { Value::Object(m) => m, _ => Map::new(), }; + drop(build_span); let worker = self.environment.clone(); let request_id = self.serials.next(&worker.service); self.last_advance_request = Some(request_id.clone()); - let want = self.media_names.clone(); + let want = self.wanted_media(); self.audit.push(format!("advance:{k}")); self.blame(Some(worker.worker_id.clone())); let advance_deadline = self.deadlines.probe; @@ -2218,12 +3189,16 @@ impl Coordinator { } }; + let parse_span = crate::profile::span("coord.advance.parse"); let result: StepResult = match reply.parse() { Ok(result) => result, Err(e) => return Err(self.fail_now(e, "advance")), }; + drop(parse_span); self.blame(None); - let (pending_views, pending_audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + self.pending_inspection = self.take_inspection(&mut artifacts); + let (pending_views, pending_audio) = media::split_attachments(artifacts); self.pending_views = pending_views; self.pending_audio = pending_audio; @@ -2289,6 +3264,326 @@ impl Coordinator { } } +// ------------------------------------------------------------------------------------------- +// Boundary actions: slot saves and the declared rollback (`step-v1` section 6 amendment) + +/// The epoch a rollback moves to: the session's epoch root, then `.rb`, or a digest-named +/// id when that would pass the `Id` length bound. Deterministic, so two runs of the same +/// session name the same epochs. +fn rollback_epoch(current: &Id, n: u64) -> Id { + let root = match current.rfind(".rb") { + Some(at) if current[at + 3..].chars().all(|c| c.is_ascii_digit()) && at > 0 => { + ¤t[..at] + } + _ => current.as_str(), + }; + let named = format!("{root}.rb{n}"); + match parse_id(&named) { + Ok(epoch) => epoch, + Err(_) => { + let digest = digest_of_bytes(named.as_bytes()); + id(&format!("rb{n}-{}", &digest[..16])) + } + } +} + +impl Coordinator { + fn require_slots(&mut self, what: &str) -> Outcome<()> { + if self + .environment_capabilities + .iter() + .any(|c| c == fly_session_types::extensions::SLOTS_CAPABILITY) + { + return Ok(()); + } + Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + format!("the task asked for {what} and the world does not advertise gameboy-slots-v1"), + MutationCertainty::Applied, + ), + "boundary", + )) + } + + /// `Environment.SaveSlot` at the committed boundary `k`, under the current epoch. + async fn save_slot( + &mut self, + k: u64, + slot_id: &Id, + ) -> Outcome { + self.require_slots("a slot save")?; + let scope = self.scope(k); + let params = fly_session_types::extensions::SaveSlotParams { slot_id: slot_id.clone() }; + let worker = self.environment.clone(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_SAVE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &[], + ) + .await?; + let result: fly_session_types::extensions::SaveSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "save-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "save-slot")); + } + if result.slot_id != *slot_id { + return Err(self.fail_now( + DomainError::before(ErrorCode::IdentityMismatch, "the world saved another slot"), + "save-slot", + )); + } + self.audit.push(format!("save-slot:{slot_id}@{k}")); + Ok(fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::SaveSlot, + slot_id: slot_id.clone(), + state_digest: Some(result.state_digest), + }) + } + + /// The declared rollback policy at `Ready(e, k)` (`step-v1` section 6 amendment, steps 2 to + /// 5; `legacy-gameboy-v1` section 11): a new epoch, `Environment.RestoreSlot`, the task's + /// coordinator-local part, `Agent.Rollback` on every agent, then `Ready(e', k)`. Any failure + /// fails the epoch; nothing continues in `e` once one participant is in `e'`. + async fn apply_rollback( + &mut self, + k: u64, + request: &EpisodeRequest, + ) -> Outcome<(fly_session_types::trace::BoundaryAction, RollbackDetails)> { + let Some(policy) = self.rollback_policy.clone() else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + "the task asked for a rollback and this composition declares no rollback policy", + MutationCertainty::Applied, + ), + "rollback", + )); + }; + self.require_slots("a rollback")?; + let slot_id = match fly_session_types::gameboy::RollbackRequest::from_typed(&request.outcome) + { + Ok(outcome) => outcome.slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e.0), "rollback")), + }; + let slot_id = match parse_id(&slot_id) { + Ok(slot_id) => slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e), "rollback")), + }; + self.transition(Phase::RollingBack(k))?; + let prior = self.epoch.clone(); + self.rollbacks += 1; + let epoch = rollback_epoch(&prior, self.rollbacks); + let scope = scope_at(&self.session_id, &epoch, k); + + // Step 2: the world restores the slot at the same boundary under the new epoch. + let params = fly_session_types::extensions::RestoreSlotParams { + slot_id: slot_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + }; + let worker = self.environment.clone(); + let want = self.wanted_media(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_RESTORE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &want, + ) + .await?; + let result: fly_session_types::extensions::RestoreSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "restore-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "restore-slot")); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let restored = result.observation; + let world_time = self.observation.as_ref().map(|o| o.world_time); + if restored.boundary != k || Some(restored.world_time) != world_time { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "a restored slot is not at the boundary and world time it was restored at", + ), + "restore-slot", + )); + } + if let Err(e) = restored.validate_against(&descriptor) { + return Err(self.fail_now( + DomainError::new(ErrorCode::BufferInvalid, e, MutationCertainty::Applied), + "restore-slot", + )); + } + if let Err(e) = media::check_required_views(&descriptor, &restored).and_then(|()| { + media::check_required_audio(&descriptor, &restored, media::ObservationOrigin::Installed) + }) { + return Err(self.fail_now(e, "restore-slot")); + } + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); + if !audio.is_empty() { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + "a restored slot carried an audio chunk; no interval was played", + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + match views.get(&name) { + Some(artifact) if artifact.reference() == &view.pixels => {} + _ => { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("the restored view {} arrived without a live owned handle", view.view_id), + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + } + } + let inspection = self + .read_inspection(k, &restored.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "restore-slot"))?; + self.audit.push(format!("restore-slot:{slot_id}@{k}:{epoch}")); + + // Step 3, coordinator-local: the task clears its transient observations, the executor + // cancels and observes the restored boundary, which gives the next contexts. + let evaluation = self + .task + .rollback(&scope, &inspection) + .map_err(|e| self.fail_now(e, "task-rollback"))?; + for agent_id in self.agent_ids() { + if !evaluation.next_contexts.contains_key(&agent_id) { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + format!("the task's rollback produced no context for {agent_id}"), + ), + "task-rollback", + )); + } + } + + // Step 4: every agent, with the restored view and its context. No tick. + let attachments: Vec<(String, flybus::Artifact)> = + views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); + let mut replies = Vec::new(); + for index in 0..self.agents.len() { + let agent_id = self.agents[index].agent_id.clone(); + let context = evaluation.next_contexts[&agent_id].clone(); + let params = fly_session_types::extensions::AgentRollbackParams { + agent_id: agent_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + input: self.sensory_input(&restored, k), + decision_context: context.clone(), + }; + let worker = self.agents[index].worker.clone(); + let refs: Vec<(&str, &flybus::Artifact)> = + attachments.iter().map(|(n, a)| (n.as_str(), a)).collect(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_AGENT_ROLLBACK, + Some(scope.clone()), + object(params.to_json()), + &refs, + &[], + ) + .await?; + let result: fly_session_types::extensions::AgentRollbackResult = + reply.parse().map_err(|e| self.fail_now(e, "agent-rollback"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "agent-rollback")); + } + if result.agent_id != agent_id || result.decision_context_digest != context.digest() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an agent rolled back with another identity or context", + ), + "agent-rollback", + )); + } + self.audit.push(format!("agent-rollback:{agent_id}@{k}:{epoch}")); + replies.push((agent_id, context, result)); + } + + // Step 5: every reply in hand. The session is at Ready(e', k). + let view_digests = if self.record_details && self.digest_views { + let mut out = Vec::new(); + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + if let Some(artifact) = views.get(&name) { + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + } + out + } else { + Vec::new() + }; + self.epoch = epoch.clone(); + let positions = self.timelines.positions(); + self.timelines = match AudioTimelines::restored(&descriptor, &positions) { + Ok(timelines) => timelines, + Err(e) => return Err(self.fail_now(e, "rollback")), + }; + self.views = views; + self.audio.clear(); + self.inspection_held = held; + self.current_inspection = Some(inspection); + self.observation = Some(restored.clone()); + let mut agents = Vec::new(); + for (agent_id, context, result) in replies { + let slot = self + .agents + .iter_mut() + .find(|slot| slot.agent_id == agent_id) + .expect("configured"); + slot.context_digest = context.digest(); + slot.context = context; + slot.telemetry = Some(result.telemetry.clone()); + self.admissions.set_remaining(&agent_id, result.telemetry.stimulus_remaining_ms); + agents.push((agent_id, result)); + } + self.transition(Phase::Ready(k))?; + self.audit.push(format!("rolled-back:{slot_id}@{k}:{epoch}")); + Ok(( + fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::Rollback, + slot_id: slot_id.clone(), + state_digest: None, + }, + RollbackDetails { epoch, observation: restored, view_digests, agents }, + )) + } +} + impl Coordinator { /// Phase C's verification: batch identity, boundary, cadence, schema and required views. #[allow(clippy::too_many_arguments)] @@ -2429,7 +3724,8 @@ impl Coordinator { outcomes: &mut BTreeMap, next_contexts: &mut BTreeMap, views: &BTreeMap, - ) -> Outcome> { + ) -> Outcome<(Vec<(Id, AgentCommitResult)>, Vec<(Id, String, Vec)>)> { + let mut extracted: Vec<(Id, String, Vec)> = Vec::new(); let scope = self.scope(k); let attachments: Vec<(String, flybus::Artifact)> = views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); @@ -2481,6 +3777,7 @@ impl Coordinator { params, attachments: attachments.clone(), request_id, + want: self.commit_attachments.clone(), }); } self.last_commit_requests = bodies @@ -2519,7 +3816,7 @@ impl Coordinator { params, job_attachments, request_id, - &[], + &self.commit_attachments.clone(), ) .await { @@ -2569,6 +3866,29 @@ impl Coordinator { if let Err(e) = result.telemetry.validate() { return Err(self.fail_now(DomainError::invalid(e), method)); } + for name in self.commit_attachments.clone() { + let Some(artifact) = reply.artifacts.get(&name) else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("Agent.Commit carried no {name}"), + MutationCertainty::Applied, + ), + method, + )); + }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + method, + ) + })?; + extracted.push((agent_id.clone(), name, bytes)); + } self.audit.push(format!("committed:{agent_id}@{k}")); self.stats.commits += 1; self.blame(None); @@ -2625,7 +3945,7 @@ impl Coordinator { } } commits.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(commits) + Ok((commits, extracted)) } /// Records the `step-v1` section 8 trace for this transition. @@ -2645,6 +3965,7 @@ impl Coordinator { result: &StepResult, outcomes: &BTreeMap, event_ids: &[Id], + boundary_actions: &[fly_session_types::trace::BoundaryAction], ) { let mut agents = Vec::new(); let mut outcome_ids = Vec::new(); @@ -2695,8 +4016,9 @@ impl Coordinator { outcome_ids, event_ids: event_ids.to_vec(), published_boundary: k + 1, - // The synthetic composition takes no boundary actions (step-v1 section 8 amendment). - boundary_actions: Vec::new(), + // Saves first, each slot once, at most one rollback, last (step-v1 section 8 + // amendment). The synthetic composition takes none. + boundary_actions: boundary_actions.to_vec(), }; let operational = TraceOperational { // Wall time is for pacing, health and presentation only. @@ -2996,6 +4318,33 @@ impl Coordinator { } } } + // In-memory media (the local lane) cross the router as sealed copies: the snapshot names + // the copies it attaches (the PERF-01 amendment). + let mut snapshot = snapshot; + for (_, artifact) in attachments.iter_mut() { + if !artifact.is_in_memory() { + continue; + } + let copy = match self.publication_handle(artifact).await { + Ok(copy) => copy, + Err(e) => return Err(self.fail_now(e, "publish")), + }; + let (old, new) = (artifact.reference().clone(), copy.reference().clone()); + for view in &mut snapshot.views { + if view.pixels == old { + view.pixels = new.clone(); + } + } + for chunk in &mut snapshot.audio { + if chunk.samples == old { + chunk.samples = new.clone(); + } + } + *artifact = copy; + } + for (_, unused) in std::mem::take(&mut self.promoting) { + unused.abort(); + } if self.injections.substituted_published_handle && self.injections.at_step + 1 == boundary { // The same attachment name and the same bytes, a different object. Only the // artifact identity sees it, which is why the check compares that and not names. @@ -3125,7 +4474,7 @@ impl Coordinator { /// The live composition's compatibility identities. pub fn compatibility(&self) -> Outcome { match &self.descriptor { - Some(descriptor) => Ok(crate::state::Compatibility::of(descriptor)), + Some(descriptor) => Ok(self.world_compatibility(descriptor)), None => Err(SessionFailure { error: DomainError::before( ErrorCode::InvalidPhase, @@ -3160,8 +4509,8 @@ impl Coordinator { &slot.agent_id, &slot.profile.digest, &graph.dataset_digest, - crate::agent::MODEL_VERSION, - crate::agent::PLASTICITY_VERSION, + &slot.model_version, + &slot.plasticity_version, slot.seed, &graph.index_digest, )) @@ -3393,8 +4742,8 @@ impl Coordinator { profile_digest: slot.profile.digest.clone(), dataset_digest: graph.dataset_digest, index_digest: graph.index_digest, - model_version: crate::agent::MODEL_VERSION.to_owned(), - plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), seed: slot.seed, brain_ticks: slot.brain_ticks, remainder: slot.remainder, @@ -3409,6 +4758,22 @@ impl Coordinator { self.seal_own(crate::state::TASK_LEDGER_PAYLOAD, &ledger.to_json()) .await?, ); + let attachments = + self.task.capture_attachments().map_err(|e| self.fail_now(e, "capture"))?; + for (name, bytes) in attachments { + let name = crate::state::task_attachment_payload(&name); + let digest = digest_of_bytes(&bytes); + let artifact = match crate::state::seal_payload(&self.bus, &bytes, &digest).await { + Ok(artifact) => artifact, + Err(e) => return Err(self.fail_now(e, "capture")), + }; + payloads.push(crate::state::CapturedPayload { + name, + byte_length: bytes.len() as u64, + digest, + artifact, + }); + } let inspection = self .observation .as_ref() @@ -3693,8 +5058,13 @@ impl Coordinator { /// A replacement is the only way a fenced participant comes back: `step-v1` section 7's /// incarnation row says every live participant of a failed epoch belongs to an invalid /// one, so the reference is exchanged deliberately here and never repaired in place. + /// + /// A session that bootstrapped and has taken no transition may also replace a participant: + /// that is how a checkpoint of another format is installed as its start + /// ([`Coordinator::import`]) into a world that stages only on a fresh replacement. pub fn replace_participant(&mut self, worker_id: &Id, worker: WorkerRef) -> Outcome<()> { - if !self.fenced { + let unstarted = self.phases.phase() == Phase::Ready(0) && self.stats.advances == 0; + if !self.fenced && !unstarted { return Err(self.fail_now( DomainError::before( ErrorCode::InvalidPhase, @@ -3813,13 +5183,214 @@ impl Coordinator { } let boundary = manifest.source_scope.step; self.transition(Phase::Restoring(boundary))?; - let outcome = self.restore_group(&envelope, &manifest, new_epoch, boundary).await; + let outcome = self.restore_group(&envelope.payloads, &manifest, new_epoch, boundary).await; match outcome { Ok(report) => Ok(report), Err(e) => Err(e), } } + pub fn session_id(&self) -> &Id { + &self.session_id + } + + /// Installs a checkpoint of another format as this session's start (TASK-01: the legacy + /// composition's FLYSIM01 import). + /// + /// Only a session that bootstrapped and has taken no transition may import, and the install + /// is the ordinary group restore of `state-media-v1` section 6 -- stage every participant, + /// validate the coordinator's own state, activate, install, `Paused(k)` -- over payloads the + /// importer assembled in each participant's own capture format. The coordinator's own + /// payloads (executor state, prior inspection, the admission record) are written here, from + /// the live composition, exactly as a capture writes them. Nothing a participant stages is + /// trusted: each validates its payload as it would one of its own captures. + pub async fn import(&mut self, spec: ImportSpec, new_epoch: &Id) -> Outcome { + if self.fenced || self.phases.phase() != Phase::Ready(0) || self.stats.advances != 0 { + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + "a checkpoint is imported as the start of a session that has taken no transition", + ), + "import", + )); + } + if *new_epoch == self.epoch { + return Err(self.fail_now( + DomainError::before(ErrorCode::StaleEpoch, "an import installs a fresh epoch"), + "import", + )); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let boundary = spec.boundary; + if spec.source_scope.step != boundary || spec.source_scope.session_id != self.session_id { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an import's source scope is this session at the imported boundary", + ), + "import", + )); + } + let world_time = RationalNs::reduced( + u128::from(descriptor.step_duration.numerator) * u128::from(boundary), + u128::from(descriptor.step_duration.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let world_time = match world_time { + Ok(time) => time, + Err(e) => return Err(self.fail_now(e, "import")), + }; + let recorded: Vec = spec.agents.iter().map(|a| a.agent_id.clone()).collect(); + if recorded != self.agent_ids() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "the import's agents are not this composition's", + ), + "import", + )); + } + let compatibility = self.compatibility()?; + let canonical = |value: &Value| -> DomainResult> { + canonicalize(value) + .map(String::into_bytes) + .map_err(|e| DomainError::invalid(e.0)) + }; + let mut payloads: Vec<(String, Vec)> = Vec::new(); + payloads.push((crate::state::WORLD_PAYLOAD.to_owned(), spec.world_payload)); + let mut agent_rows = Vec::new(); + for imported in &spec.agents { + let slot = self.agent(&imported.agent_id).expect("checked"); + let Some(graph) = slot.graph.clone() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::InvalidPhase, "an agent attested no graph"), + "import", + )); + }; + let name = crate::state::agent_payload(&imported.agent_id); + agent_rows.push(crate::state::AgentEntry { + agent_id: imported.agent_id.clone(), + profile_digest: slot.profile.digest.clone(), + dataset_digest: graph.dataset_digest, + index_digest: graph.index_digest, + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), + seed: slot.seed, + brain_ticks: imported.brain_ticks, + remainder: imported.remainder, + payload: name.clone(), + }); + payloads.push((name, imported.payload.clone())); + } + let mut own = |name: &str, value: &Value| -> DomainResult<()> { + payloads.push((name.to_owned(), canonical(value)?)); + Ok(()) + }; + let mut executor_rows = Vec::new(); + let mut failure = None; + if let Err(e) = own(crate::state::TASK_LEDGER_PAYLOAD, &spec.task_ledger.to_json()) { + failure = Some(e); + } + let prior = self.observation.as_ref().map(|o| o.inspection.to_json()).expect("bootstrapped"); + if let Err(e) = own(crate::state::PRIOR_INSPECTION_PAYLOAD, &prior) { + failure = failure.or(Some(e)); + } + for agent_id in self.agent_ids() { + let name = crate::state::executor_payload(&agent_id); + match self.executors.get(&agent_id).map(|e| e.capture()) { + Some(Ok(state)) => { + if let Err(e) = own(&name, &state.to_json()) { + failure = failure.or(Some(e)); + } + } + Some(Err(e)) => failure = failure.or(Some(e)), + None => { + failure = failure.or(Some(DomainError::before( + ErrorCode::IdentityMismatch, + format!("{agent_id} has no configured action executor"), + ))) + } + } + executor_rows.push((agent_id, name)); + } + let record = json!({ + "payloadVersion": 1, + "kind": "coordinator", + "committedStep": boundary.to_string(), + "admission": {"audienceInput": "none-configured", "admitted": Value::Array(Vec::new())}, + "eventWatermarks": {"lastSourceStep": "0", "issued": "0"}, + "audioPositions": Value::Object( + spec.audio_positions + .iter() + .map(|(stream, sample)| (stream.clone(), Value::String(sample.to_string()))) + .collect(), + ), + "agents": Value::Array( + spec.agents + .iter() + .map(|imported| { + let slot = self.agent(&imported.agent_id).expect("checked"); + json!({ + "agentId": imported.agent_id.as_str(), + "portId": slot.port_id.as_str(), + "profile": slot.profile.to_json(), + "seed": slot.seed, + "workerThreads": slot.worker_threads.to_string(), + "committedStep": boundary.to_string(), + "brainTicks": imported.brain_ticks.to_string(), + "remainder": imported.remainder.to_json(), + "context": imported.context.to_json(), + }) + }) + .collect(), + ), + }); + if let Err(e) = own(crate::state::ADMISSION_PAYLOAD, &record) { + failure = failure.or(Some(e)); + } + for (name, bytes) in &spec.task_attachments { + payloads.push((crate::state::task_attachment_payload(name), bytes.clone())); + } + if let Some(e) = failure { + return Err(self.fail_now(e, "import")); + } + let manifest = crate::state::CheckpointManifest { + checkpoint_id: spec.checkpoint_id.clone(), + source_scope: spec.source_scope.clone(), + episode_id: self.episode_id.clone(), + world_time, + scheduler_id: "lockstep-v1".to_owned(), + composition_digest: self.composition_digest(), + port_map: self + .agents + .iter() + .map(|slot| (slot.port_id.clone(), slot.agent_id.clone())) + .collect(), + compatibility, + agents: agent_rows, + coordinator: crate::state::CoordinatorEntry { + task_ledger: crate::state::TASK_LEDGER_PAYLOAD.to_owned(), + prior_inspection: crate::state::PRIOR_INSPECTION_PAYLOAD.to_owned(), + executor_state: executor_rows, + admission_state: crate::state::ADMISSION_PAYLOAD.to_owned(), + event_watermarks: crate::state::EventWatermarks { last_source_step: 0, issued: 0 }, + }, + environment: crate::state::EnvironmentEntry { + worker_id: self.environment.worker_id.clone(), + payload: crate::state::WORLD_PAYLOAD.to_owned(), + }, + helper_state: Vec::new(), + payloads: payloads + .iter() + .map(|(name, bytes)| (name.clone(), bytes.len() as u64, digest_of_bytes(bytes))) + .collect(), + }; + self.transition(Phase::Restoring(boundary))?; + let report = self.restore_group(&payloads, &manifest, new_epoch, boundary).await?; + self.audit.push(format!("imported:{}@{boundary}", spec.checkpoint_id)); + Ok(report) + } + /// Marks every participant of an abandoned group install as one that must be replaced. /// /// A participant that staged holds a replacement state nothing installed; one that @@ -3866,7 +5437,7 @@ impl Coordinator { )); } let live = match &self.descriptor { - Some(descriptor) => crate::state::Compatibility::of(descriptor), + Some(descriptor) => self.world_compatibility(descriptor), None => { return Err(DomainError::before( ErrorCode::InvalidPhase, @@ -3921,7 +5492,7 @@ impl Coordinator { #[allow(clippy::too_many_lines)] async fn restore_group( &mut self, - envelope: &fly_session_types::checkpoint::Envelope, + envelope_payloads: &[(String, Vec)], manifest: &crate::state::CheckpointManifest, new_epoch: &Id, boundary: u64, @@ -3930,7 +5501,7 @@ impl Coordinator { // Step 3: import the payloads as *new* artifacts. Nothing the fence dropped is asked // to come back, and a router that restarted has none of the old roots anyway. let mut imported: BTreeMap = BTreeMap::new(); - for (name, bytes) in &envelope.payloads { + for (name, bytes) in envelope_payloads { let digest = digest_of_bytes(bytes); let artifact = match crate::state::seal_payload(&self.bus, bytes, &digest).await { Ok(artifact) => artifact, @@ -4043,8 +5614,7 @@ impl Coordinator { // coordinator** state validates". The coordinator's own staged ledgers are checked // here, before a single token is activated, so a checkpoint whose task ledger or // executor state is unreadable installs nothing anywhere. - let payloads: BTreeMap> = envelope - .payloads + let payloads: BTreeMap> = envelope_payloads .iter() .map(|(name, bytes)| (name.clone(), bytes.clone())) .collect(); @@ -4078,10 +5648,11 @@ impl Coordinator { let mut activated: Vec = Vec::new(); let mut restored_observation: Option<(WorldObservation, BTreeMap)> = None; + let mut restored_inspection: BTreeMap = BTreeMap::new(); for (who, worker, token) in &staged { let params = ActivateRestoreParams { restore_token: token.clone() }; let want = if *who == self.environment.worker_id { - self.media_names.clone() + self.wanted_media() } else { Vec::new() }; @@ -4129,7 +5700,9 @@ impl Coordinator { )); } if let Some(observation) = result.observation { - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + restored_inspection = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); if !audio.is_empty() { self.taint_group(&staged); return Err(self.fail_now( @@ -4172,6 +5745,69 @@ impl Coordinator { self.taint_group(&staged); return Err(self.fail_now(e, "restore")); } + // The restored boundary's inspection, and the task's own look at it: a task whose + // executor state is transient (`legacy-transient-reset`) re-observes the restored world + // here, and the contexts it derives must be the ones the checkpoint recorded -- the + // agents hold those, and a Prepare under another would be refused. + let restored_value = self + .observation + .as_ref() + .map(|o| o.inspection.clone()) + .expect("installed above"); + let inspection = match self.read_inspection(boundary, &restored_value, &restored_inspection).await + { + Ok(inspection) => inspection, + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + }; + let clock = match self.agents.first() { + Some(slot) => RationalNs::reduced( + u128::from(slot.tick_duration.numerator) * u128::from(slot.brain_ticks), + u128::from(slot.tick_duration.denominator), + ) + .unwrap_or(RationalNs::ZERO), + None => RationalNs::ZERO, + }; + let restored_scope = scope_at(&self.session_id, new_epoch, boundary); + match self.task.restored(&restored_scope, &inspection, &clock) { + Ok(Some(contexts)) => { + let differing = self + .agents + .iter() + .find(|slot| { + contexts.get(&slot.agent_id).map(TypedValue::digest) + != Some(slot.context_digest.clone()) + }) + .map(|slot| slot.agent_id.clone()); + if let Some(agent_id) = differing { + { + self.taint_group(&staged); + return Err(self.fail_now( + DomainError::before( + ErrorCode::IncompatibleState, + format!( + "the restored world gives {} another decision context than the \ + checkpoint recorded", + agent_id + ), + ), + "restore", + )); + } + } + } + Ok(None) => {} + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + } + self.inspection_held = restored_inspection; + self.current_inspection = Some(inspection); + // The pulse is unknown until the new epoch's first commit (`legacy-gameboy-v1` 15). + self.admissions.forget_remaining(); // Step 5: Paused(k), and only now is the fence lifted. self.epoch = new_epoch.clone(); @@ -4231,7 +5867,7 @@ impl Coordinator { &manifest.coordinator.task_ledger, )?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; - task.validate_restore(&ledger)?; + task.validate_restore_with(&ledger, &crate::state::task_attachments(payloads))?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&Coordinator::read_payload(payloads, name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4332,7 +5968,8 @@ impl Coordinator { let ledger = TypedValue::from_json(&read(&manifest.coordinator.task_ledger)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; - self.task.validate_restore(&ledger)?; + let task_attachments = crate::state::task_attachments(payloads); + self.task.validate_restore_with(&ledger, &task_attachments)?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&read(name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4398,7 +6035,7 @@ impl Coordinator { audio_positions.insert(stream.clone(), sample); } // Everything above validated. From here the coordinator installs, in one pass. - self.task.install_restore(new_epoch, &ledger)?; + self.task.install_restore_with(new_epoch, &ledger, &task_attachments)?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&read(name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4522,3 +6159,79 @@ impl Coordinator { }) } } + +#[cfg(test)] +mod admission_race_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// TASK-01 review R2-3: a sugar arriving while a commit ends the in-flight admission and + /// reports the pulse must never see "no pending admission" beside the old, over pulse. The + /// only state the hammer accepts in is exactly that torn one; the commit under test is + /// atomic, so it is never seen. + #[test] + fn no_sugar_is_admitted_between_a_commit_ending_and_its_pulse() { + let queue = AdmissionQueue::default(); + let agent = id("fly"); + let in_flight = Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-1"), + kind_id: id("reward-pulse"), + duration_ms: 400.0, + }; + let stop = AtomicBool::new(false); + let torn = AtomicBool::new(false); + // The hammer must never find the queue's empty initial state (no pulse, nothing + // pending), which is a legitimate admission, not a torn commit: on a loaded box it + // can run before the first iteration below sets the state up (PERF-01 saw it once). + { + let mut state = queue.lock(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } + std::thread::scope(|scope| { + scope.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let admitted = queue.admit_with(&agent, |remaining, pending| { + if remaining.unwrap_or(0.0).max(pending.unwrap_or(0.0)) > 0.0 { + Err(()) + } else { + Ok(Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-x"), + kind_id: id("reward-pulse"), + duration_ms: 1.0, + }) + } + }); + if admitted.is_ok() { + torn.store(true, Ordering::Relaxed); + return; + } + } + }); + for _ in 0..200_000 { + if torn.load(Ordering::Relaxed) { + break; + } + // The state after a cut: the sugar is in flight and the last pulse is over. + { + let mut state = queue.lock(); + state.queued.clear(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } + queue.commit( + vec![in_flight.clone()], + AdmissionEnd::Applied { boundary: 1 }, + &[(agent.clone(), Some(400.0))], + ); + } + stop.store(true, Ordering::Relaxed); + }); + assert!( + !torn.load(Ordering::Relaxed), + "a sugar was admitted into a live pulse in the commit's window" + ); + } +} diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index d867ede..088077c 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -42,6 +42,10 @@ use crate::worker::{StatusCell, WorkerHandle, serve}; pub enum Via { Memory, Unix, + /// In memory, and every in-process participant is also offered over its local lane + /// ([`crate::worker::LocalLane`], PERF-01): its endpoint methods are called without a bus + /// message. A thread or a separate process still reaches the router over its socket. + Local, } /// Where a participant runs. @@ -340,6 +344,8 @@ pub struct LaunchedWorker { pub peak_rss_kib: u64, body: Body, status: Option, + /// The local lane a reference carries, when the launcher offers it. + local: Option, /// The per-participant socket endpoint, kept alive for the connection's lifetime. _listener: Option, } @@ -354,6 +360,7 @@ impl LaunchedWorker { &self.identity.worker_id, ); r.domain_incarnation = Some(self.domain_incarnation.clone()); + r.local = self.local.clone(); r } @@ -419,7 +426,7 @@ impl Endpoints { /// A connection this process owns, over the configured transport. async fn connect(&self, client_id: &str) -> Result { let transport = match self.via { - Via::Memory => self.router.connect_in_memory_as(client_id), + Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id), Via::Unix => { let path = self.socket_path(client_id); let listener = self.listen(&path, client_id).await?; @@ -471,6 +478,8 @@ pub struct Launcher { supervisor: Client, workers: BTreeMap, serial: u64, + /// Whether an in-process participant's reference carries its local lane (PERF-01). + local_lane: bool, } /// The bus client id the supervisor connects under. @@ -534,9 +543,18 @@ impl Launcher { supervisor, workers: BTreeMap::new(), serial: 0, + local_lane: mode == ExecutionMode::InProcess && via == Via::Local, }) } + /// Offers every in-process participant launched from now on over the local lane + /// ([`crate::worker::LocalLane`]): its [`LaunchedWorker::worker_ref`] carries the lane, so a + /// coordinator in this process calls its endpoint methods without the bus. A thread or a + /// separate process has no lane and is always reached over the bus. + pub fn use_local_lane(&mut self, on: bool) { + self.local_lane = on; + } + pub fn mode(&self) -> ExecutionMode { self.mode } @@ -742,6 +760,10 @@ impl Launcher { Body::Process(Some(child)) => Some(child.id()), _ => None, }; + let local = match &body { + Body::Task(Some(handle)) if self.local_lane => Some(handle.local.clone()), + _ => None, + }; // The registration is discovered, not assumed: the launcher says hello with the // identity it configured, and the reply is what the coordinator later pins. let identified = self.identify(identity).await; @@ -756,6 +778,7 @@ impl Launcher { peak_rss_kib: 0, body, status, + local: None, _listener: listener, }; terminate(&mut dying); @@ -770,6 +793,7 @@ impl Launcher { peak_rss_kib: 0, body, status, + local, _listener: listener, }; worker.refresh_rss(); diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 3367247..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; @@ -312,6 +325,43 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// A capture's inputs, copied at the boundary so the encoding can run off the endpoint's lock. +struct CaptureSnapshot { + state: AgentState, + agent_id: Id, + checkpoint_id: Id, + scope: Scope, + committed_step: u64, + profile: AssetRef, + seed: i32, + reinforcements: u64, + macro_channels: Vec, + accumulator: TickAccumulator, + context: TypedValue, +} + +impl CaptureSnapshot { + fn encode(&self) -> DomainResult> { + encode_payload( + &self.state, + &PayloadIdentity { + agent_id: &self.agent_id, + checkpoint_id: &self.checkpoint_id, + source_scope: &self.scope, + committed_step: self.committed_step, + profile: &self.profile, + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: &self.macro_channels, + }, + &self.accumulator, + &self.context, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + } +} + /// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { let parts = decode_envelope(bytes, PAYLOAD_MAGIC) @@ -365,9 +415,21 @@ pub fn spike_bitset(last_spike_ms: &[f64], since_ms: f64, now_ms: f64) -> Vec= since_ms { - bytes[index >> 3] |= 1 << (index & 7); + // Eight neurons per byte, branch-free, so the compiler vectorises the comparison (PERF-01: + // 139,255 neurons a frame). The same `last >= since` test as the bit-at-a-time loop. + let chunks = last_spike_ms.chunks_exact(8); + let tail = chunks.remainder(); + for (byte, chunk) in bytes.iter_mut().zip(chunks) { + let mut bits = 0u8; + for (bit, last) in chunk.iter().enumerate() { + bits |= u8::from(*last >= since_ms) << bit; + } + *byte = bits; + } + if !tail.is_empty() { + let at = last_spike_ms.len() / 8; + for (bit, last) in tail.iter().enumerate() { + bytes[at] |= u8::from(*last >= since_ms) << bit; } } bytes @@ -440,6 +502,11 @@ pub struct LegacyAgentWorker { prepared: Option<(DomainRequestId, PreparedDecision)>, /// The brain time before the in-flight transition's ticks: the spike window's start. transition_start_ms: f64, + /// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike + /// lists during Prepare (PERF-01). It is the bitset `spike_bitset` would scan out of + /// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the + /// kernel keeps no per-tick list (the GPU backend): Commit scans as before. + tick_spikes: Option>, staged: Option, activated: BTreeSet, /// Every mutation this worker applied, reported as its progress counter. @@ -543,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. @@ -579,6 +706,7 @@ impl LegacyAgentWorker { context: None, prepared: None, transition_start_ms: 0.0, + tick_spikes: None, staged: None, activated: BTreeSet::new(), mutations: 0, @@ -816,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 @@ -1005,7 +1155,32 @@ impl LegacyAgentWorker { let brain_ticks = accumulator.brain_ticks(); let remainder = accumulator.remainder(); self.transition_start_ms = agent.network.ms; - agent.network.step(ticks); + // Profiling runs the brain's own phase clock too, as a measured legacy loop does, so + // the two brains carry the same instrumentation (PERF-01). + agent.network.profile = crate::profile::enabled(); + let phase_before = agent.network.timings().total_ns(); + let ticks_span = crate::profile::span("agent.ticks"); + // One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped + // are its spike list, so the transition's bitset is their union. + let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)]; + let mut listed = true; + for _ in 0..ticks { + let count = agent.network.step(1) as usize; + match agent.network.tick_spikes(count) { + Some(list) if listed => { + for &neuron in list { + bits[neuron as usize >> 3] |= 1 << (neuron & 7); + } + } + _ => listed = false, + } + } + self.tick_spikes = listed.then_some(bits); + drop(ticks_span); + crate::profile::record( + "agent.ticks.phase_clock", + std::time::Duration::from_nanos(agent.network.timings().total_ns() - phase_before), + ); if agent.network.ms != brain_ticks as f64 { return Err(applied( ErrorCode::Internal, @@ -1080,7 +1255,9 @@ impl LegacyAgentWorker { "Agent.Commit must carry the step of its transition, not the new boundary", )); } + let parse_span = crate::profile::span("agent.commit.parse"); let params: CommitParams = ctx.params()?; + drop(parse_span); params .validate_against_scope(&scope) .map_err(DomainError::invalid)?; @@ -1110,7 +1287,9 @@ impl LegacyAgentWorker { } let context = self.read_context(¶ms.next_decision_context)?; // The complete request and its owned artifact are validated before anything applies. + let read_span = crate::profile::span("agent.read_lcd"); let frame = self.read_lcd(ctx, ¶ms.next_input).await?; + drop(read_span); self.status.set_state(WorkerState::Committing); let agent = self.agent.as_mut().expect("initialized"); @@ -1139,7 +1318,12 @@ impl LegacyAgentWorker { self.transient.location = Some(location); self.transient.blocked_since_ms = ms; } - let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms); + let spikes_span = crate::profile::span("agent.spikes"); + let spikes = match self.tick_spikes.take() { + Some(bits) => bits, + None => spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms), + }; + drop(spikes_span); // 4. Retain the next context and acknowledge k+1. let digest = context.digest.clone(); self.context = Some(context); @@ -1152,7 +1336,9 @@ impl LegacyAgentWorker { decision_context_digest: digest, telemetry: self.telemetry(), }; - let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes) + let _seal_span = crate::profile::span("agent.seal_spikes"); + let artifact = ctx + .seal(SPIKES_CONTENT_TYPE, spikes) .await .map_err(|e| applied(e.code, e.message))?; self.status.set_state(WorkerState::Ready); @@ -1273,7 +1459,8 @@ impl LegacyAgentWorker { /// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session` /// manifest member with the accumulator, the context and the identities. The readout /// transient is not in it (`legacy-transient-reset`). - fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult> { + /// Everything a capture payload is encoded from, copied out of the live agent. + fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult { let agent = self.agent.as_ref().expect("initialized"); let accumulator = self.accumulator.as_ref().expect("initialized"); let context = self.context.as_ref().expect("initialized"); @@ -1281,23 +1468,19 @@ impl LegacyAgentWorker { // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; - encode_payload( - &state, - &PayloadIdentity { - agent_id: &self.config.agent_id, - checkpoint_id, - source_scope: scope, - committed_step: k, - profile: &self.profile.asset, - seed: self.seed, - reinforcements: self.reinforcements, - macro_channels: &self.config.macro_channels, - }, - accumulator, - &context.typed, - None, - ) - .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + Ok(CaptureSnapshot { + state, + agent_id: self.config.agent_id.clone(), + checkpoint_id: checkpoint_id.clone(), + scope: scope.clone(), + committed_step: k, + profile: self.profile.asset.clone(), + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: self.config.macro_channels.clone(), + accumulator: accumulator.clone(), + context: context.typed.clone(), + }) } async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1323,36 +1506,50 @@ impl LegacyAgentWorker { )); } let params: CaptureParams = ctx.params()?; - let previous = self.status.state(); - self.status.set_state(WorkerState::Capturing); - let bytes = self.payload(¶ms.checkpoint_id, &scope, k); - let bytes = match bytes { - Ok(bytes) => bytes, - Err(e) => { - self.status.set_state(previous); - return Err(e); - } + // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's + // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full + // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next + // Prepare does not wait for them (TASK-01 review N5). + let snapshot = { + let _span = crate::profile::span("agent.capture.snapshot"); + self.snapshot(¶ms.checkpoint_id, &scope, k)? }; - let digest = digest_of_bytes(&bytes); - let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; - self.status.set_state(previous); - let artifact = artifact?; let graph = self.graph.as_ref().expect("initialized"); - let result = CaptureResult { - checkpoint_id: params.checkpoint_id, - boundary: k, - compatibility_digest: compatibility_digest( - &self.config.agent_id, - &self.profile.asset, - graph, - self.seed, - ), - payload: artifact.reference().clone(), - }; - Ok(HandlerReply::with_artifacts( - object(result.to_json()), - vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], - )) + let compatibility = compatibility_digest( + &self.config.agent_id, + &self.profile.asset, + graph, + self.seed, + ); + let client = ctx.client.clone(); + Ok(HandlerReply::deferred(Box::pin(async move { + let bytes = tokio::task::spawn_blocking(move || { + let _span = crate::profile::span("agent.capture.encode"); + let bytes = snapshot.encode()?; + let digest = { + let _span = crate::profile::span("agent.capture.digest"); + digest_of_bytes(&bytes) + }; + Ok::<_, DomainError>((bytes, digest)) + }) + .await + .map_err(|e| DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None))?; + let (bytes, digest) = bytes?; + let artifact = { + let _span = crate::profile::span("agent.capture.seal"); + crate::state::seal_payload(&client, &bytes, &digest).await? + }; + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: k, + compatibility_digest: compatibility, + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + }))) } async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1724,6 +1921,7 @@ impl WorkerEndpoint for LegacyAgentWorker { id("pixel-observation-v1"), id(crate::state::CHECKPOINT_CAPABILITY), id(ROLLBACK_CAPABILITY), + id(FEED_STATUS_CAPABILITY), ] } @@ -1744,6 +1942,7 @@ impl WorkerEndpoint for LegacyAgentWorker { "State.Capture", "State.StageRestore", "State.ActivateRestore", + METHOD_FEED_STATUS, ] } @@ -1751,12 +1950,19 @@ impl WorkerEndpoint for LegacyAgentWorker { Box::pin(async move { let outcome = match ctx.method { "Agent.Initialize" => self.initialize(&ctx).await, - "Agent.Prepare" => self.prepare(&ctx).await, - "Agent.Commit" => self.commit(&ctx).await, + "Agent.Prepare" => { + let _span = crate::profile::span("agent.prepare.handler"); + self.prepare(&ctx).await + } + "Agent.Commit" => { + let _span = crate::profile::span("agent.commit.handler"); + self.commit(&ctx).await + } METHOD_AGENT_ROLLBACK => self.rollback(&ctx).await, "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"), @@ -1807,6 +2013,46 @@ mod tests { ); } + #[test] + fn the_bytewise_spike_bitset_is_the_bit_at_a_time_one() { + // PERF-01 replaced the per-neuron loop; every length and window agrees with it, + // including NaN (never >=) and infinities. + fn reference(last: &[f64], since: f64, now: f64) -> Vec { + let mut bytes = vec![0u8; last.len().div_ceil(8)]; + if now <= since { + return bytes; + } + for (index, value) in last.iter().enumerate() { + if *value >= since { + bytes[index >> 3] |= 1 << (index & 7); + } + } + bytes + } + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + for len in 0..40usize { + for _ in 0..20 { + let last: Vec = (0..len) + .map(|_| match next() % 10 { + 0 => f64::NAN, + 1 => f64::NEG_INFINITY, + 2 => -1_000_000.0, + n => (n * 3) as f64, + }) + .collect(); + let since = (next() % 30) as f64; + let now = since + (next() % 3) as f64; + assert_eq!(spike_bitset(&last, since, now), reference(&last, since, now)); + } + } + } + #[test] fn the_macro_in_a_decision_is_the_first_bound_channel_held() { let active = vec![ diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs index a423c70..246b41f 100644 --- a/services/flysim/crates/fly-session/src/legacy_env.rs +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -854,13 +854,35 @@ impl LegacyGameboyEnvironment { /// if there was one. async fn observation( live: &mut Live, - client: &flybus::Client, + ctx: &HandlerCtx<'_>, audio: Option>, ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { - let frame = - media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; - let image = memory_image(&mut live.emulator).map_err(backend_failure)?; - let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; + let image = { + let _span = crate::profile::span("env.image"); + memory_image(&mut live.emulator).map_err(backend_failure)? + }; + if let Some(raw) = &audio + && raw.len() % AUDIO_CHANNELS as usize != 0 + { + return Err(backend_failure("binjgb returned half a stereo frame")); + } + let audio_f32 = audio.as_deref().map(audio_f32le); + // The three artifacts are independent: they are sealed concurrently, so the boundary + // waits for the router's round trips once rather than three times. Over the local lane + // each is an in-memory artifact owning its bytes (`HandlerCtx::seal`). + let seal_span = crate::profile::span("env.seal"); + let (frame, memory, samples) = tokio::join!( + ctx.seal(FRAME_CONTENT_TYPE, live.framebuffer.to_vec()), + ctx.seal(MEMORY_CONTENT_TYPE, image), + async { + match audio_f32 { + Some(bytes) => ctx.seal(AUDIO_CONTENT_TYPE, bytes).await.map(Some), + None => Ok(None), + } + } + ); + drop(seal_span); + let (frame, memory, samples) = (frame?, memory?, samples?); let view = ViewRef { view_id: gameboy::VIEW_ID.to_owned(), produced_step: live.boundary, @@ -876,13 +898,8 @@ impl LegacyGameboyEnvironment { (MEMORY_ATTACHMENT.to_owned(), memory), ]; let mut chunks = Vec::new(); - if let Some(raw) = audio { - if raw.len() % AUDIO_CHANNELS as usize != 0 { - return Err(backend_failure("binjgb returned half a stereo frame")); - } + if let (Some(raw), Some(samples)) = (audio, samples) { let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; - let samples = - media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?; chunks.push(AudioRef { stream_id: id(AUDIO_STREAM_ID), first_sample: live.audio_next_sample, @@ -980,7 +997,7 @@ impl LegacyGameboyEnvironment { audio_discontinuity: false, }; let (observation, attachments) = - LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?; self.live = Some(live); // The world is stopped when O[0] goes out and cannot free-run while the brain warms up. self.status.set_state(WorkerState::Ready); @@ -998,6 +1015,7 @@ impl LegacyGameboyEnvironment { // -- Environment.Advance ----------------------------------------------------------------- async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let _span = crate::profile::span("env.advance.handler"); let scope = ctx.scope()?.clone(); let params: AdvanceParams = ctx.params()?; let status = self.status.clone(); @@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment { let applied_from = live.boundary; // `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. + let frame_span = crate::profile::span("env.frame"); live.buttons = mask; live.emulator.set_buttons(mask); live.emulator @@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment { live.framebuffer .copy_from_slice(live.emulator.framebuffer()); let audio = live.emulator.take_audio_u8(); + drop(frame_span); live.boundary += 1; live.world_time = live .world_time @@ -1054,7 +1074,7 @@ impl LegacyGameboyEnvironment { status.progress(1); let (observation, attachments) = - LegacyGameboyEnvironment::observation(live, ctx.client, Some(audio)).await?; + LegacyGameboyEnvironment::observation(live, ctx, Some(audio)).await?; let result = StepResult { batch_id: params.batch_id, applied_from_step: applied_from, @@ -1150,7 +1170,7 @@ impl LegacyGameboyEnvironment { live.batches.clear(); live.audio_discontinuity = true; let (observation, attachments) = - LegacyGameboyEnvironment::observation(live, ctx.client, None).await?; + LegacyGameboyEnvironment::observation(live, ctx, None).await?; status.set_state(WorkerState::Ready); status.set_scope(Some(scope.clone())); status.progress(1); @@ -1415,7 +1435,7 @@ impl LegacyGameboyEnvironment { audio_discontinuity: true, }; let (observation, attachments) = - LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?; self.live = Some(live); self.activated.insert(token); self.status.set_state(WorkerState::Ready); diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 63edd03..ad32a6c 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -38,6 +38,7 @@ pub mod measure; pub mod media; pub mod metrics; pub mod phase; +pub mod profile; pub mod publish; pub mod rpc; pub mod state; diff --git a/services/flysim/crates/fly-session/src/metrics.rs b/services/flysim/crates/fly-session/src/metrics.rs index fd5d1a3..a226ce8 100644 --- a/services/flysim/crates/fly-session/src/metrics.rs +++ b/services/flysim/crates/fly-session/src/metrics.rs @@ -79,6 +79,16 @@ impl Metrics { pub fn clear(&mut self) { self.samples.clear(); } + + /// Bounds every path to between `keep` and `2 * keep` of its newest samples (trimmed in + /// batches, so a long run does not shift the vector every step). + pub fn truncate(&mut self, keep: usize) { + for values in self.samples.values_mut() { + if values.len() > 2 * keep { + values.drain(..values.len() - keep); + } + } + } } /// This process's peak resident set, in KiB, from its own status file. diff --git a/services/flysim/crates/fly-session/src/phase.rs b/services/flysim/crates/fly-session/src/phase.rs index f528112..235576a 100644 --- a/services/flysim/crates/fly-session/src/phase.rs +++ b/services/flysim/crates/fly-session/src/phase.rs @@ -9,6 +9,8 @@ //! Ready(k) / Paused(k) -> Capturing(k) -> same boundary //! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k) //! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0) +//! declared rollback: Ready(e, k) -> RollingBack(e', k) -> Ready(e', k) +//! checkpoint as the start: Ready(0), no transition taken -> Restoring(k) -> Paused(k) //! ``` //! //! A transition the table does not list is a bug, not a recoverable condition, so it returns @@ -34,6 +36,9 @@ pub enum Phase { Restoring(u64), /// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0. Resetting(u64), + /// A declared rollback policy running at a committed boundary (`step-v1` section 2 + /// amendment of 2026-09-23): same boundary, new epoch, no capture. + RollingBack(u64), } impl Phase { @@ -50,6 +55,7 @@ impl Phase { Phase::Failed => "Failed".to_owned(), Phase::Restoring(k) => format!("Restoring({k})"), Phase::Resetting(k) => format!("Resetting({k})"), + Phase::RollingBack(k) => format!("RollingBack({k})"), } } @@ -115,6 +121,14 @@ impl PhaseMachine { (Restoring(k), Paused(j)) => k == j, (Paused(k), Resetting(j)) => k == j, (Resetting(_), Ready(0)) => true, + // `step-v1` section 2, amendment of 2026-09-23: `Ready(e, k) -> RollingBack(e', k) + // -> Ready(e', k)`. The epoch changes, which is the coordinator's; the boundary + // does not. + (Ready(k), RollingBack(j)) | (RollingBack(k), Ready(j)) => k == j, + // A session that bootstrapped and has taken no transition may install a checkpoint + // as its start: the legacy composition's FLYSIM01 import (TASK-01). The install is + // the group restore of `state-media-v1` section 6 and ends `Paused(k)` like one. + (Ready(0), Restoring(_)) => true, _ => false, } } @@ -150,6 +164,21 @@ impl PhaseMachine { mod tests { use super::*; + #[test] + fn a_rollback_keeps_its_boundary_and_an_import_starts_from_an_unstepped_zero() { + let mut m = PhaseMachine::new(); + m.to(Phase::Ready(0)).unwrap(); + m.to(Phase::Restoring(40)).unwrap(); + m.to(Phase::Paused(40)).unwrap(); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::RollingBack(41)).is_err(), "a rollback keeps the boundary"); + m.to(Phase::RollingBack(40)).unwrap(); + assert!(m.to(Phase::Capturing(40)).is_err(), "no capture inside a rollback"); + assert!(m.to(Phase::Preparing(40)).is_err(), "no Prepare before every reply"); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::Restoring(3)).is_err(), "only boundary 0 may take a start"); + } + #[test] fn the_happy_path_walks_the_section_2_diagram() { let mut m = PhaseMachine::new(); diff --git a/services/flysim/crates/fly-session/src/profile.rs b/services/flysim/crates/fly-session/src/profile.rs new file mode 100644 index 0000000..a618b57 --- /dev/null +++ b/services/flysim/crates/fly-session/src/profile.rs @@ -0,0 +1,96 @@ +//! A switchable per-phase timer for measuring the session runtime (TASK-01 review N5). +//! +//! Off unless `FLY_SESSION_PROFILE` is set when the process starts; off, a span is one relaxed +//! atomic load. On, every span adds its duration to a process-wide table that [`report`] reads. +//! In-process execution puts the coordinator and every worker in one table; a worker process +//! keeps its own. Not a service metric: a measurement tool. + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::{Duration, Instant}; + +static STATE: AtomicU8 = AtomicU8::new(0); // 0 unknown, 1 off, 2 on +static TABLE: Mutex> = Mutex::new(BTreeMap::new()); + +/// Whether profiling is on for this process (`FLY_SESSION_PROFILE`). +pub fn enabled() -> bool { + on() +} + +fn on() -> bool { + match STATE.load(Ordering::Relaxed) { + 1 => false, + 2 => true, + _ => { + let enabled = std::env::var_os("FLY_SESSION_PROFILE").is_some(); + STATE.store(if enabled { 2 } else { 1 }, Ordering::Relaxed); + enabled + } + } +} + +/// Times until dropped. +pub struct Span(Option<(&'static str, Instant)>); + +/// Starts timing `name`. +pub fn span(name: &'static str) -> Span { + Span(on().then(|| (name, Instant::now()))) +} + +impl Drop for Span { + fn drop(&mut self) { + if let Some((name, started)) = self.0.take() { + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO)); + let elapsed = started.elapsed(); + entry.0 += 1; + entry.1 += elapsed; + entry.2 = entry.2.max(elapsed); + } + } +} + +/// Adds one sample measured elsewhere (a clock the caller already runs) under `name`. +pub fn record(name: &'static str, elapsed: Duration) { + if !on() { + return; + } + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO)); + entry.0 += 1; + entry.1 += elapsed; + entry.2 = entry.2.max(elapsed); +} + +/// `(name, count, mean)` for every span recorded, then clears the table. +pub fn report() -> Vec<(&'static str, u64, Duration)> { + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let out = table + .iter() + .map(|(name, (count, total, _))| (*name, *count, *total / (*count).max(1) as u32)) + .collect(); + table.clear(); + out +} + +/// As [`report`], with each span's longest single sample: `(name, count, mean, max)`. +pub fn report_with_max() -> Vec<(&'static str, u64, Duration, Duration)> { + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let out = table + .iter() + .map(|(name, (count, total, max))| { + (*name, *count, *total / (*count).max(1) as u32, *max) + }) + .collect(); + table.clear(); + out +} diff --git a/services/flysim/crates/fly-session/src/publish.rs b/services/flysim/crates/fly-session/src/publish.rs index 8390298..c19e166 100644 --- a/services/flysim/crates/fly-session/src/publish.rs +++ b/services/flysim/crates/fly-session/src/publish.rs @@ -635,8 +635,31 @@ impl Publisher { .map(|(name, artifact)| (name.clone(), artifact.reference().clone())) .collect(); check_publication(descriptor, snapshot, &named, audio_next_sample)?; - let refs: Vec<(&str, &flybus::Artifact)> = - attachments.iter().map(|(n, a)| (n.as_str(), a)).collect(); + // An in-memory artifact (the in-process local lane) is in no router's store, so the + // published message carries a sealed copy of it and names that copy: the coherence + // check above ran against the handles the agents were given. + let mut published = std::borrow::Cow::Borrowed(snapshot); + let mut sealed = Vec::with_capacity(attachments.len()); + for (name, artifact) in attachments { + let copy = crate::rpc::promote(&self.bus, artifact).await?; + if copy.reference() != artifact.reference() { + let (old, new) = (artifact.reference(), copy.reference()); + let snapshot = published.to_mut(); + for view in &mut snapshot.views { + if &view.pixels == old { + view.pixels = new.clone(); + } + } + for chunk in &mut snapshot.audio { + if &chunk.samples == old { + chunk.samples = new.clone(); + } + } + } + sealed.push((name.as_str(), copy)); + } + let refs: Vec<(&str, &flybus::Artifact)> = sealed.iter().map(|(n, a)| (*n, a)).collect(); + let snapshot = published.as_ref(); let topic = self.snapshot_topic.topic.clone(); let outcome = PublicationOutcome::from_bus( &topic, diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index 11a4477..cf38049 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -20,6 +20,10 @@ pub struct WorkerRef { pub worker_id: Id, /// The domain `incarnationId` Hello negotiated, once it has. pub domain_incarnation: Option, + /// The worker's shell in this process, when the launcher offers it (PERF-01): endpoint + /// methods then go over the local lane instead of the bus. Same shell, same admission, + /// same outcomes; no router in between. + pub local: Option, } impl WorkerRef { @@ -29,6 +33,7 @@ impl WorkerRef { bus_incarnation: bus_incarnation.to_owned(), worker_id: worker_id.clone(), domain_incarnation: None, + local: None, } } } @@ -69,8 +74,61 @@ pub async fn call( request_id: DomainRequestId, want_artifacts: &[String], ) -> Result { + send(bus, target, method, scope, params, attachments, request_id, want_artifacts) + .await? + .finish() + .await +} + +/// A domain call that has been sent and not yet answered: the bus has it in order, so a call +/// sent after it to the same worker is dispatched after it. +pub struct SentCall { + method: String, + pending: Pending, + request_id: DomainRequestId, + want_artifacts: Vec, +} + +enum Pending { + Bus(flybus::PendingCall), + Local(crate::worker::LocalPending), +} + +/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits). +#[allow(clippy::too_many_arguments)] +pub async fn send( + bus: &flybus::Client, + target: &WorkerRef, + method: &str, + scope: Option, + params: Map, + attachments: &[(&str, &flybus::Artifact)], + request_id: DomainRequestId, + want_artifacts: &[String], +) -> Result { let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) }; - let mut pending = bus + if let Some(lane) = &target.local + && crate::worker::local_lane_carries(method) + { + let attachments = attachments + .iter() + .map(|(name, artifact)| ((*name).to_owned(), (*artifact).clone())) + .collect(); + let _span = crate::profile::span("rpc.local.send"); + let pending = lane.send(method, request, attachments).await?; + return Ok(SentCall { + method: method.to_owned(), + pending: Pending::Local(pending), + request_id, + want_artifacts: want_artifacts.to_vec(), + }); + } + // An in-memory artifact is in no router's store: a bus call carries a sealed copy of it. + let promoted = promote_all(bus, attachments).await?; + let attachments: Vec<(&str, &flybus::Artifact)> = + promoted.iter().map(|(n, a)| (n.as_str(), a)).collect(); + let attachments = attachments.as_slice(); + let pending = bus .call( &target.service, Some(&target.bus_incarnation), @@ -80,26 +138,108 @@ pub async fn call( ) .await .map_err(|e| bus_error(method, &e))?; - let result = pending.result().await.map_err(|e| bus_error(method, &e))?; - let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) - .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; - let mut artifacts = BTreeMap::new(); - for name in want_artifacts { - if let Ok(artifact) = result.artifact(name) { - // An independent explicit hold, so the handle outlives this delivery and can be - // forwarded to several Commit calls and to publication. - match artifact.retain().await { - Ok(hold) => { - artifacts.insert(name.clone(), hold); - } - Err(_) => { - artifacts.insert(name.clone(), artifact); + Ok(SentCall { + method: method.to_owned(), + pending: Pending::Bus(pending), + request_id, + want_artifacts: want_artifacts.to_vec(), + }) +} + +impl SentCall { + /// Waits for the terminal reply. + pub async fn finish(self) -> Result { + let method = self.method.as_str(); + let mut pending = match self.pending { + Pending::Bus(pending) => pending, + Pending::Local(pending) => { + let wait_span = crate::profile::span("rpc.local.wait"); + let reply = pending.finish().await; + drop(wait_span); + let reply = reply.ok_or_else(|| { + DomainError::new( + ErrorCode::BackendFailure, + format!("{method}: the worker stopped before it answered"), + MutationCertainty::Unknown, + ) + })?; + // The handles are the worker's own (in memory, or sealed holds its cache + // keeps too); only the wanted ones are kept, as the bus path extracts. + // A sealed handle is only valid as an attachment on the worker's own + // connection, so a sealed reply artifact (a handler that sealed through the + // bus) reaches the caller in memory, under the same reference. + let mut artifacts = BTreeMap::new(); + for (name, artifact) in reply.artifacts { + if !self.want_artifacts.contains(&name) { + continue; + } + let artifact = artifact.to_memory().await.map_err(|e| bus_error(method, &e))?; + artifacts.insert(name, artifact); } + return Ok(DomainReply { + outcome: reply.outcome, + request_id: self.request_id, + artifacts, + }); + } + }; + let result = pending.result().await.map_err(|e| bus_error(method, &e))?; + let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) + .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; + // An independent explicit hold on each wanted attachment, so the handle outlives this + // delivery and can be forwarded to several Commit calls and to publication. The holds + // are independent router round trips, so they are taken concurrently. + let wanted: Vec<(String, flybus::Artifact)> = self + .want_artifacts + .iter() + .filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a))) + .collect(); + let retains: Vec<_> = wanted + .into_iter() + .map(|(name, artifact)| { + tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }) + }) + .collect(); + let mut artifacts = BTreeMap::new(); + for retain in retains { + if let Ok((name, artifact)) = retain.await { + artifacts.insert(name, artifact); } } + drop(result); + Ok(DomainReply { outcome, request_id: self.request_id, artifacts }) + } +} + +/// Every attachment as a bus artifact: sealed handles as they are, in-memory ones as a sealed +/// copy in the caller's store. +pub async fn promote_all( + bus: &flybus::Client, + attachments: &[(&str, &flybus::Artifact)], +) -> Result, DomainError> { + let mut out = Vec::with_capacity(attachments.len()); + for (name, artifact) in attachments { + out.push(((*name).to_owned(), promote(bus, artifact).await?)); + } + Ok(out) +} + +/// One artifact as a bus artifact ([`promote_all`]). +pub async fn promote( + bus: &flybus::Client, + artifact: &flybus::Artifact, +) -> Result { + match artifact.memory() { + None => Ok(artifact.clone()), + Some(bytes) => { + crate::media::seal_copy(bus, artifact.reference().content_type.clone(), bytes).await + } } - drop(result); - Ok(DomainReply { outcome, request_id, artifacts }) } /// Maps a bus failure onto a domain error, preserving how certain the mutation is. diff --git a/services/flysim/crates/fly-session/src/state.rs b/services/flysim/crates/fly-session/src/state.rs index 220310f..92c0796 100644 --- a/services/flysim/crates/fly-session/src/state.rs +++ b/services/flysim/crates/fly-session/src/state.rs @@ -110,6 +110,28 @@ pub fn executor_payload(agent_id: &str) -> String { pub const WORLD_PAYLOAD: &str = "world"; /// The task ledger's payload name. pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger"; +/// The prefix of the payloads that carry a task ledger's attachments: bytes beside its typed +/// value, for a ledger over the 32 KiB `TypedValue` bound (`workers-v1` section 1, "explicit +/// artifact-backed schema"; `Task::capture_attachments`). `task-ledger-`. +pub const TASK_ATTACHMENT_PREFIX: &str = "task-ledger-"; + +/// The payload name of one task ledger attachment. +pub fn task_attachment_payload(name: &str) -> String { + format!("{TASK_ATTACHMENT_PREFIX}{name}") +} + +/// The task ledger's attachments among a checkpoint's payloads, by attachment name. +pub fn task_attachments( + payloads: &std::collections::BTreeMap>, +) -> std::collections::BTreeMap> { + payloads + .iter() + .filter_map(|(name, bytes)| { + name.strip_prefix(TASK_ATTACHMENT_PREFIX).map(|n| (n.to_owned(), bytes.clone())) + }) + .collect() +} + /// The prior world inspection's payload name. pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection"; /// The coordinator's admission state and event watermarks. diff --git a/services/flysim/crates/fly-session/src/task.rs b/services/flysim/crates/fly-session/src/task.rs index bbb2bf4..60873b9 100644 --- a/services/flysim/crates/fly-session/src/task.rs +++ b/services/flysim/crates/fly-session/src/task.rs @@ -7,6 +7,7 @@ //! writes a controller or neural state directly. use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -53,6 +54,48 @@ pub fn controller_schema_ref() -> SchemaRef { synthetic_schema("arena.controller.v1", 1) } +/// One boundary's inspection as the task and the executor read it: the observation's typed +/// `inspection` value plus the bytes of the attachments the task declared +/// ([`Task::inspection_attachments`]). +/// +/// An artifact-backed inspection (`gameboy-memory-inspection-v1`: a 64 KiB image per boundary) +/// names its bytes by `ArtifactRef`; the coordinator holds the artifact until the transition +/// that reads it has been evaluated (`step-v1` section 3, Phase C amendment) and hands the task +/// the bytes, so neither the task nor the executor ever reads a live world. The synthetic +/// composition declares no attachment, and its inspection derefs to the typed value it always +/// was. +#[derive(Clone, Debug)] +pub struct Inspection { + /// The boundary the observation belongs to. + pub boundary: u64, + pub value: TypedValue, + /// Attachment name to bytes, for the names the task declared. + pub attachments: BTreeMap>>, +} + +impl Inspection { + /// An inspection with no attachment: the synthetic composition's. + pub fn plain(boundary: u64, value: TypedValue) -> Inspection { + Inspection { boundary, value, attachments: BTreeMap::new() } + } +} + +impl std::ops::Deref for Inspection { + type Target = TypedValue; + + fn deref(&self) -> &TypedValue { + &self.value + } +} + +/// What a task's part of a rollback produced (`step-v1` section 6 amendment, step 3): the next +/// decision contexts for the restored boundary, and any events it reports. +#[derive(Clone, Debug)] +pub struct RollbackEvaluation { + pub next_contexts: BTreeMap, + pub events: Vec, +} + /// What `Task.bootstrap` produced. #[derive(Clone, Debug)] pub struct Bootstrap { @@ -70,16 +113,27 @@ pub struct Evaluation { pub progress: TypedValue, pub events: Vec, pub episode: Option, + /// Slot saves the transition asks for at the boundary it reached, applied by the coordinator + /// after every Commit and before any capture or rollback there (`step-v1` section 3, Phase C + /// amendment; environment capability `gameboy-slots-v1`). Empty in every composition that + /// declares no slots. + pub slot_saves: Vec, } /// A checkpointable task ledger and the two evaluation entry points. pub trait Task: Send { fn schema(&self) -> SchemaRef; + /// The inspection attachments this task and its executor read, which the coordinator asks + /// the environment for, holds and hands over as bytes. None by default. + fn inspection_attachments(&self) -> Vec { + Vec::new() + } + /// Called once, at boundary 0, before any agent is initialized. fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult; @@ -87,11 +141,40 @@ pub trait Task: Send { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult; + /// Step 3 of a declared rollback policy, coordinator-local (`step-v1` section 6 amendment): + /// the task clears its transient observations and the executor cancels any running action + /// and observes the restored boundary, which yields the next decision contexts. `scope` is + /// the new epoch at the restored boundary. A task that declares no rollback policy refuses. + fn rollback( + &mut self, + _scope: &Scope, + _restored: &Inspection, + ) -> DomainResult { + Err(DomainError::before( + ErrorCode::Unsupported, + "this task declares no rollback policy", + )) + } + + /// After a group restore installed this task's ledger: the restored boundary's inspection + /// and the agents' restored brain clock. A task whose executor state is transient + /// (`restore: legacy-transient-reset`) re-observes the world here and returns the decision + /// contexts it would hand the agents, which the coordinator holds against the ones the + /// checkpoint recorded. `None` (the default) means the recorded contexts stand unchecked. + fn restored( + &mut self, + _scope: &Scope, + _restored: &Inspection, + _clock: &RationalNs, + ) -> DomainResult>> { + Ok(None) + } + fn progress(&self) -> TypedValue; /// How many times `evaluate_transition` has run. A transition must evaluate once. @@ -100,6 +183,35 @@ pub trait Task: Send { /// The checkpointable ledger at a committed boundary (`workers-v1` section 4). fn capture(&self) -> DomainResult; + /// Bytes the ledger carries beside its typed value, by name: for a ledger over the 32 KiB + /// `TypedValue` bound, the "explicit artifact-backed schema" of `workers-v1` section 1. A + /// checkpoint files each as its own payload (`state::task_attachment_payload`). None by + /// default. + fn capture_attachments(&self) -> DomainResult>> { + Ok(BTreeMap::new()) + } + + /// [`Task::validate_restore`] with the ledger's attachments. + fn validate_restore_with( + &self, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let _ = attachments; + self.validate_restore(state) + } + + /// [`Task::install_restore`] with the ledger's attachments. + fn install_restore_with( + &mut self, + epoch: &Id, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let _ = attachments; + self.install_restore(epoch, state) + } + /// Validates a captured ledger without installing it, so a group install can fail before /// anything is changed. fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>; @@ -127,7 +239,7 @@ pub trait ActionExecutor: Send { &mut self, scope: &Scope, decision: &TypedValue, - current_game_state: &TypedValue, + current_game_state: &Inspection, progress: &TypedValue, clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)>; @@ -151,7 +263,7 @@ impl ActionExecutor for IdentityExecutor { &mut self, _scope: &Scope, decision: &TypedValue, - _current_game_state: &TypedValue, + _current_game_state: &Inspection, _progress: &TypedValue, _clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)> { @@ -294,7 +406,7 @@ impl Task for CounterTask { fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult { if initial_inspection.schema != inspection_schema() { @@ -329,8 +441,8 @@ impl Task for CounterTask { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult { let old = old_inspection.integer("counter").map_err(DomainError::invalid)?; @@ -445,6 +557,7 @@ impl Task for CounterTask { progress: self.progress_value(), events, episode, + slot_saves: Vec::new(), }) } diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index 4451900..d62a3b3 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -113,24 +113,39 @@ impl StatusCell { } } +/// The rest of a reply a handler finishes outside the endpoint's lock. +pub type DeferredReply = + std::pin::Pin> + Send>>; + /// What a handler produced: a domain `result` object and the artifacts it attaches. pub struct HandlerReply { pub result: Map, pub artifacts: Vec<(String, flybus::Artifact)>, /// True when a failure left the endpoint mutated; the shell reports it as such. pub mutated: bool, + /// When set, the reply is this future's: the handler took what it needs from the endpoint + /// (a state snapshot at the committed boundary) and the rest -- encoding, digesting and + /// sealing a capture payload -- runs after the endpoint's lock is released, so the next + /// mutation (the next `Agent.Prepare`) does not wait for it. The bus call is answered + /// when it completes, and cached like any other reply. + pub deferred: Option, } impl HandlerReply { pub fn new(result: Map) -> HandlerReply { - HandlerReply { result, artifacts: Vec::new(), mutated: true } + HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None } } pub fn with_artifacts( result: Map, artifacts: Vec<(String, flybus::Artifact)>, ) -> HandlerReply { - HandlerReply { result, artifacts, mutated: true } + HandlerReply { result, artifacts, mutated: true, deferred: None } + } + + /// A reply finished by `rest` outside the endpoint's lock ([`HandlerReply::deferred`]). + pub fn deferred(rest: DeferredReply) -> HandlerReply { + HandlerReply { result: Map::new(), artifacts: Vec::new(), mutated: true, deferred: Some(rest) } } /// The canonical JSON of one method result. @@ -144,7 +159,29 @@ pub struct HandlerCtx<'a> { pub method: &'a str, pub request: &'a SessionRpcRequest, pub client: &'a flybus::Client, - pub incoming: &'a flybus::Request, + pub incoming: &'a Incoming, +} + +/// How a domain request reached the shell, and so where its attachments are. +pub enum Incoming { + /// A bus request delivery: the attachments are the delivery's. + Bus(Box), + /// The in-process local lane ([`LocalLane`]): the caller's own handles, in memory or + /// sealed, handed over without a bus message. + Local(Vec<(String, flybus::Artifact)>), +} + +impl Incoming { + fn artifact(&self, name: &str) -> Result { + match self { + Incoming::Bus(request) => request.artifact(name).map_err(|e| e.message), + Incoming::Local(list) => list + .iter() + .find(|(n, _)| n == name) + .map(|(_, a)| a.clone()) + .ok_or_else(|| format!("no attachment named {name:?}")), + } + } } impl HandlerCtx<'_> { @@ -170,10 +207,25 @@ impl HandlerCtx<'_> { self.incoming.artifact(name).map_err(|e| { DomainError::before( ErrorCode::BufferInvalid, - format!("attachment {name:?} is missing or unowned: {}", e.message), + format!("attachment {name:?} is missing or unowned: {e}"), ) }) } + + /// True when the request came over the in-process local lane. + pub fn is_local(&self) -> bool { + matches!(self.incoming, Incoming::Local(_)) + } + + /// One immutable reply artifact holding `bytes`. Over the local lane it is an in-memory + /// artifact that owns `bytes` (no copy, no store file, no router round trip); over the bus + /// it is allocated, written and sealed in the router's store as before. + pub async fn seal(&self, content_type: &str, bytes: Vec) -> DomainResult { + if self.is_local() { + return Ok(flybus::Artifact::in_memory(content_type, bytes)); + } + crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await + } } /// A handler's boxed future, so the endpoint trait stays dyn-compatible. @@ -216,6 +268,8 @@ pub struct WorkerHandle { pub service_incarnation: String, pub status: StatusCell, pub cache: Arc>, + /// The same shell, reachable without the bus by a caller in this process. + pub local: LocalLane, task: tokio::task::JoinHandle<()>, client: flybus::Client, } @@ -233,6 +287,7 @@ impl WorkerHandle { /// Stops serving and closes the worker's bus connection, which drops its registration and /// every owner it held. A later reply from it can attach to nothing. pub async fn stop(self) { + self.local.close(); self.task.abort(); let _ = self.task.await; self.client.close().await; @@ -242,6 +297,7 @@ impl WorkerHandle { /// dropped, which this does. For a supervisor's `Drop`, where there is no runtime to wait /// on. pub fn abort(self) { + self.local.close(); self.task.abort(); } @@ -251,10 +307,158 @@ impl WorkerHandle { /// the process's exit are the same event rather than two racing ones. pub async fn join(self) { let _ = self.task.await; + self.local.close(); self.client.close().await; } } +// ------------------------------------------------------------------------------------------- +// The in-process local lane (PERF-01) + +/// A terminal domain reply delivered over the local lane, with the artifacts it attaches. +pub struct LocalReply { + pub outcome: SessionRpcOutcome, + pub artifacts: Vec<(String, flybus::Artifact)>, +} + +/// A request admitted by the local lane and not yet answered. Like an admitted bus call, it is +/// in the worker's order already: a request sent after it to the same worker runs after it. +pub struct LocalPending(tokio::sync::oneshot::Receiver); + +impl LocalPending { + /// Waits for the terminal reply. `None` when the worker stopped before answering, which + /// the caller treats exactly as a bus call whose connection was lost. + pub async fn finish(self) -> Option { + self.0.await.ok() + } +} + +/// What the local lane dispatches into: one worker's shell, the same one its bus loop uses. +trait LocalDispatch: Send + Sync { + fn send( + &self, + method: String, + request: SessionRpcRequest, + attachments: Vec<(String, flybus::Artifact)>, + ) -> BoxFuture<'_, Result>; + fn close(&self); +} + +/// A handle on a worker's shell for a caller in the same process (`workers-v1` PERF-01 +/// amendment). A request sent this way goes through exactly the admission a bus request goes +/// through -- deduplication and the operation key, the result cache, the arrival-order lock and +/// the endpoint -- and returns the same `SessionRpcOutcome`; only the transport differs: no bus +/// message, no router, and reply artifacts the handler may keep in memory +/// ([`HandlerCtx::seal`]). The common `Worker.*` methods are not served here: they stay on the +/// bus, where the supervisor asks them. +#[derive(Clone)] +pub struct LocalLane(Arc); + +impl std::fmt::Debug for LocalLane { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LocalLane") + } +} + +impl LocalLane { + /// Admits one domain request in this worker's order and returns without waiting for it + /// to execute. Refuses what the bus loop would answer without entering the endpoint's + /// order (the common methods) with UNSUPPORTED, before any mutation. + pub async fn send( + &self, + method: &str, + request: SessionRpcRequest, + attachments: Vec<(String, flybus::Artifact)>, + ) -> Result { + self.0.send(method.to_owned(), request, attachments).await + } + + fn close(&self) { + self.0.close(); + } +} + +/// True for a method the local lane carries: every method the shell admits into the endpoint +/// (step mutations, lifecycle and capture, and an endpoint's own read-only extensions such as +/// SERVE-01's `Legacy.FeedStatus`). The common `Worker.*` methods stay on the bus. +pub fn local_lane_carries(method: &str) -> bool { + !method.starts_with("Worker.") +} + +/// How the shell answers one request: over the bus, or into a local waiter. +enum Answer { + Bus(flybus::Responder), + Local(tokio::sync::oneshot::Sender), +} + +impl Answer { + async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) { + match self { + Answer::Bus(responder) => { + let list: Vec<(&str, &flybus::Artifact)> = + artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect(); + let _ = responder.reply(outcome.to_outcome(), &list).await; + } + Answer::Local(tx) => { + let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() }); + } + } + } +} + +/// Everything fixed about one worker's shell, shared by its bus loop and its local lane. +struct Shell { + client: flybus::Client, + endpoint: Arc>, + cache: Arc>, + order: Arc, + status: StatusCell, + worker_id: Id, + incarnation_id: Id, + session_id: Id, + methods: Vec<&'static str>, + /// Admission is one request at a time across both lanes, so tickets follow arrival. + admission: tokio::sync::Mutex<()>, + closed: std::sync::atomic::AtomicBool, + /// The admitted mutations' tasks, awaited when the shell stops. + running: Mutex>>, +} + +/// The local lane's hold on a shell. +struct ShellRef(Arc>); + +impl LocalDispatch for ShellRef { + fn send( + &self, + method: String, + request: SessionRpcRequest, + attachments: Vec<(String, flybus::Artifact)>, + ) -> BoxFuture<'_, Result> { + let shell = &self.0; + Box::pin(async move { + if shell.closed.load(std::sync::atomic::Ordering::SeqCst) { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!("{method}: the worker {} has stopped", shell.worker_id), + )); + } + if !local_lane_carries(&method) { + return Err(DomainError::before( + ErrorCode::Unsupported, + format!("{method} is not carried by the local lane"), + )); + } + let (tx, rx) = tokio::sync::oneshot::channel(); + shell.admit(method, request, Incoming::Local(attachments), Answer::Local(tx)).await; + Ok(LocalPending(rx)) + }) + } + + fn close(&self) { + self.0.closed.store(true, std::sync::atomic::Ordering::SeqCst); + } +} + /// Registers `service_name` and serves `endpoint` on it until the service ends or Shutdown. pub fn serve( client: flybus::Client, @@ -267,7 +471,30 @@ pub fn serve( let service_name = service.name().to_owned(); let service_incarnation = service.incarnation().to_owned(); let cache = Arc::new(tokio::sync::Mutex::new(ResultCache::new())); - let task = tokio::spawn(run(client.clone(), service, Arc::new(tokio::sync::Mutex::new(endpoint)), cache.clone())); + // Identity and capabilities are fixed for the endpoint's lifetime, so the shell reads them + // once and never takes the endpoint mutex to answer Hello or Status. + let common = Common { + role: endpoint.role(), + capabilities: endpoint.capabilities(), + threads: endpoint.worker_threads(), + extra_ack: endpoint.acknowledge_extra_id(), + }; + let shell = Arc::new(Shell { + client: client.clone(), + session_id: endpoint.session_id(), + methods: endpoint.methods(), + endpoint: Arc::new(tokio::sync::Mutex::new(endpoint)), + cache: cache.clone(), + order: Arc::new(LockOrder::default()), + status: status.clone(), + worker_id: worker_id.clone(), + incarnation_id: incarnation_id.clone(), + admission: tokio::sync::Mutex::new(()), + closed: std::sync::atomic::AtomicBool::new(false), + running: Mutex::new(Vec::new()), + }); + let local = LocalLane(Arc::new(ShellRef(shell.clone()))); + let task = tokio::spawn(run(shell, service, common)); WorkerHandle { worker_id, incarnation_id, @@ -275,35 +502,25 @@ pub fn serve( service_incarnation, status, cache, + local, task, client, } } -async fn run( - client: flybus::Client, - mut service: flybus::Service, - endpoint: Arc>, - cache: Arc>, -) { - // Identity and capabilities are fixed for the endpoint's lifetime, so the shell reads them - // once and never takes the endpoint mutex to answer Hello or Status. - #[allow(clippy::type_complexity)] - let (worker_id, incarnation_id, session_id, role, capabilities, status, methods, threads, extra_ack) = { - let e = endpoint.lock().await; - ( - e.worker_id(), - e.incarnation_id(), - e.session_id(), - e.role(), - e.capabilities(), - e.status_cell(), - e.methods(), - e.worker_threads(), - e.acknowledge_extra_id(), - ) - }; - let mut running: Vec> = Vec::new(); +/// What the bus loop answers without entering the endpoint. +struct Common { + role: Role, + capabilities: Vec, + threads: u64, + extra_ack: Option, +} + +async fn run(shell: Arc>, mut service: flybus::Service, common: Common) { + let Common { role, capabilities, threads, extra_ack } = common; + let (worker_id, incarnation_id, session_id) = + (shell.worker_id.clone(), shell.incarnation_id.clone(), shell.session_id.clone()); + let (status, cache) = (shell.status.clone(), shell.cache.clone()); while let Some(incoming) = service.next().await { let method = incoming.method().to_owned(); let responder = incoming.responder(); @@ -324,8 +541,6 @@ async fn run( continue; } }; - // The contract type already validated the `req-` form when it read the envelope. - let serial = request.request_id.clone(); // The common methods never enter the endpoint mutex, so they answer during a mutation. match method.as_str() { @@ -381,7 +596,12 @@ async fn run( let value = result.to_json(); let outcome = success(&request, &worker_id, &incarnation_id, object(value)); + // The local lane stops with the bus loop: nothing is admitted after a + // Shutdown on either. + shell.closed.store(true, std::sync::atomic::Ordering::SeqCst); let _ = responder.reply(outcome.to_outcome(), &[]).await; + // Admitted mutations still finish and answer. + shell.drain().await; return; } Err(e) => { @@ -399,36 +619,63 @@ async fn run( } _ => {} } + shell + .admit(method, request, Incoming::Bus(Box::new(incoming)), Answer::Bus(responder)) + .await; + } + shell.drain().await; +} - let class = if methods.contains(&method.as_str()) { +impl Shell { + /// Waits until every admitted mutation has answered. + async fn drain(&self) { + let running = std::mem::take(&mut *self.running.lock().expect("never poisoned")); + for task in running { + let _ = task.await; + } + } + + /// Classification, deduplication and the arrival-order ticket for one endpoint request, + /// then its execution in a task of its own. Both lanes come here, one request at a time. + async fn admit( + self: &Arc, + method: String, + request: SessionRpcRequest, + incoming: Incoming, + answer: Answer, + ) { + let (worker_id, incarnation_id) = (&self.worker_id, &self.incarnation_id); + let refuse = |e: DomainError, scope: Option| { + failure(&request.request_id, worker_id, incarnation_id, scope, e) + }; + // One admission at a time across both lanes: the ticket order is the arrival order. + let _admission = self.admission.lock().await; + let _span = crate::profile::span("shell.admit"); + // The contract type already validated the `req-` form when it read the envelope. + let serial = request.request_id.clone(); + let class = if self.methods.contains(&method.as_str()) { classify_default(&method) } else { None }; let Some(class) = class else { - let outcome = failure( - &request.request_id, - &worker_id, - &incarnation_id, - request.scope.clone(), + let outcome = refuse( DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")), + request.scope.clone(), ); - let _ = responder.reply(outcome.to_outcome(), &[]).await; - continue; + answer.send(outcome, &[]).await; + return; }; - let body = match request.body_digest(&method) { + let digest_span = crate::profile::span("shell.digest"); + let body = request.body_digest(&method); + drop(digest_span); + let body = match body { Ok(body) => body, Err(e) => { - let outcome = failure( - &request.request_id, - &worker_id, - &incarnation_id, - request.scope.clone(), - DomainError::invalid(format!("{method}: {e}")), - ); - let _ = responder.reply(outcome.to_outcome(), &[]).await; - continue; + let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone()); + answer.send(outcome, &[]).await; + return; } }; let key = match (class, &request.scope) { @@ -440,18 +687,12 @@ async fn run( worker_id: worker_id.clone(), }, (OpClass::StepMutation, None) => { - let outcome = failure( - &request.request_id, - &worker_id, - &incarnation_id, - None, - DomainError::invalid(format!("{method} requires a scope")), - ); - let _ = responder.reply(outcome.to_outcome(), &[]).await; - continue; + let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None); + answer.send(outcome, &[]).await; + return; } _ => OperationKey { - session_id: session_id.clone(), + session_id: self.session_id.clone(), epoch: id("lifecycle"), step: 0, method: method.clone(), @@ -463,96 +704,169 @@ async fn run( // is dereferenced, because a duplicate may arrive after its input delivery was // consumed and needs only the cached result. let admission = { - let mut c = cache.lock().await; + let mut c = self.cache.lock().await; c.admit(class, &key, serial.clone(), &body) }; match admission { Admission::Replay(reply) => { - let _ = responder.reply(reply.outcome.to_outcome(), &reply.attachments()).await; - continue; + answer.send(reply.outcome.clone(), &reply.artifacts).await; + return; } Admission::Refuse(e) => { - let outcome = failure( - &request.request_id, - &worker_id, - &incarnation_id, - request.scope.clone(), - e, - ); - let _ = responder.reply(outcome.to_outcome(), &[]).await; - continue; + let outcome = refuse(e, request.scope.clone()); + answer.send(outcome, &[]).await; + return; } Admission::Execute => {} } - status.set_active(Some(request.request_id.clone())); + self.status.set_active(Some(request.request_id.clone())); // The mutation runs in its own task so the shell keeps reading. That is what lets an // exact duplicate arriving mid-execution be refused with IN_PROGRESS while the - // original bus call still completes normally. The endpoint mutex, not this loop, + // original call still completes normally. The endpoint mutex, not this loop, // enforces one mutation at a time. + let ticket = self.order.issue(); + let task = tokio::spawn(execute( + self.clone(), + ticket, + Admitted { class, key, serial, body, method, request, incoming }, + answer, + )); + let mut running = self.running.lock().expect("never poisoned"); running.retain(|task| !task.is_finished()); - running.push(tokio::spawn(execute( - client.clone(), - endpoint.clone(), - cache.clone(), - status.clone(), - worker_id.clone(), - incarnation_id.clone(), - class, - key, - serial, - body, - method, - request, - incoming, - ))); - } - for task in running { - let _ = task.await; + running.push(task); } } -/// Runs one admitted mutation, records its reply and answers the bus call. -#[allow(clippy::too_many_arguments)] -async fn execute( - client: flybus::Client, - endpoint: Arc>, - cache: Arc>, - status: StatusCell, - worker_id: Id, - incarnation_id: Id, +/// Admitted mutations take the endpoint's lock in the order they arrived. +/// +/// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in +/// spawn order: without this, a `State.Capture` followed on the wire by the next +/// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken +/// in arrival order, and the lock taken only on the ticket's turn keep the wire's order. +#[derive(Default)] +struct LockOrder { + issued: std::sync::atomic::AtomicU64, + turn: std::sync::atomic::AtomicU64, + changed: tokio::sync::Notify, +} + +impl LockOrder { + fn issue(&self) -> u64 { + self.issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + } + + async fn lock_in_turn<'a, E>( + &self, + ticket: u64, + endpoint: &'a tokio::sync::Mutex, + ) -> tokio::sync::MutexGuard<'a, E> { + loop { + let changed = self.changed.notified(); + if self.turn.load(std::sync::atomic::Ordering::SeqCst) == ticket { + break; + } + changed.await; + } + // Queue on the lock first, then hand the turn on: the next ticket queues behind this + // one on the (fair) mutex. + let lock = endpoint.lock(); + tokio::pin!(lock); + let guard = match futures_poll_once(lock.as_mut()).await { + Some(guard) => guard, + None => { + self.advance(); + return lock.await; + } + }; + self.advance(); + guard + } + + fn advance(&self) { + self.turn.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.changed.notify_waiters(); + } +} + +/// Polls a future once: its output if it is ready, else `None` with the future registered. +async fn futures_poll_once(mut f: F) -> Option { + std::future::poll_fn(|cx| match std::pin::Pin::new(&mut f).poll(cx) { + std::task::Poll::Ready(v) => std::task::Poll::Ready(Some(v)), + std::task::Poll::Pending => std::task::Poll::Ready(None), + }) + .await +} + +/// One admitted request, as `execute` needs it. +struct Admitted { class: OpClass, key: OperationKey, serial: DomainRequestId, body: Digest, method: String, request: SessionRpcRequest, - incoming: flybus::Request, + incoming: Incoming, +} + +/// Runs one admitted mutation, records its reply and answers the call. +async fn execute( + shell: Arc>, + ticket: u64, + admitted: Admitted, + answer: Answer, ) { - let responder = incoming.responder(); + let Admitted { class, key, serial, body, method, request, incoming } = admitted; + let (worker_id, incarnation_id, status, cache) = + (&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache); let outcome = { // One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // never held across a bus round trip taken by anything else. - let mut e = endpoint.lock().await; + let mut e = shell.order.lock_in_turn(ticket, &shell.endpoint).await; + let _span = crate::profile::span("shell.handle"); let ctx = HandlerCtx { method: &method, request: &request, - client: &client, + client: &shell.client, incoming: &incoming, }; e.handle(ctx).await }; + // A deferred reply finishes here, with the endpoint's lock released. + let outcome = match outcome { + Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await, + other => other, + }; + let _span = crate::profile::span("shell.record"); match outcome { - Ok(reply) => { - let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone()); - let mut holds = Vec::with_capacity(reply.artifacts.len()); - for (name, artifact) in &reply.artifacts { - // The cache owns its own hold, so a replay survives the first caller - // consuming its delivery. - match artifact.retain().await { - Ok(hold) => holds.push((name.clone(), hold)), - Err(_) => holds.push((name.clone(), artifact.clone())), - } + Ok(mut reply) => { + let result = std::mem::take(&mut reply.result); + let outcome = success(&request, worker_id, incarnation_id, result); + // The cache owns its own hold on every artifact, so a replay survives the first + // caller consuming its delivery. The holds are independent router round trips, so + // they are taken concurrently; an in-memory artifact is its own hold. + let retains: Vec<_> = reply + .artifacts + .iter() + .map(|(name, artifact)| { + let (name, artifact) = (name.clone(), artifact.clone()); + async move { + if artifact.is_in_memory() { + return (name, artifact); + } + let task = tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }); + task.await.expect("a retain task never panics") + } + }) + .collect(); + let mut holds = Vec::with_capacity(retains.len()); + for retain in retains { + holds.push(retain.await); } let cached = CachedReply::with_artifacts(outcome.clone(), holds); { @@ -564,9 +878,7 @@ async fn execute( } } status.set_completed(request.request_id.clone()); - let attachments: Vec<(&str, &flybus::Artifact)> = - reply.artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect(); - let _ = responder.reply(outcome.to_outcome(), &attachments).await; + answer.send(outcome, &reply.artifacts).await; } Err(e) => { if e.mutation == MutationCertainty::None { @@ -576,8 +888,8 @@ async fn execute( } else { let cached = CachedReply::new(failure_outcome( &request.request_id, - &worker_id, - &incarnation_id, + worker_id, + incarnation_id, request.scope.clone(), e.clone(), )); @@ -592,12 +904,12 @@ async fn execute( status.set_active(None); let outcome = failure( &request.request_id, - &worker_id, - &incarnation_id, + worker_id, + incarnation_id, request.scope.clone(), e, ); - let _ = responder.reply(outcome.to_outcome(), &[]).await; + answer.send(outcome, &[]).await; } } } @@ -627,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/fly-session/tests/common/mod.rs b/services/flysim/crates/fly-session/tests/common/mod.rs index 92e1866..8dd2013 100644 --- a/services/flysim/crates/fly-session/tests/common/mod.rs +++ b/services/flysim/crates/fly-session/tests/common/mod.rs @@ -29,6 +29,15 @@ macro_rules! both_transports { } )* } + // PERF-01: in memory, in-process participants over their local lane. + mod local_lane { + $( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn $name() { + super::$name($crate::common::via_local()).await + } + )* + } }; } @@ -40,6 +49,10 @@ pub fn via_unix() -> Via { Via::Unix } +pub fn via_local() -> Via { + Via::Local +} + /// A started session plus the temporary directory its store lives in. pub struct Fixture { pub dir: tempfile::TempDir, diff --git a/services/flysim/crates/fly-session/tests/failures.rs b/services/flysim/crates/fly-session/tests/failures.rs index 7de2bc1..7a2bb01 100644 --- a/services/flysim/crates/fly-session/tests/failures.rs +++ b/services/flysim/crates/fly-session/tests/failures.rs @@ -282,6 +282,7 @@ async fn a_reply_from_another_incarnation_is_rejected(via: Via) { bus_incarnation: restarted.service_incarnation.clone(), worker_id: fly_b(), domain_incarnation: old.domain_incarnation.clone(), + local: None, }; assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone())); let err = within("status", f.harness.coordinator.status(&stale)) diff --git a/services/flysim/crates/fly-session/tests/media.rs b/services/flysim/crates/fly-session/tests/media.rs index 220221c..69f2144 100644 --- a/services/flysim/crates/fly-session/tests/media.rs +++ b/services/flysim/crates/fly-session/tests/media.rs @@ -136,7 +136,21 @@ async fn one_shared_image_reaches_both_agents_through_owned_attachments(via: Via "one snapshot carries the whole multi-agent session" ); let last = a.last().expect("an entry per boundary"); - assert_eq!(published.view.pixels.artifact_id, last.artifact_id); + if via == Via::Local { + // Over the local lane the agents' handle is in memory, in no router's store, so + // publication carries a sealed copy of the same bytes (the PERF-01 amendment). + assert_ne!(published.view.pixels.artifact_id, last.artifact_id); + let held = f + .harness + .coordinator + .media_bytes(&fly_session::media::view_attachment(&published.view.view_id)) + .await + .unwrap() + .expect("the boundary's frame"); + assert_eq!(published.artifact.read_all().await.unwrap(), held, "the same bytes"); + } else { + assert_eq!(published.view.pixels.artifact_id, last.artifact_id); + } assert_eq!(published.view.produced_step, last.produced_step); let bytes = published.artifact.read_all().await.expect("the published frame"); assert_eq!(bytes.len() as u64, VIEW_WIDTH * VIEW_HEIGHT * 4); @@ -395,12 +409,20 @@ async fn one_audio_chunk_per_boundary_with_an_exact_sample_budget(via: Via) { let published = frame_at(&mut spectator, STEPS).await; let (published_chunk, artifact) = published.audio.first().expect("the published chunk"); - assert_eq!(published_chunk.samples, chunk.samples); - assert_eq!( - artifact.reference().artifact_id, - chunk.samples.artifact_id, - "the same owned handle is published, not a copy" - ); + if via == Via::Local { + // A sealed copy of the in-memory chunk (the PERF-01 amendment): same bytes, same + // position, another artifact. + assert_eq!(published_chunk.first_sample, chunk.first_sample); + assert_eq!(published_chunk.samples.byte_length, chunk.samples.byte_length); + assert_ne!(artifact.reference().artifact_id, chunk.samples.artifact_id); + } else { + assert_eq!(published_chunk.samples, chunk.samples); + assert_eq!( + artifact.reference().artifact_id, + chunk.samples.artifact_id, + "the same owned handle is published, not a copy" + ); + } let bytes = artifact.read_all().await.expect("the published chunk"); assert_eq!(bytes.len() as u64, per_step * CHANNELS * 4); require_finite_samples(&bytes).expect("native samples are finite f32"); diff --git a/services/flysim/crates/fly-session/tests/processes.rs b/services/flysim/crates/fly-session/tests/processes.rs index 76f853d..7a48d20 100644 --- a/services/flysim/crates/fly-session/tests/processes.rs +++ b/services/flysim/crates/fly-session/tests/processes.rs @@ -905,6 +905,7 @@ async fn an_old_worker_reply_after_a_restart_is_rejected_on_stale_epoch_or_incar bus_incarnation: restarted.service_incarnation.clone(), worker_id: fly_b(), domain_incarnation: old.domain_incarnation.clone(), + local: None, }; assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone())); let err = within("status", f.harness.coordinator.status(&stale)) diff --git a/services/flysim/crates/fly-session/tests/session.rs b/services/flysim/crates/fly-session/tests/session.rs index fcce346..1c40fe5 100644 --- a/services/flysim/crates/fly-session/tests/session.rs +++ b/services/flysim/crates/fly-session/tests/session.rs @@ -25,7 +25,7 @@ both_transports!( the_committed_snapshot_names_the_boundary_that_just_ended, a_terminal_episode_pauses_at_its_own_boundary, a_rollback_request_without_a_declared_policy_fails_the_epoch, - a_declared_rollback_policy_holds_the_session_at_its_boundary, + a_declared_rollback_policy_needs_participants_that_apply_it, status_answers_with_the_committed_boundary, a_worker_refuses_a_second_initialize, a_single_agent_composition_runs_the_same_transaction, @@ -329,9 +329,13 @@ async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via) f.shutdown().await; } -/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and -/// the session holds at its boundary with the request recorded, for the policy to run. -async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) { +/// With `legacy-ratchet-rollback-v1` declared the coordinator runs the policy itself +/// (`step-v1` section 6 amendment; TASK-01), so a composition may only declare it over +/// participants that can apply it: agents that answer `Agent.Rollback` and a world with +/// `gameboy-slots-v1`. The synthetic agents answer neither, so the session never starts -- +/// rather than accepting a rollback request it cannot apply. (Until TASK-01 the declared request +/// paused the session at its boundary.) +async fn a_declared_rollback_policy_needs_participants_that_apply_it(via: Via) { let config = HarnessConfig { terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), ..HarnessConfig::default() @@ -342,13 +346,11 @@ async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) .declare_rollback_policy("legacy-ratchet-rollback-v1") .unwrap(); assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err()); - within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); - let reports = within("run", f.harness.coordinator.run(4)).await.unwrap(); - assert_eq!(reports.len(), 2); - assert!(!f.harness.coordinator.is_fenced()); - assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2)); - let request = f.harness.coordinator.episode_request().unwrap(); - assert_eq!(request.kind, EpisodeRequestKind::Rollback); + let err = within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap_err(); + assert_eq!(err.error.code, ErrorCode::Unsupported, "{}", err.error.message); + assert!(err.error.message.contains("Agent.Rollback"), "{}", err.error.message); + assert!(f.harness.coordinator.is_fenced()); + assert!(f.harness.coordinator.episode_request().is_none()); f.shutdown().await; } diff --git a/services/flysim/crates/flybrain-core/src/lif.rs b/services/flysim/crates/flybrain-core/src/lif.rs index beb9496..11ebfdf 100644 --- a/services/flysim/crates/flybrain-core/src/lif.rs +++ b/services/flysim/crates/flybrain-core/src/lif.rs @@ -509,6 +509,18 @@ impl LifNetwork { } /// Run `milliseconds` ticks and return the total spike count. + /// The neurons the last CPU tick emitted, when `count` is what that one-tick + /// [`LifNetwork::step`] returned: exactly the neurons whose `last_spike_ms` it stamped, in the + /// sweep's order. `None` while the GPU backend runs the ticks, whose host copy of the list is + /// not kept per tick. A read-only view; it changes nothing a tick computes. + pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> { + #[cfg(feature = "cuda")] + if self.cuda.is_some() { + return None; + } + self.spikes.get(..count) + } + pub fn step(&mut self, milliseconds: u64) -> u64 { // The GPU backend runs the same ticks in batches and replays the host-side phases; with the // feature off this compiles to nothing and the loop below is the whole method. diff --git a/services/flysim/crates/flybrain-core/tests/tick_spikes.rs b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs new file mode 100644 index 0000000..83c01d6 --- /dev/null +++ b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs @@ -0,0 +1,54 @@ +//! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons +//! that tick stamped in `last_spike_ms`, so the union of the lists over a window is the window +//! bitset a scan of `last_spike_ms` gives. + +mod common; + +use std::collections::BTreeSet; +use std::sync::Arc; + +use common::visual_toy_dataset; +use flybrain_core::lif::{LifConfig, LifNetwork}; +use flybrain_core::plasticity::PlasticityConfig; + +#[test] +fn a_ticks_list_is_the_neurons_it_stamped_and_windows_agree_with_the_scan() { + let config = LifConfig { noise_amount: 40.0, ..LifConfig::default() }; + let mut network = + LifNetwork::new(Arc::new(visual_toy_dataset()), config, PlasticityConfig::default()) + .expect("a network"); + network.stimulate(200.0); + let neurons = network.last_spike_ms.len(); + let mut spiking_ticks = 0; + for window in 0..200 { + let since = network.ms; + let mut union = vec![0u8; neurons.div_ceil(8)]; + for _ in 0..(16 + window % 2) { + let before = network.ms; + let count = network.step(1) as usize; + let list: BTreeSet = network + .tick_spikes(count) + .expect("the CPU kernel keeps its list") + .iter() + .copied() + .collect(); + assert_eq!(list.len(), count, "a neuron spikes at most once a tick"); + let stamped: BTreeSet = (0..neurons as u32) + .filter(|&n| network.last_spike_ms[n as usize] == before) + .collect(); + assert_eq!(list, stamped); + spiking_ticks += usize::from(count > 0); + for n in list { + union[n as usize >> 3] |= 1 << (n & 7); + } + } + let mut scan = vec![0u8; neurons.div_ceil(8)]; + for (n, last) in network.last_spike_ms.iter().enumerate() { + if *last >= since { + scan[n >> 3] |= 1 << (n & 7); + } + } + assert_eq!(union, scan); + } + assert!(spiking_ticks > 0, "the fixture must spike for the test to mean anything"); +} diff --git a/services/flysim/crates/flybus/src/client/handles.rs b/services/flysim/crates/flybus/src/client/handles.rs index b10674b..6442377 100644 --- a/services/flysim/crates/flybus/src/client/handles.rs +++ b/services/flysim/crates/flybus/src/client/handles.rs @@ -37,17 +37,25 @@ impl Drop for OwnerGuard { pub(crate) fn attachment_list( list: &[(&str, &Artifact)], -) -> (Vec, Vec>) { - let atts = list - .iter() - .map(|(name, a)| Attachment { +) -> Result<(Vec, Vec>), BusError> { + let mut atts = Vec::with_capacity(list.len()); + let mut keep = Vec::with_capacity(list.len()); + for (name, a) in list { + let Holder::Bus(owner) = &a.holder else { + // An in-memory artifact is not in any router's store, so no message may name it. + return Err(BusError::invalid(format!( + "attachment {name:?} is an in-memory artifact; seal a copy into the store first" + )) + .with_dispatch(Dispatch::NotDispatched)); + }; + atts.push(Attachment { name: (*name).to_owned(), reference: a.reference.as_ref().clone(), - owner_id: a.owner.id.clone(), - }) - .collect(); - let keep = list.iter().map(|(_, a)| a.owner.clone()).collect(); - (atts, keep) + owner_id: owner.id.clone(), + }); + keep.push(owner.clone()); + } + Ok((atts, keep)) } fn find( @@ -59,7 +67,7 @@ fn find( .find(|(n, _)| n == name) .map(|(_, r)| Artifact { reference: Arc::new(r.clone()), - owner: guard.clone(), + holder: Holder::Bus(guard.clone()), }) .ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}"))) } @@ -69,43 +77,129 @@ fn find( /// A read-only, cloneable handle on an immutable artifact. While any clone (or a file opened /// from it) lives, the owner it came from keeps the bytes alive. +/// +/// An artifact is either sealed in a router's store (every handle the bus hands out) or an +/// **in-memory** artifact ([`Artifact::in_memory`]): an immutable buffer in this address space +/// that no router knows about. The second kind is for participants that share one process and +/// hand each other buffers directly, without a bus message (PERF-01's in-process local lane); +/// it reads, clones and retains like any other handle, and it is refused as a bus attachment, +/// so it can never be named by a message a router would have to resolve. #[derive(Clone)] pub struct Artifact { pub(crate) reference: Arc, - pub(crate) owner: Arc, + pub(crate) holder: Holder, } +/// What keeps an artifact's bytes alive. +#[derive(Clone)] +pub(crate) enum Holder { + /// A router-side owner: a delivery or an explicit hold. + Bus(Arc), + /// The bytes themselves. + Memory(Arc<[u8]>), +} + +/// The store id every in-memory artifact reference carries. No router issues it: a router's +/// store ids are `store-`. +pub const IN_MEMORY_STORE_ID: &str = "in-memory"; + impl std::fmt::Debug for Artifact { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Artifact") .field("reference", &self.reference) - .field("owner", &self.owner.id) + .field("owner", &self.owner_id()) .finish() } } impl Artifact { + /// An immutable in-memory artifact holding `bytes`, with no digest. Nothing is copied. + pub fn in_memory(content_type: &str, bytes: impl Into>) -> Artifact { + use std::sync::atomic::{AtomicU64, Ordering}; + static SERIAL: AtomicU64 = AtomicU64::new(0); + let bytes: Arc<[u8]> = bytes.into(); + let serial = SERIAL.fetch_add(1, Ordering::Relaxed) + 1; + Artifact { + reference: Arc::new(ArtifactRef { + store_id: IN_MEMORY_STORE_ID.to_owned(), + artifact_id: format!("m-{serial}"), + generation: GENERATION, + byte_length: bytes.len() as u64, + content_type: content_type.to_owned(), + digest: None, + }), + holder: Holder::Memory(bytes), + } + } + pub fn reference(&self) -> &ArtifactRef { &self.reference } + /// The same artifact as an in-memory handle with the **same reference**: a sealed one is + /// read once, an in-memory one is returned as it is. For a caller in the owner's process + /// that must keep the bytes without holding the owner's connection (a handle is only valid + /// as an attachment on the connection that owns it). + pub async fn to_memory(&self) -> Result { + if self.is_in_memory() { + return Ok(self.clone()); + } + let bytes = self.read_all().await?; + if bytes.len() as u64 != self.reference.byte_length { + return Err(BusError::new( + ErrorCode::ArtifactMismatch, + "sealed bytes disagree with the reference's length", + )); + } + Ok(Artifact { + reference: self.reference.clone(), + holder: Holder::Memory(bytes.into()), + }) + } + + /// True for an [`Artifact::in_memory`] handle. + pub fn is_in_memory(&self) -> bool { + matches!(self.holder, Holder::Memory(_)) + } + + /// The bytes of an in-memory artifact, without a copy; `None` for a sealed one. + pub fn memory(&self) -> Option<&Arc<[u8]>> { + match &self.holder { + Holder::Memory(bytes) => Some(bytes), + Holder::Bus(_) => None, + } + } + /// The router-side owner this handle rides on: a delivery id or an explicit hold id. + /// An in-memory artifact has none and reports its store id. pub fn owner_id(&self) -> &str { - &self.owner.id + match &self.holder { + Holder::Bus(owner) => &owner.id, + Holder::Memory(_) => IN_MEMORY_STORE_ID, + } } /// Opens the sealed bytes read-only. The file keeps this handle (and so its owner) alive. pub async fn open(&self) -> Result { + let owner = match &self.holder { + Holder::Bus(owner) => owner, + Holder::Memory(bytes) => { + return Ok(ArtifactFile { + file: Backing::Memory(io::Cursor::new(bytes.clone())), + _artifact: self.clone(), + }); + } + }; let mut body = Map::new(); body.insert("ref".into(), self.reference.to_json()); - body.insert("ownerId".into(), self.owner.id.clone().into()); - let shared = &self.owner.conn.shared; + body.insert("ownerId".into(), owner.id.clone().into()); + let shared = &owner.conn.shared; let reply = shared .command( "artifact.open", body, Vec::new(), - vec![self.owner.clone()], + vec![owner.clone()], Hook::None, ) .await?; @@ -130,13 +224,16 @@ impl Artifact { )); } Ok(ArtifactFile { - file, + file: Backing::File(file), _artifact: self.clone(), }) } - /// Reads the whole artifact (on the blocking pool). + /// Reads the whole artifact (on the blocking pool; an in-memory one is copied in place). pub async fn read_all(&self) -> Result, BusError> { + if let Holder::Memory(bytes) = &self.holder { + return Ok(bytes.to_vec()); + } let mut file = self.open().await?; tokio::task::spawn_blocking(move || { let mut out = Vec::with_capacity(file.len() as usize); @@ -148,24 +245,29 @@ impl Artifact { } /// Creates an independent explicit hold, so the bytes outlive this handle's delivery. + /// An in-memory artifact's hold is another handle on the same bytes. pub async fn retain(&self) -> Result { + let owner = match &self.holder { + Holder::Bus(owner) => owner, + Holder::Memory(_) => return Ok(self.clone()), + }; let mut body = Map::new(); body.insert("ref".into(), self.reference.to_json()); - body.insert("ownerId".into(), self.owner.id.clone().into()); - let shared = &self.owner.conn.shared; + body.insert("ownerId".into(), owner.id.clone().into()); + let shared = &owner.conn.shared; let reply = shared .command( "artifact.retain", body, Vec::new(), - vec![self.owner.clone()], + vec![owner.clone()], Hook::Owner, ) .await?; match reply.extra { Extra::Owner(owner) => Ok(Artifact { reference: self.reference.clone(), - owner, + holder: Holder::Bus(owner), }), _ => Err(BusError::lost("retain reply without an owner")), } @@ -174,10 +276,15 @@ impl Artifact { /// An open, read-only sealed file. Holds its [`Artifact`]. pub struct ArtifactFile { - file: File, + file: Backing, _artifact: Artifact, } +enum Backing { + File(File), + Memory(io::Cursor>), +} + impl ArtifactFile { pub fn len(&self) -> u64 { self._artifact.reference.byte_length @@ -194,13 +301,19 @@ impl ArtifactFile { impl Read for ArtifactFile { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.file.read(buf) + match &mut self.file { + Backing::File(file) => file.read(buf), + Backing::Memory(cursor) => cursor.read(buf), + } } } impl Seek for ArtifactFile { fn seek(&mut self, pos: SeekFrom) -> io::Result { - self.file.seek(pos) + match &mut self.file { + Backing::File(file) => file.seek(pos), + Backing::Memory(cursor) => cursor.seek(pos), + } } } @@ -251,7 +364,7 @@ impl ArtifactWriter { let reference = ArtifactRef::from_json(Fields::of(&reply.value, "reply").value("ref")?)?; Ok(Artifact { reference: Arc::new(reference), - owner: self.owner.clone(), + holder: Holder::Bus(self.owner.clone()), }) } } @@ -401,7 +514,7 @@ impl Responder { outcome: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let mut body = Map::new(); body.insert("callId".into(), self.call_id.clone().into()); body.insert( diff --git a/services/flysim/crates/flybus/src/client/mod.rs b/services/flysim/crates/flybus/src/client/mod.rs index fb043f3..1ef0a80 100644 --- a/services/flysim/crates/flybus/src/client/mod.rs +++ b/services/flysim/crates/flybus/src/client/mod.rs @@ -14,7 +14,7 @@ use tokio::sync::oneshot; use handles::attachment_list; pub use handles::{ - Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder, + IN_MEMORY_STORE_ID, Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder, RpcResult, Service, Subscription, }; use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared}; @@ -361,7 +361,7 @@ impl Client { payload: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let (tx, rx) = oneshot::channel(); let (reply_tx, reply_rx) = oneshot::channel(); let shared = self.shared(); @@ -522,7 +522,7 @@ impl Client { payload: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let mut body = Map::new(); body.insert("topic".into(), topic.into()); body.insert("payload".into(), Value::Object(payload)); diff --git a/services/flysim/crates/flybus/src/lib.rs b/services/flysim/crates/flybus/src/lib.rs index fd8b4f9..fc19bc1 100644 --- a/services/flysim/crates/flybus/src/lib.rs +++ b/services/flysim/crates/flybus/src/lib.rs @@ -25,7 +25,7 @@ mod store; mod transport; pub use client::{ - Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, Message, + Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message, Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service, ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo, }; diff --git a/services/flysim/crates/flysim/src/frame.rs b/services/flysim/crates/flysim/src/frame.rs index d916a56..0eb5cee 100644 --- a/services/flysim/crates/flysim/src/frame.rs +++ b/services/flysim/crates/flysim/src/frame.rs @@ -54,6 +54,38 @@ pub struct Parts<'a> { pub macros: Option<&'a mut MacroLayer>, } +/// The ledgers after a boundary as one canonical string: the adapter's export (its lifetime +/// ledgers), the ratchet's state and whether it holds a snapshot, and the macro layer's observable +/// state -- scene, bound channels, running macro, outcome counts, "nearer the objective". +/// +/// This is the one definition both runtimes use: `FLY_TRACE_LEDGERS` digests it here, and the +/// session runtime's task (`fly-legacy-session::task::ledgers_of`) computes it from its own parts, +/// which is how the shadow run holds the executor's ledgers -- which no checkpoint carries -- to +/// the live loop's (SHADOW-01). Reading it changes nothing. +pub fn ledgers_string( + adapter: &dyn GameAdapter, + ratchet: &Ratchet, + macros: Option<&MacroLayer>, +) -> String { + let executor = match macros { + Some(layer) => serde_json::json!({ + "scene": layer.scene_name(), + "bound": layer.bound_channels(), + "running": layer.running(), + "counts": format!("{:?}", layer.counts()), + "nearer": layer.nearer_the_objective(), + }), + None => serde_json::Value::Null, + }; + serde_json::json!({ + "adapter": adapter.export_state(), + "ratchet": serde_json::to_value(ratchet.state).expect("a ratchet state serializes"), + "slot": ratchet.snapshot.is_some(), + "executor": executor, + }) + .to_string() +} + /// Where a host may look in, or time a phase. Every method defaults to nothing. /// /// The stream's loop uses [`FrameObserver::after`] for its per-phase profile and nothing else. A @@ -654,6 +686,15 @@ impl LegacyFrame { } else { None }; + if let Some(trace) = self.trace.as_mut() + && trace.wants_ledgers() + { + trace.ledgers(&ledgers_string( + &*parts.adapter, + parts.ratchet, + parts.macros.as_deref(), + )); + } Ok(Boundary { captured: saved, rollback, 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/services/flysim/crates/flysim/src/trace.rs b/services/flysim/crates/flysim/src/trace.rs index 3cd9abf..6464c11 100644 --- a/services/flysim/crates/flysim/src/trace.rs +++ b/services/flysim/crates/flysim/src/trace.rs @@ -29,6 +29,28 @@ //! Wall time is never written, so a run with the periodic checkpoint intervals pushed out of the //! way produces the same file twice. Off by default; when off, nothing here is constructed and the //! loop pays one `Option` test per hook. +//! +//! **The shadow run's input (SHADOW-01).** The trace is also what the shadow run +//! (`fly-legacy-session::shadow`) follows beside the live service, so three switches serve it. +//! None changes a line's behaviour fields or anything the fly does: +//! +//! - `FLY_TRACE_DIR=` writes one file per process, `trace--.jsonl`, +//! instead of the one `FLY_TRACE` path a restart would truncate. File names sort in start order; +//! a process's file ends where the next one begins. +//! - `FLY_TRACE_MAX_BYTES` caps one file (default 4 GiB in directory mode, none otherwise). At the +//! cap the recorder writes `{"truncated":true}` and stops; the loop runs on untouched. +//! - *A consumer must be alive* (directory mode). The shadow touches `/consumer` every 30 s. +//! A process starts no trace when that file is missing or older than +//! `FLY_TRACE_CONSUMER_STALE_SECONDS` (default 600), and a running one checks it once a minute +//! of frames and stops the same way as at the cap, with `"reason":"no-consumer"`. A dead or +//! diverged shadow therefore turns the trace off by itself, with no root action and no restart. +//! - *The directory is bounded* (directory mode). Before a process creates its file it deletes +//! the oldest `trace-*.jsonl` until the ones left and the new file's cap fit in +//! `FLY_TRACE_DIR_MAX_BYTES` (default 8 GiB). The shadow deletes each file once compared. +//! - `FLY_TRACE_LEDGERS=` adds `ledgersDigest` to every transition whose `step` is a multiple +//! of `n`: the SHA-256 of [`crate::frame::ledgers_string`] after the boundary (adapter export, +//! ratchet, slot, executor scene/bound/running/counts/nearer). `1` is every transition. The +//! header then carries `ledgersEvery`. use std::fs::File; use std::io::{BufWriter, Write}; @@ -48,6 +70,79 @@ pub const FORMAT: &str = "flysim-legacy-frame-trace-v1"; /// The environment variable that turns the trace on. pub const ENV: &str = "FLY_TRACE"; +/// One file per process in this directory (SHADOW-01). +pub const DIR_ENV: &str = "FLY_TRACE_DIR"; + +/// The per-file byte cap. +pub const MAX_BYTES_ENV: &str = "FLY_TRACE_MAX_BYTES"; + +/// The ledger digest's period in transitions. +pub const LEDGERS_ENV: &str = "FLY_TRACE_LEDGERS"; + +/// The default per-file cap in directory mode: about 23 hours of stream. +pub const DEFAULT_DIR_MAX_BYTES: u64 = 4 << 30; + +/// The consumer's heartbeat file in [`DIR_ENV`] mode. +pub const CONSUMER_FILE: &str = "consumer"; + +/// How old the heartbeat may be (seconds). +pub const CONSUMER_STALE_ENV: &str = "FLY_TRACE_CONSUMER_STALE_SECONDS"; +pub const DEFAULT_CONSUMER_STALE_SECONDS: u64 = 600; + +/// The cap over every trace file in the directory. +pub const DIR_MAX_BYTES_ENV: &str = "FLY_TRACE_DIR_MAX_BYTES"; +pub const DEFAULT_DIR_TOTAL_BYTES: u64 = 8 << 30; + +/// Transitions between two heartbeat checks: about a minute of frames. +const CONSUMER_CHECK_EVERY: u64 = 3_600; + +/// Whether `dir`'s consumer heartbeat is at most `stale` old. +pub fn consumer_alive(dir: &Path, stale: std::time::Duration) -> bool { + std::fs::metadata(dir.join(CONSUMER_FILE)) + .and_then(|m| m.modified()) + .ok() + // A heartbeat dated ahead of this clock (a clock stepped back) is fresh, not missing. + .map(|t| { + std::time::SystemTime::now() + .duration_since(t) + .unwrap_or_default() + }) + .is_some_and(|age| age <= stale) +} + +/// Deletes the oldest trace files in `dir` until those left total at most `keep` bytes. +pub fn prune_dir(dir: &Path, keep: u64) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + let mut files: Vec<(std::path::PathBuf, u64)> = entries + .flatten() + .filter(|e| { + e.file_name() + .to_str() + .is_some_and(|n| n.starts_with("trace-") && n.ends_with(".jsonl")) + }) + .filter_map(|e| Some((e.path(), e.metadata().ok()?.len()))) + .collect(); + files.sort(); + let mut total: u64 = files.iter().map(|(_, len)| len).sum(); + for (path, len) in files { + if total <= keep { + break; + } + if std::fs::remove_file(&path).is_ok() { + tracing::warn!(path = %path.display(), "removed an old frame trace to bound its directory"); + total -= len; + } + } +} + +/// The per-process file name in [`DIR_ENV`] mode: start wall time (13 digits, so names sort in +/// start order) and pid. +pub fn dir_file_name(wall_ms: u64, pid: u32) -> String { + format!("trace-{wall_ms:013}-{pid}.jsonl") +} + /// The ratchet's one slot, as the legacy composition declares it (legacy-gameboy-v1 section 9). pub const SLOT: &str = "best"; @@ -122,6 +217,7 @@ struct Record { rank: u32, boundary_actions: Vec, captures: Vec, + ledgers: Option, } /// The recorder. The loop calls it at fixed points of the frame order; it holds the transition @@ -137,21 +233,100 @@ pub struct FrameTrace { admissions: Vec, /// Brain clock before this transition's ticks, the lower edge of its spike window. ms_before: f64, + /// Bytes written so far, and the cap (`FLY_TRACE_MAX_BYTES`). + written: u64, + max_bytes: Option, + /// Set once the cap was reached: nothing more is written. + stopped: bool, + /// `FLY_TRACE_LEDGERS`: a ledger digest every this many transitions. + ledgers_every: Option, + /// Directory mode: the directory whose consumer heartbeat keeps the trace on, and its limit. + consumer: Option<(std::path::PathBuf, std::time::Duration)>, + transitions: u64, } impl FrameTrace { /// `FLY_TRACE`, if it is set and non-empty. A path that cannot be created is an error rather /// than a silent run without the trace that was asked for. + /// + /// `FLY_TRACE_DIR` (one file per process) wins over `FLY_TRACE`; `FLY_TRACE_MAX_BYTES` and + /// `FLY_TRACE_LEDGERS` apply to either. pub fn from_env() -> std::io::Result> { - match std::env::var_os(ENV) { - Some(path) if !path.is_empty() => Self::create(Path::new(&path)).map(Some), - _ => Ok(None), + let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty()); + let number = |name: &str| -> std::io::Result> { + match var(name) { + None => Ok(None), + Some(value) => value + .to_str() + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| *v > 0) + .map(Some) + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{name} must be a positive integer"), + ) + }), + } + }; + let ledgers_every = number(LEDGERS_ENV)?; + let max_bytes = number(MAX_BYTES_ENV)?; + if let Some(dir) = var(DIR_ENV) { + let dir = Path::new(&dir); + let stale = std::time::Duration::from_secs( + number(CONSUMER_STALE_ENV)?.unwrap_or(DEFAULT_CONSUMER_STALE_SECONDS), + ); + if !consumer_alive(dir, stale) { + tracing::warn!( + dir = %dir.display(), + "FLY_TRACE_DIR is set but no consumer is alive there: no frame trace this run" + ); + return Ok(None); + } + let cap = max_bytes.unwrap_or(DEFAULT_DIR_MAX_BYTES); + let total = number(DIR_MAX_BYTES_ENV)?.unwrap_or(DEFAULT_DIR_TOTAL_BYTES); + prune_dir(dir, total.saturating_sub(cap)); + let wall_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + let path = dir.join(dir_file_name(wall_ms, std::process::id())); + // A trace the live service cannot create (a full disk, a missing directory, its + // permissions) never stops the live fly from starting: it runs untraced, and the + // shadow, which checks every boot header in the sugar journal against the trace + // files, reports that process as a coverage gap and fails its verdict. + let mut trace = match Self::create_with(&path, Some(cap), ledgers_every) { + Ok(trace) => trace, + Err(error) => { + tracing::error!(%error, path = %path.display(), "could not create the frame trace: this run is untraced"); + return Ok(None); + } + }; + trace.consumer = Some((dir.to_owned(), stale)); + return Ok(Some(trace)); + } + match var(ENV) { + Some(path) => Self::create_with(Path::new(&path), max_bytes, ledgers_every).map(Some), + None => Ok(None), } } pub fn create(path: &Path) -> std::io::Result { + Self::create_with(path, None, None) + } + + /// A trace with a byte cap and a ledger digest period (see the module notes). + pub fn create_with( + path: &Path, + max_bytes: Option, + ledgers_every: Option, + ) -> std::io::Result { let mut out = BufWriter::with_capacity(1 << 20, File::create(path)?); - writeln!(out, "{}", json!({ "format": FORMAT }))?; + let header = match ledgers_every { + Some(every) => json!({ "format": FORMAT, "ledgersEvery": every }), + None => json!({ "format": FORMAT }), + }; + let header = header.to_string(); + writeln!(out, "{header}")?; Ok(Self { out, initial: Vec::new(), @@ -159,13 +334,63 @@ impl FrameTrace { open: None, admissions: Vec::new(), ms_before: 0.0, + written: header.len() as u64 + 1, + max_bytes, + stopped: false, + ledgers_every, + consumer: None, + transitions: 0, }) } - fn write(&mut self, value: &Value) { - if let Err(error) = writeln!(self.out, "{value}") { + /// Stops the trace: one marker line, then nothing more. The loop is unaffected. + fn stop(&mut self, reason: &str) { + if self.stopped { + return; + } + self.stopped = true; + if let Err(error) = writeln!( + self.out, + "{}", + json!({ "truncated": true, "reason": reason }) + ) { tracing::warn!(%error, "could not write the frame trace"); } + let _ = self.out.flush(); + tracing::warn!(reason, "the frame trace stopped"); + } + + fn write(&mut self, value: &Value) { + if self.stopped { + return; + } + let line = value.to_string(); + let len = line.len() as u64 + 1; + if let Some(cap) = self.max_bytes + && self.written + len > cap + { + self.stop("byte-cap"); + return; + } + self.written += len; + if let Err(error) = writeln!(self.out, "{line}") { + tracing::warn!(%error, "could not write the frame trace"); + } + } + + /// Whether the open transition takes a ledger digest (`FLY_TRACE_LEDGERS`). + pub fn wants_ledgers(&self) -> bool { + match (self.ledgers_every, self.open.as_ref()) { + (Some(every), Some(record)) => !self.stopped && record.step % every == 0, + _ => false, + } + } + + /// The ledgers after the boundary, as [`crate::frame::ledgers_string`] writes them. + pub fn ledgers(&mut self, ledgers: &str) { + if let Some(record) = self.open.as_mut() { + record.ledgers = Some(sha256_hex(ledgers.as_bytes())); + } } /// Sugar admitted at the top of the frame, before the brain ticks. @@ -198,6 +423,15 @@ impl FrameTrace { /// Transition `step -> step + 1` begins: the previous one is complete. pub fn begin(&mut self, step: u64, ms_before: f64) { self.flush_open(); + self.transitions += 1; + let consumer_gone = self.transitions.is_multiple_of(CONSUMER_CHECK_EVERY) + && self + .consumer + .as_ref() + .is_some_and(|(dir, stale)| !consumer_alive(dir, *stale)); + if consumer_gone { + self.stop("no-consumer"); + } if let Some(start) = self.initial_step.take() { let initial = std::mem::take(&mut self.initial); self.write(&json!({ @@ -309,7 +543,7 @@ impl FrameTrace { let Some(record) = self.open.take() else { return; }; - let line = json!({ + let mut line = json!({ "behaviour": { "step": record.step.to_string(), "admissions": record.admissions, @@ -331,6 +565,9 @@ impl FrameTrace { }, "operational": { "captures": record.captures }, }); + if let Some(digest) = record.ledgers { + line["behaviour"]["ledgersDigest"] = Value::String(digest); + } self.write(&line); } @@ -353,6 +590,122 @@ impl Drop for FrameTrace { mod tests { use super::*; + fn lines(path: &Path) -> Vec { + std::fs::read_to_string(path) + .unwrap() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() + } + + #[test] + fn the_directory_is_bounded_and_needs_a_live_consumer() { + let dir = std::env::temp_dir().join(format!("fly-trace-dir-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let minute = std::time::Duration::from_secs(60); + assert!(!consumer_alive(&dir, minute), "no heartbeat file"); + std::fs::write(dir.join(CONSUMER_FILE), b"x").unwrap(); + assert!(consumer_alive(&dir, minute)); + for (name, len) in [ + ("trace-1-1.jsonl", 100), + ("trace-2-1.jsonl", 100), + ("trace-3-1.jsonl", 100), + ] { + std::fs::write(dir.join(name), vec![b'x'; len]).unwrap(); + } + std::fs::write(dir.join("other.txt"), vec![b'x'; 1000]).unwrap(); + prune_dir(&dir, 150); + assert!(!dir.join("trace-1-1.jsonl").exists()); + assert!(!dir.join("trace-2-1.jsonl").exists()); + assert!(dir.join("trace-3-1.jsonl").exists()); + assert!( + dir.join("other.txt").exists(), + "only trace files are pruned" + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_running_trace_stops_when_its_consumer_goes_away() { + let dir = std::env::temp_dir().join(format!("fly-trace-gone-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(CONSUMER_FILE), b"x").unwrap(); + let path = dir.join("t.jsonl"); + let mut trace = FrameTrace::create_with(&path, None, None).unwrap(); + trace.consumer = Some((dir.clone(), std::time::Duration::from_secs(600))); + for step in 0..CONSUMER_CHECK_EVERY { + trace.begin(step, 0.0); + } + assert!(!trace.stopped, "a live consumer keeps it on"); + std::fs::remove_file(dir.join(CONSUMER_FILE)).unwrap(); + for step in CONSUMER_CHECK_EVERY..3 * CONSUMER_CHECK_EVERY { + trace.begin(step, 0.0); + } + trace.finish(); + drop(trace); + let all = lines(&path); + assert_eq!(all.last().unwrap()["reason"], "no-consumer"); + assert!(all.len() < (2 * CONSUMER_CHECK_EVERY) as usize + 3); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn directory_files_sort_in_start_order() { + assert!(dir_file_name(999, 70_000) < dir_file_name(1000, 5)); + assert_eq!(dir_file_name(1, 2), "trace-0000000000001-2.jsonl"); + } + + #[test] + fn the_byte_cap_ends_the_file_with_a_marker_and_nothing_after() { + let dir = std::env::temp_dir().join(format!("fly-trace-cap-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.jsonl"); + let mut trace = FrameTrace::create_with(&path, Some(1500), None).unwrap(); + for step in 0..40 { + trace.begin(step, 0.0); + } + trace.finish(); + drop(trace); + let all = lines(&path); + assert_eq!(all.first().unwrap()["format"], FORMAT); + assert_eq!(all.last().unwrap()["truncated"], true); + assert_eq!(all.last().unwrap()["reason"], "byte-cap"); + assert!(all.len() > 2 && all.len() < 40); + let size = std::fs::metadata(&path).unwrap().len(); + assert!(size <= 1500 + 20, "{size}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn ledger_digests_every_nth_step() { + let dir = std::env::temp_dir().join(format!("fly-trace-ledgers-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.jsonl"); + let mut trace = FrameTrace::create_with(&path, None, Some(2)).unwrap(); + for step in 10..14 { + trace.begin(step, 0.0); + if trace.wants_ledgers() { + trace.ledgers("the ledgers"); + } + } + trace.finish(); + drop(trace); + let all = lines(&path); + assert_eq!(all[0]["ledgersEvery"], 2); + let digests: Vec = all[1..] + .iter() + .map(|l| l["behaviour"].get("ledgersDigest").is_some()) + .collect(); + assert_eq!(digests, vec![true, false, true, false]); + assert_eq!( + all[1]["behaviour"]["ledgersDigest"], + sha256_hex(b"the ledgers").as_str() + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn every_legacy_remainder_is_exact_nanoseconds() { // The first twelve legacy frames' remainders, from the clock the fixture records. 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); diff --git a/tools/shadow-rehearsal.sh b/tools/shadow-rehearsal.sh new file mode 100755 index 0000000..18978c2 --- /dev/null +++ b/tools/shadow-rehearsal.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +# tools/shadow-rehearsal.sh -- SHADOW-01's offline rehearsal: the real `flysim` service and the +# real `fly-shadow` side by side on one machine, exactly as the release container runs them, from +# one FLYSIM01 checkpoint, with sugar posted to the control API and service restarts. +# +# FLY_ROM= tools/shadow-rehearsal.sh --checkpoint FILE [options] +# +# Options: +# --checkpoint FILE the live checkpoint the fly starts from (required) +# --brain-minutes N stop the live service after N brain minutes (default 30) +# --restart-at LIST restart flysim at these brain minutes, comma separated (default: none) +# --sugar-every S POST /stimulate about every S wall seconds (default 20; 0 = never) +# --speed X flysim loop.speed (default 0 = unthrottled; 1 = real time) +# --live-threads N flysim RAYON_NUM_THREADS (default 3, the release value) +# --mode M --threads N the shadow's execution mode and agent threads (in-process, 2) +# --ledgers N FLY_TRACE_LEDGERS (default 1: every boundary) +# --out DIR where everything goes (default: a new temporary directory) +# --bin DIR flysim, fly-shadow (and fly-session for --mode process); default +# $CARGO_TARGET_DIR/release or services/flysim/target/release +# --port N first of three local ports (default 17400) +# --guard S the shadow's --lag-guard-margin against the live metrics (0.05, as +# on the container; 0 disables) +# +# Environment: FLY_ROM (required); FLYSIM_PATHS_DATASET (default data/fafb-v783); +# FLY_ACCEPT_ADAPTERS passes through. Nothing here touches a host: every path is under --out. +# +# Result: /shadow/verdict.json (and divergence.json on a divergence) and /summary.txt: +# live and shadow CPU seconds per wall second, live frames per wall second, the verdict. +set -euo pipefail + +die() { echo "shadow-rehearsal: $*" >&2; exit 2; } +repo="$(cd "$(dirname "$0")/.." && pwd)" +checkpoint=""; brain_minutes=30; restart_at=""; sugar_every=20; speed=0; live_threads=3 +mode=in-process; threads=2; ledgers=1; out=""; bin=""; port=17400; guard=0.05 +while [ $# -gt 0 ]; do + case "$1" in + --checkpoint) checkpoint="$2"; shift 2 ;; + --brain-minutes) brain_minutes="$2"; shift 2 ;; + --restart-at) restart_at="$2"; shift 2 ;; + --sugar-every) sugar_every="$2"; shift 2 ;; + --speed) speed="$2"; shift 2 ;; + --live-threads) live_threads="$2"; shift 2 ;; + --mode) mode="$2"; shift 2 ;; + --threads) threads="$2"; shift 2 ;; + --ledgers) ledgers="$2"; shift 2 ;; + --out) out="$2"; shift 2 ;; + --bin) bin="$2"; shift 2 ;; + --port) port="$2"; shift 2 ;; + --guard) guard="$2"; shift 2 ;; + *) die "unknown option $1" ;; + esac +done +[ -n "$checkpoint" ] && [ -f "$checkpoint" ] || die "--checkpoint FILE is required" +: "${FLY_ROM:?FLY_ROM must name the cartridge}" +[ -n "$bin" ] || bin="${CARGO_TARGET_DIR:-$repo/services/flysim/target}/release" +for b in flysim fly-shadow; do [ -x "$bin/$b" ] || die "no $bin/$b (cargo build --release --bins)"; done +dataset="${FLYSIM_PATHS_DATASET:-$repo/data/fafb-v783}" +[ -n "$out" ] || out="$(mktemp -d "${TMPDIR:-/tmp}/shadow-rehearsal.XXXXXX")" +live="$out/live"; shadow_dir="$out/shadow" +mkdir -p "$live/hot" "$live/durable" "$live/trace" "$shadow_dir" +cp "$checkpoint" "$live/durable/1.checkpoint" +printf '{"generation":1,"latest":1,"previous":null,"archives":{}}\n' > "$live/durable/manifest.json" + +# The live service's configuration; the shadow reads the same (Config::load, as on the container). +export FLYSIM_PATHS_ROM="$FLY_ROM" FLYSIM_PATHS_DATASET="$dataset" FLYSIM_LOOP_GAME=pokemon-red +export FLY_STATE="$live/durable" FLY_STATE_HOT="$live/hot" FLY_MACRO_MODE=macros +export FLY_FEED_BIND="127.0.0.1:$port" FLY_CONTROL_BIND="127.0.0.1:$((port + 1))" +export FLY_METRICS_ADDR="127.0.0.1:$((port + 2))" FLY_CHAT_ENABLED=false +export FLYSIM_LOOP_SPEED="$speed" +control="http://127.0.0.1:$((port + 1))" + +cpu_seconds() { # utime+stime of a pid and its children that have been reaped, in seconds + awk -v hz="$(getconf CLK_TCK)" '{ print ($14 + $15 + $16 + $17) / hz }' "/proc/$1/stat" 2>/dev/null || echo 0 +} +status_ms() { # brain ms of a running (not booting) service, else empty + curl -fsS --max-time 2 "$control/status" 2>/dev/null | python3 -c ' +import json, sys +v = json.load(sys.stdin) +if v.get("status") == "running" and v.get("brainMs"): + print(int(v["brainMs"]))' 2>/dev/null || true; } + +live_pid=""; live_n=0; live_cpu=0 +start_live() { + live_n=$((live_n + 1)) + RAYON_NUM_THREADS="$live_threads" FLY_TRACE_DIR="$live/trace" FLY_TRACE_LEDGERS="$ledgers" \ + "$bin/flysim" > "$live/flysim-$live_n.log" 2>&1 & + live_pid=$! + for _ in $(seq 1 600); do + [ -n "$(status_ms)" ] && return 0 + kill -0 "$live_pid" 2>/dev/null || { tail -20 "$live/flysim-$live_n.log" >&2; die "flysim exited"; } + sleep 0.5 + done + die "flysim did not come up" +} +stop_live() { + local c; c=$(cpu_seconds "$live_pid"); live_cpu=$(awk -v a="$live_cpu" -v b="$c" 'BEGIN{print a+b}') + kill -TERM "$live_pid"; wait "$live_pid" || true +} + +wall0=$(date +%s.%N) +"$bin/fly-shadow" run --out "$shadow_dir" --trace-dir "$live/trace" --all-files --keep-traces --keep-spool \ + --mode "$mode" --threads "$threads" --lag-guard-margin "$guard" \ + --required-brain-seconds "$((brain_minutes * 60))" > "$out/shadow.log" 2>&1 & +shadow_pid=$! +# flysim starts no trace without the shadow's heartbeat. +for _ in $(seq 1 120); do [ -f "$live/trace/consumer" ] && break; sleep 0.5; done +[ -f "$live/trace/consumer" ] || die "fly-shadow wrote no heartbeat" +start_live +echo "shadow-rehearsal: $out (flysim $live_pid, fly-shadow $shadow_pid)" + +brain_done=0; seg_start="$(status_ms)"; seg_last="$seg_start"; next_sugar=$(date +%s); sugar_posted=0 +IFS=',' read -r -a restarts <<< "$restart_at" +restart_i=0 +while :; do + sleep 1 + ms="$(status_ms)"; [ -n "$ms" ] && seg_last="$ms" + elapsed=$(( brain_done + seg_last - seg_start )) + kill -0 "$shadow_pid" 2>/dev/null || { echo "shadow-rehearsal: fly-shadow exited early" >&2; break; } + if [ "$sugar_every" != 0 ] && [ "$(date +%s)" -ge "$next_sugar" ]; then + duration=$(( 200 + RANDOM % 800 )) + code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 -X POST "$control/stimulate" \ + -H 'content-type: application/json' \ + -d "{\"durationMs\":$duration,\"by\":\"rehearsal\",\"source\":\"operator\"}" || true) + case "$code" in 2*) sugar_posted=$((sugar_posted + 1)) ;; esac + next_sugar=$(( $(date +%s) + sugar_every / 2 + RANDOM % (sugar_every + 1) )) + fi + if [ "$restart_i" -lt "${#restarts[@]}" ] && [ -n "${restarts[$restart_i]}" ] \ + && [ "$elapsed" -ge $(( ${restarts[$restart_i]} * 60000 )) ]; then + echo "shadow-rehearsal: restarting flysim at brain $((elapsed / 1000)) s" + stop_live; brain_done=$elapsed + start_live; seg_start="$(status_ms)"; seg_last="$seg_start" + restart_i=$((restart_i + 1)) + fi + [ "$elapsed" -ge $(( brain_minutes * 60000 )) ] && break +done +stop_live +live_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}') +total=$(cat "$live"/trace/trace-*.jsonl | grep -c '"behaviour"' || true) +echo "shadow-rehearsal: live stopped after $((elapsed / 1000)) brain s, $total transitions traced; waiting for the shadow" +while kill -0 "$shadow_pid" 2>/dev/null; do + compared=$(python3 -c 'import json,sys; v=json.load(open(sys.argv[1])); print(v["compared"]["transitions"] + sum(s["transitionsCompared"] for s in v["skipped"]))' "$shadow_dir/verdict.json" 2>/dev/null || echo 0) + [ "$compared" -ge "$total" ] && break + sleep 2 +done +shadow_cpu=$(cpu_seconds "$shadow_pid") +shadow_wall=$(awk -v a="$wall0" -v b="$(date +%s.%N)" 'BEGIN{print b-a}') +kill -TERM "$shadow_pid" 2>/dev/null || true +rc=0; wait "$shadow_pid" || rc=$? +{ + echo "checkpoint: $(basename "$checkpoint")" + echo "live: $live_n process(es), $total transitions, $((elapsed / 1000)) brain s, ${live_wall%.*} wall s, sugar posted $sugar_posted" + awk -v c="$live_cpu" -v w="$live_wall" -v t="$total" 'BEGIN{printf "live: %.2f cores, %.1f frames per wall second\n", c/w, t/w}' + awk -v c="$shadow_cpu" -v w="$shadow_wall" -v t="$total" 'BEGIN{printf "shadow (%s, %s threads): %.2f cores over %.0f wall s, %.1f frames per wall second\n", "'"$mode"'", "'"$threads"'", c/w, w, t/w}' + echo "shadow exit: $rc" + python3 - "$shadow_dir/verdict.json" <<'PY' +import json, sys +v = json.load(open(sys.argv[1])) +c = v["compared"] +print(f"verdict: {v['status']} ({v['reason']})") +print(f"compared: {c['transitions']} transitions, {c['brainSeconds']} brain s, {c['segments']} segments, " + f"{c['sugar']} sugar, {c['rewards']} rewards {c['rewardKinds']}, {c['macroEvents']} macro events, " + f"{c['slotSaves']} slot saves, {c['rollbacks']} rollbacks, {c['ledgerChecks']} ledger checks, " + f"checkpoints {c['checkpoints']}") +print(f"skipped: {v['skipped']}") +print(f"cost: {v['cost']}") +if v["firstDivergence"]: + print(f"FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}") +PY +} | tee "$out/summary.txt"