Compare commits

...

65 commits

Author SHA1 Message Date
acamilo
4200a99e7e docs: v0.7.0 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-09-30 14:15:14 +00:00
acamilo
c0be101c5f Merge release/v0.7.0-rc: the flybus session runtime ships beside legacy (installed, not selected), with the shadow run and the guarded cutover 2026-09-30 14:15:14 +00:00
acamilo
6c0cc2b717 infra: session stops the shadow and guard; shadow start verifies its cpuset
fly-runtime session now stops a running shadow and its guard (fly-shadow-run stop,
no flysim restart) once flysim is healthy on the session runtime, so the guard
cannot judge the session against the legacy baseline during the probation. The
runbook cutover drops the restart in step 5.

fly-shadow-run start refuses, starting nothing, unless flyshadow's cpuset drop-in
exists and its AllowedCPUs is non-empty and disjoint from flysim.service's.

Tests in infra/tests/lint.sh cover both.
2026-09-30 13:36:12 +00:00
acamilo
a3a0d957e2 Merge feat/cut-01-probation: the switch to the session runtime is a 30-minute speed probation 2026-09-30 12:59:57 +00:00
acamilo
c1f0dde9e9 infra: CUT-01 speed probation after fly-runtime session
fly-runtime session now starts fly-runtime-probation (timer every 60 s, 30 minutes):
after a 300 s warm-up, a sustained median realtime factor below 0.97 or lag growth
over 30 s in a 10-minute window runs fly-runtime fallback with reason speed. A pass
writes /run/fly/runtime-probation.json and stops the timer; fly-runtime legacy and
every fallback cancel it; state on disk resumes it after a reboot. Lint drives it over
synthetic traces; runbook gets the end-to-end cutover procedure.
2026-09-30 12:58:05 +00:00
acamilo
416c73941a lint: the build and package checks name flysim-session, fly-shadow and fly-session together 2026-09-30 10:19:32 +00:00
acamilo
b3f6d6fbba Merge port/shadow-01 (SHADOW-01) into v0.7.0 release candidate
Conflicts: deploy/build/package scripts (flysim-session, fly-shadow and fly-session all
built, packaged and given cpuset drop-ins; fly-runtime and fly-shadow-run both converged),
fly-legacy-session Cargo.toml and lib.rs (service and shadow both kept, tokio gains signal),
runbook and implementation guide (both sections kept).
2026-09-30 10:09:01 +00:00
acamilo
b996695f0a Merge port/serve-01 (SERVE-01) into v0.7.0 release candidate
Conflicts in fly-legacy-session task.rs (feed record next to PERF-01 profile spans) and
fly-session coordinator.rs (media_bytes doc, read_agent_extension and trim_records kept
alongside PERF-01 spans, publish span and publish metric both kept).
2026-09-30 10:06:03 +00:00
acamilo
7f5f5d0e5d Merge port/perf-01 (PERF-01) into v0.7.0 release candidate 2026-09-30 10:05:07 +00:00
acamilo
6b77b87991 Merge port/task-01 (TASK-01) into v0.7.0 release candidate 2026-09-30 10:05:06 +00:00
acamilo
0b56e03ae3 shadow: a live process that leaves no trace fails the verdict; the test builds the flysim it runs
tests/shadow.rs failed with 'one trace file per process' (0 vs 2) on a
build box because it ran 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 box's bx target directory was shared by name
with other trees, so the binary beside the test predated FLY_TRACE_DIR
and wrote no trace. Reproduced by running that test binary against its
stale flysim; not a timing or segment-handling bug. The test now builds
the flysim binary itself (cargo build -p flysim --bin flysim, same
target directory and profile), proved on a target another tree had
populated.

Production could miss a whole process the same way (a trace that
cannot be created, a failed consumer check), so the shadow now holds
every flysim boot header in the live sugar journal since it started to
a trace file created during that boot; an untraced process is a
coverage divergence and fails the verdict. In FLY_TRACE_DIR mode a trace
that cannot be created no longer stops flysim from starting (it runs
untraced and the shadow fails), and a heartbeat dated ahead of the
clock counts as fresh. The test adds an untraced third process and
expects the coverage divergence.
2026-09-30 04:57:50 +00:00
acamilo
e04b0c76b0 session_trace: boot parity accepts the adapter migrations v0.6.7 deploys with
The live checkpoints the boot parity starts from are pokered-unique8-v7 files;
since row 68 (v8) a boot takes them only with FLY_ACCEPT_ADAPTERS, as the
v0.6.7 deploy sets it. The test sets the adapter's own MIGRATES_FROM when the
environment names none; both runtimes read the same list.
2026-09-30 04:11:06 +00:00
acamilo
f7ca35ba2c infra: the shadow guard survives the shadow's crash-restart delay; check needs a live guard and a baseline; refuse a verdict dated in the future
Review round 3, G1-a: the guard stops only when flyshadow's ActiveState is inactive or failed
(systemctl show), not while it is activating/auto-restart. check also requires the guard timer
active and baseline.json. allows_cutover refuses an updatedAt more than 60 s ahead of the clock.
Lint drives the guard and check with a fake systemctl; a real systemd 257 user manager run is
kept in the review notes.
2026-09-30 04:06:38 +00:00
acamilo
c56e04cdf8 docs: PERF-01 in legacy-gameboy-v1 (release configuration) and the implementation guide 2026-09-30 03:57:05 +00:00
acamilo
d2d65a4a60 tests: recorded live-fly RTF traces for the shadow guard; docs: review round 2 (SHADOW-01)
Four recordings from a real flysim at real time, with and without a real
fly-shadow (infra/tests/fixtures/shadow-guard): alone and with an idle
shadow on other cpus the guard does not trip; with a shadow on the fly's
own cpu (0.66 -> 0.44-0.60) it trips at check 7. Section 18 and the
implementation guide record R3, G1 (both guards), N3, the rebase onto
port/task-01 eaf588d and the merge of main v0.6.7 (adapter v8).
2026-09-30 03:47:37 +00:00
acamilo
5a7747210f Merge main (v0.6.7: row 68 damage reward, adapter pokered-unique8-v8) into port/shadow-01 2026-09-30 03:16:36 +00:00
acamilo
6634b33e80 infra: the guard's baseline is robust to a step in its window (median, MAD)
A real recording (a flysim whose box load stepped 1.0 -> 0.66 inside the
10-minute window) widened the old mean/sd margin to 0.25 and hid a
genuine shadow-induced drop to 0.44-0.60. The baseline RTF is now the
median of the window, its spread 1.4826 x the median absolute deviation,
and the lag rate is taken over the most recent half. The recording now
trips at check 7; over 800 synthetic 3-hour runs shaped on the release
CT (flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per second and per sample)
there is no false trip, and all 400 degradations (to 0.55-0.75, and
0.66 -> 0.58) trip.
2026-09-30 03:16:36 +00:00
acamilo
2058fff54a Merge main (606e386, row 68: pokered-unique8-v8) into port/perf-01 2026-09-30 03:09:59 +00:00
acamilo
8618e38a5f fly-session: clippy (box the bus request), race test starts from its torn state
The admission race test (TASK-01 R2-3) spawned its hammer before the first
iteration set the queue up; on a loaded build box the hammer could admit into
the empty initial queue, which is a legitimate admission, and fail the test.
2026-09-30 02:55:51 +00:00
acamilo
9a2d7c0286 PERF-01: the local lane carries every endpoint method but Worker.*; contract amendments
- worker: local_lane_carries is every method but Worker.*, so an endpoint's
  read-only extension (SERVE-01's Legacy.FeedStatus) no longer crosses the bus.
- ipc-v1 section 1, bus-v1 section 12, step-v1 and the framework README: the
  in-process local lane and in-memory artifacts, dated 2026-09-30.
2026-09-30 02:42:17 +00:00
acamilo
fa8c9305a7 PERF-01: spikes gathered per tick, 1 Hz session snapshots, fewer copies
- flybrain-core: LifNetwork::tick_spikes, the last CPU tick's spike list
  (None under the GPU backend); a test proves it is exactly the neurons the
  tick stamped and that window unions equal the last_spike_ms scan.
- legacy agent: Prepare runs its ticks one at a time and ORs each tick's list
  into the transition's bitset; Commit uses it instead of scanning 139,255
  last-spike times (falls back to the scan when no list is kept).
- legacy composition: a service session publishes its committed snapshot
  every 60th boundary (plus every boundary with events or boundary actions);
  nothing in the release subscribes, and each publication seals copies of
  the frame and the audio.
- coordinator: a single dispatch job is called in place; worker shell moves
  the reply result instead of cloning it; publication promotions begin when
  Advance answers whatever the cadence.
- profile: record() for a sample from another clock; finer spans (shell,
  local lane, handlers, advance parse/build, the brain's phase clock).
2026-09-30 02:15:25 +00:00
acamilo
d4b448f14c Merge port/task-01 (eaf588d, TASK-01 round-2 notes) into port/perf-01 2026-09-30 01:46:10 +00:00
acamilo
9aa7b92d04 fly-legacy-session: in-process sessions over the local lane; speed_ab arms
LegacySession starts in-process participants with Via::Local
(FLY_SESSION_LOCAL_LANE=0 keeps the bus path, a measurement knob). speed_ab
takes FLY_PERF_ARMS (local, bus, process), FLY_PERF_SERVICE (the service
host's per-frame reads), FLY_PERF_WORKERS (1 or 2 Tokio workers) and prints
the legacy brain's own tick time beside the session's.
2026-09-30 01:46:07 +00:00
acamilo
aaf660d48e fly-session: the in-process local lane, and the per-frame costs it leaves
- worker: one Shell per worker serves its bus loop and a LocalLane. A local
  request goes through the same admission (classification, body digest,
  result cache, arrival-order ticket, endpoint lock) and answers the same
  SessionRpcOutcome, without a bus message. Worker.* stays on the bus.
  HandlerCtx::seal keeps a local request's reply media in memory.
- rpc: a WorkerRef carrying a lane sends endpoint methods over it; sealed reply
  handles reach the caller in memory under the same reference; a bus call
  carries sealed copies of in-memory attachments (promote).
- launcher: Via::Local offers in-process participants over their lane.
- coordinator: publication attaches sealed copies of in-memory media, begun
  when Environment.Advance answers; defer_snapshots (publish without waiting
  for admission, settled at the next snapshot); digest_views and media_bytes
  as SERVE-01 has them.
- legacy env/agent: frame, memory image, audio and spike bitset sealed via
  HandlerCtx::seal; the spike bitset is built eight neurons a byte.
- profile: span maxima, enabled(); the agent runs the brain's phase clock
  when profiling.
- tests: every synthetic transport test also runs over the local lane; the
  two publication-identity checks state the sealed copy there.
2026-09-30 01:46:07 +00:00
acamilo
35d5a1f38d flybus: in-memory artifacts that never cross a router
Artifact::in_memory holds an immutable buffer in the caller's address space
(store id 'in-memory', no digest): it reads, clones and retains like any other
handle without a router round trip, and a bus call, reply or publish refuses it
as an attachment before anything is sent. Artifact::to_memory reads a sealed
handle into one under the same reference. PERF-01's local lane hands these
between participants of one process.
2026-09-30 01:46:07 +00:00
acamilo
504e4bb116 docs: implementation guide, a blank line before SHADOW-01 2026-09-30 01:41:19 +00:00
acamilo
19d84de387 infra: the guard judges the live fly against its own baseline (SHADOW-01 review round 2, G1)
fly-shadow-run start measures a 10-minute baseline before the shadow
exists (sixty 10-s realtime-factor means: mean, spread; the lag growth
rate). The guard trips only on a sustained degradation against it: 3
checks in a row where 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). It stops itself when
flyshadow.service is not running; check refuses after a guard trip or
with the shadow down. lint drives the rule over RTF traces shaped on the
release CT (a flat 0.66, 0.77-0.99 noisy, real time with hiccups) which
must not trip, and degradations which must. Section 18 and the runbook
follow.
2026-09-30 01:39:52 +00:00
acamilo
a472adcaf4 fly-shadow: review round 2, R3, G1 (in-shadow back-off), N3 (SHADOW-01)
R3: allows_cutover floors the window at REQUIRED_BRAIN_SECONDS (10,800):
a verdict run with a shorter --required-brain-seconds never passes
check. G1: the in-shadow back-off (LagJudge) judges the live lag growth
rate against fly-shadow-run's pre-start baseline (baseline.json lagRate
and margin, re-read every poll) instead of any growth, and lifts itself
for 10 minutes when a pause did not help (the shadow is not the cause);
--lag-guard-margin replaces --max-live-lag-seconds. N3: lagTransitions
is refreshed at every verdict write, backed off or not, over the rest of
the current file and every newer one.
2026-09-30 01:39:52 +00:00
acamilo
37c7befc11 docs: SHADOW-01 review fix round (legacy-gameboy-v1 section 18, implementation guide)
Section 18: skips are the live side's own kinds only, every session-side
failure is a divergence, the live fly never pays for the shadow
(heartbeat, directory cap, guard), and the cutover rule requires the
release /opt/fly/current resolves to, compared saves and a caught-up
shadow. host-fields' reason updated. The guide records the fix round and
the cost re-measured on the rebased tip.
2026-09-30 01:39:52 +00:00
acamilo
2d8b529f42 infra: the shadow's live-impact guard (SHADOW-01 review N2, N1)
fly-shadow-run start records the live fly's baseline (fly_realtime_factor
over 10 s, fly_lag_seconds, uptime), waits for the shadow's heartbeat and
starts flyshadow-guard.timer. fly-shadow-run guard (every 60 s, root)
stops the shadow and the guard, removes the trace drop-in and restarts
flysim without the trace when fly_lag_seconds grew 1 s in the same
process or the mean realtime factor fell below min(0.97, baseline-0.03);
a paused fly is not judged, a restarted one rebaselines. check passes
--current /opt/fly/current --binary flysim-session. lint drives the
guard's rule on six cases. Runbook rewritten: the trace cannot outlive
the shadow (heartbeat, 8 GiB directory cap), not the old claim.
2026-09-30 01:39:52 +00:00
acamilo
e085876d79 fly-shadow: review fixes R1, R2, N3 (SHADOW-01)
R1: the verdict hashes flysim-session (SERVE-01's service) with the
other release binaries; check takes --current (default /opt/fly/current)
and --binary (default flysim-session) and requires the verdict's release
to be the directory the link resolves to, every shadowed binary
unchanged there. R2: a session that does not start, a restore-gate
refusal, a capture with no agent, an unrecorded transition and an
unbuildable trace line are divergences; skips carry a kind and only the
live side's own kinds (startup-save-gone, operator-reward-pulse,
trace-cap, no-transition) allow a cutover. N3: pass and the cutover rule
require one live save compared per 600 brain seconds and at most 10 %
unavailable, and the cutover rule a shadow at most 3,600 transitions
behind. N1: the shadow writes the consumer heartbeat, removes it when it
stops, and prunes history files. The coordinator's history is bounded
per segment. The test adds a gate refusal (a boot divergence) and waits
for the heartbeat; so does the rehearsal script.
2026-09-30 01:39:52 +00:00
acamilo
4bf664ee22 flysim: the trace needs a live consumer and a bounded directory (SHADOW-01 review N1)
In FLY_TRACE_DIR mode a process starts no trace unless the shadow's
heartbeat (<dir>/consumer) is fresh (FLY_TRACE_CONSUMER_STALE_SECONDS,
600), and a running trace stops within a minute of frames once it is
stale ({"truncated":true,"reason":"no-consumer"}). Before a
process creates its file the oldest trace files are deleted to keep the
directory under FLY_TRACE_DIR_MAX_BYTES (8 GiB). A dead or diverged
shadow can no longer leave the live service tracing.
2026-09-30 01:39:52 +00:00
acamilo
9a3a4f5a9c docs: SHADOW-01 final rehearsal (final binary, lag guard on) 2026-09-30 01:39:52 +00:00
acamilo
c09ac100ce docs: SHADOW-01 (legacy-gameboy-v1 section 18, implementation guide) and the rehearsal script
Section 18 fixes what the 3-hour zero-divergence gate means: the inputs,
the architecture (the live legacy fly stays primary; the shadow follows
its trace), what is compared, the declared differences, the window and
the verdict contract. tools/shadow-rehearsal.sh runs the real service and
the real shadow side by side from one checkpoint.
2026-09-30 01:39:52 +00:00
acamilo
095cf7b1da infra: flyshadow.service and fly-shadow-run (SHADOW-01)
Report-only unit, off by default, not bound to flysim, SCHED_IDLE on the
page and encoder CPUs, stays stopped after a divergence (exit 3).
fly-shadow-run start|stop|status|check installs the flysim trace drop-in,
restarts flysim once and reads the verdict. Deploy, build and packaging
ship fly-shadow and fly-session; lint holds the unit to its rules; the
runbook has a Shadow run section.
2026-09-30 01:39:42 +00:00
acamilo
12f361436f fly-legacy-session: the shadow run, its comparator and verdict (SHADOW-01)
shadow::run follows the live service's per-process trace files: each
segment boots a session from that process's startup save (a fresh start
powers on instead), replays the transition's admissions, runs it, takes
the live captures in the live order around a deferred rollback, and
compares its own trace line field by field, the ledger digest, and the
FLYSIM01 bytes of every live save (host-fields and archive-order
substituted). The first difference stops it with a diverged verdict and
divergence.json. A spool copies live generations as they appear; a lag
guard backs off while the live fly loses real time.

