From 002fcbe26c8ec1944fb4d2d5929073340663907f Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 20:31:20 +0000 Subject: [PATCH] docs, tools: SERVE-01 implementation entry and the runtime soak client tools/runtime-soak.ts drives a running flysim or flysim-session with the stage's own feed decoder and the bridge's HttpSimClient for a wall-clock soak and samples the store cadence. --- .../session-framework/implementation.md | 85 +++++ tools/runtime-soak.ts | 317 ++++++++++++++++++ 2 files changed, 402 insertions(+) create mode 100644 tools/runtime-soak.ts diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index 21bda41..7873e23 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -550,6 +550,91 @@ 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 (`save_queued`) 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. + ### 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/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);