verdict.json is fly-shadow-verdict-v1, the contract CUT-01 reads;
fly-shadow check applies the cutover rule. trace::compare_line is shared
with trace::compare. tests/shadow.rs runs the real service through a
restart under a shadow and plants four differences, each caught with the
right kind, field and step.
2026-09-30 01:39:42 +00:00
acamilo
105f526200 flysim: trace switches for the shadow run (SHADOW-01)
FLY_TRACE_DIR writes one FLY_TRACE file per process (a restart truncated
the single path), FLY_TRACE_MAX_BYTES caps a file (4 GiB in directory
mode: a trace nobody consumes cannot fill the disk), FLY_TRACE_LEDGERS=<n>
adds ledgersDigest every n transitions. frame::ledgers_string is now the
one definition of the ledger string both runtimes digest. Recording only:
no behaviour field and nothing the fly does changes; compatibility string
unchanged.
2026-09-30 01:39:42 +00:00
acamilo
68bde25493 Merge port/task-01 (TASK-01 round-2 fixes) into port/serve-01; hand begun captures to the writer on pause 2026-09-30 01:37:12 +00:00
acamilo
6c7c58b35a infra: RestartMode=direct so OnFailure= fires only at the start limit; one lock for fly-runtime rollback and fallback
Verified on systemd 257: with the default RestartMode=normal the unit passes through failed
before every auto-restart, so OnFailure= ran on the first crash. The session drop-in now sets
RestartMode=direct. session, legacy, fallback and the trap rollback share one flock; a switch
holds it only until its restart is queued (restart --no-block, health checked against the new
invocation), and the rollback skips restoring an older drop-in once a fallback has completed.
lint.sh covers the drop-in key, the interleaving and the shared lock; runbook corrected.
2026-09-30 01:36:23 +00:00
acamilo
eaf588d2e2 TASK-01 round-2 notes: saves reach the writer on a failed step and on pause, every save outcome reported, sugar admission atomic with the commit
R2-1: a failed step hands the begun captures to the writer before it reports the error, and LegacySession::flush_captures hands them over while the loop idles.
R2-2: completed_saves reports every queued save's outcome instead of stopping at the first error.
R2-3: the commit ends the in-flight admissions and records the pulses under one lock, and a sugar's reads and queueing take that same lock.
2026-09-30 01:30:56 +00:00
acamilo
405cf11498 flysim: read adapter.progress() once per publish
feed_game and feed_milestone each called adapter.progress() (a pure read), so every publish
computed it twice. Both now take the snapshot as an argument; publish and the session service
read it once. The header bytes are unchanged (service_parity and journal_replay pass).
2026-09-30 00:11:25 +00:00
acamilo
1d29ab1ff8 infra: persistent session-to-legacy fallback, signal-safe fly-runtime, MALLOC_ARENA_MAX=2
The fallback used to live only inside one 'fly-runtime session' invocation. The session
drop-in now carries OnFailure=fly-runtime-fallback.service and a 3-starts-in-10-minutes
start limit, so a session binary that will not stay up puts flysim.service back on legacy
after a reboot, a watchdog or loop-recover restart or a deploy. 'fly-runtime fallback'
removes the drop-in, daemon-reloads, restarts on legacy, writes /run/fly/runtime-fellback.json
and a journal line; it is locked, idempotent and keeps the drop-in if legacy cannot start.
fly-runtime traps INT/TERM/HUP and any failure during a switch and rolls back to the
previous state. Session drop-in and flysim-session.service set MALLOC_ARENA_MAX=2.
05-deploy keeps the chosen runtime (operator decision: session stays, trust gates),
refreshes the drop-in in place, and says so; the runbook documents all of it.
lint.sh drives the fallback, the interrupts and the deploy policy against a fake systemctl.
2026-09-30 00:11:25 +00:00
acamilo
7ec9a3c9ef docs: TASK-01 review fix round in the implementation guide 2026-09-29 23:43:17 +00:00
acamilo
12940a5215 tests: speed_ab, the session against the legacy loop interleaved in chunks on one box 2026-09-29 23:08:12 +00:00
acamilo
d35eda399b N5: captures off the loop; wanted and cached artifacts held concurrently
- worker: a handler may finish its reply outside the endpoint's lock
  (HandlerReply::deferred); admitted mutations take the lock in arrival
  order (LockOrder), so a request sent before another is handled first;
  a reply's cache holds are taken concurrently.
- legacy agent: State.Capture copies the state under the lock and
  encodes, digests and seals it off the lock, so the next Prepare ticks
  while the payload is written.
- rpc: send/finish split (SentCall); the caller's holds on wanted
  attachments are taken concurrently.
- coordinator: begin_capture sends every State.Capture and returns;
  finish_capture collects them. LegacySession begins a boundary's saves
  and collects them after the next transition, then queues them to the
  writer thread.
2026-09-29 23:03:37 +00:00
acamilo
1bfaf923b2 N5: publication at the feed's rate, in-memory transport in-process, capture spans; docs for the fix round
- Coordinator::snapshot_every(n): a snapshot every n-th boundary plus
  every boundary with events or boundary actions; a service session
  publishes every other boundary, the legacy feed's 30 Hz from 60 Hz.
- In-process participants reach the router in memory (a separate process
  still uses its socket).
- Spans on the agent's and the coordinator's capture path; tests/speed.rs
  times the legacy frame's phases, its agent export, and a session save.
- legacy-gameboy-v1: the artifact-backed ledger, the palette seed and the
  pending pulse (amendments of 2026-09-29).
2026-09-29 22:20:39 +00:00
acamilo
d3c61286bf docs: SERVE-01 results and what is open for CUT-01 2026-09-29 22:13:51 +00:00
acamilo
2fc9fd7247 tests: the reward segments include row 64 and the row 65 yard 2026-09-29 21:58:23 +00:00
acamilo
42f3c91c29 journal_replay: compare the adapter ledger as numbers
The session's ledger crosses the task's canonical JSON, which writes an
integral f64 as 7580031 where the legacy export writes 7580031.0; the
values are equal and the legacy import reads both alike.
2026-09-29 21:54:41 +00:00
acamilo
5cf40c3148 Merge port/task-01 (TASK-01 review fixes) into port/serve-01
Takes the artifact-backed task ledger (B1), the pending pulse (N1), the
palette seed (N3), queue_save/completed_saves (N4) and the bounded history
and concurrent seals (N5). The service host now queues its saves through
TASK-01's queue_save; SERVE-01's save_queued is gone.
2026-09-29 21:29:31 +00:00
acamilo
46d07260e9 TASK-01 review N5: the per-boundary costs measured, the world's seals concurrent, bounded history
- fly-session::profile: switchable per-phase spans (FLY_SESSION_PROFILE),
  in the coordinator's phases, the world's advance and the agent's
  prepare and commit.
- The world seals the view, the image and the audio chunk concurrently.
- Coordinator::bound_history: a service session keeps the newest 4096
  transitions of trace, phase and audit logs and latency samples (it
  grew without bound).
- tests/speed.rs: legacy loop against the session on one box, unpaced
  and paced at 1x, in-process and process, with the span breakdown.
2026-09-29 21:06:32 +00:00
acamilo
0776fab225 service_parity: two sugars in one drain; repeat a run whose recorder fell behind
The TASK-01 review's N1: a second sugar before the next commit is refused
with the first one's pulse as the retry, legacy and session alike. A run
whose recorder misses a frame on a loaded box is repeated rather than
failed (it cannot be compared, and it says nothing about either runtime).
2026-09-29 20:48:37 +00:00
acamilo
7a61877e78 TASK-01 review fixes: an artifact-backed task ledger, the pending pulse, the palette seed, queued saves
- B1: the pokered ledger's adapter state travels as an attachment
  ('reward', its JSON) beside a small typed value {reward: {digest,
  byteLength}, ratchet, slotFilled}; Task gains capture_attachments /
  validate_restore_with / install_restore_with, and the coordinator files
  them as task-ledger-<name> payloads in captures and imports. Every
  failure is an IncompatibleState error, so boot falls to the next
  candidate. Tests: ledger_size (past 64 KB, and malformed ones).
- N1: a sugar admitted and not yet reported on by a commit is an active
  pulse (AdmissionQueue::pending_stimulus_ms): two sugars between two
  commits are one admission and one PulseActive, as the legacy drain.
- N3: a restore seeds the palette with the restored brain's RNG state,
  as Sim::boot does; palette_seed holds on the cartridge that two seeds
  press the same buttons (a fresh start's constant is therefore exact).
- N4: interval, milestone and after-rollback saves are queued to the
  checkpointer's writer thread; startup and shutdown saves block.
- Boot parity adds row64 and the row65 yard (the largest ledgers); the
  segments add them too. tests/speed.rs measures N5.
2026-09-29 20:47:19 +00:00
acamilo
002fcbe26c 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.
2026-09-29 20:31:20 +00:00
acamilo
0012759ace infra: flysim-session.service, fly-runtime, and shipping the session runtime
fly-runtime session|legacy|status switches which binary flysim.service runs
with one drop-in (flysim.service.d/10-runtime.conf), so fly.target, flyedge's
Requires=, the watchdog, fly-loop-recover and its sudoers line,
fly-loop-reset, fly-reset-to-milestone and the unstick rule keep naming
flysim.service, 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 when the session runtime does not come up.

flysim-session.service: the standalone unit (flysim's limits, cpuset and
environment, Conflicts=flysim.service, no [Install]). build-flysim.sh and
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. lint.sh checks all of it and drives
fly-runtime against stubs. Runbook: Switch the runtime.
2026-09-29 20:31:20 +00:00
acamilo
98f29e47c6 fly-legacy-session: flysim-session, the session runtime as the live service
The service host (service.rs, bin flysim-session) runs the legacy composition
behind flysim::serve with flysim's own Config and keeps Sim's order and
bookkeeping: TASK-01's boot (legacy candidate order and gate), boot events,
chat sidecar, sugar journal (runtime fly-session), startup/shutdown durable
saves, queued hot/durable/milestone/after-rollback saves on the wall clock,
macro/reward/milestone/recovery/sugar/checkpoint events, the recovering
status, flysim's Pacer, sd_notify ready/watchdog, and the 30 Hz feed built
by flysim's feed_* functions from the committed view, the step's audio
through the legacy DC blocker, the OR of the commits' spike bitsets, the
task's adapter/ratchet/macro layer and the agent's Legacy.FeedStatus.

Task: FeedRecord (executed/rewards/abandoned/rollback events), the applied
mask (0 after a rollback, the checkpoint's after an import), inspect().
Composition: boot_unsaved, save_queued, the event-log watermark setter.

Tests: service_parity (legacy Sim vs session host behind flysim's router,
one scripted request set, every header/attachment/response/event/journal
line and the final checkpoint compared), journal_replay (a killed session
run's journal replayed from the seed in the legacy loop onto its last hot
checkpoint), unit tests for the audio path and the feed status;
examples/seed_store.
2026-09-29 20:31:13 +00:00
acamilo
4fcd9233c7 fly-session: what a service host needs from the session
- Legacy.FeedStatus (capability legacy-feed-status-v1): the legacy agent's
  read-only feed status at a committed boundary -- rates, pulse, the whole
  plasticity statistics and the decoder's baselines/scores -- which no
  session message carries and the legacy header and /status report.
- Coordinator::read_agent_extension (never fences), media_bytes (the
  committed view/audio chunk), digest_views (off for a host that reads the
  details only for commit attachments), trim_records (the trace, phase log,
  audit and injection log grew with every transition: ~120 KB/s on the live
  fly), and timings for the feed status and the per-step publication.
2026-09-29 20:31:13 +00:00
acamilo
95614122a9 flysim: serve() shell and shared feed-header builders for a second runtime
flysim::run is now serve(config, Sim::boot + Sim::run): serve binds the feed
(or the feed bus), the control API and the metrics listener, handles the
signals and runs any runtime on the calling thread with the shared state,
the snapshot slot and the command queue. The fly-derived pieces of a feed
header (feed_rates/learning/game/milestone/sugar) and the chat admission
(admit_chat) are free functions both runtimes call; DcBlocker gains an f32
entry point for audio already converted with v/255. No behaviour change:
the legacy frame, header bytes and compatibility string are unchanged.
2026-09-29 20:31:13 +00:00
acamilo
7ef16be317 docs: TASK-01 on STATE-02 (the store, the boot, the task ledger) 2026-09-29 18:23:11 +00:00
acamilo
e561c81295 TASK-01 on STATE-02: the store, the boot and the task ledger
- The task ledger is STATE-02's TaskHalf ledger {reward, ratchet,
  slotFilled} (pokered-task-ledger-v1); the task exposes its half, rank
  and brain time for the host.
- The FLYSIM01 import uses legacy_checkpoint's halves, agent_payload
  (the file's framebuffer as the next input, its reinforcement count)
  and world_payload, with ids from the file; ImportSpec carries the
  source scope.
- The coordinator can defer a rollback so the host captures first
  (apply_pending_rollback) and takes a participant-coherent capture
  for the legacy store (capture_payloads).
- LegacySession: attach_store (LegacyCheckpointer), save, advance in the
  declared boundary order (slot save, milestone archive on a climb,
  rollback, durable save after it, interval saves), shutdown_save; boot()
  restores from the live stores in the legacy order and gate, one
  session per attempt, fresh when the stores are empty.
- tests: fafb_boot_run_save_restore, the SHADOW-01 entry gate.
2026-09-29 18:16:55 +00:00
acamilo
e6fa92613a Merge port/integration (STATE-02) into port/task-01 2026-09-29 18:11:33 +00:00
acamilo
1a6e064e4f docs: TASK-01 in the implementation guide; dated amendments (2026-09-29) to legacy-gameboy-v1 sections 10, 11, 14 and 15, step-v1 sections 2 and 3, workers-v1 sections 4 and 5 2026-09-29 18:11:30 +00:00
acamilo
851b4f85c4 fly-session: clippy (slice from_ref) 2026-09-29 18:11:30 +00:00
acamilo
7c8d5a33dc fly-legacy-session: pokered-macros-v1 on the session framework (TASK-01)
The live fly's composition under one coordinator: AGENT-01's agent,
ENV-01's world, and the Pokemon Red task and executor as one object
running the unchanged legacy engine (flysim's MacroLayer, flybrain-gb's
palette, executor, PokeState, reward adapter and ratchet) over MEM-01's
ImageReader of each boundary's memory image.

- task: Phase B decide over O[k], Phase C sample/observe/ratchet over
  O[k+1], rollback clear_transient/cancel/observe over O'[k]; slot save
  and rollback requests; legacy-transient-reset on restore; a reward
  with no stimulation is a Reward alone; uncaptured reads are recorded.
- import: a FLYSIM01 checkpoint as the start (world, agent, task halves
  in each participant's own format, the context from the checkpoint's
  image), onto a replacement world.
- admission: sugar by flysim's RateLimiter against the last commit's
  pulse; the operator reward pulse is refused.
- trace: the session's own FLY_TRACE lines and the comparison;
  driver: the ROM tests' rotation stub readout for reward-bearing runs.
- tests: session_trace (toy raw from power-on; FAFB from the service
  traces' checkpoints and from stream checkpoints, brain and driver
  arms; in-process and process) and rollback_sequence (ROM-free).
2026-09-29 18:03:59 +00:00
acamilo
817318f014 fly-session: the coordinator runs the legacy composition's boundary (TASK-01)
- A task declares the inspection attachments it reads; the coordinator
  holds them (O[k] until its transition is evaluated) and hands the task
  and the executor their bytes (task::Inspection).
- The executor's clock is the agent's brain time after Prepare.
- Evaluation.slot_saves: Environment.SaveSlot at the boundary reached.
- A declared rollback policy runs itself: Ready(e,k) -> RollingBack(k)
  -> Ready(e',k) with RestoreSlot, Task::rollback, Agent.Rollback; a
  composition that declares it needs agents that advertise it.
- AdmissionQueue: admitted stimuli cut into each Prepare, ended applied
  or aborted; the last commit's stimulusRemainingMs for the edge.
- Coordinator::import: a checkpoint of another format as a session's
  start, through the ordinary group restore (Ready(0) -> Restoring(k));
  Task::restored re-observes the restored world and must agree with the
  recorded contexts. capture_participant, import_scope.
- Composition setters: environment config, media, decision schema,
  world state format, per-agent model versions; StepDetails for parity.
- ENV-01's interim 'declared rollback pauses' test now states the rule:
  a declared policy needs participants that apply it.
2026-09-29 18:03:59 +00:00
98 changed files with 19059 additions and 460 deletions

View file

@ -78,7 +78,10 @@ Application / supervisor Application presentation
This diagram is connectivity, not execution order. The step contract defines causal order. 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 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, 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 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 per-agent executors begin as coordinator-local libraries. An environment helper may own a

View file

@ -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 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 section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled
illustrative. 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.

View file

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

View file

@ -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 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. 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 ## 2. Common domain types
```ts ```ts

View file

@ -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 - **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world
the fly now stands in. 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` ## 11. Episode policy `legacy-ratchet-rollback-v1`
The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during 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. 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. 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<n>`,
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 ## 12. Composition declaration and digest
```ts ```ts
@ -376,6 +415,31 @@ interface LegacyGameboyComposition {
for publication, traces and descriptor revisions, not a restore gate. This matches today's for publication, traces and descriptor revisions, not a restore gate. This matches today's
behaviour, where a decoder change does not refuse a checkpoint. 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 ## 13. Machine-readable parts
| Where | What | | 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 unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps
the rung. 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 ## 15. Sugar admission
The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap 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 bridge's fulfil path and refund path both get tests in the slice that wires them
([workers-v1](workers-v1.md) section 5 amendment). ([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 ## 16. Checkpoint format of record
**Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)` **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. **not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
Nothing here constrains them, except that a new profile never reuses this profile's id or its Nothing here constrains them, except that a new profile never reuses this profile's id or its
legacy exception. legacy exception.
## 18. The shadow run (SHADOW-01)
**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic
cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that
means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit
`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`.
**The inputs.** The legacy loop is deterministic, given two things: the state a process starts
from and the admissions applied at the top of each frame. Every nondeterministic input reaches
the fly through one of those two:
| Input | How it reaches the fly | How the shadow gets it |
| --- | --- | --- |
| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g<N>`); the shadow boots a new session from it through the ordinary FLYSIM01 import |
| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) |
| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared |
| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where |
| Chat | A caption track; it reaches nothing the fly does | Not needed |
| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own |
So "the same inputs" means *the same start state per process and the same admissions per
transition*. Admission itself is not compared. The session runtime decides admission against a
pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on
its own clock would diverge by design, not by fault.
**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live
service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a
behaviour field or anything the fly does:
- `FLY_TRACE_DIR` writes one file per process, `trace-<start wall ms>-<pid>.jsonl`.
- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode).
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of
`flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the
executor's scene, bound set, running macro, counts and "nearer".
`fly-shadow` follows the files in start order. For each file it takes these steps:
1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup
save. A fresh start is different: the stores were empty and the startup save is at boundary 0.
In that case the shadow runs the same power-on scaffold and warm-up
(`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own
boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio
resampler phase is not in its exported state, so the channel accumulators of an imported
emulator drift from those of a powered-on one, in the exported state only. Both restores of a
restart import, so they agree.
2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a
capture wherever the live trace records one, before or after the boundary's rollback as the
live loop took it, then applies the deferred rollback.
3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and
compares it with the live line, field by field.
A spool thread copies every new store generation as it appears, because a hot file lives only
about ten seconds. The shadow never writes to the live stores.
The reverse arrangement was considered: the session runtime as primary, with legacy as the
checker. It would make the shadow run the cutover itself, and a divergence would already be on
the stream. A second legacy process in lockstep was also considered. It adds nothing, because the
live process's own trace *is* the legacy behaviour.
**What is compared, per boundary.**
- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`,
`brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`,
`macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary`
and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and
the rollbacks.
- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same
string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's
ledgers, which no checkpoint carries.
- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same
boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export
byte for byte with the live file after the substitutions named below. `compatibility`,
`speed` and `rankSinceMs` are the shadow's own, so they are compared too.
**Declared differences**, excluded by name. The verdict lists the same names.
| Name | What is excluded |
| --- | --- |
| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") |
| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) |
| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. 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
(`<trace dir>/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.

View file

@ -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 maps it step by step), so the amendments below add capabilities to the protocol and change
none of its ordering rules. 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 ## 1. Committed boundary
At `Ready(epoch, k)`: 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 lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
not allowed in `RollingBack`. 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 ## 3. Transaction sequence
### Phase A: prepare all agents concurrently ### 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 the next request. Transport/control scaffolding may have a measured fixed latency; it must
be declared in its descriptor and conformance tests. 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 ### Phase C: observe and evaluate the task
The coordinator receives the environment result and verifies batch identity, boundary, The coordinator receives the environment result and verifies batch identity, boundary,

View file

@ -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 "cannot reset the environment directly": the coordinator applies the policy through the
section 7 methods. 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 ## 5. Admission and audience boundary
The first synthetic implementation has no audience input. Later integration maps permitted 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 accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
kind; paid interactions in general still need the public v2 contract. 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 ## 6. Health, shutdown and extensions
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore

View file

@ -953,3 +953,17 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO"). segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO").
Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift
within two hours. Review: APPROVE-WITH-NOTES. within two hours. Review: APPROVE-WITH-NOTES.
- 2026-09-30 (v0.7.0, the port): the flybus session runtime ships beside the legacy loop, installed
and not selected. AGENT-01 (the brain as a worker), MEM-01 (the macros read a 64 KiB memory image
with the same engine), ENV-01 (the Game Boy as a worker), STATE-02 (one checkpoint store for
both runtimes, FLYSIM01 of record), TASK-01 (the macros in the coordinator), PERF-01 (an
in-process local lane: the session costs ~1.3x legacy per frame, down from 2.45x), SERVE-01
(`flysim-session` serves the same feed/control/metrics contracts; `fly-runtime session|legacy`
swaps the binary behind flysim.service; a crash loop falls back to legacy by itself), SHADOW-01
(`fly-shadow` replays the live fly's trace through the session runtime and compares every
transition, ledger and save byte; a baseline-relative guard stops it if the live fly suffers),
CUT-01 (the switch is a 30-minute speed probation: a median realtime factor under 0.97 falls back
with reason "speed"). Deploying changes nothing live: legacy's output is byte-identical to
v0.6.7. Cutover is `fly-shadow-run check && fly-runtime session` after three hours of zero
divergence; rollback is `fly-runtime legacy`. Every slice and the release candidate were
independently reviewed (APPROVE-WITH-NOTES).

View file

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

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

@ -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" <<EOF
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
# Keep [Service] in step with units/flysim-session.service.
[Unit]
OnFailure=${FALLBACK_UNIT}
StartLimitIntervalSec=600
StartLimitBurst=3
[Service]
RestartMode=direct
ExecStart=
ExecStart=${SESSION_BIN}
Environment=FLY_SESSION_DIR=${SESSION_DIR}
Environment=MALLOC_ARENA_MAX=2
EOF
chmod 0644 "$tmp"
mv -f "$tmp" "$DROPIN"
}
# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
healthy() {
local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
local first=""
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
local frame
frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
| sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$frame" ]; then
if [ -z "$first" ]; then
first="$frame"
elif [ "$frame" -gt "$first" ]; then
log "healthy: frame ${first} -> ${frame}"
return 0
fi
fi
fi
sleep 1
done
return 1
}
# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
locked=0
take_lock() {
if [ "$locked" -eq 1 ]; then return 0; fi
mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
exec 9>>"$FLY_RUNTIME_LOCK"
if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
return 1
}
drop_lock() {
exec 9>&-
locked=0
}
restarted=0
old_invocation=""
restart_and_check() {
systemctl daemon-reload
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
log "restarting ${FLY_SERVICE} on the $(current) runtime"
restarted=1
# --no-block: a blocking restart of a unit that never becomes READY holds this process (and
# the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
# that it is talking to the NEW invocation, not the old process that is still shutting down.
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
drop_lock
healthy
}
# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
do_fallback() {
local reason="$1" result nrestarts saved
take_lock || log "continuing without the lock"
if [ ! -f "$DROPIN" ]; then
log "fallback: the legacy runtime is already selected; nothing to do"
return 0
fi
if [ ! -x "$LEGACY_BIN" ]; then
record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
return 1
fi
result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
reason="${reason//[\"\\]/}"
reason="${reason//$'\n'/ }"
mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
>"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
cp -f "$DROPIN" "$saved"
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
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}"

299
infra/bin/fly-runtime-probation Executable file
View file

@ -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

437
infra/bin/fly-shadow-run Executable file
View file

@ -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 (<trace dir>/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-<ms>-<pid>.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" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service]
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
EOF
systemctl daemon-reload
systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat.
for _ in $(seq 1 60); do
[ -f "$SHADOW_DIR/trace/consumer" ] && break
sleep 1
done
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up"; }
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
systemctl restart flysim.service
systemctl start flyshadow-guard.timer
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
}
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
stop_all() {
systemctl stop flyshadow-guard.timer 2>/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

View file

@ -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 # without a rebuild. It lands next to OUT_PATH, where package-release.sh
# looks for it. # looks for it.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
# that `fly-runtime session` points flysim.service at; 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" built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
@ -118,4 +125,12 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
cp "$edge_built" "$edge_out" cp "$edge_built" "$edge_out"
chmod 0755 "$edge_out" chmod 0755 "$edge_out"
log "built $edge_out ($(du -h "$edge_out" | cut -f1))" log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
for extra in flysim-session fly-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 <stage-dir> <bridge-dir> <out-dir>" log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>"

View file

@ -14,6 +14,12 @@
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh # fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
# left one beside FLYSIM_BIN; flyedge.service stays # left one beside FLYSIM_BIN; flyedge.service stays
# inactive on a release without it) # inactive on a release without it)
# flysim-session (the session runtime, SERVE-01, and fly-session, its
# fly-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) # stage/... (apps/stage's build output)
# bridge/... (services/bridge + node_modules) # bridge/... (services/bridge + node_modules)
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
@ -82,6 +88,18 @@ if [ -x "$EDGE_BIN" ]; then
else else
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)" log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
fi fi
for extra in flysim-session fly-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 "$STAGE_DIR" "${release_dir}/stage"
cp -a "$BRIDGE_DIR" "${release_dir}/bridge" cp -a "$BRIDGE_DIR" "${release_dir}/bridge"

View file

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

View file

@ -443,6 +443,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`. touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`.
On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above. On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above.
## Switch the runtime (legacy loop or session runtime)
Two binaries in every release from SERVE-01 on run the same fly: `flysim`, the legacy loop, and
`flysim-session`, the same composition on the session framework (agent, Game Boy environment and
macro task as participants). They read the same `/etc/fly/fly.env`, write the same checkpoint
stores, event log, sugar journal and chat sidecar, and serve the same feed, control API and
metrics through the same listener code, so nothing else on the container can tell them apart.
`flysim.service` is the fly's one unit name either way; which binary it runs is one drop-in,
written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/opt/fly/bin`).
```
pct exec $CTID -- /opt/fly/bin/fly-runtime status # legacy | session
pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict (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 <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, shadow + guard, one flysim restart
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict (and a guard trip) in one screen
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
pct exec <ctid> -- /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) ## CPU partition (cpuset)
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit

View file

@ -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.

View file

@ -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}

View file

@ -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}

View file

@ -0,0 +1 @@
pass

View file

@ -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}

View file

@ -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}

View file

@ -0,0 +1 @@
pass

View file

@ -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}

View file

@ -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}

View file

@ -0,0 +1 @@
pass

View file

@ -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}

View file

@ -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}

View file

@ -0,0 +1 @@
trip

View file

@ -510,6 +510,212 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR
else else
pass "07-enable.sh and verify.sh leave flyedge.service alone" pass "07-enable.sh and verify.sh leave flyedge.service alone"
fi 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" \ 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 && 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" 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" pass "flysim.service leaves FLY_FEED_VIA to fly.env"
fi fi
# ---------------------------------------------------------------------------
# 3b3. The session runtime (SERVE-01): flysim-session, its standalone unit and
# the fly-runtime switch CUT-01 calls.
#
# flysim.service stays the fly's one unit name; `fly-runtime session` points it at
# flysim-session with a drop-in, `fly-runtime legacy` removes it. What would break
# that: the standalone unit drifting from flysim.service (limits, env, ports),
# becoming enable-able or pulled in beside flysim, the drop-in naming another
# binary or session dir, the release not shipping the binary, the deploy
# forgetting it. fly-runtime itself is driven for real against stubs.
# ---------------------------------------------------------------------------
echo "--- the session runtime: flysim-session.service and fly-runtime ---"
SESSION_UNIT="$INFRA_DIR/units/flysim-session.service"
if [ ! -f "$SESSION_UNIT" ]; then
fail "units/flysim-session.service is missing"
else
grep -qE '^ExecStart=/opt/fly/current/flysim-session$' "$SESSION_UNIT" \
&& pass "flysim-session.service runs the release's flysim-session" \
|| fail "flysim-session.service ExecStart must be /opt/fly/current/flysim-session"
grep -qE '^Conflicts=flysim\.service$' "$SESSION_UNIT" \
&& pass "flysim-session.service Conflicts=flysim.service (same ports, same stores)" \
|| fail "flysim-session.service must Conflict with flysim.service"
if grep -qE '^\[Install\]' "$SESSION_UNIT"; then
fail "flysim-session.service has an [Install] section; it must not be enable-able beside flysim"
else
pass "flysim-session.service cannot be enabled (no [Install])"
fi
# The [Service] section, comments and blank lines dropped: flysim.service's, line for
# line, but for ExecStart and the one variable of its own.
service_lines() {
awk '/^\[/{sec=$0; next} sec=="[Service]" && !/^[[:space:]]*(#|$)/' "$1" \
| grep -vE '^(ExecStart=|Environment=FLY_SESSION_DIR=|Environment=MALLOC_ARENA_MAX=)' || true
}
if [ "$(service_lines "$INFRA_DIR/units/flysim.service")" = "$(service_lines "$SESSION_UNIT")" ]; then
pass "flysim-session.service [Service] is flysim.service's but for ExecStart and FLY_SESSION_DIR"
else
fail "flysim-session.service [Service] drifted from flysim.service: $(diff <(service_lines "$INFRA_DIR/units/flysim.service") <(service_lines "$SESSION_UNIT") | tr '\n' ' ')"
fi
grep -qx 'Environment=MALLOC_ARENA_MAX=2' "$SESSION_UNIT" \
&& ! grep -q 'MALLOC_ARENA_MAX' "$INFRA_DIR/units/flysim.service" \
&& pass "flysim-session.service sets MALLOC_ARENA_MAX=2; legacy flysim.service is untouched" \
|| fail "flysim-session.service must set MALLOC_ARENA_MAX=2 (and flysim.service must not)"
grep -qE '^Environment=FLY_SESSION_DIR=/run/fly/session$' "$SESSION_UNIT" \
&& pass "flysim-session.service keeps its session dir on /run/fly/session" \
|| fail "flysim-session.service must set FLY_SESSION_DIR=/run/fly/session"
fi
if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flysim-session.service'; then
fail "fly.target pulls flysim-session.service in beside flysim.service"
else
pass "fly.target does not pull flysim-session.service in"
fi
if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flysim-session'; then
fail "07-enable.sh or verify.sh lists flysim-session.service"
else
pass "07-enable.sh and verify.sh leave flysim-session.service alone"
fi
grep -qE '^d /run/fly/session +0700 fly +fly' "$INFRA_DIR/config/fly-tmpfiles.conf" \
&& pass "tmpfiles creates /run/fly/session 0700 fly" \
|| fail "config/fly-tmpfiles.conf must create /run/fly/session 0700 fly fly"
grep -qE 'for name in .*\bfly-runtime\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh installs fly-runtime" \
|| fail "05-deploy.sh must converge bin/fly-runtime to /opt/fly/bin"
grep -qE '^[[:space:]]*for u in flysim .*\bflysim-session\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes flysim-session.service's cpuset drop-in" \
|| fail "05-deploy.sh cpuset loop must include flysim-session (flysim's cores)"
grep -qF 'flysim.service.d/10-runtime.conf' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"${release_path}/flysim-session"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without flysim-session while the session runtime runs" \
|| fail "05-deploy.sh must refuse a release without flysim-session while 10-runtime.conf is present"
grep -qE -- '--bin flysim-session --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 ---" echo "--- fly-watchdog check 2: the feed counters follow FLY_FEED_VIA ---"
if ! tail -n1 "$INFRA_DIR/bin/fly-watchdog" | grep -qE '^main "\$@"$'; then if ! tail -n1 "$INFRA_DIR/bin/fly-watchdog" | grep -qE '^main "\$@"$'; then
fail "fly-watchdog: expected the last line to be 'main \"\$@\"' — the check-2 fixture strips it" fail "fly-watchdog: expected the last line to be 'main \"\$@\"' — the check-2 fixture strips it"

View file

@ -0,0 +1,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 <case>/baseline.jsonl and <case>/checks.jsonl in fly-shadow-run's sample format
({t, status, rtMean, lag, uptime}) and prints one line per case: `<case> <expect>`, where
<expect> 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()

View file

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

View file

@ -0,0 +1,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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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 (<trace dir>/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

View file

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

View file

@ -435,6 +435,29 @@ dependencies = [
"tracing-subscriber", "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]] [[package]]
name = "fly-session" name = "fly-session"
version = "0.1.1" version = "0.1.1"

View file

@ -2,6 +2,7 @@
resolver = "3" resolver = "3"
members = [ members = [
"crates/fly-edge", "crates/fly-edge",
"crates/fly-legacy-session",
"crates/fly-session", "crates/fly-session",
"crates/fly-session-types", "crates/fly-session-types",
"crates/flybrain-core", "crates/flybrain-core",

View file

@ -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"] }

View file

@ -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<String> = 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}");
}

View file

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

View file

@ -0,0 +1,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<f64>) -> 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<Id, &'static str> {
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
}
}

View file

@ -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` | `<out>/spool` |
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/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 (`<out>/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<String>);
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<String> {
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<T: std::str::FromStr>(&mut self, name: &str) -> Option<T> {
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<PathBuf> {
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<String, String> {
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<String> = 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<u64> = 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),
}
}

View file

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

View file

@ -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<String>, 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<u8>,
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<LegacyCheckpointer>,
saves: u64,
/// Saves on the writer thread whose outcome has not been collected.
pending_saves: Vec<SaveTicket>,
/// 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<String>,
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<String> = 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<u32>,
}
/// One transition as a parity run sees it.
pub struct Step {
pub report: StepReport,
pub details: Option<StepDetails>,
pub records: Vec<TaskRecord>,
}
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<LegacySession, String> {
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<Id, Box<dyn ActionExecutor>> =
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<crate::import::Imported, String> {
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<crate::import::Imported, String> {
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<SaveReport, String> {
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<SaveTicket, String> {
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<Vec<SaveTicket>, 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<u8>); 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<Result<SaveReport, String>> {
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<Vec<SaveQueued>, 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<SaveQueued>), 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<Step, String> {
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<Option<SaveReport>, 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;
}
}

View file

@ -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<String>);
}
/// 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<String>) {
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),
);
}
}

View file

@ -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<generation>`, 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<MemoryImage, String> {
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<Imported, String> {
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<String, u64> = 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,
})
}

View file

@ -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;

File diff suppressed because it is too large Load diff

View file

@ -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<N>`, 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<u8>,
pub agent_payload: Vec<u8>,
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<u8>,
}
/// 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<Outcome, Box<Mismatch>> {
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
}

View file

@ -0,0 +1,154 @@
//! Following the live service's `FLY_TRACE_DIR`: one file per flysim process, named
//! `trace-<start wall ms>-<pid>.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<Vec<PathBuf>> {
let mut files: Vec<PathBuf> = 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<Option<PathBuf>> {
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<File>,
partial: Vec<u8>,
pub lines: u64,
/// Bytes of complete lines handed out.
pub consumed: u64,
}
impl Follower {
pub fn open(path: &Path) -> std::io::Result<Follower> {
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<Option<String>> {
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);
}
}

File diff suppressed because it is too large Load diff

View file

@ -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
//! `<gen>.checkpoint` into the spool at once. Store commits write `<gen>.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, `<gen>.checkpoint`.
pub fn generation_of(name: &str) -> Option<u64> {
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<PathBuf>,
max_bytes: u64,
floor: Arc<AtomicU64>,
stop: Arc<AtomicBool>,
evicted: Arc<AtomicU64>,
/// 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<PathBuf>, max_bytes: u64) -> std::io::Result<Spool> {
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<PathBuf> {
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<Vec<u8>> {
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<Duration>) {
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<u64> = 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::<u64>() > 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<u64>,
held: BTreeMap<u64, u64>,
}
#[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());
}
}

View file

@ -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<u64>,
pub difference: Option<Difference>,
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::<Vec<_>>(),
})
}
}
/// The per-frame cost of the shadow, wall time.
#[derive(Clone, Debug, Default)]
pub struct Cost {
samples: Vec<f64>,
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<String, String>,
/// 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<Skipped>,
pub divergence: Option<Divergence>,
pub started_at: String,
pub passed_at: Option<String>,
pub current_trace: Option<String>,
/// Complete live lines not yet compared in the current segment, when known.
pub lag_transitions: u64,
pub live_lag_seconds: Option<f64>,
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::<Vec<_>>(),
"declaredDifferences": DECLARED.iter().map(|(name, what)| json!({"name": name, "what": what})).collect::<Vec<_>>(),
"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<String, String>,
}
/// 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<i64> {
let b = text.as_bytes();
if b.len() != 24 || b[23] != b'Z' {
return None;
}
let n = |r: std::ops::Range<usize>| -> Option<i64> { 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<String, String> =
[("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<String, String> =
[("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());
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<Value, String> {
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<Value> = 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<Value> = 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<String>, Option<String>) {
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<Vec<Value>, 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<String>,
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<Difference>> {
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<String>],
) -> Result<Agreement, String> {
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;

View file

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

View file

@ -0,0 +1,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<Value> = (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
);
}
}

View file

@ -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");
}

View file

@ -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<u64, String>,
restored: Option<(u64, String)>,
}
struct Scripted {
agent: Id,
seen: Arc<Mutex<Seen>>,
evaluations: u64,
}
fn context() -> TypedValue {
ReadoutContext {
boot: false,
bound: Vec::new(),
location: None,
}
.to_typed()
}
fn image_digest(inspection: &Inspection) -> DomainResult<String> {
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<String> {
vec![MEMORY_ATTACHMENT.to_owned()]
}
fn bootstrap(
&mut self,
initial: &Inspection,
_bindings: &[PortBinding],
) -> DomainResult<Bootstrap> {
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<Evaluation> {
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<RollbackEvaluation> {
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<TypedValue> {
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<BTreeMap<Id, Id>> {
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<TaskEvent>)> {
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<TypedValue> {
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<Id, Box<dyn ActionExecutor>> =
BTreeMap::from([(id("fly"), Box::new(Buttons) as Box<dyn ActionExecutor>)]);
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<String> = 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;
}

View file

@ -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:?}");
}

View file

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

View file

@ -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<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
fn fafb() -> Option<PathBuf> {
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<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!(
"process mode skipped: no worker program at {}",
program.display()
);
}
modes
}
/// 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<RotationDriver>);
impl flysim::frame::FrameObserver for Driven {
fn readout(&mut self, ms: f64, bound: Option<&[String]>, active: &mut Vec<String>) {
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<u8>),
}
/// The run's `FLY_TRACE` behaviours and, when it has them, the ledgers after every boundary.
struct Run {
behaviours: Vec<Value>,
ledgers: Vec<String>,
/// The bound set of each transition's decision (session runs only).
bounds: Vec<Vec<String>>,
}
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<BrainDataset>,
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<String> = 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<fly_legacy_session::composition::SaveQueued>) {
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::<Vec<_>>(),
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<u8> {
let mut checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let reward = &mut checkpoint.runtime.reward;
let map = reward["location"]
.as_str()
.and_then(|l| l.split(':').next())
.unwrap_or("0")
.to_owned();
if let Some(seen) = reward["seen"].as_array_mut() {
seen.retain(|key| {
let key = key.as_str().unwrap_or("");
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
});
}
if let Some(tiles) = reward["tiles"].as_array_mut() {
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
}
if let Some(counts) = reward["tileCounts"].as_object_mut() {
counts.remove(&map);
}
reward["wildWins"] = 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<String> = 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(),
);
}
}
}
}

View file

@ -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<PathBuf> {
let exe = std::env::current_exe().ok()?;
let profile_dir = exe.parent()?.parent()?; // <target>/<profile>/deps/<test>
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<f64> {
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<Result<(Ended, shadow::verdict::Verdict), String>> {
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(&copy).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::<Value>(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, &copy, &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());
}

View file

@ -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;
}
}
}

View file

@ -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<MacroLayer>,
}
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;
}
}

File diff suppressed because it is too large Load diff

View file

@ -42,6 +42,10 @@ use crate::worker::{StatusCell, WorkerHandle, serve};
pub enum Via { pub enum Via {
Memory, Memory,
Unix, 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. /// Where a participant runs.
@ -340,6 +344,8 @@ pub struct LaunchedWorker {
pub peak_rss_kib: u64, pub peak_rss_kib: u64,
body: Body, body: Body,
status: Option<StatusCell>, status: Option<StatusCell>,
/// The local lane a reference carries, when the launcher offers it.
local: Option<crate::worker::LocalLane>,
/// The per-participant socket endpoint, kept alive for the connection's lifetime. /// The per-participant socket endpoint, kept alive for the connection's lifetime.
_listener: Option<UnixListenerHandle>, _listener: Option<UnixListenerHandle>,
} }
@ -354,6 +360,7 @@ impl LaunchedWorker {
&self.identity.worker_id, &self.identity.worker_id,
); );
r.domain_incarnation = Some(self.domain_incarnation.clone()); r.domain_incarnation = Some(self.domain_incarnation.clone());
r.local = self.local.clone();
r r
} }
@ -419,7 +426,7 @@ impl Endpoints {
/// A connection this process owns, over the configured transport. /// A connection this process owns, over the configured transport.
async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> { async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> {
let transport = match self.via { 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 => { Via::Unix => {
let path = self.socket_path(client_id); let path = self.socket_path(client_id);
let listener = self.listen(&path, client_id).await?; let listener = self.listen(&path, client_id).await?;
@ -471,6 +478,8 @@ pub struct Launcher {
supervisor: Client, supervisor: Client,
workers: BTreeMap<Id, LaunchedWorker>, workers: BTreeMap<Id, LaunchedWorker>,
serial: u64, 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. /// The bus client id the supervisor connects under.
@ -534,9 +543,18 @@ impl Launcher {
supervisor, supervisor,
workers: BTreeMap::new(), workers: BTreeMap::new(),
serial: 0, 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 { pub fn mode(&self) -> ExecutionMode {
self.mode self.mode
} }
@ -742,6 +760,10 @@ impl Launcher {
Body::Process(Some(child)) => Some(child.id()), Body::Process(Some(child)) => Some(child.id()),
_ => None, _ => 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 // The registration is discovered, not assumed: the launcher says hello with the
// identity it configured, and the reply is what the coordinator later pins. // identity it configured, and the reply is what the coordinator later pins.
let identified = self.identify(identity).await; let identified = self.identify(identity).await;
@ -756,6 +778,7 @@ impl Launcher {
peak_rss_kib: 0, peak_rss_kib: 0,
body, body,
status, status,
local: None,
_listener: listener, _listener: listener,
}; };
terminate(&mut dying); terminate(&mut dying);
@ -770,6 +793,7 @@ impl Launcher {
peak_rss_kib: 0, peak_rss_kib: 0,
body, body,
status, status,
local,
_listener: listener, _listener: listener,
}; };
worker.refresh_rss(); worker.refresh_rss();

View file

@ -84,6 +84,19 @@ pub const SPIKES_ATTACHMENT: &str = "telemetry.spikes";
/// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes: /// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes:
/// the legacy feed's `spike_bitset` layout. /// the legacy feed's `spike_bitset` layout.
pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset"; pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
/// The legacy agent's read-only feed status (SERVE-01), and the capability that advertises it.
///
/// The legacy feed header and `GET /status` carry numbers from inside the network that no
/// session-framework message carries: the plasticity rule's whole statistics (`learning.changed`
/// counts synapses whose gain moved, `learning.synapses` the rule's edges), the decoder's
/// per-channel baseline and last score, and the rates and pulse as they stand at the committed
/// boundary. The session runtime's service host reads them here, once per published snapshot, at a
/// committed `Ready(k)`, which is where the legacy loop reads them for its own publish. It is a
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
/// answered in any phase once initialized, and is not in any trace.
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
/// The one stimulus kind the profile supports. /// The one stimulus kind the profile supports.
pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE; pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE;
@ -312,6 +325,43 @@ pub fn encode_payload(
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) 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<String>,
accumulator: TickAccumulator,
context: TypedValue,
}
impl CaptureSnapshot {
fn encode(&self) -> DomainResult<Vec<u8>> {
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`). /// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`).
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> { pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
let parts = decode_envelope(bytes, PAYLOAD_MAGIC) 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<u8
if now_ms <= since_ms { if now_ms <= since_ms {
return bytes; return bytes;
} }
for (index, last) in last_spike_ms.iter().enumerate() { // Eight neurons per byte, branch-free, so the compiler vectorises the comparison (PERF-01:
if *last >= since_ms { // 139,255 neurons a frame). The same `last >= since` test as the bit-at-a-time loop.
bytes[index >> 3] |= 1 << (index & 7); 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 bytes
@ -440,6 +502,11 @@ pub struct LegacyAgentWorker {
prepared: Option<(DomainRequestId, PreparedDecision)>, prepared: Option<(DomainRequestId, PreparedDecision)>,
/// The brain time before the in-flight transition's ticks: the spike window's start. /// The brain time before the in-flight transition's ticks: the spike window's start.
transition_start_ms: f64, 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<Vec<u8>>,
staged: Option<StagedAgent>, staged: Option<StagedAgent>,
activated: BTreeSet<Id>, activated: BTreeSet<Id>,
/// Every mutation this worker applied, reported as its progress counter. /// 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<Value> = network
.rates
.iter()
.map(|(name, hz)| json!([name, finite_or_zero(hz)]))
.collect();
let channels: Vec<Value> = decoder
.channel_roles()
.into_iter()
.map(|(channel, role)| {
json!({
"channel": channel,
"role": role,
"baseline": finite_or_zero(baselines.get_or_zero(role)),
"score": finite_or_zero(scores.get_or_zero(channel)),
})
})
.collect();
json!({
"brainMs": finite_or_zero(network.ms),
"rates": rates,
"populationRate": finite_or_zero(network.population_rate),
"rewardRemainingMs": finite_or_zero(network.reward_remaining()),
"learning": {
"enabled": stats.enabled,
"updates": finite_or_zero(stats.updates),
"changed": stats.changed,
"synapses": stats.synapses,
"signal": finite_or_zero(stats.signal),
},
"decoder": {
"calibrated": decoder.calibrated(),
"pending": decoder.pending_baseline_roles(),
"channels": channels,
},
})
}
/// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS` /// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS`
/// order, and the first bound channel the decode holds, which is exactly the channel the legacy /// order, and the first bound channel the decode holds, which is exactly the channel the legacy
/// macro layer's `asked` would start. /// macro layer's `asked` would start.
@ -579,6 +706,7 @@ impl LegacyAgentWorker {
context: None, context: None,
prepared: None, prepared: None,
transition_start_ms: 0.0, transition_start_ms: 0.0,
tick_spikes: None,
staged: None, staged: None,
activated: BTreeSet::new(), activated: BTreeSet::new(),
mutations: 0, mutations: 0,
@ -816,6 +944,28 @@ impl LegacyAgentWorker {
telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements) telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements)
} }
// ---------------------------------------------------------------------------------------
// Legacy.FeedStatus (SERVE-01)
/// The network as the legacy loop's `publish` reads it, at the committed boundary.
fn feed_status(&self) -> DomainResult<HandlerReply> {
let Some(agent) = self.agent.as_ref() else {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus needs an initialized agent",
));
};
if matches!(self.phase, AgentPhase::Prepared(_) | AgentPhase::Failed) {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"Legacy.FeedStatus reads a committed boundary",
));
}
let mut reply = HandlerReply::new(object(feed_status_of(agent)));
reply.mutated = false;
Ok(reply)
}
// --------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------
// Agent.Initialize // Agent.Initialize
@ -1005,7 +1155,32 @@ impl LegacyAgentWorker {
let brain_ticks = accumulator.brain_ticks(); let brain_ticks = accumulator.brain_ticks();
let remainder = accumulator.remainder(); let remainder = accumulator.remainder();
self.transition_start_ms = agent.network.ms; 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 { if agent.network.ms != brain_ticks as f64 {
return Err(applied( return Err(applied(
ErrorCode::Internal, ErrorCode::Internal,
@ -1080,7 +1255,9 @@ impl LegacyAgentWorker {
"Agent.Commit must carry the step of its transition, not the new boundary", "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()?; let params: CommitParams = ctx.params()?;
drop(parse_span);
params params
.validate_against_scope(&scope) .validate_against_scope(&scope)
.map_err(DomainError::invalid)?; .map_err(DomainError::invalid)?;
@ -1110,7 +1287,9 @@ impl LegacyAgentWorker {
} }
let context = self.read_context(&params.next_decision_context)?; let context = self.read_context(&params.next_decision_context)?;
// The complete request and its owned artifact are validated before anything applies. // 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, &params.next_input).await?; let frame = self.read_lcd(ctx, &params.next_input).await?;
drop(read_span);
self.status.set_state(WorkerState::Committing); self.status.set_state(WorkerState::Committing);
let agent = self.agent.as_mut().expect("initialized"); let agent = self.agent.as_mut().expect("initialized");
@ -1139,7 +1318,12 @@ impl LegacyAgentWorker {
self.transient.location = Some(location); self.transient.location = Some(location);
self.transient.blocked_since_ms = ms; 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. // 4. Retain the next context and acknowledge k+1.
let digest = context.digest.clone(); let digest = context.digest.clone();
self.context = Some(context); self.context = Some(context);
@ -1152,7 +1336,9 @@ impl LegacyAgentWorker {
decision_context_digest: digest, decision_context_digest: digest,
telemetry: self.telemetry(), 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 .await
.map_err(|e| applied(e.code, e.message))?; .map_err(|e| applied(e.code, e.message))?;
self.status.set_state(WorkerState::Ready); 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` /// 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 /// manifest member with the accumulator, the context and the identities. The readout
/// transient is not in it (`legacy-transient-reset`). /// transient is not in it (`legacy-transient-reset`).
fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<Vec<u8>> { /// Everything a capture payload is encoded from, copied out of the live agent.
fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<CaptureSnapshot> {
let agent = self.agent.as_ref().expect("initialized"); let agent = self.agent.as_ref().expect("initialized");
let accumulator = self.accumulator.as_ref().expect("initialized"); let accumulator = self.accumulator.as_ref().expect("initialized");
let context = self.context.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`). // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
encode_payload( Ok(CaptureSnapshot {
&state, state,
&PayloadIdentity { agent_id: self.config.agent_id.clone(),
agent_id: &self.config.agent_id, checkpoint_id: checkpoint_id.clone(),
checkpoint_id, scope: scope.clone(),
source_scope: scope,
committed_step: k, committed_step: k,
profile: &self.profile.asset, profile: self.profile.asset.clone(),
seed: self.seed, seed: self.seed,
reinforcements: self.reinforcements, reinforcements: self.reinforcements,
macro_channels: &self.config.macro_channels, macro_channels: self.config.macro_channels.clone(),
}, accumulator: accumulator.clone(),
accumulator, context: context.typed.clone(),
&context.typed, })
None,
)
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
} }
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> { async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
@ -1323,36 +1506,50 @@ impl LegacyAgentWorker {
)); ));
} }
let params: CaptureParams = ctx.params()?; let params: CaptureParams = ctx.params()?;
let previous = self.status.state(); // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's
self.status.set_state(WorkerState::Capturing); // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
let bytes = self.payload(&params.checkpoint_id, &scope, k); // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next
let bytes = match bytes { // Prepare does not wait for them (TASK-01 review N5).
Ok(bytes) => bytes, let snapshot = {
Err(e) => { let _span = crate::profile::span("agent.capture.snapshot");
self.status.set_state(previous); self.snapshot(&params.checkpoint_id, &scope, k)?
return Err(e);
}
}; };
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 graph = self.graph.as_ref().expect("initialized");
let result = CaptureResult { let compatibility = compatibility_digest(
checkpoint_id: params.checkpoint_id,
boundary: k,
compatibility_digest: compatibility_digest(
&self.config.agent_id, &self.config.agent_id,
&self.profile.asset, &self.profile.asset,
graph, graph,
self.seed, 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(), payload: artifact.reference().clone(),
}; };
Ok(HandlerReply::with_artifacts( Ok(HandlerReply::with_artifacts(
object(result.to_json()), object(result.to_json()),
vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)],
)) ))
})))
} }
async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> { async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
@ -1724,6 +1921,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
id("pixel-observation-v1"), id("pixel-observation-v1"),
id(crate::state::CHECKPOINT_CAPABILITY), id(crate::state::CHECKPOINT_CAPABILITY),
id(ROLLBACK_CAPABILITY), id(ROLLBACK_CAPABILITY),
id(FEED_STATUS_CAPABILITY),
] ]
} }
@ -1744,6 +1942,7 @@ impl WorkerEndpoint for LegacyAgentWorker {
"State.Capture", "State.Capture",
"State.StageRestore", "State.StageRestore",
"State.ActivateRestore", "State.ActivateRestore",
METHOD_FEED_STATUS,
] ]
} }
@ -1751,12 +1950,19 @@ impl WorkerEndpoint for LegacyAgentWorker {
Box::pin(async move { Box::pin(async move {
let outcome = match ctx.method { let outcome = match ctx.method {
"Agent.Initialize" => self.initialize(&ctx).await, "Agent.Initialize" => self.initialize(&ctx).await,
"Agent.Prepare" => self.prepare(&ctx).await, "Agent.Prepare" => {
"Agent.Commit" => self.commit(&ctx).await, 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, METHOD_AGENT_ROLLBACK => self.rollback(&ctx).await,
"State.Capture" => self.state_capture(&ctx).await, "State.Capture" => self.state_capture(&ctx).await,
"State.StageRestore" => self.state_stage_restore(&ctx).await, "State.StageRestore" => self.state_stage_restore(&ctx).await,
"State.ActivateRestore" => self.state_activate_restore(&ctx).await, "State.ActivateRestore" => self.state_activate_restore(&ctx).await,
METHOD_FEED_STATUS => self.feed_status(),
other => Err(DomainError::before( other => Err(DomainError::before(
ErrorCode::Unsupported, ErrorCode::Unsupported,
format!("{other} is not an agent method"), format!("{other} is not an agent method"),
@ -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<u8> {
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<f64> = (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] #[test]
fn the_macro_in_a_decision_is_the_first_bound_channel_held() { fn the_macro_in_a_decision_is_the_first_bound_channel_held() {
let active = vec![ let active = vec![

View file

@ -854,13 +854,35 @@ impl LegacyGameboyEnvironment {
/// if there was one. /// if there was one.
async fn observation( async fn observation(
live: &mut Live, live: &mut Live,
client: &flybus::Client, ctx: &HandlerCtx<'_>,
audio: Option<Vec<u8>>, audio: Option<Vec<u8>>,
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
let frame = let image = {
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; let _span = crate::profile::span("env.image");
let image = memory_image(&mut live.emulator).map_err(backend_failure)?; memory_image(&mut live.emulator).map_err(backend_failure)?
let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; };
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 { let view = ViewRef {
view_id: gameboy::VIEW_ID.to_owned(), view_id: gameboy::VIEW_ID.to_owned(),
produced_step: live.boundary, produced_step: live.boundary,
@ -876,13 +898,8 @@ impl LegacyGameboyEnvironment {
(MEMORY_ATTACHMENT.to_owned(), memory), (MEMORY_ATTACHMENT.to_owned(), memory),
]; ];
let mut chunks = Vec::new(); let mut chunks = Vec::new();
if let Some(raw) = audio { if let (Some(raw), Some(samples)) = (audio, samples) {
if raw.len() % AUDIO_CHANNELS as usize != 0 {
return Err(backend_failure("binjgb returned half a stereo frame"));
}
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; 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 { chunks.push(AudioRef {
stream_id: id(AUDIO_STREAM_ID), stream_id: id(AUDIO_STREAM_ID),
first_sample: live.audio_next_sample, first_sample: live.audio_next_sample,
@ -980,7 +997,7 @@ impl LegacyGameboyEnvironment {
audio_discontinuity: false, audio_discontinuity: false,
}; };
let (observation, attachments) = let (observation, attachments) =
LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?;
self.live = Some(live); self.live = Some(live);
// The world is stopped when O[0] goes out and cannot free-run while the brain warms up. // The world is stopped when O[0] goes out and cannot free-run while the brain warms up.
self.status.set_state(WorkerState::Ready); self.status.set_state(WorkerState::Ready);
@ -998,6 +1015,7 @@ impl LegacyGameboyEnvironment {
// -- Environment.Advance ----------------------------------------------------------------- // -- Environment.Advance -----------------------------------------------------------------
async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> { async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
let _span = crate::profile::span("env.advance.handler");
let scope = ctx.scope()?.clone(); let scope = ctx.scope()?.clone();
let params: AdvanceParams = ctx.params()?; let params: AdvanceParams = ctx.params()?;
let status = self.status.clone(); let status = self.status.clone();
@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment {
let applied_from = live.boundary; let applied_from = live.boundary;
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. // `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.buttons = mask;
live.emulator.set_buttons(mask); live.emulator.set_buttons(mask);
live.emulator live.emulator
@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment {
live.framebuffer live.framebuffer
.copy_from_slice(live.emulator.framebuffer()); .copy_from_slice(live.emulator.framebuffer());
let audio = live.emulator.take_audio_u8(); let audio = live.emulator.take_audio_u8();
drop(frame_span);
live.boundary += 1; live.boundary += 1;
live.world_time = live live.world_time = live
.world_time .world_time
@ -1054,7 +1074,7 @@ impl LegacyGameboyEnvironment {
status.progress(1); status.progress(1);
let (observation, attachments) = let (observation, attachments) =
LegacyGameboyEnvironment::observation(live, ctx.client, Some(audio)).await?; LegacyGameboyEnvironment::observation(live, ctx, Some(audio)).await?;
let result = StepResult { let result = StepResult {
batch_id: params.batch_id, batch_id: params.batch_id,
applied_from_step: applied_from, applied_from_step: applied_from,
@ -1150,7 +1170,7 @@ impl LegacyGameboyEnvironment {
live.batches.clear(); live.batches.clear();
live.audio_discontinuity = true; live.audio_discontinuity = true;
let (observation, attachments) = let (observation, attachments) =
LegacyGameboyEnvironment::observation(live, ctx.client, None).await?; LegacyGameboyEnvironment::observation(live, ctx, None).await?;
status.set_state(WorkerState::Ready); status.set_state(WorkerState::Ready);
status.set_scope(Some(scope.clone())); status.set_scope(Some(scope.clone()));
status.progress(1); status.progress(1);
@ -1415,7 +1435,7 @@ impl LegacyGameboyEnvironment {
audio_discontinuity: true, audio_discontinuity: true,
}; };
let (observation, attachments) = let (observation, attachments) =
LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?;
self.live = Some(live); self.live = Some(live);
self.activated.insert(token); self.activated.insert(token);
self.status.set_state(WorkerState::Ready); self.status.set_state(WorkerState::Ready);

View file

@ -38,6 +38,7 @@ pub mod measure;
pub mod media; pub mod media;
pub mod metrics; pub mod metrics;
pub mod phase; pub mod phase;
pub mod profile;
pub mod publish; pub mod publish;
pub mod rpc; pub mod rpc;
pub mod state; pub mod state;

View file

@ -79,6 +79,16 @@ impl Metrics {
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.samples.clear(); 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. /// This process's peak resident set, in KiB, from its own status file.

View file

@ -9,6 +9,8 @@
//! Ready(k) / Paused(k) -> Capturing(k) -> same boundary //! Ready(k) / Paused(k) -> Capturing(k) -> same boundary
//! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k) //! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k)
//! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0) //! 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 //! 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), Restoring(u64),
/// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0. /// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0.
Resetting(u64), 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 { impl Phase {
@ -50,6 +55,7 @@ impl Phase {
Phase::Failed => "Failed".to_owned(), Phase::Failed => "Failed".to_owned(),
Phase::Restoring(k) => format!("Restoring({k})"), Phase::Restoring(k) => format!("Restoring({k})"),
Phase::Resetting(k) => format!("Resetting({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, (Restoring(k), Paused(j)) => k == j,
(Paused(k), Resetting(j)) => k == j, (Paused(k), Resetting(j)) => k == j,
(Resetting(_), Ready(0)) => true, (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, _ => false,
} }
} }
@ -150,6 +164,21 @@ impl PhaseMachine {
mod tests { mod tests {
use super::*; 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] #[test]
fn the_happy_path_walks_the_section_2_diagram() { fn the_happy_path_walks_the_section_2_diagram() {
let mut m = PhaseMachine::new(); let mut m = PhaseMachine::new();

View file

@ -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<BTreeMap<&'static str, (u64, Duration, Duration)>> = 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
}

View file

@ -635,8 +635,31 @@ impl Publisher {
.map(|(name, artifact)| (name.clone(), artifact.reference().clone())) .map(|(name, artifact)| (name.clone(), artifact.reference().clone()))
.collect(); .collect();
check_publication(descriptor, snapshot, &named, audio_next_sample)?; check_publication(descriptor, snapshot, &named, audio_next_sample)?;
let refs: Vec<(&str, &flybus::Artifact)> = // An in-memory artifact (the in-process local lane) is in no router's store, so the
attachments.iter().map(|(n, a)| (n.as_str(), a)).collect(); // 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 topic = self.snapshot_topic.topic.clone();
let outcome = PublicationOutcome::from_bus( let outcome = PublicationOutcome::from_bus(
&topic, &topic,

View file

@ -20,6 +20,10 @@ pub struct WorkerRef {
pub worker_id: Id, pub worker_id: Id,
/// The domain `incarnationId` Hello negotiated, once it has. /// The domain `incarnationId` Hello negotiated, once it has.
pub domain_incarnation: Option<Id>, pub domain_incarnation: Option<Id>,
/// 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<crate::worker::LocalLane>,
} }
impl WorkerRef { impl WorkerRef {
@ -29,6 +33,7 @@ impl WorkerRef {
bus_incarnation: bus_incarnation.to_owned(), bus_incarnation: bus_incarnation.to_owned(),
worker_id: worker_id.clone(), worker_id: worker_id.clone(),
domain_incarnation: None, domain_incarnation: None,
local: None,
} }
} }
} }
@ -69,8 +74,61 @@ pub async fn call(
request_id: DomainRequestId, request_id: DomainRequestId,
want_artifacts: &[String], want_artifacts: &[String],
) -> Result<DomainReply, DomainError> { ) -> Result<DomainReply, DomainError> {
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<String>,
}
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<Scope>,
params: Map<String, Value>,
attachments: &[(&str, &flybus::Artifact)],
request_id: DomainRequestId,
want_artifacts: &[String],
) -> Result<SentCall, DomainError> {
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) }; 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( .call(
&target.service, &target.service,
Some(&target.bus_incarnation), Some(&target.bus_incarnation),
@ -80,26 +138,108 @@ pub async fn call(
) )
.await .await
.map_err(|e| bus_error(method, &e))?; .map_err(|e| bus_error(method, &e))?;
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<DomainReply, DomainError> {
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 result = pending.result().await.map_err(|e| bus_error(method, &e))?;
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
let mut artifacts = BTreeMap::new(); // An independent explicit hold on each wanted attachment, so the handle outlives this
for name in want_artifacts { // delivery and can be forwarded to several Commit calls and to publication. The holds
if let Ok(artifact) = result.artifact(name) { // are independent router round trips, so they are taken concurrently.
// An independent explicit hold, so the handle outlives this delivery and can be let wanted: Vec<(String, flybus::Artifact)> = self
// forwarded to several Commit calls and to publication. .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 { match artifact.retain().await {
Ok(hold) => { Ok(hold) => (name, hold),
artifacts.insert(name.clone(), hold); Err(_) => (name, artifact),
}
Err(_) => {
artifacts.insert(name.clone(), artifact);
}
} }
})
})
.collect();
let mut artifacts = BTreeMap::new();
for retain in retains {
if let Ok((name, artifact)) = retain.await {
artifacts.insert(name, artifact);
} }
} }
drop(result); drop(result);
Ok(DomainReply { outcome, request_id, artifacts }) 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<Vec<(String, flybus::Artifact)>, 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<flybus::Artifact, DomainError> {
match artifact.memory() {
None => Ok(artifact.clone()),
Some(bytes) => {
crate::media::seal_copy(bus, artifact.reference().content_type.clone(), bytes).await
}
}
} }
/// Maps a bus failure onto a domain error, preserving how certain the mutation is. /// Maps a bus failure onto a domain error, preserving how certain the mutation is.

View file

@ -110,6 +110,28 @@ pub fn executor_payload(agent_id: &str) -> String {
pub const WORLD_PAYLOAD: &str = "world"; pub const WORLD_PAYLOAD: &str = "world";
/// The task ledger's payload name. /// The task ledger's payload name.
pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger"; 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-<name>`.
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<String, Vec<u8>>,
) -> std::collections::BTreeMap<String, Vec<u8>> {
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. /// The prior world inspection's payload name.
pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection"; pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection";
/// The coordinator's admission state and event watermarks. /// The coordinator's admission state and event watermarks.

View file

@ -7,6 +7,7 @@
//! writes a controller or neural state directly. //! writes a controller or neural state directly.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@ -53,6 +54,48 @@ pub fn controller_schema_ref() -> SchemaRef {
synthetic_schema("arena.controller.v1", 1) 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<String, Arc<Vec<u8>>>,
}
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<Id, TypedValue>,
pub events: Vec<TaskEvent>,
}
/// What `Task.bootstrap` produced. /// What `Task.bootstrap` produced.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Bootstrap { pub struct Bootstrap {
@ -70,16 +113,27 @@ pub struct Evaluation {
pub progress: TypedValue, pub progress: TypedValue,
pub events: Vec<TaskEvent>, pub events: Vec<TaskEvent>,
pub episode: Option<EpisodeRequest>, pub episode: Option<EpisodeRequest>,
/// 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<Id>,
} }
/// A checkpointable task ledger and the two evaluation entry points. /// A checkpointable task ledger and the two evaluation entry points.
pub trait Task: Send { pub trait Task: Send {
fn schema(&self) -> SchemaRef; 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<String> {
Vec::new()
}
/// Called once, at boundary 0, before any agent is initialized. /// Called once, at boundary 0, before any agent is initialized.
fn bootstrap( fn bootstrap(
&mut self, &mut self,
initial_inspection: &TypedValue, initial_inspection: &Inspection,
bindings: &[PortBinding], bindings: &[PortBinding],
) -> DomainResult<Bootstrap>; ) -> DomainResult<Bootstrap>;
@ -87,11 +141,40 @@ pub trait Task: Send {
fn evaluate_transition( fn evaluate_transition(
&mut self, &mut self,
scope: &Scope, scope: &Scope,
old_inspection: &TypedValue, old_inspection: &Inspection,
new_inspection: &TypedValue, new_inspection: &Inspection,
applied_controls: &[PortControl], applied_controls: &[PortControl],
) -> DomainResult<Evaluation>; ) -> DomainResult<Evaluation>;
/// 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<RollbackEvaluation> {
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<Option<BTreeMap<Id, TypedValue>>> {
Ok(None)
}
fn progress(&self) -> TypedValue; fn progress(&self) -> TypedValue;
/// How many times `evaluate_transition` has run. A transition must evaluate once. /// 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). /// The checkpointable ledger at a committed boundary (`workers-v1` section 4).
fn capture(&self) -> DomainResult<TypedValue>; fn capture(&self) -> DomainResult<TypedValue>;
/// 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<BTreeMap<String, Vec<u8>>> {
Ok(BTreeMap::new())
}
/// [`Task::validate_restore`] with the ledger's attachments.
fn validate_restore_with(
&self,
state: &TypedValue,
attachments: &BTreeMap<String, Vec<u8>>,
) -> 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<String, Vec<u8>>,
) -> DomainResult<()> {
let _ = attachments;
self.install_restore(epoch, state)
}
/// Validates a captured ledger without installing it, so a group install can fail before /// Validates a captured ledger without installing it, so a group install can fail before
/// anything is changed. /// anything is changed.
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>; fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>;
@ -127,7 +239,7 @@ pub trait ActionExecutor: Send {
&mut self, &mut self,
scope: &Scope, scope: &Scope,
decision: &TypedValue, decision: &TypedValue,
current_game_state: &TypedValue, current_game_state: &Inspection,
progress: &TypedValue, progress: &TypedValue,
clock: &RationalNs, clock: &RationalNs,
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)>; ) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)>;
@ -151,7 +263,7 @@ impl ActionExecutor for IdentityExecutor {
&mut self, &mut self,
_scope: &Scope, _scope: &Scope,
decision: &TypedValue, decision: &TypedValue,
_current_game_state: &TypedValue, _current_game_state: &Inspection,
_progress: &TypedValue, _progress: &TypedValue,
_clock: &RationalNs, _clock: &RationalNs,
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> { ) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
@ -294,7 +406,7 @@ impl Task for CounterTask {
fn bootstrap( fn bootstrap(
&mut self, &mut self,
initial_inspection: &TypedValue, initial_inspection: &Inspection,
bindings: &[PortBinding], bindings: &[PortBinding],
) -> DomainResult<Bootstrap> { ) -> DomainResult<Bootstrap> {
if initial_inspection.schema != inspection_schema() { if initial_inspection.schema != inspection_schema() {
@ -329,8 +441,8 @@ impl Task for CounterTask {
fn evaluate_transition( fn evaluate_transition(
&mut self, &mut self,
scope: &Scope, scope: &Scope,
old_inspection: &TypedValue, old_inspection: &Inspection,
new_inspection: &TypedValue, new_inspection: &Inspection,
applied_controls: &[PortControl], applied_controls: &[PortControl],
) -> DomainResult<Evaluation> { ) -> DomainResult<Evaluation> {
let old = old_inspection.integer("counter").map_err(DomainError::invalid)?; let old = old_inspection.integer("counter").map_err(DomainError::invalid)?;
@ -445,6 +557,7 @@ impl Task for CounterTask {
progress: self.progress_value(), progress: self.progress_value(),
events, events,
episode, episode,
slot_saves: Vec::new(),
}) })
} }

View file

@ -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<Box<dyn std::future::Future<Output = DomainResult<HandlerReply>> + Send>>;
/// What a handler produced: a domain `result` object and the artifacts it attaches. /// What a handler produced: a domain `result` object and the artifacts it attaches.
pub struct HandlerReply { pub struct HandlerReply {
pub result: Map<String, Value>, pub result: Map<String, Value>,
pub artifacts: Vec<(String, flybus::Artifact)>, pub artifacts: Vec<(String, flybus::Artifact)>,
/// True when a failure left the endpoint mutated; the shell reports it as such. /// True when a failure left the endpoint mutated; the shell reports it as such.
pub mutated: bool, 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<DeferredReply>,
} }
impl HandlerReply { impl HandlerReply {
pub fn new(result: Map<String, Value>) -> HandlerReply { pub fn new(result: Map<String, Value>) -> HandlerReply {
HandlerReply { result, artifacts: Vec::new(), mutated: true } HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None }
} }
pub fn with_artifacts( pub fn with_artifacts(
result: Map<String, Value>, result: Map<String, Value>,
artifacts: Vec<(String, flybus::Artifact)>, artifacts: Vec<(String, flybus::Artifact)>,
) -> HandlerReply { ) -> 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. /// The canonical JSON of one method result.
@ -144,7 +159,29 @@ pub struct HandlerCtx<'a> {
pub method: &'a str, pub method: &'a str,
pub request: &'a SessionRpcRequest, pub request: &'a SessionRpcRequest,
pub client: &'a flybus::Client, 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<flybus::Request>),
/// 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<flybus::Artifact, String> {
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<'_> { impl HandlerCtx<'_> {
@ -170,10 +207,25 @@ impl HandlerCtx<'_> {
self.incoming.artifact(name).map_err(|e| { self.incoming.artifact(name).map_err(|e| {
DomainError::before( DomainError::before(
ErrorCode::BufferInvalid, 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<u8>) -> DomainResult<flybus::Artifact> {
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. /// A handler's boxed future, so the endpoint trait stays dyn-compatible.
@ -216,6 +268,8 @@ pub struct WorkerHandle {
pub service_incarnation: String, pub service_incarnation: String,
pub status: StatusCell, pub status: StatusCell,
pub cache: Arc<tokio::sync::Mutex<ResultCache>>, pub cache: Arc<tokio::sync::Mutex<ResultCache>>,
/// The same shell, reachable without the bus by a caller in this process.
pub local: LocalLane,
task: tokio::task::JoinHandle<()>, task: tokio::task::JoinHandle<()>,
client: flybus::Client, client: flybus::Client,
} }
@ -233,6 +287,7 @@ impl WorkerHandle {
/// Stops serving and closes the worker's bus connection, which drops its registration and /// 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. /// every owner it held. A later reply from it can attach to nothing.
pub async fn stop(self) { pub async fn stop(self) {
self.local.close();
self.task.abort(); self.task.abort();
let _ = self.task.await; let _ = self.task.await;
self.client.close().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 /// dropped, which this does. For a supervisor's `Drop`, where there is no runtime to wait
/// on. /// on.
pub fn abort(self) { pub fn abort(self) {
self.local.close();
self.task.abort(); self.task.abort();
} }
@ -251,10 +307,158 @@ impl WorkerHandle {
/// the process's exit are the same event rather than two racing ones. /// the process's exit are the same event rather than two racing ones.
pub async fn join(self) { pub async fn join(self) {
let _ = self.task.await; let _ = self.task.await;
self.local.close();
self.client.close().await; 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<LocalReply>);
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<LocalReply> {
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<LocalPending, DomainError>>;
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<dyn LocalDispatch>);
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<LocalPending, DomainError> {
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<LocalReply>),
}
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<E> {
client: flybus::Client,
endpoint: Arc<tokio::sync::Mutex<E>>,
cache: Arc<tokio::sync::Mutex<ResultCache>>,
order: Arc<LockOrder>,
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<Vec<tokio::task::JoinHandle<()>>>,
}
/// The local lane's hold on a shell.
struct ShellRef<E>(Arc<Shell<E>>);
impl<E: WorkerEndpoint> LocalDispatch for ShellRef<E> {
fn send(
&self,
method: String,
request: SessionRpcRequest,
attachments: Vec<(String, flybus::Artifact)>,
) -> BoxFuture<'_, Result<LocalPending, DomainError>> {
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. /// Registers `service_name` and serves `endpoint` on it until the service ends or Shutdown.
pub fn serve<E: WorkerEndpoint>( pub fn serve<E: WorkerEndpoint>(
client: flybus::Client, client: flybus::Client,
@ -267,7 +471,30 @@ pub fn serve<E: WorkerEndpoint>(
let service_name = service.name().to_owned(); let service_name = service.name().to_owned();
let service_incarnation = service.incarnation().to_owned(); let service_incarnation = service.incarnation().to_owned();
let cache = Arc::new(tokio::sync::Mutex::new(ResultCache::new())); 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 { WorkerHandle {
worker_id, worker_id,
incarnation_id, incarnation_id,
@ -275,35 +502,25 @@ pub fn serve<E: WorkerEndpoint>(
service_incarnation, service_incarnation,
status, status,
cache, cache,
local,
task, task,
client, client,
} }
} }
async fn run<E: WorkerEndpoint>( /// What the bus loop answers without entering the endpoint.
client: flybus::Client, struct Common {
mut service: flybus::Service, role: Role,
endpoint: Arc<tokio::sync::Mutex<E>>, capabilities: Vec<Id>,
cache: Arc<tokio::sync::Mutex<ResultCache>>, threads: u64,
) { extra_ack: Option<Id>,
// 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)] async fn run<E: WorkerEndpoint>(shell: Arc<Shell<E>>, mut service: flybus::Service, common: Common) {
let (worker_id, incarnation_id, session_id, role, capabilities, status, methods, threads, extra_ack) = { let Common { role, capabilities, threads, extra_ack } = common;
let e = endpoint.lock().await; let (worker_id, incarnation_id, session_id) =
( (shell.worker_id.clone(), shell.incarnation_id.clone(), shell.session_id.clone());
e.worker_id(), let (status, cache) = (shell.status.clone(), shell.cache.clone());
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<tokio::task::JoinHandle<()>> = Vec::new();
while let Some(incoming) = service.next().await { while let Some(incoming) = service.next().await {
let method = incoming.method().to_owned(); let method = incoming.method().to_owned();
let responder = incoming.responder(); let responder = incoming.responder();
@ -324,8 +541,6 @@ async fn run<E: WorkerEndpoint>(
continue; continue;
} }
}; };
// The contract type already validated the `req-<U64>` 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. // The common methods never enter the endpoint mutex, so they answer during a mutation.
match method.as_str() { match method.as_str() {
@ -381,7 +596,12 @@ async fn run<E: WorkerEndpoint>(
let value = result.to_json(); let value = result.to_json();
let outcome = let outcome =
success(&request, &worker_id, &incarnation_id, object(value)); 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; let _ = responder.reply(outcome.to_outcome(), &[]).await;
// Admitted mutations still finish and answer.
shell.drain().await;
return; return;
} }
Err(e) => { Err(e) => {
@ -399,36 +619,63 @@ async fn run<E: WorkerEndpoint>(
} }
_ => {} _ => {}
} }
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<E: WorkerEndpoint> Shell<E> {
/// 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<Self>,
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<Scope>| {
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-<U64>` form when it read the envelope.
let serial = request.request_id.clone();
let class = if self.methods.contains(&method.as_str()) {
classify_default(&method) classify_default(&method)
} else { } else {
None None
}; };
let Some(class) = class else { let Some(class) = class else {
let outcome = failure( let outcome = refuse(
&request.request_id,
&worker_id,
&incarnation_id,
request.scope.clone(),
DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")), DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")),
request.scope.clone(),
); );
let _ = responder.reply(outcome.to_outcome(), &[]).await; answer.send(outcome, &[]).await;
continue; 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, Ok(body) => body,
Err(e) => { Err(e) => {
let outcome = failure( let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone());
&request.request_id, answer.send(outcome, &[]).await;
&worker_id, return;
&incarnation_id,
request.scope.clone(),
DomainError::invalid(format!("{method}: {e}")),
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
} }
}; };
let key = match (class, &request.scope) { let key = match (class, &request.scope) {
@ -440,18 +687,12 @@ async fn run<E: WorkerEndpoint>(
worker_id: worker_id.clone(), worker_id: worker_id.clone(),
}, },
(OpClass::StepMutation, None) => { (OpClass::StepMutation, None) => {
let outcome = failure( let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None);
&request.request_id, answer.send(outcome, &[]).await;
&worker_id, return;
&incarnation_id,
None,
DomainError::invalid(format!("{method} requires a scope")),
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
} }
_ => OperationKey { _ => OperationKey {
session_id: session_id.clone(), session_id: self.session_id.clone(),
epoch: id("lifecycle"), epoch: id("lifecycle"),
step: 0, step: 0,
method: method.clone(), method: method.clone(),
@ -463,96 +704,169 @@ async fn run<E: WorkerEndpoint>(
// is dereferenced, because a duplicate may arrive after its input delivery was // is dereferenced, because a duplicate may arrive after its input delivery was
// consumed and needs only the cached result. // consumed and needs only the cached result.
let admission = { let admission = {
let mut c = cache.lock().await; let mut c = self.cache.lock().await;
c.admit(class, &key, serial.clone(), &body) c.admit(class, &key, serial.clone(), &body)
}; };
match admission { match admission {
Admission::Replay(reply) => { Admission::Replay(reply) => {
let _ = responder.reply(reply.outcome.to_outcome(), &reply.attachments()).await; answer.send(reply.outcome.clone(), &reply.artifacts).await;
continue; return;
} }
Admission::Refuse(e) => { Admission::Refuse(e) => {
let outcome = failure( let outcome = refuse(e, request.scope.clone());
&request.request_id, answer.send(outcome, &[]).await;
&worker_id, return;
&incarnation_id,
request.scope.clone(),
e,
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
} }
Admission::Execute => {} 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 // 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 // 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. // 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.retain(|task| !task.is_finished());
running.push(tokio::spawn(execute( running.push(task);
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;
} }
} }
/// Runs one admitted mutation, records its reply and answers the bus call. /// Admitted mutations take the endpoint's lock in the order they arrived.
#[allow(clippy::too_many_arguments)] ///
async fn execute<E: WorkerEndpoint>( /// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in
client: flybus::Client, /// spawn order: without this, a `State.Capture` followed on the wire by the next
endpoint: Arc<tokio::sync::Mutex<E>>, /// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken
cache: Arc<tokio::sync::Mutex<ResultCache>>, /// in arrival order, and the lock taken only on the ticket's turn keep the wire's order.
status: StatusCell, #[derive(Default)]
worker_id: Id, struct LockOrder {
incarnation_id: Id, 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<E>,
) -> 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<F: std::future::Future + Unpin>(mut f: F) -> Option<F::Output> {
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, class: OpClass,
key: OperationKey, key: OperationKey,
serial: DomainRequestId, serial: DomainRequestId,
body: Digest, body: Digest,
method: String, method: String,
request: SessionRpcRequest, request: SessionRpcRequest,
incoming: flybus::Request, incoming: Incoming,
}
/// Runs one admitted mutation, records its reply and answers the call.
async fn execute<E: WorkerEndpoint>(
shell: Arc<Shell<E>>,
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 = { let outcome = {
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // 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. // 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 { let ctx = HandlerCtx {
method: &method, method: &method,
request: &request, request: &request,
client: &client, client: &shell.client,
incoming: &incoming, incoming: &incoming,
}; };
e.handle(ctx).await 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 { match outcome {
Ok(reply) => { Ok(mut reply) => {
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone()); let result = std::mem::take(&mut reply.result);
let mut holds = Vec::with_capacity(reply.artifacts.len()); let outcome = success(&request, worker_id, incarnation_id, result);
for (name, artifact) in &reply.artifacts { // The cache owns its own hold on every artifact, so a replay survives the first
// The cache owns its own hold, so a replay survives the first caller // caller consuming its delivery. The holds are independent router round trips, so
// consuming its delivery. // they are taken concurrently; an in-memory artifact is its own hold.
match artifact.retain().await { let retains: Vec<_> = reply
Ok(hold) => holds.push((name.clone(), hold)), .artifacts
Err(_) => holds.push((name.clone(), artifact.clone())), .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); let cached = CachedReply::with_artifacts(outcome.clone(), holds);
{ {
@ -564,9 +878,7 @@ async fn execute<E: WorkerEndpoint>(
} }
} }
status.set_completed(request.request_id.clone()); status.set_completed(request.request_id.clone());
let attachments: Vec<(&str, &flybus::Artifact)> = answer.send(outcome, &reply.artifacts).await;
reply.artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
let _ = responder.reply(outcome.to_outcome(), &attachments).await;
} }
Err(e) => { Err(e) => {
if e.mutation == MutationCertainty::None { if e.mutation == MutationCertainty::None {
@ -576,8 +888,8 @@ async fn execute<E: WorkerEndpoint>(
} else { } else {
let cached = CachedReply::new(failure_outcome( let cached = CachedReply::new(failure_outcome(
&request.request_id, &request.request_id,
&worker_id, worker_id,
&incarnation_id, incarnation_id,
request.scope.clone(), request.scope.clone(),
e.clone(), e.clone(),
)); ));
@ -592,12 +904,12 @@ async fn execute<E: WorkerEndpoint>(
status.set_active(None); status.set_active(None);
let outcome = failure( let outcome = failure(
&request.request_id, &request.request_id,
&worker_id, worker_id,
&incarnation_id, incarnation_id,
request.scope.clone(), request.scope.clone(),
e, e,
); );
let _ = responder.reply(outcome.to_outcome(), &[]).await; answer.send(outcome, &[]).await;
} }
} }
} }
@ -627,6 +939,9 @@ fn classify_default(method: &str) -> Option<OpClass> {
"Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => { "Worker.Hello" | "Worker.Status" | "Worker.Acknowledge" | "Worker.Shutdown" => {
Some(OpClass::ReadOnly) Some(OpClass::ReadOnly)
} }
// The legacy agent's feed status (SERVE-01): a read of the committed boundary that
// changes nothing, so a duplicate simply reads again.
crate::legacy_agent::METHOD_FEED_STATUS => Some(OpClass::ReadOnly),
_ => None, _ => None,
} }
} }

View file

@ -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 Via::Unix
} }
pub fn via_local() -> Via {
Via::Local
}
/// A started session plus the temporary directory its store lives in. /// A started session plus the temporary directory its store lives in.
pub struct Fixture { pub struct Fixture {
pub dir: tempfile::TempDir, pub dir: tempfile::TempDir,

View file

@ -282,6 +282,7 @@ async fn a_reply_from_another_incarnation_is_rejected(via: Via) {
bus_incarnation: restarted.service_incarnation.clone(), bus_incarnation: restarted.service_incarnation.clone(),
worker_id: fly_b(), worker_id: fly_b(),
domain_incarnation: old.domain_incarnation.clone(), domain_incarnation: old.domain_incarnation.clone(),
local: None,
}; };
assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone())); assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone()));
let err = within("status", f.harness.coordinator.status(&stale)) let err = within("status", f.harness.coordinator.status(&stale))

View file

@ -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" "one snapshot carries the whole multi-agent session"
); );
let last = a.last().expect("an entry per boundary"); let last = a.last().expect("an entry per boundary");
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.pixels.artifact_id, last.artifact_id);
}
assert_eq!(published.view.produced_step, last.produced_step); assert_eq!(published.view.produced_step, last.produced_step);
let bytes = published.artifact.read_all().await.expect("the published frame"); let bytes = published.artifact.read_all().await.expect("the published frame");
assert_eq!(bytes.len() as u64, VIEW_WIDTH * VIEW_HEIGHT * 4); 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 = frame_at(&mut spectator, STEPS).await;
let (published_chunk, artifact) = published.audio.first().expect("the published chunk"); let (published_chunk, artifact) = published.audio.first().expect("the published chunk");
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!(published_chunk.samples, chunk.samples);
assert_eq!( assert_eq!(
artifact.reference().artifact_id, artifact.reference().artifact_id,
chunk.samples.artifact_id, chunk.samples.artifact_id,
"the same owned handle is published, not a copy" "the same owned handle is published, not a copy"
); );
}
let bytes = artifact.read_all().await.expect("the published chunk"); let bytes = artifact.read_all().await.expect("the published chunk");
assert_eq!(bytes.len() as u64, per_step * CHANNELS * 4); assert_eq!(bytes.len() as u64, per_step * CHANNELS * 4);
require_finite_samples(&bytes).expect("native samples are finite f32"); require_finite_samples(&bytes).expect("native samples are finite f32");

View file

@ -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(), bus_incarnation: restarted.service_incarnation.clone(),
worker_id: fly_b(), worker_id: fly_b(),
domain_incarnation: old.domain_incarnation.clone(), domain_incarnation: old.domain_incarnation.clone(),
local: None,
}; };
assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone())); assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone()));
let err = within("status", f.harness.coordinator.status(&stale)) let err = within("status", f.harness.coordinator.status(&stale))

View file

@ -25,7 +25,7 @@ both_transports!(
the_committed_snapshot_names_the_boundary_that_just_ended, the_committed_snapshot_names_the_boundary_that_just_ended,
a_terminal_episode_pauses_at_its_own_boundary, a_terminal_episode_pauses_at_its_own_boundary,
a_rollback_request_without_a_declared_policy_fails_the_epoch, 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, status_answers_with_the_committed_boundary,
a_worker_refuses_a_second_initialize, a_worker_refuses_a_second_initialize,
a_single_agent_composition_runs_the_same_transaction, 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; f.shutdown().await;
} }
/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and /// With `legacy-ratchet-rollback-v1` declared the coordinator runs the policy itself
/// the session holds at its boundary with the request recorded, for the policy to run. /// (`step-v1` section 6 amendment; TASK-01), so a composition may only declare it over
async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) { /// 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 { let config = HarnessConfig {
terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), terminal: fly_session::task::Terminal::RollbackAfterTransitions(2),
..HarnessConfig::default() ..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") .declare_rollback_policy("legacy-ratchet-rollback-v1")
.unwrap(); .unwrap();
assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err()); assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err());
within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); let err = within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap_err();
let reports = within("run", f.harness.coordinator.run(4)).await.unwrap(); assert_eq!(err.error.code, ErrorCode::Unsupported, "{}", err.error.message);
assert_eq!(reports.len(), 2); assert!(err.error.message.contains("Agent.Rollback"), "{}", err.error.message);
assert!(!f.harness.coordinator.is_fenced()); assert!(f.harness.coordinator.is_fenced());
assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2)); assert!(f.harness.coordinator.episode_request().is_none());
let request = f.harness.coordinator.episode_request().unwrap();
assert_eq!(request.kind, EpisodeRequestKind::Rollback);
f.shutdown().await; f.shutdown().await;
} }

View file

@ -509,6 +509,18 @@ impl LifNetwork {
} }
/// Run `milliseconds` ticks and return the total spike count. /// 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 { 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 // 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. // feature off this compiles to nothing and the loop below is the whole method.

View file

@ -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<u32> = 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<u32> = (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");
}

View file

@ -37,17 +37,25 @@ impl Drop for OwnerGuard {
pub(crate) fn attachment_list( pub(crate) fn attachment_list(
list: &[(&str, &Artifact)], list: &[(&str, &Artifact)],
) -> (Vec<Attachment>, Vec<Arc<OwnerGuard>>) { ) -> Result<(Vec<Attachment>, Vec<Arc<OwnerGuard>>), BusError> {
let atts = list let mut atts = Vec::with_capacity(list.len());
.iter() let mut keep = Vec::with_capacity(list.len());
.map(|(name, a)| Attachment { 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(), name: (*name).to_owned(),
reference: a.reference.as_ref().clone(), reference: a.reference.as_ref().clone(),
owner_id: a.owner.id.clone(), owner_id: owner.id.clone(),
}) });
.collect(); keep.push(owner.clone());
let keep = list.iter().map(|(_, a)| a.owner.clone()).collect(); }
(atts, keep) Ok((atts, keep))
} }
fn find( fn find(
@ -59,7 +67,7 @@ fn find(
.find(|(n, _)| n == name) .find(|(n, _)| n == name)
.map(|(_, r)| Artifact { .map(|(_, r)| Artifact {
reference: Arc::new(r.clone()), reference: Arc::new(r.clone()),
owner: guard.clone(), holder: Holder::Bus(guard.clone()),
}) })
.ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}"))) .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 /// 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. /// 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)] #[derive(Clone)]
pub struct Artifact { pub struct Artifact {
pub(crate) reference: Arc<ArtifactRef>, pub(crate) reference: Arc<ArtifactRef>,
pub(crate) owner: Arc<OwnerGuard>, 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<OwnerGuard>),
/// 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-<tag>`.
pub const IN_MEMORY_STORE_ID: &str = "in-memory";
impl std::fmt::Debug for Artifact { impl std::fmt::Debug for Artifact {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Artifact") f.debug_struct("Artifact")
.field("reference", &self.reference) .field("reference", &self.reference)
.field("owner", &self.owner.id) .field("owner", &self.owner_id())
.finish() .finish()
} }
} }
impl Artifact { 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<Arc<[u8]>>) -> 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 { pub fn reference(&self) -> &ArtifactRef {
&self.reference &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<Artifact, BusError> {
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. /// 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 { 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. /// Opens the sealed bytes read-only. The file keeps this handle (and so its owner) alive.
pub async fn open(&self) -> Result<ArtifactFile, BusError> { pub async fn open(&self) -> Result<ArtifactFile, BusError> {
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(); let mut body = Map::new();
body.insert("ref".into(), self.reference.to_json()); body.insert("ref".into(), self.reference.to_json());
body.insert("ownerId".into(), self.owner.id.clone().into()); body.insert("ownerId".into(), owner.id.clone().into());
let shared = &self.owner.conn.shared; let shared = &owner.conn.shared;
let reply = shared let reply = shared
.command( .command(
"artifact.open", "artifact.open",
body, body,
Vec::new(), Vec::new(),
vec![self.owner.clone()], vec![owner.clone()],
Hook::None, Hook::None,
) )
.await?; .await?;
@ -130,13 +224,16 @@ impl Artifact {
)); ));
} }
Ok(ArtifactFile { Ok(ArtifactFile {
file, file: Backing::File(file),
_artifact: self.clone(), _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<Vec<u8>, BusError> { pub async fn read_all(&self) -> Result<Vec<u8>, BusError> {
if let Holder::Memory(bytes) = &self.holder {
return Ok(bytes.to_vec());
}
let mut file = self.open().await?; let mut file = self.open().await?;
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
let mut out = Vec::with_capacity(file.len() as usize); 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. /// 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<Artifact, BusError> { pub async fn retain(&self) -> Result<Artifact, BusError> {
let owner = match &self.holder {
Holder::Bus(owner) => owner,
Holder::Memory(_) => return Ok(self.clone()),
};
let mut body = Map::new(); let mut body = Map::new();
body.insert("ref".into(), self.reference.to_json()); body.insert("ref".into(), self.reference.to_json());
body.insert("ownerId".into(), self.owner.id.clone().into()); body.insert("ownerId".into(), owner.id.clone().into());
let shared = &self.owner.conn.shared; let shared = &owner.conn.shared;
let reply = shared let reply = shared
.command( .command(
"artifact.retain", "artifact.retain",
body, body,
Vec::new(), Vec::new(),
vec![self.owner.clone()], vec![owner.clone()],
Hook::Owner, Hook::Owner,
) )
.await?; .await?;
match reply.extra { match reply.extra {
Extra::Owner(owner) => Ok(Artifact { Extra::Owner(owner) => Ok(Artifact {
reference: self.reference.clone(), reference: self.reference.clone(),
owner, holder: Holder::Bus(owner),
}), }),
_ => Err(BusError::lost("retain reply without an owner")), _ => Err(BusError::lost("retain reply without an owner")),
} }
@ -174,10 +276,15 @@ impl Artifact {
/// An open, read-only sealed file. Holds its [`Artifact`]. /// An open, read-only sealed file. Holds its [`Artifact`].
pub struct ArtifactFile { pub struct ArtifactFile {
file: File, file: Backing,
_artifact: Artifact, _artifact: Artifact,
} }
enum Backing {
File(File),
Memory(io::Cursor<Arc<[u8]>>),
}
impl ArtifactFile { impl ArtifactFile {
pub fn len(&self) -> u64 { pub fn len(&self) -> u64 {
self._artifact.reference.byte_length self._artifact.reference.byte_length
@ -194,13 +301,19 @@ impl ArtifactFile {
impl Read for ArtifactFile { impl Read for ArtifactFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file.read(buf) match &mut self.file {
Backing::File(file) => file.read(buf),
Backing::Memory(cursor) => cursor.read(buf),
}
} }
} }
impl Seek for ArtifactFile { impl Seek for ArtifactFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
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")?)?; let reference = ArtifactRef::from_json(Fields::of(&reply.value, "reply").value("ref")?)?;
Ok(Artifact { Ok(Artifact {
reference: Arc::new(reference), reference: Arc::new(reference),
owner: self.owner.clone(), holder: Holder::Bus(self.owner.clone()),
}) })
} }
} }
@ -401,7 +514,7 @@ impl Responder {
outcome: Map<String, Value>, outcome: Map<String, Value>,
attachments: &[(&str, &Artifact)], attachments: &[(&str, &Artifact)],
) -> Result<bool, BusError> { ) -> Result<bool, BusError> {
let (atts, keep) = attachment_list(attachments); let (atts, keep) = attachment_list(attachments)?;
let mut body = Map::new(); let mut body = Map::new();
body.insert("callId".into(), self.call_id.clone().into()); body.insert("callId".into(), self.call_id.clone().into());
body.insert( body.insert(

View file

@ -14,7 +14,7 @@ use tokio::sync::oneshot;
use handles::attachment_list; use handles::attachment_list;
pub use handles::{ 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, RpcResult, Service, Subscription,
}; };
use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared}; use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared};
@ -361,7 +361,7 @@ impl Client {
payload: Map<String, Value>, payload: Map<String, Value>,
attachments: &[(&str, &Artifact)], attachments: &[(&str, &Artifact)],
) -> Result<PendingCall, BusError> { ) -> Result<PendingCall, BusError> {
let (atts, keep) = attachment_list(attachments); let (atts, keep) = attachment_list(attachments)?;
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
let (reply_tx, reply_rx) = oneshot::channel(); let (reply_tx, reply_rx) = oneshot::channel();
let shared = self.shared(); let shared = self.shared();
@ -522,7 +522,7 @@ impl Client {
payload: Map<String, Value>, payload: Map<String, Value>,
attachments: &[(&str, &Artifact)], attachments: &[(&str, &Artifact)],
) -> Result<PublishReceipt, BusError> { ) -> Result<PublishReceipt, BusError> {
let (atts, keep) = attachment_list(attachments); let (atts, keep) = attachment_list(attachments)?;
let mut body = Map::new(); let mut body = Map::new();
body.insert("topic".into(), topic.into()); body.insert("topic".into(), topic.into());
body.insert("payload".into(), Value::Object(payload)); body.insert("payload".into(), Value::Object(payload));

View file

@ -25,7 +25,7 @@ mod store;
mod transport; mod transport;
pub use client::{ 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, Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service,
ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo, ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo,
}; };

View file

@ -54,6 +54,38 @@ pub struct Parts<'a> {
pub macros: Option<&'a mut MacroLayer>, 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. /// 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 /// The stream's loop uses [`FrameObserver::after`] for its per-phase profile and nothing else. A
@ -654,6 +686,15 @@ impl LegacyFrame {
} else { } else {
None 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 { Ok(Boundary {
captured: saved, captured: saved,
rollback, rollback,

View file

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

View file

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

View file

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

View file

@ -29,6 +29,28 @@
//! Wall time is never written, so a run with the periodic checkpoint intervals pushed out of the //! 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 //! way produces the same file twice. Off by default; when off, nothing here is constructed and the
//! loop pays one `Option` test per hook. //! 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=<dir>` writes one file per process, `trace-<wall ms, 13 digits>-<pid>.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 `<dir>/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=<n>` 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::fs::File;
use std::io::{BufWriter, Write}; 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. /// The environment variable that turns the trace on.
pub const ENV: &str = "FLY_TRACE"; 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). /// The ratchet's one slot, as the legacy composition declares it (legacy-gameboy-v1 section 9).
pub const SLOT: &str = "best"; pub const SLOT: &str = "best";
@ -122,6 +217,7 @@ struct Record {
rank: u32, rank: u32,
boundary_actions: Vec<Value>, boundary_actions: Vec<Value>,
captures: Vec<Value>, captures: Vec<Value>,
ledgers: Option<String>,
} }
/// The recorder. The loop calls it at fixed points of the frame order; it holds the transition /// 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<Value>, admissions: Vec<Value>,
/// Brain clock before this transition's ticks, the lower edge of its spike window. /// Brain clock before this transition's ticks, the lower edge of its spike window.
ms_before: f64, ms_before: f64,
/// Bytes written so far, and the cap (`FLY_TRACE_MAX_BYTES`).
written: u64,
max_bytes: Option<u64>,
/// 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<u64>,
/// 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 { impl FrameTrace {
/// `FLY_TRACE`, if it is set and non-empty. A path that cannot be created is an error rather /// `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. /// 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<Option<Self>> { pub fn from_env() -> std::io::Result<Option<Self>> {
match std::env::var_os(ENV) { let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
Some(path) if !path.is_empty() => Self::create(Path::new(&path)).map(Some), let number = |name: &str| -> std::io::Result<Option<u64>> {
_ => Ok(None), match var(name) {
None => Ok(None),
Some(value) => value
.to_str()
.and_then(|v| v.trim().parse::<u64>().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> { pub fn create(path: &Path) -> std::io::Result<Self> {
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<u64>,
ledgers_every: Option<u64>,
) -> std::io::Result<Self> {
let mut out = BufWriter::with_capacity(1 << 20, File::create(path)?); 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 { Ok(Self {
out, out,
initial: Vec::new(), initial: Vec::new(),
@ -159,13 +334,63 @@ impl FrameTrace {
open: None, open: None,
admissions: Vec::new(), admissions: Vec::new(),
ms_before: 0.0, 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) { /// Stops the trace: one marker line, then nothing more. The loop is unaffected.
if let Err(error) = writeln!(self.out, "{value}") { 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"); 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. /// 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. /// Transition `step -> step + 1` begins: the previous one is complete.
pub fn begin(&mut self, step: u64, ms_before: f64) { pub fn begin(&mut self, step: u64, ms_before: f64) {
self.flush_open(); 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() { if let Some(start) = self.initial_step.take() {
let initial = std::mem::take(&mut self.initial); let initial = std::mem::take(&mut self.initial);
self.write(&json!({ self.write(&json!({
@ -309,7 +543,7 @@ impl FrameTrace {
let Some(record) = self.open.take() else { let Some(record) = self.open.take() else {
return; return;
}; };
let line = json!({ let mut line = json!({
"behaviour": { "behaviour": {
"step": record.step.to_string(), "step": record.step.to_string(),
"admissions": record.admissions, "admissions": record.admissions,
@ -331,6 +565,9 @@ impl FrameTrace {
}, },
"operational": { "captures": record.captures }, "operational": { "captures": record.captures },
}); });
if let Some(digest) = record.ledgers {
line["behaviour"]["ledgersDigest"] = Value::String(digest);
}
self.write(&line); self.write(&line);
} }
@ -353,6 +590,122 @@ impl Drop for FrameTrace {
mod tests { mod tests {
use super::*; use super::*;
fn lines(path: &Path) -> Vec<Value> {
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<bool> = 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] #[test]
fn every_legacy_remainder_is_exact_nanoseconds() { fn every_legacy_remainder_is_exact_nanoseconds() {
// The first twelve legacy frames' remainders, from the clock the fixture records. // The first twelve legacy frames' remainders, from the clock the fixture records.

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

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

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

@ -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=<cartridge> tools/shadow-rehearsal.sh --checkpoint FILE [options]
#
# Options:
# --checkpoint FILE the live checkpoint the fly starts from (required)
# --brain-minutes N stop the live service after N brain minutes (default 30)
# --restart-at LIST restart flysim at these brain minutes, comma separated (default: none)
# --sugar-every S POST /stimulate about every S wall seconds (default 20; 0 = never)
# --speed X flysim loop.speed (default 0 = unthrottled; 1 = real time)
# --live-threads N flysim RAYON_NUM_THREADS (default 3, the release value)
# --mode M --threads N the shadow's execution mode and agent threads (in-process, 2)
# --ledgers N FLY_TRACE_LEDGERS (default 1: every boundary)
# --out DIR where everything goes (default: a new temporary directory)
# --bin DIR flysim, fly-shadow (and fly-session for --mode process); default
# $CARGO_TARGET_DIR/release or services/flysim/target/release
# --port N first of three local ports (default 17400)
# --guard S the shadow's --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: <out>/shadow/verdict.json (and divergence.json on a divergence) and <out>/summary.txt:
# live and shadow CPU seconds per wall second, live frames per wall second, the verdict.
set -euo pipefail
die() { echo "shadow-rehearsal: $*" >&2; exit 2; }
repo="$(cd "$(dirname "$0")/.." && pwd)"
checkpoint=""; brain_minutes=30; restart_at=""; sugar_every=20; speed=0; live_threads=3
mode=in-process; threads=2; ledgers=1; out=""; bin=""; port=17400; guard=0.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"