Compare commits

...

232 commits
v0.6.5 ... main

Author SHA1 Message Date
acamilo
291620f5d5 Merge nobs/feed-sigpipe2 (nobs MiniMax M3; Claude review: the test did not reproduce the bug and printf still printed its error; fixed on top)
Some checks failed
ci / node 22 (test + typecheck) (push) Has been cancelled
ci / rust stable (cargo test --workspace --release) (push) Has been cancelled
ci / infra/tests/lint.sh (push) Has been cancelled
ci / playwright apps/stage (allowed to fail) (push) Has been cancelled
2026-10-02 13:16:49 +00:00
acamilo
f21bd45077 fly-feed: silence the failed write itself; the test reproduces pct exec (SIGPIPE ignored, a reader that leaves)
The previous test sent stdout to /dev/null before the pipe, so head never
closed it, and printf still printed its write error. With SIGPIPE ignored
and a slow systemctl stub the old fly-feed prints the live error
('echo: write error: Broken pipe'); the fix prints nothing.
2026-10-02 13:16:49 +00:00
acamilo
75e231c707 fly-feed: status exits quietly on a closed stdout (no broken-pipe error on stderr)
When stdout is closed early (e.g. `fly-feed status | head -1`), the second and later
status_report writes fail with EPIPE; bash's builtins report "write error: Broken pipe"
to stderr even with `trap '' PIPE`, because the failed write is reported by the
runtime, not the signal handler. Route every status_report write through a `say`
helper that checks printf's exit status and exits 0 on the first EPIPE: the reader
is gone, nothing useful is left to do, and `set -e` must not trip on the failing
write.

The change is scoped to status_report: bus/direct's stderr log/record writes are
unaffected, the output text is unchanged, and the switching behaviour and exit
codes are untouched. A test in infra/tests/lint.sh runs `fly-feed status` with
the existing stubbed state into `| head -1` and asserts nothing is written to
stderr.
2026-10-02 13:04:20 +00:00
acamilo
02afc659a4 Merge nobs/gpu-devbox-doc (nobs MiniMax M3; Claude review: fixed the checksum file name, --target and the bench command; re-authored) 2026-10-02 12:48:29 +00:00
acamilo
d501db689c docs: GPU on a build box (dev and benchmarks) section 2026-10-02 12:48:29 +00:00
acamilo
6759555744 docs: v0.7.8 status 2026-10-02 12:27:21 +00:00
acamilo
e4d9d7c9ff Merge port/bus-02 (reviewed: APPROVE-WITH-NOTES; N1-N7 fixed with tests, live speakers soaked): cheaper bus round trips (seal-on-reply, recycled zero-filled staging writers, encode once); session bus transport still off 2026-10-02 12:25:09 +00:00
acamilo
e1f594425e Merge port/gpu-02 (reviewed: APPROVE-WITH-NOTES; N1/N2 fixed: a dead GPU makes the process CPU-only and the replacement restores on the CPU): the GPU brain steps a whole frame per call with state resident on the card (cuda feature, off by default) 2026-10-02 11:51:47 +00:00
acamilo
9a4542de5f flybus: zero-fill a recycled staging file in place instead of truncating and reserving it again
Freeing the blocks and faulting them back in on the producer's next write cost about 36 us a
92,160-byte reply on tmpfs; writing zeros over the blocks already there costs about 10 (rtt,
process mode, interleaved against the branch before the review round). Same guarantee: a
reissued writer reads as zeros, as a fresh allocation does.
2026-10-02 10:59:47 +00:00
acamilo
7d2650ae5e gpu-02 notes: a GPU failure falls back to the CPU for the process lifetime
A CUDA failure (a failed batch or read-back, or an attach that fails at a restart) now marks the
GPU unusable for the process: the replacement agent worker is created on the CPU and restores the
last checkpoint, so a lost device no longer leaves the session unable to restore and a flaky one is
never re-attached in a loop. Worker processes share the record through a marker file the launcher
owns and empties when it starts. Exposed as the LIF_GPU_FALLBACK log line,
fly_brain_backend{backend}, fly_brain_backend_wanted and fly_brain_backend_fallbacks_total, and
fly-watchdog check 11 (report only).

Adds a committed fault-injection hook for the cuda feature (FLY_LIF_CUDA_FAULT or the inject
setters), the recovery harness in legacy_parity, and the cuda_fallback test: init failure, transient
(host current) and permanent (in-process and process) faults, each equal to the CPU reference.
Corrects the runbook, documents the stale host arrays on LifNetwork, and has cuda_session assert
that no fallback hid a CPU pass.
2026-10-02 10:15:03 +00:00
acamilo
da8fa2a927 Merge main (v0.7.7: row 73 + notes, feed and control over flybus, integration feed-rate, BUS-01 notes) into port/bus-02 2026-10-02 10:14:26 +00:00
acamilo
6a92a1902b BUS-02 review notes: recycled writers zero-filled, replays wait for the sealing reply, typed seal failures
The feed and the control API run over flybus in production, so these notes are treated as
live-path correctness.

- N3: the router empties and re-reserves a recycled writer's staging file before reissuing it,
  so no artifact sealed from it (by prefix or whole) carries the previous artifact's bytes;
  ArtifactWriter::seal's doc now holds for every writer. contractDigest text says so.
- N2: a sealing reply is sent with the worker's result cache held, so a duplicate replays the
  sealed artifacts instead of attaching the still-unsealed writer.
- N1: a refused sealing reply is answered as the handler's own seal failure was before BUS-02
  (BACKEND_FAILURE, mutation applied), cached the same way, worker marked failed, and logged.
- N5: a failed staging rename unlinks the writer's own staging file.
- N4: recycle without a sealing attachment is refused even when false; one writer named by two
  attachments is refused as INVALID_ENVELOPE; the SDK checks writers on rpc.call and publish
  replies too.
- N6: the store-directory cache is per client connection; bus-v1 notes the residual case.
- N7: the fly-edge stall test waits for the feed topic; SERVE-01 parity accepts a refused
  /stimulate drained one frame late (retryAfterMs one frame apart, nothing else).
- tests: the review's adversarial lifecycle suite (sealing_lifecycle.rs); recycled-writer content,
  rename failure and recycle edges (sealing.rs); replay-vs-sealing and typed refusal in the worker
  shell; smaller-after-larger artifacts through fly-edge and fly-control-edge.
2026-10-02 10:14:23 +00:00
acamilo
37b3195b0b docs: v0.7.7 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-10-02 09:43:02 +00:00
acamilo
4b29f08c21 Merge fix/loop-row73-notes (coordinator review of the round; N5 cleared: no live watchdog rule fires): bad hidden-object entries skipped, room ledger forgotten on leaving, blocked one-sided targets release the exits 2026-10-02 09:42:53 +00:00
acamilo
49e48a5075 macros: row 73 review notes -- an errand room's talked entries are forgotten when the fly leaves it, a one-sided target with no standable tile is not waited for, an off-map hidden-event entry is skipped
N3: the talked ledger never forgot within a session, but the cartridge re-shows Bill after the fly
leaves and a Bill whose bag was full never hands over the ticket. While the objective is an errand in
a room the palette notes the room, and on the first frame the fly stands elsewhere with that errand
still the objective it forgets that room's talked entries (Talked::forget_map).

N4: a hidden event pressed from one side whose only stand tile is pushed had no aim, earned no
blocked entry and kept the exits withheld. It now leaves the errand's list at once (palette::servable).

N1: state::hidden_events skipped nothing; one entry off its own map voided the whole map's list. It
now skips that entry and keeps the others.

N2: the item-use dispatch doc comment is back on mod items.
2026-10-02 09:40:49 +00:00
acamilo
bbbfe4b68a docs: control runs over flybus 2026-10-02 07:56:18 +00:00
acamilo
5dad5b3cd7 Merge main into port/gpu-02 2026-10-02 07:49:17 +00:00
acamilo
7d817d8cee GPU-02: the session steps a frame per call, the CUDA backend keeps its state on the device
LifNetwork::step_frame runs a game frame's ticks in one call and ORs every
tick's spikes into the transition's bitset. On the CPU it is exactly the
one-tick loop the session ran; on the GPU it is one batch, with membrane
and refractory left on the device (device-owned state): per frame only the
noise draws, visual drive and plastic gains go up and the spike lists come
down, instead of 1.4 MB per tick (about 24 MB per frame) with the old
step(1) loop and per-batch host sync.

- LifBackend (cpu / cuda:<ordinal>) from FLY_LIF_CUDA / FLY_LIF_CUDA_DEVICE,
  set_backend, configure_sweep (set_sweep_plan without the test hook),
  sync_host, host_state_current, try_step, take_backend_fault.
- export_state downloads the device arrays itself while the host copy is
  stale, so no capture can read old values; the session syncs before
  State.Capture.
- A CUDA failure detaches the backend: if the host state was current the
  frame continues bit-exactly on the CPU, otherwise the agent fails and a
  restore in that worker runs on the CPU. Warm-up no longer panics.
- The legacy agent worker picks its backend explicitly and refuses a GPU it
  cannot have (no feature, no device) at Agent.Initialize instead of
  running the CPU under a GPU label. The FLY_LIF_CUDA hook in
  set_sweep_plan stays for the golden suite and the legacy loop.
- cuda passthrough features on fly-session and fly-legacy-session, so
  FLY_CARGO_FEATURES=cuda reaches flysim-session, fly-shadow, fly-session.
- Tests: step_frame vs the one-tick loop (state and bitset, 1 and 3
  threads), the backend switch; cuda_exact frame mode; a cuda-feature
  session test (FAFB, rollback, restore, checkpoints) against the CPU
  reference.
2026-10-02 07:49:17 +00:00
acamilo
0004ffaf36 Merge fix/loop-row73 (reviewed: APPROVE-WITH-NOTES): rung 16 is Bill's errand inside his house; hidden objects read from the cartridge's table are targets only as the errand's next step; Cerulean graph 2026-10-02 07:43:20 +00:00
acamilo
8b696f8f1c docs: the feed runs over flybus 2026-10-02 07:34:50 +00:00
acamilo
6a063d32b4 Merge fix/integration-feed-rate (ported from a stray archive worktree; 8/8 under load): the integration test asserts the feed's structure, not a wall-clock rate 2026-10-02 07:03:50 +00:00
acamilo
48aedd25ff Merge fix/bus-01-notes (coordinator review): bus shadow check refuses on the session runtime; worker children die with their parent (PDEATHSIG, spawned from async worker threads, never spawn_blocking); digest-mismatch test 2026-10-02 07:03:35 +00:00
acamilo
91d0214cbc flysim integration test: assert the feed's structure, not a wall-clock rate
The publish cadence is a 30 Hz wall-clock timer, so the 25..31 Hz bound failed on a
loaded box (22.5 Hz in the v0.7.6 gate). Log the rate, bound it only against the 2 Hz
idle path, and assert what is deterministic: contiguous seq, at least one frame per
snapshot, brain time advancing 16-17 ticks per frame.

Two more load-dependent races in the same test: /status read the boot header (a 1-rung
ladder) right after /healthz, and the first feed message after the restart could be the
frame-0 boot header. Wait for a running snapshot in both.
2026-10-02 06:20:46 +00:00
acamilo
9d5dd398ca Cargo.lock: the fly-edge dependency the EDGE-02/CTRL-01 merge resolution left out
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-10-02 06:06:08 +00:00
acamilo
29b51ff336 docs: implementation guide BUS-02 (port slice) entry 2026-10-02 05:30:31 +00:00
acamilo
6bc447a5bd docs: flybus README and bus conformance rows for sealing sends (BUS-02) 2026-10-02 05:23:08 +00:00
acamilo
4935dcc045 BUS-01 review notes: clippy fixes in the new tests 2026-10-02 05:15:45 +00:00
acamilo
210296a0ff docs: v0.7.6 status 2026-10-02 05:00:24 +00:00
acamilo
fc5a579027 Merge port/edge-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE): the video feed over flybus (off by default), fly-feed switch, aux cpus for the bus threads 2026-10-02 04:57:52 +00:00
acamilo
ef48a6aed9 Merge feat/scorecard (reviewed: BLOCK; B1/B2 fixed with the review's proofs): multi-seed play regression harness, per-checkpoint trap rule, v0.7.5 baseline 2026-10-02 04:56:04 +00:00
acamilo
a2449488a5 scorecard: the lockfile gains libc for the crate; docs for the trap rule, Holm and the throws metric 2026-10-02 04:40:14 +00:00
acamilo
0a35b393aa flybus: sealing sends, encode-once router, cheaper client hot path (BUS-02)
- bus-v1 section 12 amendment 2026-10-02: an rpc.call/rpc.reply/publish attachment may name the
  sender's own unsealed writer; the router seals its declared prefix on admission (copy outside
  the state lock), the writer becomes the sender's hold, and with recycle:true the staging
  allocation comes back as a new writer in the reply. A refused sealing send releases every
  writer it named. contractDigest changes.
- SDK: ArtifactWriter::into_unsealed, Responder::reply_sealing; no rpc.responder.release after an
  admitted reply; delivery payloads moved, not cloned; Fields without hashing.
- Router: every frame encoded once (id spliced at selection); admitted payloads forwarded as
  pre-encoded JSON instead of deep copies; seal copies via copy_file_range with a sized buffer;
  client location resolution caches the store directories.
- fly-session: result attachments kept as delivered (no artifact.retain round trip per
  attachment); reply artifacts sealed by the reply that carries them, writers recycled into a
  capacity-bucketed pool.
- tests: sealing.rs; artifacts.rs updated to the amendment. examples/rtt.rs measures a round trip.
2026-10-02 04:28:05 +00:00
acamilo
2bae8a7b6a macros-traps: row 73, with the multi-seed hunt before and after 2026-10-02 04:26:09 +00:00
acamilo
eaae6fd82a EDGE-02 notes: bus threads on an aux cpu (FLY_SESSION_AUX_CPUS, SESSION_AUX_CPUS in the deploy), fly-feed direct never rolled back, watchdog falls back to direct at the 4th failure and never reboots for the edge; runbook cost corrected 2026-10-02 04:22:39 +00:00
acamilo
49309a83bd scorecard: per-checkpoint trap rule, Holm over the metric family, throws count throws, children die with the suite, LegacyConfig fields
The compare could not fail a trap confined to one checkpoint: add a rule per checkpoint
(B trapped on two or more runs and two more than A, or a blocked-macro storm A lacks).
Holm-adjust the sign-flip p-values over the judged metrics (the unadjusted family false-failed
about 15% of releases). throws_per_hour counts THROW BALL done, not starts; blocked throws are
their own reported metric. run-one children get PR_SET_PDEATHSIG. runner.rs sets transport and
placements (main's LegacyConfig); overlay.sh drops those lines for trees without the fields.
2026-10-02 03:50:50 +00:00
acamilo
397a589fae Merge branch 'main' into feat/scorecard 2026-10-02 03:42:45 +00:00
acamilo
d5b576a2c1 Merge main into port/edge-02 (CTRL-01, BUS-01, row 72, parity flake fix) 2026-10-02 03:19:30 +00:00
acamilo
076a6bcbbf BUS-01 review notes: shadow check refuses on the session runtime (N1), workers die with their parent via PR_SET_PDEATHSIG (N2), test for the Hello digest refusal (N3) 2026-10-02 03:04:49 +00:00
acamilo
c6ab8247d9 Merge port/bus-01 (reviewed: APPROVE-WITH-NOTES): the session can run its agent and world over the flybus router on Unix sockets (off by default); per-frame work metric 2026-10-02 02:53:23 +00:00
acamilo
7dc744fe63 scorecard: the lockfile gains the crate 2026-10-02 02:29:15 +00:00
acamilo
ae05221495 scorecard: the v0.7.5 reference card and what it shows; the hunt's windows are reported, not judged 2026-10-02 02:28:16 +00:00
acamilo
3181c5ef7b scorecard: one thread per run and eight runs at a time, and --resume 2026-10-02 02:28:16 +00:00
acamilo
d7547085e5 scorecard: ten brain minutes, four threads, two jobs: the cost the box can bear 2026-10-02 02:28:16 +00:00
acamilo
ae5db47801 scorecard: the overlay can be run from a copy outside a checkout 2026-10-02 02:28:15 +00:00
acamilo
49bae21a4d scorecard: a multi-seed good-play regression harness (fly-scorecard)
A fixed checkpoint set x seeds x brain minutes on the real connectome, on the session runtime or the legacy loop, reduced to JSON: rungs per hour, empty pad, watchdog check 10 rules, ladder-worthy traps, the shop-to-catch funnel, heals, whiteouts, battles, blocked macros. Compare mode pairs two cards by (checkpoint, seed) and judges each metric with a sign-flip permutation test and a tolerance. PokeredTask gains a read-only with_reader for the harness.
2026-10-02 02:28:15 +00:00
acamilo
872dcfc214 docs: macros.md 12.35 and macros-wram.md 17 (row 73); the hidden-event list bound covers the Game Corner's 48 entries, checked on the cartridge 2026-10-02 02:18:22 +00:00
acamilo
24753db620 Merge fix/service-parity-flake (coordinator review: test-only): the parity test waits for the pause's idle header instead of racing it 2026-10-02 02:16:43 +00:00
acamilo
1ebf35d845 Merge main (v0.7.5 + loop-row72 + ctrl-01) into port/bus-01
service_parity: the control-bus runtime runs on SessionArm::LOCAL.
2026-10-02 02:05:33 +00:00
acamilo
0caade6b20 macros: rung 16 is an errand in Bill's house, its PC is a hidden event, and Cerulean's south is behind the trashed house (row 73)
Rung 16's place was at(ROUTE_25), so inside Bill's house GO OBJECTIVE and GO OUT were both the
door: the live Route 25 <-> Bill's house ring. It is now errand(BILLS_HOUSE): the room's people
first, then its things, where the things include the cartridge's own hidden events, read from
HiddenEventMaps/HiddenEventPointers ($11:$6A40/$6A96, pinned from CheckForHiddenEvent's operands
and shape-checked on every read). A hidden event is only ever the errand's next step: GO ITEM,
GO NPC and TALK elsewhere are unchanged. One with a SPRITE_FACING argument (Bill's PC) is
approached and faced from that side only.

Cerulean is split a third time: the town's ground ends at row 28, and Route 5 and Route 9 are on
the ground behind the trashed house ($3e), in by its front door and out by the hole in its back
wall. The house is on the map graph, so the objective toward rung 17 walks through it.

ROM tests from the scout checkpoints (door ring, PC step, live row-71 Route 25, Cerulean
south-half and trashed house) fail on main and pass here. No button, readout, catalog or adapter
change; the compatibility string is unchanged.
2026-10-02 02:05:33 +00:00
acamilo
7d98fbf8ba Merge port/ctrl-01 (reviewed: APPROVE-WITH-NOTES; N1 edge follows flysim, N2 large bodies as artifacts): control API as flybus RPC with per-agent grants, off by default 2026-10-02 01:44:56 +00:00
acamilo
d50914e4c7 control edge follows flysim's stops and starts; large request bodies match direct
N1: flysim.service Wants= flycontrol-edge.service and the edge gets an ExecCondition on FLY_CONTROL_VIA
(no [Install]), the pattern flyedge uses, so fly-loop-reset's stop and start brings :7401 back in bus
mode and the edge stays skipped in direct mode. lint.sh checks the wiring and runs the condition;
runbook and flybus.md updated (no enable step).

N2: a request body over 48 KiB of JSON travels as a sealed request artifact, so the edge answers
what direct answers instead of 503 INVALID_ENVELOPE. parity test covers 49 KB to 300 KB bodies on
/chat, /stimulate and /reward plus an unparseable large body.
2026-10-02 01:43:34 +00:00
acamilo
3ea56ef3f8 tests: service_parity waits for the idle header instead of racing the pause
The idle-headers check failed 8 of 12 runs on a loaded build box (main
46e25ef: 3 of 4). The script paused and resumed 2 ms apart, so whether the
loop published a header-only idle snapshot in that window (due at 2 Hz) was
wall-clock luck, and legacy and session often disagreed. Not a product race:
the cadence is the protocol's.

The recorder now holds the resume until the first idle header has been seen
(bounded wait, 30 s), and the compare requires BOTH runtimes to have published
one, rather than merely agreeing on whether any did. The first idle header is
compared as before except for its `events` list: which publish carries the
pause's events is wall clock, and the events are compared in the running
snapshots and the event log.

Also fixed, found once the first was gone (1 in 20 under load): the two
sugars sent at one frame must be drained together; when the loop publishes
a snapshot while they are being sent the run is flagged incomplete and
repeated, like a missed frame.

What it proves, unchanged: a pause makes each runtime publish header-only
idle snapshots (status paused, no attachments) whose fields match the legacy
loop, and the script's responses, feed, event log, journal and final
checkpoint are identical between runtimes.

Under load (build box, load ~25 on 6 cores), toy_raw_service_contracts:
before 4/12 pass, after 40/40.
2026-10-02 01:12:56 +00:00
acamilo
74a3c12857 Merge fix/loop-row72 (coordinator review: test-only, both tests stale): the GO SHOP and GO HEAL ROM tests start where the macro is dealt 2026-10-02 00:44:35 +00:00
acamilo
1382f94cf3 runbook: what the rehearsal measured 2026-10-02 00:43:32 +00:00
acamilo
021c92c66f docs: BUS-01 (port slice) in the implementation guide
The live session's participants on the router: how to select it, what it
took, parity in every arm, and the measurement -- about 8 ms a frame over
the lane on the release CPU model, so the lane stays live.
2026-10-02 00:33:25 +00:00
acamilo
b2fd148f52 session: the live composition's participants on the router (BUS-01)
FLY_SESSION_TRANSPORT=bus (flysim-session --transport bus) runs the
agent and the world as socket clients of the session's router, one
process each by default (FLY_SESSION_MODE=thread and in-process too);
local, the PERF-01 lane, stays the default. Results, traces, checkpoints
and the compatibility string are the same in every arm (SessionArm:
local, bus/in-process, bus/thread, bus/process; FLY_PARITY_ARMS picks
them for the parity suites).

- process-mode placement: the service splits its cpuset as PERF-02 does
  and hands each process its CPUs (--host-cpus, --sweep-cpus;
  Launcher::place_process; pool::apply_placement); FLY_SESSION_AUX_CPUS
  moves the service and the world
- the launcher's own clients in memory in thread and process modes
- participants on a one-worker runtime; long handlers under
  block_in_place, which fixes a process-mode boot that failed when
  Agent.Initialize outlived the 2 s probe on a loaded box
- writers allocated ahead (WriterPool); a worker's own seals cached by
  clone, not a second hold
- over the bus the agent's Commit attaches its feed status, which the
  host reads instead of calling Legacy.FeedStatus at every publish
- fly-shadow --mode / FLY_SHADOW_MODE names the topology, forwarded to a
  remote box; the verdict records candidate.transport; fly-shadow check
  --require-arm

legacy-gameboy-v1 section 12 and 18 carry the dated amendments.
2026-10-02 00:09:41 +00:00
acamilo
8b6d69e13c infra: fly-runtime session --bus; shadow of the bus topology
fly-runtime session --bus (session-bus) writes FLY_SESSION_TRANSPORT=bus
into the runtime drop-in and needs the release's fly-session worker;
session --local takes it out; a flag-less session (05-deploy's refresh)
keeps it. status prints the transport. 05-deploy refuses a release
without fly-session while the drop-in says bus.

fly-shadow-run start --bus runs the shadow's session on the bus
(FLY_SHADOW_MODE=bus/process, forwarded to a remote box by the relay);
check --bus requires a verdict that ran it. start refuses while the live
fly runs the session runtime, which writes no trace to follow. Runbook
and lint cover both.
2026-10-01 23:57:34 +00:00
acamilo
673eec54d5 flysim: per-frame compute time on /metrics
fly_frame_work_mean_ms, _p99_ms, _max_ms and _frames: the loop's work per
frame without its pacing sleep, over the last 3,600 frames, so the
headroom a paced realtime factor of 1.0 hides is visible. The legacy loop
records it here; the session runtime's host records it the same way.
2026-10-01 23:57:29 +00:00
acamilo
49f5496d2a flybus: deliveries carry read locations; small store I/O in place; no body copies
A delivery's attachments now name the read location their ownership
grants (bus-v1 section 12, amendment 2026-10-01; contractDigest changes),
so a delivered artifact is read without an artifact.open round trip. A
client attachment that carries one is refused as an unknown field.

SDK and router only, no wire change: staging allocation, seals and
read_all up to 256 KiB run in place instead of on the blocking pool;
Artifact::is_hold tells an explicit hold from a delivery's handle; an
envelope is encoded from borrowed parts and decoded without copying its
body.
2026-10-01 23:57:29 +00:00
acamilo
39efc4af5c docs: control over the bus (CTRL-01)
Services and methods, the grant table as the no-button guarantee, scoping
per session, agent and controller port, and what in control-api.md is
single-fly.
2026-10-01 23:33:59 +00:00
acamilo
8474d93eb0 infra: flycontrol-edge.service and the FLY_CONTROL_VIA switch
Off by default. 05-deploy validates and writes FLY_CONTROL_VIA; the build
and package ship fly-control-edge; the edge gets the page's cpus. With the
control API on the bus, watchdog check 1 reads flysim's own /healthz and
check 1b restarts only the edge. Runbook: the live switch and rollback.
2026-10-01 23:33:59 +00:00
acamilo
29f9b7da3b flysim: the control API as flybus services with per-client grants (FLY_CONTROL_VIA=bus)
The control semantics move to flysim::control, one ControlRequest per
docs/control-api.md endpoint; flysim::api becomes the HTTP layer over a
ControlBackend. flysim::controlbus registers them as services scoped per
session and per agent (fly), with a closed grant table per client role;
flysim::bus composes the feed and control on one embedded router.
fly-control-edge serves :7401 from the services with flysim's own router.

Tests: every endpoint through the edge equals direct (status, headers,
body, and raw HTTP over TCP); grants refuse what they should, including
an input service on a shared router and per-agent/per-port player grants;
backpressure, cancel, deadlines and the edge's unbind/rebind; serve() in
control-bus mode; the session runtime's service contracts over the bus.
2026-10-01 23:33:59 +00:00
acamilo
6851d6f5a3 rom_macros_mode: GO SHOP test from a state where it is dealt (rung-11 Pewter), GO HEAL test forced hot from the first frame
Both tests passed vacuously until the Viridian stall checkpoint was mapped. GO SHOP is dealt for
a service need since rows 62/66 and the parcel errand is GO OBJECTIVE's, so the Viridian
checkpoint (parcel in the bag) rightly has no GO SHOP. In the GO HEAL test the first hold was the
rotation's GO OBJECTIVE, which walked to Oak's lab and left the area.
2026-10-01 23:26:24 +00:00
acamilo
5ca3488c1f runbook, flybus and tour: the feed over the bus in production 2026-10-01 23:17:58 +00:00
acamilo
6612f9ae9c feed bus in production: fly-feed switch, flysim wants the edge, watchdog checks the edge and falls back, deploy refuses a release without fly-edge 2026-10-01 22:10:44 +00:00
acamilo
12321bb513 fly-edge: healthz fails when the bus goes silent; snapshot age gauge 2026-10-01 21:56:34 +00:00
acamilo
23cc217221 flysim-session serves the feed over the bus: a test of the real binary against direct, and a restart under the edge 2026-10-01 21:55:12 +00:00
acamilo
46e25ef3fc docs: cutover to the session runtime
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-10-01 20:47:16 +00:00
acamilo
49bb69e5da docs: v0.7.5 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-10-01 15:58:22 +00:00
acamilo
2c1b51695a Merge port/perf-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE-WITH-NOTES; R1-R3 addressed): the session pins its sweep workers, and the sim's cpus are its own 2026-10-01 15:58:22 +00:00
acamilo
ac7be4a204 infra: fly-cpu-confine also confines /.lxc, check ignores its own chain (PERF-02 review R1-R3)
apply/release/status now cover the cgroup pct exec lands in (/.lxc, only when
it already exists, warn-only when unwritable). check no longer counts its own
process or its parents. Runbook: rollback via an older 05-deploy needs
fly-cpu-confine release; the exact post-first-deploy status/check commands.
2026-10-01 15:57:46 +00:00
acamilo
ab537d1045 infra: the sim's cpus are exclusive to the sim (PERF-02 review N1)
A pinned sweep worker cannot leave its cpu, so any sustained cpu-bound process allowed there
collapsed the session runtime to 0.14x real time. flysim and flysim-session now run in
flysim.slice (AllowedCPUs = the sim's set) and bin/fly-cpu-confine, run by their ExecStartPre,
confines system.slice, user.slice and init.scope to the other cpus. It refuses while a sim unit
still sits outside the slice (shrinking system.slice under it would make it float). Without a
partition the deploy writes FLY_SESSION_PIN=0. fly-recap and fly-retention run at SCHED_IDLE.
The drop-in plan is one function (cpuset_dropin_plan) shared by the deploy and lint; lint covers the
plan, the units, the deploy wiring and fly-cpu-confine against a stub systemctl and a fake /proc.
Runbook and README updated.
2026-10-01 15:01:47 +00:00
acamilo
80104f0d98 docs: v0.7.4 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-10-01 14:47:23 +00:00
acamilo
15ab7ee002 Merge fix/loop-row71 (reviewed: APPROVE both): the bag and mart cursors count the list's scroll offset 2026-10-01 14:47:23 +00:00
acamilo
ecff9bcff4 docs: macros-traps row 71 trap hunt before/after 2026-10-01 13:49:20 +00:00
acamilo
2ca0853c9a docs: macros-traps row 71 2026-10-01 13:18:49 +00:00
acamilo
a6632b4acf macros: the mart's list cursor is the entry too; the catch test pins its first-window ball (row 71)
state::shop reports the buy and sell lists' cursor as row plus
wListScrollOffset, only while the list is on screen. MART_CURSOR_ROWS
stays. The catch ROM test now asserts its ball sits in the bag window's
first rows, so it covers the unscrolled throw beside row 71's scrolled
one.
2026-10-01 13:10:05 +00:00
acamilo
2dcce9452a docs: row 71, the battle bag's scroll offset (macros.md 12.34, macros-wram.md 16) 2026-10-01 12:57:03 +00:00
acamilo
85d2da363a macros: the battle bag's cursor is the entry, not the window's row (row 71)
The battle bag is a DisplayListMenuID list: the arrow walks rows 0..2 and
the window scrolls under it. state::battle reported wCurrentMenuItem alone
as the bag cursor, so THROW BALL and ITEM could never reach a bag entry
past the third. Live on rung 15 a wild Oddish sat at low HP with the
Poke Ball fifth in the bag; row 69 left THROW BALL alone on the pad and
every start blocked.

The cursor is now wCurrentMenuItem + wListScrollOffset, the sum the
cartridge makes on A. wListScrollOffset ($CC36) is pinned from the operand
of DisplayListMenuIDLoop's read and checked by a ROM test. The ROM test
from the live trap checkpoint (FLY_ROW71_CHECKPOINT) blocks on main and
throws and catches on this branch.
2026-10-01 12:57:03 +00:00
acamilo
8fa98b0b03 session: pin the sweep workers one per cpu in flysim-session (PERF-02)
CUT-01's speed probation fell back at a median realtime factor of 0.959.
With exactly as many cpus as sweep threads, the session's host threads
(dispatching tokio worker, coordinator, listeners) sleep and wake around
every transition, the sweep workers park and wake with them, and the
scheduler often stacks two workers on one cpu: the session's ticks ran
about 35% slower than the legacy loop's on the same frames (equal with a
spare cpu).

flybrain_core::pool::place_workers gives each spawned sweep worker a cpu
of its own and confines every other thread to the rest of the cpuset;
flysim-session calls it before spawning anything (in-process and thread
modes; FLY_SESSION_PIN=0 turns it off). Placement chooses cpus only, so
no result, trace or checkpoint changes; the legacy loop, process mode and
the shadow binary never call it. The compatibility string is unchanged.

On the release cpu model, 4 cpus, 4 threads, same frames: session 16.16
-> 12.98 ms/frame (legacy 10.53). The service's profile line prints the
measurement spans and the brain's phase split when FLY_SESSION_PROFILE is
set. Docs: legacy-gameboy-v1 section 12 amendment, implementation entry.
2026-10-01 12:16:59 +00:00
acamilo
390d118460 infra: fly-shadow-run check reads fly.env as KEY=VALUE lines, never sources it
fly.env is systemd EnvironmentFile syntax; GAME_TITLE=Pokemon Red is valid
there and a shell error when sourced. The v0.7.3 cutover's check died on it
(exit 127) after a passing verdict. Parse it as fly-runtime does; lint
refuses any infra/bin script that sources fly.env.
2026-10-01 09:54:11 +00:00
acamilo
16cb3b754b infra: the box set-up's ingest probe tolerates the usage exit
fly-shadow ingest without --root exits 2; piped into grep under pipefail the
probe failed even when the message matched, so the set-up refused every
release. Found on its first run as root on a real box.
2026-10-01 05:56:11 +00:00
acamilo
519503a523 docs: v0.7.3 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-10-01 05:10:22 +00:00
acamilo
e8d8584647 Merge port/shadow-02 (reviewed: r1 BLOCK, r2 BLOCK, r3 APPROVE-WITH-NOTES, final APPROVE): the shadow runs on a build box; the release container relays the trace and keeps the guard and the verdict 2026-10-01 05:10:22 +00:00
acamilo
01fae60e37 shadow: r3 notes: a reward skip still reads on for a stop; the relay flags a byte-cap stop; a window end takes back a pass; runbook: a new run after a long outage
N5: after an operator reward pulse the shadow reads the rest of the trace for its stop line, which ends the window. N4: the relay treats a byte-cap stop exactly like a no-consumer stop. N3: end_window turns a pass back into running and clears passedAt and reason. N2: the runbook says plainly that a long outage costs the run and gives the command to start a new one.
2026-10-01 04:42:02 +00:00
acamilo
ff67e6cdd6 shadow: a trace stop ends the verdict's window; a pass counts only brain time after the last coverage gap (SHADOW-02 review B2)
A stopped trace (no consumer, byte cap) is no longer an allowed skip: the shadow drops the brain time and saves compared before it, so a restarted box shadow that replays a stopped trace cannot count pre-gap time. The relay closes coverageLost only when the verdict's window.lastStopTrace is the lost trace or later, persists coverageLost (fsync) before forwarding the stop, and check refuses a verdict without a window. Runbook: a mid-run relay restart costs the run.
2026-10-01 03:49:18 +00:00
acamilo
239a86f793 infra: fly-shadow-run's check reads FLY_ENV_FILE and FLY_CURRENT_DIR when set (the two-box run); shellcheck 2026-10-01 00:45:54 +00:00
acamilo
b39ee8e805 shadow: a lost coverage is never forgotten (SHADOW-02 review B1) and the review notes
B1: after an outage of more than ten minutes flysim stops its trace for want of a
consumer and the live fly runs untraced. When the link heals the relay reported healthy
and, counted in trace lines, the box's lag fell under the catch-up bound before its
shadow reached the stop, so `check` could pass for about a minute. The relay now scans
the trace bytes it forwards for that stop and sets a sticky coverageLost in relay.json
(kept across a relay restart of the run; cleared only by a new shadow window, which
takes the stop as history) and reports itself not healthy. `check` refuses on
coverageLost, on a live trace not written for 90 s, and on a run id that is not the
drop-in's (also for a verdict that carries one without a remote drop-in).

Notes: the divergence files the box may send are bounded (after a diverged verdict, at
most three, capped in size); the saves queue holds twelve minutes and the relay unit
gets 1G; fly-shadow-remote-setup keeps authorized_keys in a root-owned home apart from
the mirror, never follows a symlink there as root and requires --from; the runbook
documents the clock-skew refusal, the recovered-stop rule and the first-hour RTF watch.
Also: the ingest lists the mirror's traces under its ledger lock (a file created between
the listing and the lock was marked finished).
2026-10-01 00:45:54 +00:00
acamilo
32df851c16 shadow: saves read by the relay survive a broken connection
A save is pending from the moment the relay reads it until the box's byte
count shows it arrived; a new connection sends again every pending save the
box does not hold, before any trace. In the two-box rehearsal an 11-minute
stall that ended in a broken connection lost the saves queued on it.
2026-10-01 00:45:54 +00:00
acamilo
c418a9b352 docs, infra: SHADOW-02 measurements; box setup --threads
implementation.md gains the SHADOW-02 entry (tests, the two-box rehearsal,
per-box cost, the trace's own cost on the live loop and why a writer thread
was rejected). The runbook's resources and box choice carry the measured
numbers; fly-shadow-remote-setup takes --threads (default 4) with --cpus in
one drop-in.
2026-10-01 00:45:54 +00:00
acamilo
b03ddc957d shadow: the relay never blocks on a stalled link
A writer thread owns the ssh pipe. The relay keeps ticking through a stall,
reports itself unhealthy and stops the heartbeat; new saves are still read the
moment they appear and held in memory (256 MiB, about 8 minutes of hot saves:
the container keeps a hot save about ten seconds, and a 3-minute stall in the
two-box rehearsal lost 33 of them); trace bytes wait on disk (16 MiB queued at
most), and a newer trace file and the journal wait until every older file is
complete on its way. A reconnect resends what the box does not hold.
2026-10-01 00:45:54 +00:00
acamilo
ac7762eb00 shadow: ingest unit tests (release refusal, offsets, names, run reset, env allowlist) 2026-10-01 00:45:54 +00:00
acamilo
56a315eda1 shadow: SHADOW-02, the shadow run on a build box
The on-container shadow cost the live fly real time (RTF 0.9998 -> 0.93-0.98,
27 ms/frame on shared CPUs, falling behind every hour). fly-shadow gains:

- relay (release container, as flyshadow.service): streams new saves, the
  trace bytes of this run and the sugar journal over one ssh connection;
  writes the box shadow's verdict back (runId-bound, lagTransitions plus the
  unsynced tail, a relay member) and keeps flysim's consumer heartbeat fresh
  only while connected, the box shadow of this run is alive and the box has
  everything that was on disk a minute ago; exits 3 on a remote divergence.
- ingest (build box, the relay key's forced command): checks the release
  directory and binary hashes against its own, resets the mirror for a new
  run, writes the mirror and reports acks, liveness, verdict, divergence.
- run --run-id-file: the verdict carries runId; a new id exits 4.
- coverage: a no-consumer trace stop while following is a coverage
  divergence (a stop that predates the shadow stays a trace-cap skip); the
  journal is read before the trace directory is listed.

tests/shadow_remote.rs runs a real flysim, the relay, the real ingest binary
and a remote shadow through a restart, a remote shadow death and a sync
stall (coverage divergence relayed back).

infra: fly-shadow-run start runs remote with /etc/fly/shadow-remote.env
(a flyshadow.service drop-in running the relay; --local keeps the old
placement), check also needs relay.json healthy; infra/box/ holds the build
box's flyshadow-remote.service/.path and fly-shadow-remote-setup (release at
the same path, root-owned restrict,command= authorized_keys); 02-base adds
openssh-client. Runbook, lint and a dated legacy-gameboy-v1 section 18
amendment.
2026-10-01 00:45:54 +00:00
acamilo
ce6dcfeb65 docs: v0.7.2 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-10-01 00:45:36 +00:00
acamilo
2e92381296 Merge fix/loop-row70 ladder (reviewed: r3 APPROVE, independent read APPROVE-WITH-NOTES): resets keep a catch for 2 h and count only unseen rewards as progress 2026-10-01 00:05:49 +00:00
acamilo
e4272ba00d infra: a reset's replay is not progress; the ladder measures progress and catches against the reward names it has seen (row 70 review r3)
The watchdog names each lasting reward in window.progress.keys (kind:label).
fly-loop-recover keeps progressSeen (last 2000 names): only a new name starts
the ladder over (and only after a clear probe past SETTLE), and only a new
species opens the 2 h protection. Restarts stay HOLD apart after a start-over;
a failed reset does not mark its archive. Only-rung-11-escapes trap: 2.1 h
(3.3 h after a catch), was 5.6 h / 6.8 h; v0.7.0 2.1 h.
2026-09-30 23:58:13 +00:00
acamilo
18bef06cef infra: catch protection in the recovery ladder is 2 hours, not 6 (operator decision) 2026-09-30 23:28:44 +00:00
acamilo
e35858e96e infra: only a catch-protected reset is held; a step skipped for the archive just used climbs, so the rung below is reached promptly (row 70 review r2) 2026-09-30 20:59:58 +00:00
acamilo
a84e617fc9 infra: a held reset does not climb the ladder and the last-archive marker expires, so a restart-proof trap is reset in bounded time (row 70 review) 2026-09-30 20:57:52 +00:00
acamilo
d7f5ef5ff7 infra: the recovery ladder starts over after real progress, keeps a recent catch, and never replays one archive twice (row 70)
Check 10 now reports window.progress (a milestone, and pokedex/area/trainer/badge rewards; the
species alone), read by no rule. fly-loop-recover returns to level 0 when lasting progress
follows the last step by more than SETTLE, demotes a milestone reset to a restart within six
hours of a species owned, and never restores the archive the last reset restored (a restore is
deterministic: the live rung-11 replay matched the first one event for event and walked into the
same trap). Ladder tests, lint check 10 case 9, loop-recovery.md, macros-traps row 70b-e.
2026-09-30 20:57:52 +00:00
acamilo
539d73bc36 tests: the shadow test waits for the verdict status to settle before asserting it
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
The compared count and the status are recomputed on different verdict
writes; on a loaded box the v0.7.1 release gate read the new count with
the status still 'running'. Bounded wait (120 s); assertions unchanged.
2026-09-30 20:57:27 +00:00
acamilo
7420541df6 docs: v0.7.1 status 2026-09-30 20:21:19 +00:00
acamilo
59ac004b76 Merge fix/loop-row70 hotfix (6eeff4a, reviewed: APPROVE): the SHIFT-style change-Pokémon offer is not a forced switch 2026-09-30 20:21:19 +00:00
acamilo
6eeff4a735 macros: the SHIFT offer's party list is the fly's turn, not a forced switch (row 70)
EnemySendOut opens the party list with BATTLE_PARTY_MENU when the fly answers YES to
"Will <mon> change POKeMON?", the value ChooseNextMon uses after a faint. Read as a forced
switch its pad was SWITCH, NEXT with no B: live in Mt. Moon after the first catch, NEXT on the
Pokemon already out for 58 brain minutes. A forced switch now also needs the active battler at
0 HP; the offer's pad is the party list's SWITCH and BACK.

Unit tests for both lists; ROM tests from the live trap (FLY_ROW70_CHECKPOINT) and from a real
forced switch after a faint (FLY_ROW70_FORCED_CHECKPOINT); macros.md 12.33, macros-traps row 70.
2026-09-30 19:27:08 +00:00
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
606e386e86 docs: v0.6.7 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 03:06:09 +00:00
acamilo
790347af7d Merge feat/damage-reward (reviewed: APPROVE-WITH-NOTES): pay the fly for damage its own attacks deal, adapter pokered-unique8-v8 2026-09-30 03:06:05 +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
be73014bf5 docs: the stage folds a battle's damage hits into one ticker row 2026-09-30 02:41:58 +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
d10aa09afa stage: the ticker folds a battle's hits into one damage row, with two ticker mockups 2026-09-30 02:14:41 +00:00
acamilo
9462c2e28a docs: row 68, the damage reward survey, and a status line
macros-traps: row 68, the catalog's answer to row 67. Three starts x 120 brain
minutes from the row 67 checkpoint, v7 against v8 (the palette seed does not
diversify a run; the starts are the checkpoint and the game run 7 and 19 frames
ahead of the brain). v8 beat the Jr. Trainer in 2 of 3 (one also took the
Boulder Badge), v7 in 0 of 3; the move choice did not shift more under v8 than
under v7 (BUBBLE about 15% -> 20% in both), so no learned preference is shown
inside two brain hours. stream-mvp-plan: an unreleased status line.
2026-09-30 02:11:56 +00:00
acamilo
e9d8f1a753 docs: the damage reward, and the v7 migration in deploy examples
rewards-learning: the catalog row, "Damage rewards" (what counts as the fly's
attack, the magnitudes against the catalog, what cannot be farmed, why `damage`
has no feed counter, the measured press-to-payout delay against the 5 s trace,
the migration) and an honesty paragraph. flysim.md: v7 -> v8 under "Restoring
across an adapter version", with the exact compatibility-string change.
macros-wram: hWhoseTurn, wPlayerMoveNum, wEnemyMonPartyPos and the stale
wEnemyMon. Deploy examples name pokered-unique8-v7 (example.env: add v6 to keep
the pre-v0.6.0 milestone archives restorable).
2026-09-30 02:11:45 +00:00
acamilo
3914f824ce rewards: rom_damage reports how long after the MOVE press each hit is paid 2026-09-30 02:11:45 +00:00
acamilo
17c4c88423 session types: the legacy composition names pokered-unique8-v8
The example composition's adapter and FLYSIM01 string move to v8 with the live
adapter, and the fixtures are regenerated by update_fixtures (composition digest
44916db0... -> d37ccb40...); invalid.json's hand-written cases follow, with the
one deliberately mismatched string moving from v6 to v7 so it is still the
previous adapter. Branches that carry these fixtures (the port stack) regenerate
them the same way on rebase.
2026-09-30 02:11:45 +00:00
acamilo
dfc9a2d227 rewards: damage, adapter v8 with a v7 migration
The operator's decision of 2026-09-29, chosen over a pad rule that would have
withheld a stat move once used: pay the fly for the HP its own attack removes
from the Pokemon it is fighting, so the move that deals damage is worth more
than the one that does not. Row 67: the live fly lost the Pewter Gym's Jr.
Trainer 29 times running with TAIL WHIP 155, BUBBLE 23, TACKLE 0, and nothing in
the catalog paid for anything inside a battle it did not win.

`damage`, the twelfth kind, 80 ms. 0.20 per whole enemy Pokemon's max HP, paid
in proportion on the sample the HP drops; +0.05 when the fly's hit knocks out a
trainer's Pokemon; at most 0.50 a battle (the trainer rule's own value, which
two Pokemon reach exactly). A wild battle pays at the wild-KO rule's scale, 1,
1/2, 1/3, for its first three battles per (map, species, level) that paid any
damage, then nothing, and a rollback blocks every key that has paid
(damageCounts, replay-blocked damage:<key>). Trainer battles keep no lifetime
ledger: a trainer is fought again only after losing to it.

The fly's attack is a drop in wEnemyMonHP on a sample where hWhoseTurn ($FFF3,
counted from the hJoyLast anchor to the end of HRAM) reads 0 and wPlayerMoveNum
is not STRUGGLE. ApplyDamageToEnemyPokemon runs in ExecutePlayerMove with it 0;
the enemy's poison, burn and Leech Seed ticks (HandlePoisonBurnLeechSeed picks
the enemy's HP because it is 1), its recoil, confusion self-hit, Explosion and
Substitute all land with it 1. Every drop moves the target's mark, so a tick is
never paid later as part of a hit. A target is (wEnemyMonPartyPos, species,
level) and keeps its lowest HP for the battle, so a heal is never paid twice and
a switch back keeps its mark; it is marked when it first reads full HP, because
InitBattleVariables leaves the last battle's wEnemyMon in place -- in the row 67
ring that is the same trainer's Diglett at the HP it won with.

v7 -> v8. STATE_VERSION stays 4: damageCounts and battle.damage are optional and
absent in a v7 state, which restores with no wild key paid and a battle in flight
marked where it stands, so nothing lost before the restore is paid.
MIGRATES_FROM is [v7, v6]: the chain composes, since v7's own migration (the
item seed) still runs in this build on the first sample without items:seeded.

Feed: `damage` has no counter (RewardKind::from_adapter -> None). On `wildwin`
the stage would fold every hit into "N wild wins", false of a trainer battle and
of one the fly goes on to lose. A hit reaches the page as a reward event with
its own label, HIT #<species> FOR <n> HP[ KO]; the feed's closed kind set does
not move.

The compatibility string differs from main's in exactly one segment:
pokered-unique8-v7 -> pokered-unique8-v8.

Tests: the rule (fly's turn vs the enemy's, Struggle, heal, switch, twin slots,
stale enemy, restored battle, cap, knockout, wild scale, round trip); the adapter
(proportional pay, TAIL WHIP nothing, poison then hit, the ring's second battle,
wild scale and rollback, one read per address, checkpoint round trip, a v7 state
mid-battle); compat_migration (v7 and v6 FLYSIM01 envelopes refused without
their own opt-in and restored with it; the v7 one mid-battle pays only what
follows); rom_damage (FLY_ROW67_CHECKPOINT: the live v7 string and ledger
migrate; from the live state BUBBLE and TACKLE are paid on every drop they cause
and TAIL WHIP never, the fly's hits land with hWhoseTurn 0 and the enemy's with 1).
2026-09-30 02:11:45 +00:00
acamilo
c433316179 symbols: wPlayerMoveNum and wEnemyMonPartyPos for the damage reward
resolve_wram.py --emit resolved both from ram/wram.asm at the pinned commit,
each bracketed by pinned anchors (wWalkCounter/wEnemyMonSpecies and
wEnemyMonHP/wEnemyMonStatus): $cfd2 and $cfe8. 77 of 81 pinned addresses
re-derived, no disagreement. wEnemyMonPartyPos is battle_struct's third field
(macros/ram.asm: Species db, HP dw, PartyPos). gen_symbols.py's EXTRA_RAM
carries both so a regeneration keeps them.
2026-09-30 02:11:45 +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
f34b236f12 tests: the service test waits for the first snapshot before reading /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
/healthz goes green before the first snapshot is published, and until
then /status carries the placeholder header (a one-rung BOOT ladder). A
loaded box read that window and failed 'the ladder length is in
/status'. Bounded wait (30 s); every assertion unchanged.
2026-09-29 20:15:04 +00:00
acamilo
452525dc38 docs: v0.6.6 status 2026-09-29 19:34:29 +00:00
acamilo
1700bd58e9 Merge feat/row69-throw-name (reviewed: APPROVE-WITH-NOTES): throw on low HP only, the fly names its catch
# Conflicts:
#	infra/docs/macros-traps.md
2026-09-29 19:34:10 +00:00
acamilo
3c72967a5b docs: row 69, throw on low HP only and the fly names its catch
macros.md 12.32 and the 13.1 table rows; macros-wram.md 15 (the two
naming bytes); feed-protocol: padEmptyMs is 0 on the keyboard;
macros-traps row 69 with the ROM tests and the connectome survey.
2026-09-29 18:54:57 +00:00
acamilo
70aa740b37 reset: a sugar journal that cannot be cleared is a warning once the reset is complete
review-state-02 N3: the error made fly-reset-to-milestone exit non-zero
after a finished reset, so fly-loop-reset reported it failed and the
stream's splash said so.
2026-09-29 18:45:05 +00:00
acamilo
5a05b1667a Merge fix/loop-row67 (reviewed: APPROVE-WITH-NOTES)
# Conflicts:
#	docs/design/macros.md
#	infra/docs/macros-traps.md
#	services/flysim/crates/flysim/tests/rom_macros_mode.rs
2026-09-29 18:43:50 +00:00
acamilo
494477e1f2 Merge test/row66-shop-catch (reviewed: APPROVE-WITH-NOTES) 2026-09-29 18:43:19 +00:00
acamilo
70e5ad6134 Merge port/integration (reviewed: APPROVE-WITH-NOTES) 2026-09-29 18:43:19 +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
9cc3a54dc9 Merge port/state-02 (unreviewed, integration base) 2026-09-29 18:11:26 +00:00
acamilo
0d444bb00f tests: row 69 ROM tests; trap_hunt counts the throw's pad and the keyboard
rom_catch: the low-HP pad is the ball (FLY_ROW69_CHECKPOINT), the
keyboard after a catch is the fly's own buttons and closes, a fly that
types nothing is ended by the bound, and the two naming bytes are where
the cartridge stores them. The row 66 catch drive passes the readout's
own buttons and leans on A and B on the keyboard.

rom_macros_mode: the keyboard is drawn, so its CONFIRM is not an
Unknown pad on nothing.
2026-09-29 18:07:15 +00:00
acamilo
e006db3742 macros: a ball at low HP is the only attack, and the fly types its catch's name
Two operator decisions (2026-09-29, row 69).

Throw on low HP only: in a wild battle with THROW BALL dealt and the
wild Pokemon at the HP where ItemUseBall's HP factor saturates
(W = (MaxHP*255/BallFactor)/max(HP/4,1) >= 255: about a third for a
Poke Ball, a half for a Great Ball), MOVE 1-4, SWITCH, RUN and the bag's
BACK are withheld. ITEM stays for a hurt thrower. Every precondition of
THROW BALL still gates it, so no ball, a caught species or a trainer
gives the ordinary pad back.

Let the fly name it: the naming screen is read (menu bytes, the
keyboard's box, the underscores; wNamingScreenNameLength and
wNamingScreenSubmitName pinned from the cartridge's own stores) before
the battle test and reads Unknown. Its pad is the fly's own D-pad, A, B
and START, passed through Observed::raw while nothing is bound. Once
the name is full or sixty brain seconds have run, CONFIRM alone is
dealt and presses START until the keyboard closes.

Also moves two doc comments row 66 split from their items (review N3).
2026-09-29 18:07:15 +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
acamilo
0d41cc2003 docs: STATE-02, the reinforcement count in FLYSIM01 and the import's ids 2026-09-29 17:18:10 +00:00
acamilo
f0981825a0 FLYSIM01 carries the reinforcement count; the import takes its ids from the file; StageRestore refuses conflicts before building a network
AGENT-01 review: learning.updates fell back to plasticity.updates on every FLYSIM01 round trip.
Both runtimes now count reinforcement calls the same way (one per commit while the rule is
enabled) and write the count as the optional manifest member reinforcements, which old readers
ignore and old files lack (a reader then starts from plasticity.updates, once). The import's
checkpoint id is the file's generation (flysim01-g<N>), and the agent worker checks for a
staged or activated restore before it builds the replacement network.
2026-09-29 17:17:56 +00:00
acamilo
d034a26be5 legacy_env: MEM-01's bulk read behind the image seam (ENV-01 review R1)
The environment's memory image is now Emulator::read_memory_image: the
register windows read $FF (legacy-gameboy-v1 section 8, MEM-01 amendment)
and the read is neutral by construction, so the export/import guard is
gone. The toy golden's image digests are regenerated (only 'memory'
changes), the neutrality test states MEM-01's rule, and the ENV-01 guard
amendment is struck in legacy-gameboy-v1 and implementation.md. The
service traces still match in all three modes (rollback 3,199, climb
3,156, r58 11,043).
2026-09-29 17:07:48 +00:00
acamilo
bb70a3b5d7 Merge chore/pii-guard: private names out of the public tree, a scan in lint, tag-release and pre-push 2026-09-29 16:57:02 +00:00
acamilo
2c8596eaa2 pii-scan: refuse an invalid pattern instead of scanning clean, and read '+++' as a header only after '---'
review-pii-guard N2 (a broken private regex made grep exit 2 and the scan
report clean) and N3 (an added line starting '++ ' was taken for a file
header). Tests for both; the env README names BRIDGE_ID_KEY and
BRIDGE_SECRET_KEY.
2026-09-29 16:56:56 +00:00
acamilo
d211e53fab docs: STATE-02 in the implementation guide and the legacy-gameboy-v1 section 16 amendment (2026-09-29) 2026-09-29 16:26:07 +00:00
acamilo
1faccd2908 flysim: STATE-02 proofs: real-checkpoint round trips, restore-then-continue against FLY_TRACE, and the reset tools both ways 2026-09-29 16:26:07 +00:00
acamilo
9c98281f4a fly-session: legacy_checkpoint, the session runtime's FLYSIM01 export, import, store policy and restore selection (STATE-02)
The export assembles a FLYSIM01 file from the agent's FLYAGT01 and the world's FLYENV01 capture
payloads, the task's {reward, ratchet} and the host's fields, through flysim-store's encoder.
The import reads a file back into those halves. The agent payload is the shipped form of
AGENT-01's prototype: learning.updates starts at plasticity.updates, and the file's framebuffer
goes in an inputFrame chunk that StageRestore installs, as the legacy restore does.
LegacyCheckpointer keeps the legacy loop's generations, hot and durable intervals, per-process
milestone archives and writer thread. restore_from_store walks the legacy candidate order and
takes the next candidate on any refusal. The agent worker's payload encoder is now one shared
function, and legacy_parity seeds through the shipped import.
2026-09-29 16:26:07 +00:00
acamilo
32631e2d02 flysim-store: the FLYSIM01 store and the sugar journal in one crate; journal boot header, rotation and reset clearing
store.rs and journal.rs move unchanged from flysim into the new flysim-store crate, which flysim
re-exports, so the session runtime can write and read the same store (STATE-02). The journal gains
a per-process boot header, rotation at 4 MiB with three kept files, and clear(), which
flysim --reset-to-milestone now calls after copying the stores aside.
2026-09-29 16:25:42 +00:00
acamilo
ae878ede41 Merge port/env-01 (unreviewed, integration base)
Both slices add a worker to the same launcher and CLI; the resolution keeps
both: the legacy-agent and legacy-environment subcommands, launch structs,
flags, flag round-trip rows and the flybrain-core/flybrain-gb/flate2
dependencies. Cargo.lock regenerated by cargo.
2026-09-29 16:25:10 +00:00
acamilo
2defc4947a Merge port/mem-01 (unreviewed, integration base) 2026-09-29 15:59:32 +00:00
acamilo
0d6bce8838 flybrain-gb README: the image module 2026-09-29 15:54:57 +00:00
acamilo
f666b404dd docs: MEM-01 status and the section 8 memory-image amendment (2026-09-29) 2026-09-29 15:54:57 +00:00
acamilo
a23e587c96 flysim: image-backed shadow executor equals the live one (MEM-01)
tests/rom_memory_image.rs runs a live arm and a shadow task+executor that
reads only per-boundary images and the cartridge, from nine rom-env
checkpoints: every MacroState answer, deal, pad, decision, reward, ledger and
rollback compared frame by frame, and every shadow read inside the captured
ranges. Plus the gameboy-memory-inspection-v1 encoding against the session
types.
2026-09-29 15:54:57 +00:00
acamilo
3d1a81a679 flybrain-gb: the boundary memory image (MEM-01)
One read-only bulk read in the shim, fly_gb_read_memory_image: the address
space's memory in address order, the register windows (VRAM, OAM, I/O) read
$FF because binjgb's catch-up on a register read moves the exported state.
MemoryImage, Cartridge and ImageReader put an image and the ROM behind
MemoryReader, so the same macro engine and adapter run over it; the
emulator's bank reads go through the same Cartridge. ROM tests prove the read
leaves the state byte-identical, equals the single and cached reads, changes
nothing downstream, and measure its cost.
2026-09-29 15:54:57 +00:00
acamilo
05324293ee tools: pii-scan guard with a private pattern list, tag-release gate and pre-push hook
tools/pii-scan.sh scans the tree, a commit range (added lines and messages) or a push
(pre-push protocol, incl. annotated tag messages). Generic shapes stay in the script; the
proper nouns move to the operator's private list ($FLY_PII_PATTERNS), which can also name
env files whose values are matched as literals and never printed. lint.sh section 5 now
runs it (a missing list is a note, so public CI still passes) and no longer spells the
names with one bracketed character. tag-release.sh fails closed without the list and scans
the tree and every line since the previous tag. tools/install-hooks.sh installs a pre-push
hook that scans pushes to github. Tests in infra/tests/pii-scan-test.sh.
2026-09-29 15:52:35 +00:00
acamilo
49a00bc84a infra: pass entry names out of the public tree
The Twitch app id/secret entry names were spelled in 06-secrets.sh defaults and four docs.
06-secrets.sh now takes BRIDGE_ID_KEY and BRIDGE_SECRET_KEY from the env file (placeholders
in example.env) and skips twitch-app with a warning when they are unset; the docs use
twitch/<app>-client-{id,secret}, twitch/<bot>-token and twitch/<channel>-key.
2026-09-29 15:52:35 +00:00
acamilo
a69a258edd macros: no floor BUY BALL in Viridian before Oak has the parcel; docs for row 66
On the first visit the Viridian clerk's script hands the parcel over, and
his counter sells nothing until Oak has it. MacroState::parcel_delivered
reads EVENT_OAK_GOT_PARCEL (defaulted true).

docs/design/macros.md 12.30 and infra/docs/macros-traps.md row 66: the
GO SHOP ring, the one-button purchase, the bag after a catch, and the
measured choices with the connectome.
2026-09-29 15:38:51 +00:00
acamilo
df08d2eb51 docs: row 67, the Pewter Gym trainer lost on repeat (12.31, audit) 2026-09-29 15:34:01 +00:00
acamilo
7f56feac46 test: the no-PP turn's honest pad is FIGHT alone
The no-PP checkpoint is a trainer battle with a party of one and no Potion:
RUN, THROW BALL, ITEM and SWITCH have nothing behind them, and spent moves
are off the pad since 12.23/12.27, so MOVE 1 (FIGHT, then Struggle) is the
one button and the battle ends in 1,487 frames. The assertion demanded a
second button; it was red on main whenever FLY_NOPP_CHECKPOINT was set.
2026-09-29 15:34:00 +00:00
acamilo
e137260475 test: the Pewter Gym trainer is beaten from what the pad deals (row 67)
From the live checkpoint: on every own-turn frame the pad deals every move
with PP and an effect, and a uniform choice beats the Jr. Trainer the live
readout lost to 29 times. FLY_ROW67_CHECKPOINT.
2026-09-29 15:34:00 +00:00
acamilo
b6a4098992 infra: check 10 flags battles lost on repeat (row 67)
A whiteout ring in the Pewter Gym ran for an hour and a half without a
flag: every macro completed, and a stray tile reward on a walk back reset
the unrewarded rule. Reward lines now carry their rewardKind, and
unwon-battles flags 24+ MOVE n decisions with no wildwin/trainer/badge
reward in the window, on two probes, with no new ground. Report only, as
every check-10 rule; lint case 8 fails on main and passes here.
2026-09-29 15:34:00 +00:00
acamilo
6e090b0be5 Merge feat/agent-legacy-worker (unreviewed, integration base) 2026-09-29 15:13:47 +00:00
acamilo
dc403e8cdf docs: AGENT-01 rebased onto v0.6.5 and checked against FLY_TRACE; FLYSIM01 import seeds learning.updates 2026-09-29 14:26:07 +00:00
acamilo
563afb18f0 tests: the legacy agent worker checked against FND-01's FLY_TRACE of the running legacy frame
FLY_TRACE carries digests, not the frames or the {boot, bound, location} context, so it checks
a worker rather than drives one. legacy_parity gains read_frame_trace and check_against_trace
(ticks, clock, exact remainder, rates digest, spike-set digest, decision; the script held to the
trace's sugar, frames, rewards and rollback), RestoredSource, and
AgentDriver::seed_from_legacy_state for a worker started from a FLYSIM01 agent state.

flysim/tests/agent_trace_parity.rs runs LegacyFrame on the ROM with the trace on, records the
missing inputs, and checks the direct reference and the worker in-process, on a thread and as a
process: toy raw from power-on (FLY_ROM), and gameboy-legacy-fafb-v783-v1 macros mode from a
stream checkpoint with sugar and a ratchet rollback (FLY_AGENT01_FAFB=1). fly-session is a
flysim dev-dependency only.

A FLYSIM01 import starts learning.updates at the legacy plasticity.updates
(legacy_reinforcements): starting at zero broke changed <= updates on the live checkpoint.
2026-09-29 14:26:07 +00:00
acamilo
5da77454c3 macros: BUY BALL is one button from a mart's floor, like HEAL
Operator decision on row 66. Measured with the connectome, the fly walked
to the Viridian clerk again and again and never chose TALK, so the four
choices a purchase took at the counter never happened. BUY BALL is now also
offered on the overworld pad inside a mart whose first stock row is a Poke
Ball (Viridian, Pewter, Cerulean), while service_needed holds (no ball,
money for one, no Oak's parcel) and the clerk is not in the blocked window.
One press walks to the clerk, talks, advances the greeting to BUY/SELL/QUIT
(checking the first row is a Poke Ball), buys one, answers the price box
and is done when the wallet drops. The open-counter BUY BALL is unchanged.

Unit test for each offer condition; ROM row66 floor purchase from
FLY_ROW66_MART_CHECKPOINT: base never dealt on the floor, no ball; branch
dealt, started, done, one ball, 200 paid.
2026-09-29 14:09:02 +00:00
acamilo
96e3ffeeb1 examples: row 66 survey counters
trap_hunt: a shop/ball/catch tally (pad frames, starts, outcomes, balls,
party+box, Pokedex owned, mart entries) and FLY_TRAP_LOG_MACROS=1.
scene_probe offers: catch, party and Pokedex counts, FLY_PROBE_SCREEN_*
screen dumps, FLY_PROBE_SAVE_MART to save a mart entrance.
2026-09-29 13:55:23 +00:00
acamilo
36325d82dd palette: a counter the fly walked away from is not walked back to for the window
Row 62 re-deals GO SHOP/GO HEAL whenever the service is needed, with no
window. Live on v0.6.5 from the rung-8 archive that was a ring: GO SHOP to
the Viridian clerk, GO OUT/GO OBJECTIVE back out without TALK, GO SHOP again
(33 in 35 minutes). A completed GO SHOP/GO HEAL facing the counter person now
records TargetKey::Counter on the building's map; the service walk toward it
is withheld for the reached window, from the street and inside. TALK at the
counter is unchanged.

ROM row66 test (FLY_ROW66_MART_CHECKPOINT): base 31 street GO SHOPs in 10,000
frames, branch 0.
2026-09-29 13:55:23 +00:00
acamilo
5269c2f142 state: the battle bag is open only while its box is on screen
wListMenuID keeps ITEMLISTMENU after the list closes, so from a catch to the
end of the battle (caught text, Pokedex page, nickname offer, naming screen)
the pad read as the bag: BACK and THROW BALL, whose A presses typed the name.
The bag now also needs its TextBoxBorder at (4,2)-(19,12).

rom_catch: row66 test (THROW BALL dealt after the catch: base 666 frames,
branch 0), and both tests retry from idle offsets because one ball misses
about two throws in three and frame timing decides which.
2026-09-29 13:55:23 +00:00
acamilo
931fa01a8c docs: ENV-01 status and the 2026-09-29 amendments (guarded image read, FLYSIM01 boundary, names) 2026-09-29 13:16:22 +00:00
acamilo
d07653cc41 tests: legacy environment goldens and parity in every execution mode, the refusals, and the service trace replay 2026-09-29 13:16:22 +00:00
acamilo
d130a5ffe0 fly-session: a rollback request without a declared rollback policy fails the epoch 2026-09-29 13:16:22 +00:00
acamilo
4819f6ccd9 fly-session: the launcher starts the legacy Game Boy environment in-process, on a thread or as a process 2026-09-29 13:16:22 +00:00
acamilo
e28b0d8999 fly-session: LegacyGameboyEnvironment, the ENV-01 Game Boy environment worker
The emulator half of flysim's LegacyFrame behind the environment methods:
the one-frame setup scaffold, one joypad batch per Advance, f32le audio
(sample/255, unfiltered), the per-boundary memory image behind the MEM-01
seam (read between an export and an import, because emulator_read_mem syncs
OAM/VRAM/timer/STAT/LY), gameboy-slots-v1 SaveSlot/RestoreSlot, capture and
staged restore, and the world's half of FLYSIM01. SaveSlot, RestoreSlot and
Agent.Rollback are step mutations under the ipc-v1 operation key. The parity
harness (toy cartridge, direct reference in LegacyFrame order, bus driver,
FLY_TRACE replay) is in legacy_env_parity.
2026-09-29 13:16:22 +00:00
acamilo
ae503aa7a0 docs: legacy-gameboy-v1 amendments, the rate-role mapping and what the legacy agent reports 2026-09-29 12:21:06 +00:00
acamilo
8f058a402b tests: the gated FAFB run, recorded inputs through the worker against NeuralAgent driven directly 2026-09-29 12:21:06 +00:00
acamilo
625bcb6403 tests: the toy rollback lands in a world that stands still past a blocked window 2026-09-29 12:21:06 +00:00
acamilo
bd57b73b72 tests: legacy agent goldens in every execution mode, two flies, and the refusals 2026-09-29 12:21:06 +00:00
acamilo
214755f2b9 fly-session: the AGENT-01 parity harness, a direct NeuralAgent reference and a toy connectome 2026-09-29 12:21:06 +00:00
acamilo
fbf7c1e486 fly-session: the launcher starts a legacy agent in-process, on a thread or as a process 2026-09-29 12:21:06 +00:00
acamilo
9bdfb079e5 fly-session: LegacyAgentWorker, the legacy Game Boy agent over the neural core
Agent.Initialize checks the profile against the dataset fingerprint and
warms up as the legacy fresh start does; Prepare applies sugar, ticks the
548625/32768 ms frame on the rational clock and decodes with
gameboy-readout-context-v1; Commit installs the frame, stimulates, then
reinforces once; Agent.Rollback is legacy-ratchet-rollback-v1's agent
half; capture is agent_to_chunks in an envelope and a restore resets the
readout transient as a fresh legacy process has it.
2026-09-29 12:21:06 +00:00
acamilo
72cefb773b session-types: legacy-rate-role-id-v1, the identity on the Id grammar, pinned in both languages 2026-09-29 12:21:06 +00:00
300 changed files with 69031 additions and 2381 deletions

View file

@ -32,6 +32,8 @@ Read `docs/architecture-tour.md` first. Then `docs/stream-mvp-plan.md` for decis
LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass` LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass`
entry names or forge URLs. Say "the host", "the release container", "the dev container", "the entry names or forge URLs. Say "the host", "the release container", "the dev container", "the
channel", "the operator"; put the real values in the operator's infra repo. Real values belong channel", "the operator"; put the real values in the operator's infra repo. Real values belong
in an env file outside the checkout — see `infra/env/README.md`. `infra/tests/lint.sh` refuses in an env file outside the checkout — see `infra/env/README.md`. `tools/pii-scan.sh` refuses
the patterns; the rules live in the operator's infra repo and the patterns (run by `infra/tests/lint.sh`, `infra/build/tag-release.sh` and the pre-push hook
`infra/tests/de-pii-allow.txt` the few legitimate mentions. from `tools/install-hooks.sh`); the proper nouns it looks for live in the operator's private
pattern list (`$FLY_PII_PATTERNS`), never here, and `infra/tests/de-pii-allow.txt` lists the few
legitimate mentions. Run `tools/install-hooks.sh` once per clone.

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View file

@ -698,6 +698,24 @@ export function App() {
ingest.commit(hot.lastSnapshotMs, true); ingest.commit(hot.lastSnapshotMs, true);
return useStage.getState().chat.length; return useStage.getState().chat.length;
}, },
/**
* Feed reward events into the ticker by hand, `stepMs` of feed time apart, for the ticker
* mockups (a battle's hits, a KO), and settle the dwell gate five seconds after the last.
* The events go through the same `TickerQueue.push` a snapshot's do.
*/
ticker: (events, stepMs = 7000) => {
let at = hot.lastSnapshotMs;
for (const [index, item] of events.entries()) {
at = hot.lastSnapshotMs + index * stepMs;
ingest.queue().push(
{ id: 900_000 + index, wallMs: 0, brainMs: 0, kind: 'reward', label: item.label, value: item.value },
at,
);
}
at += 5000;
ingest.commit(at, true);
return useStage.getState().ticker.map((row) => `${row.label} ${String(row.amount ?? '')}`);
},
/** /**
* Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the * Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the
* splash mockups and e2e assertions. The raw object goes through the same validation as a * splash mockups and e2e assertions. The raw object goes through the same validation as a
@ -790,6 +808,8 @@ declare global {
fire: (type: MomentType, label?: string, detail?: string) => number | null; fire: (type: MomentType, label?: string, detail?: string) => number | null;
/** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */ /** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */
chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number; chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number;
/** Push reward events into the ticker by hand; returns the rows shown. */
ticker: (events: readonly { label: string; value: number }[], stepMs?: number) => string[];
/** Show a recovery notice by hand (validated like a polled one); null clears it. */ /** Show a recovery notice by hand (validated like a polled one); null clears it. */
recovery: (notice: unknown, nowS?: number) => RecoveryView | null; recovery: (notice: unknown, nowS?: number) => RecoveryView | null;
fly: () => { fly: () => {

View file

@ -89,6 +89,11 @@ export const pokemonRed: GameConfig = {
badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 }, badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 },
}, },
// The fly's own hits (adapter `damage`): several a battle, no protocol kind, so one row per
// battle that counts up. 45 s covers the slowest turn seen (about 7 s from press to payout)
// several times over and is far shorter than the gap between two battles.
hitCopy: { label: 'damage dealt', gapMs: 45_000, tier: 'quiet', koTier: 'notable' },
counters: [ counters: [
{ field: 'badges', label: 'badges', outOf: 8 }, { field: 'badges', label: 'badges', outOf: 8 },
{ field: 'uniqueLocations', label: 'places' }, { field: 'uniqueLocations', label: 'places' },

View file

@ -29,6 +29,21 @@ export interface RewardCopy {
collapsedNoun?: string; collapsedNoun?: string;
} }
/**
* Copy and window for the adapter's per-hit reward, which the protocol has no `rewardKind` for
* (Pokémon Red's `damage`, `HIT #<species> FOR <n> HP[ KO]`). Hits are folded stage-side into one
* row per battle instead of one row per hit.
*/
export interface HitCopy {
/** Row text. Constant; the feed's label is only read for the KO suffix. */
label: string;
/** A row is joined by a hit up to this long after the previous hit folded into it. */
gapMs: number;
/** Tier of the row; a KO raises it to `koTier`. */
tier: RewardTier;
koTier: RewardTier;
}
/** A counter shown in the progress row beside the milestone ladder. */ /** A counter shown in the progress row beside the milestone ladder. */
export interface GameCounter { export interface GameCounter {
/** Which `FeedGame` field to read. */ /** Which `FeedGame` field to read. */
@ -64,6 +79,8 @@ export interface GameConfig {
modeLabels: Record<GameMode, string>; modeLabels: Record<GameMode, string>;
/** Human copy and presentation tier for each reward kind. */ /** Human copy and presentation tier for each reward kind. */
rewardCopy: Record<RewardKind, RewardCopy>; rewardCopy: Record<RewardKind, RewardCopy>;
/** How a reward event with no `rewardKind` that reads as a hit is rolled up. Absent: never. */
hitCopy?: HitCopy;
/** /**
* Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g. * Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g.
* "3/8 badges · 214 places". Per-game *data*, not copy: the values come * "3/8 badges · 214 places". Per-game *data*, not copy: the values come

View file

@ -68,6 +68,9 @@ export const DEFAULT_TICKER_OPTIONS = {
*/ */
const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']); const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']);
/** The adapter's hit label: `HIT #<species> FOR <n> HP` with ` KO` when the hit felled a trainer's Pokémon. */
const HIT_LABEL = /^HIT #\d+ FOR \d+ HP( KO)?$/;
export class TickerQueue { export class TickerQueue {
private readonly visibleRows: number; private readonly visibleRows: number;
private readonly minDwellMs: number; private readonly minDwellMs: number;
@ -77,6 +80,8 @@ export class TickerQueue {
private visible: TickerItem[] = []; private visible: TickerItem[] = [];
private pending: TickerItem[] = []; private pending: TickerItem[] = [];
private lastPromotionMs = Number.NEGATIVE_INFINITY; private lastPromotionMs = Number.NEGATIVE_INFINITY;
/** Feed time of the last hit folded into each hit row, by the row. */
private readonly lastHitMs = new WeakMap<TickerItem, number>();
/** Bumped whenever the visible list changes, so the store can push to React on change only. */ /** Bumped whenever the visible list changes, so the store can push to React on change only. */
private revision = 0; private revision = 0;
@ -106,10 +111,11 @@ export class TickerQueue {
push(event: FeedEvent, nowMs: number): boolean { push(event: FeedEvent, nowMs: number): boolean {
if (HIDDEN_KINDS.has(event.kind)) return false; if (HIDDEN_KINDS.has(event.kind)) return false;
const tier = this.tierOf(event); const hit = this.hitOf(event);
const label = this.labelOf(event); const tier = hit ? this.hitTier(hit.ko) : this.tierOf(event);
const label = hit ? `${this.game.hitCopy?.label ?? event.label}${hit.ko ? ' KO' : ''}` : this.labelOf(event);
const folded = this.fold(event, nowMs); const folded = hit ? this.foldHit(event, hit.ko, nowMs) : this.fold(event, nowMs);
if (folded) return true; if (folded) return true;
const item: TickerItem = { const item: TickerItem = {
@ -125,6 +131,8 @@ export class TickerQueue {
...(event.by === undefined ? {} : { by: event.by }), ...(event.by === undefined ? {} : { by: event.by }),
}; };
if (hit) this.lastHitMs.set(item, nowMs);
if (tier === 'moment') { if (tier === 'moment') {
// Jump the gate: the badge is the reason anyone is watching. // Jump the gate: the badge is the reason anyone is watching.
this.promote(item, nowMs); this.promote(item, nowMs);
@ -176,6 +184,42 @@ export class TickerQueue {
return false; return false;
} }
/** Is this a hit the game rolls up? Only a reward with no `rewardKind` and the adapter's own label. */
private hitOf(event: FeedEvent): { ko: boolean } | null {
if (!this.game.hitCopy || event.kind !== 'reward' || event.rewardKind) return null;
const match = HIT_LABEL.exec(event.label);
return match ? { ko: match[1] !== undefined } : null;
}
private hitTier(ko: boolean): TickerTier {
const copy = this.game.hitCopy;
return copy ? (ko ? copy.koTier : copy.tier) : 'quiet';
}
/**
* Fold a hit into the battle's row: the newest hit row whose last hit is within `gapMs`. The
* window slides with each hit (unlike `fold`'s, which is from creation) because a battle has
* no fixed length; a row that has left the panel is not resurrected, the next hit starts one.
* The row shows the summed reward, a `x<n>` count and a KO once any hit in it felled a Pokémon.
*/
private foldHit(event: FeedEvent, ko: boolean, nowMs: number): boolean {
const copy = this.game.hitCopy;
if (!copy) return false;
for (const item of [...this.visible, ...this.pending]) {
const last = this.lastHitMs.get(item);
if (last === undefined || nowMs - last > copy.gapMs) continue;
item.count += 1;
if (event.value !== undefined) item.amount = (item.amount ?? 0) + event.value;
const knocked = ko || item.label.endsWith(' KO');
item.label = `${copy.label} x${item.count}${knocked ? ' KO' : ''}`;
if (knocked) item.tier = copy.koTier;
this.lastHitMs.set(item, nowMs);
this.revision += 1;
return true;
}
return false;
}
private tierOf(event: FeedEvent): TickerTier { private tierOf(event: FeedEvent): TickerTier {
if (event.kind === 'reward' && event.rewardKind) { if (event.kind === 'reward' && event.rewardKind) {
return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet'; return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet';

View file

@ -147,3 +147,41 @@ test('the platformer config paces the same way with different copy', async () =>
queue.push(reward('explore'), 100); queue.push(reward('explore'), 100);
assert.equal(queue.items()[0]?.label, '2 new ground'); assert.equal(queue.items()[0]?.label, '2 new ground');
}); });
function hit(hp: number, value: number, ko = false): FeedEvent {
return event('reward', `HIT #59 FOR ${hp} HP${ko ? ' KO' : ''}`, { value });
}
test('a battle\'s hits fold into one damage row that sums and counts', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(9, 0.05), 7_000);
queue.push(hit(4, 0.03), 15_000);
assert.equal(queue.items().length, 1);
const row = queue.items()[0];
assert.equal(row?.label, 'damage dealt x3');
assert.equal(row?.count, 3);
assert.ok(Math.abs((row?.amount ?? 0) - 0.14) < 1e-9);
assert.equal(row?.tier, 'quiet');
});
test('a KO marks the row and raises its tier; the window slides, then a new battle is a new row', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(5, 0.08, true), 30_000);
assert.equal(queue.items()[0]?.label, 'damage dealt x2 KO');
assert.equal(queue.items()[0]?.tier, 'notable');
queue.push(hit(3, 0.02), 70_000);
assert.equal(queue.items().length, 1, 'still inside 45 s of the last hit');
queue.push(hit(3, 0.02), 200_000);
assert.equal(queue.items().length, 2, 'a later battle gets its own row');
assert.equal(queue.items()[0]?.label, 'damage dealt');
});
test('a hit is not confused with other rewards, and a lone KO says so', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(31, 0.25, true), 0);
assert.equal(queue.items()[0]?.label, 'damage dealt KO');
queue.push(event('reward', 'NEW MAP', { value: 0.1 }), 10);
assert.equal(queue.items().length, 2, 'an unrelated no-kind reward keeps its own row');
});

View file

@ -93,6 +93,31 @@ const CHAT_WRAP: { by: string; text: string; bot?: boolean }[] = [
}, },
]; ];
/**
* The ticker in a battle (row 68): the fly's hits arrive as `HIT #<species> FOR <n> HP` rewards and
* fold into one "damage dealt" row. Injected by hand through `window.__stage.ticker`, seven feed
* seconds apart, because no fixture holds a battle recorded on adapter v8.
*/
const TICKER_SHOTS: { name: string; events: { label: string; value: number }[] }[] = [
{
name: 'row68-ticker-hits',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
],
},
{
name: 'row68-ticker-ko',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 12 HP KO', value: 0.13 },
],
},
];
const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [ const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [
{ name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' }, { name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' },
{ name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' }, { name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' },
@ -294,6 +319,18 @@ async function main(): Promise<void> {
console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`); console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`);
} }
for (const shot of TICKER_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const rows = await page.evaluate((events) => window.__stage?.ticker(events) ?? [], shot.events);
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${rows.join(' | ')})`);
}
for (const shot of RECOVERY_SHOTS) { for (const shot of RECOVERY_SHOTS) {
if (!wanted(shot.name)) continue; if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' })); await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));

View file

@ -89,8 +89,9 @@ decoder preset to use.
disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already
achieved flags on the first sample so a restore never replays them, and pays only positive achieved flags on the first sample so a restore never replays them, and pays only positive
rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors and items flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors, items
picked up (`docs/rewards-learning.md`). Version `pokered-unique8-v7`; a deploy that names the picked up and the HP the fly's own attacks remove in battle (`docs/rewards-learning.md`).
Version `pokered-unique8-v8`; a deploy that names the
previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them. previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them.
- Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel, - Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel,
Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a
@ -135,7 +136,8 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame
audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset. audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset.
flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an
embedded flybus router and the `fly-edge` process serves the same bytes embedded flybus router and the `fly-edge` process serves the same bytes
(`docs/design/flybus.md`, "Feed over the bus"). (`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
"Feed over the bus").
- Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM - Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM
pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat` pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat`
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`, (sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,

View file

@ -6,6 +6,12 @@ nothing outside the container can reach it, and the bridge is the only intended
There is deliberately **no endpoint that presses buttons, edits game memory, or changes the There is deliberately **no endpoint that presses buttons, edits game memory, or changes the
reward catalog**. That is a structural guarantee, not a configuration. reward catalog**. That is a structural guarantee, not a configuration.
Who serves it (2026-10-01): flysim itself (`FLY_CONTROL_VIA=direct`, the default), or
`fly-control-edge` from flysim's control services on the bus (`FLY_CONTROL_VIA=bus`,
`docs/design/flybus.md`, "Control over the bus"). Both are the same HTTP code over the same
request handling, so nothing in this document depends on the switch. On the bus, the
guarantee above is also a grant table.
| Method and path | Body | Effect | | Method and path | Body | Effect |
|---|---|---| |---|---|---|
| `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). | | `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). |

View file

@ -1,7 +1,9 @@
# flybus: the communications bus # flybus: the communications bus
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default**. Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
Written 2026-09-22, amended 2026-09-23 (EDGE-01, below). Index only; the `FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
authority for the API and the wire format is the crate's own authority for the API and the wire format is the crate's own
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against [README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
the draft is the [conformance report](session-framework/bus-conformance.md). the draft is the [conformance report](session-framework/bus-conformance.md).
@ -61,13 +63,13 @@ allocate/seal/read with quotas and router restarts, plus the conformance suites
## Wiring still pending ## Wiring still pending
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus". - ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
- **flysim control services.** The control endpoints as RPC services with grants, so the - ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
"no button endpoint" structural guarantee is expressed as a grant table. over the bus". The "no button endpoint" guarantee is a grant table there.
- **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either - **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either
a binding or a thin translating edge process is required before they leave the WebSocket a binding or a thin translating edge process is required before they leave the WebSocket
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
the feed it exists (`fly-edge`), and they keep the WebSocket contract unchanged. The the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
control API (:7401) is the next slice and stays in flysim until then. contracts byte for byte.
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below. - ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below.
- ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below. - ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below.
- **Migration order.** The feed is the cheaper first move; control should follow only once - **Migration order.** The feed is the cheaper first move; control should follow only once
@ -188,3 +190,252 @@ Accepted for now and written down rather than fixed:
escalates. Switch back to `direct` first (the unit header's way back), then roll back. escalates. Switch back to `direct` first (the unit header's way back), then roll back.
- **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a - **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a
Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`. Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`.
### Amendment 2026-10-01: the feed in production (EDGE-02)
- **The session runtime needed nothing.** `flysim-session` serves its listeners through
`flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was
written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs`
runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of
one store, direct and bus, records both feeds over a WebSocket and requires every frame in
common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then
stops the binary and starts a new one under the same edge, which must unbind, reconnect and
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review
N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the
sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts
one page CPU into `flysim.slice` for it).
- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an
`ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`;
`flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and
start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus
mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim
all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct`
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes.
- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off
the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle
header, so silence means a wedged subscription, which `Subscription::next` alone would never
report.
- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote
fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while
flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth
switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots.
Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to
connect to.
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the
env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no
binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and
the edge both follow fly.env at their next start, so a disagreement never leaves the stage with
no feed.
- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens
on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
## Control over the bus (2026-10-01, CTRL-01)
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the
default and the behaviour that predates the bus. With `bus`:
```text
api router (flysim::api) BusBackend flybus (Unix socket) control host (in flysim)
:7401 in fly-control-edge --> encode_request --> <bus_dir>/control-edge.sock --> fly.control.s.main.* services
same routes, extractors, (controlbus) bound to "fly-control-edge" -> flysim::control::handle
404s, headers, bodies -> the same Command queue
```
- `docs/control-api.md` is unchanged and still binding: every endpoint, status code and body.
flysim's control code is split in two. `flysim::control` holds the semantics: one
`ControlRequest` per endpoint, and `handle`, the only code that validates a request, talks to
the loop and picks a status. `flysim::api` is the HTTP layer over any `ControlBackend`. Direct
mode is `api` over `control` in one process. Bus mode is the same `api` in `fly-control-edge`
over a `BusBackend`, which carries the request to the `control` services in flysim. Neither
process has an HTTP table or a validation rule of its own, so the bytes on `:7401` are the
same in both modes. `crates/fly-control-edge/tests/parity.rs` sends every endpoint, each
validation case and each refusal to both paths and requires equal status, headers and
body. Over real sockets, it also requires the whole HTTP/1.1 response to be equal apart from
`date`. `fly-legacy-session/tests/service_parity.rs` runs the session runtime once more with
its control on the bus and compares it with the legacy loop. The comparison covers 120
frames, 19 control responses, the event log, the journal and the final checkpoint.
- Both runtimes get it: `flysim` and `flysim-session` both run `flysim::serve`, which in bus mode
does not bind `control.bind`. Instead it registers the services on the embedded router. That
is the feed's router when the feed is on the bus too: one router, one store, one closed policy
(`flysim::bus`). The read-only `control.metrics_bind` listener (`:9101`) stays in flysim in
both modes.
- Nothing about the fly changes. The command queue, its bound and its timeouts are the same.
The compatibility string is byte-identical in both modes.
### Services and methods
flybus grants name services, not methods. The surface is therefore split into six service
*families*, and a grant names families. Every family is scoped either to a session or to one
agent (fly) of it. Each method's payload and outcome:
| Service (live names) | Method | Endpoint | Payload |
| --- | --- | --- | --- |
| `fly.control.s.main.read` | `Control.Status` | `GET /status`, `/status.json` | `{}` |
| | `Control.Healthz` | `GET /healthz` | `{}` |
| | `Control.Metrics` | `GET /metrics` | `{}` |
| | `Control.Events` | `GET /events` | `{since?: string, limit?: string}`, the raw query values |
| `fly.control.s.main.a.fly.status` | `Control.Status` | (none: the fly's own status, for native clients) | `{}` |
| `fly.control.s.main.a.fly.sugar` | `Control.Stimulate` | `POST /stimulate` | `{request?: <body JSON>}` |
| `fly.control.s.main.a.fly.reward` | `Control.Reward` | `POST /reward` | `{request?: <body JSON>}` |
| `fly.control.s.main.chat` | `Control.Chat` | `POST /chat` | `{request?: <body JSON>}` |
| `fly.control.s.main.ops` | `Control.Checkpoint`, `Control.Pause`, `Control.Resume` | `POST /checkpoint`, `/pause`, `/resume` | `{}` |
- **Outcome.** `{"status": <the control-api.md code>, "body": <the JSON body>}`, or `{"status",
"text"}` for `/metrics`. Above 48 KiB (a full `/events` page can be 4,096 events) the body
travels as a sealed `body` artifact instead, with `bodyArtifact` naming its type. The status
code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an
HTTP caller does, so the edge needs no table of its own.
- **Requests** carry the body as the caller sent it (`request` is absent when it was empty or
not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as
a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets
the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A
method the service does not have is a 404. Neither reaches the loop.
- **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`).
The router dispatches FIFO per service. The host answers each request in a task of its own, so
a pause waiting on a durable write does not hold up a resume. Families are separate services,
so a stuck `ops` never delays `/status`.
- **Backpressure.** The bound is on the queue at the moment of admission. A burst can
therefore be refused before the router has dispatched its first calls into the in-flight
slots. That is measured, not assumed (`tests/backpressure.rs`). A full service refuses at
once with `BACKPRESSURE`, and the edge answers it
with direct mode's `503 {"error": "the simulation command queue is full"}`. Bus failures use
direct mode's words for the same failure (`control::unavailable`). `NO_SERVICE` before
dispatch is "has stopped"; `NO_SERVICE` after dispatch, `CALL_GONE` and `ROUTER_LOST` are
"dropped the request". `NOT_AUTHORIZED` is a 403.
- **Deadlines and cancel.** The host keeps direct mode's own timeouts: 2 s for a command,
none for `/checkpoint` and `/pause`, which wait for a durable write. The edge adds a guard of
that plus 2 s for timed requests only. At the guard it cancels the call and answers direct
mode's timeout 503. A call cancelled before dispatch never reaches the loop. A dispatched call
may still act, as a direct request whose caller timed out may. An HTTP client that goes away
drops its handler, and with it the pending call. The router discards the late result, and
the call record goes once the host answers (`tests/backpressure.rs`).
### Grants: the structural guarantee as a table
| Participant (socket) | read | status | sugar | reward | chat | ops | register |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `flysim-control`, the host (in-process, no socket) | | | | | | | every control service, exact names |
| `fly-stage` (`control/stage.sock`) | yes | yes | | | | | |
| `fly-bridge` (`control/bridge.sock`) | yes | yes | yes | | yes | | |
| `fly-watchdog` (`control/watchdog.sock`): watchdog, loop-recover ladder, `fly-runtime`, probation, shadow guard, stream check | yes | yes | | | | | |
| `fly-operator` (`control/operator.sock`) | yes | yes | yes | yes | yes | yes | |
| `fly-control-edge` (`control-edge.sock`): everything on `:7401` | yes | yes | yes | yes | yes | yes | |
| a player backing one fly (`player_grants`, not wired yet) | yes | that fly | that fly | | | | |
The status, sugar and reward columns are per agent: a role gets them for every fly of the
session (`grants`), or for one fly by id or by controller port (`grants_for`, `player_grants`
with `Agents::Id` or `Agents::Port`). The table is `controlbus::Role` and `controlbus::grants`. It reflects what each client calls
today: the stage only waits on `/healthz`; the bridge calls `/status`, `/stimulate`, `/chat`,
`/events` and `/healthz`; the infra scripts only read; the operator uses `curl`. Each socket is
launcher-bound to its participant. The watchdog and the ladder restart through systemd, never
through a control call.
"Nothing can press buttons" is structurally true because of four properties. Each is tested:
1. **No method takes input.** `ControlRequest` and the loop's `Command` have no variant that
presses a button, edits game memory or changes the reward catalog, so no method can be added
without a contract change. Service and method names are scanned for the same words `api.rs`
scans routes for (`controlbus` unit tests).
2. **Grants are exact calls and nothing else.** No role is granted `Any`, a prefix, `register`,
`publish`, `subscribe` or topic management (`every_grant_is_an_exact_call_...`). On a router
that also carries an environment's input service, no control participant can call that
service, the operator and the edge included. The router refuses before dispatch
(`tests/grants.rs`, `on_a_shared_router_no_control_participant_can_reach_an_input_service`).
3. **Only the host registers.** The one register grant belongs to an in-process participant
with no socket, so nothing outside flysim can stand in for a control service. A socket admits
only its own participant; claiming another id at hello is refused.
4. **The policy is closed.** An id that is not in the table cannot connect.
What this does not change: loopback HTTP has no caller identity, so `fly-control-edge` carries
the whole surface. That is exactly the trust `:7401` has today. A client is narrowed by moving
it off HTTP onto its own role socket. That needs a native client for the TypeScript processes
(a later slice; the operator chose edges over a Node binding for now). The bus's own limit still
applies: processes running as the same OS user are inside the trust boundary (crate README,
"Limitations").
### N flies, M environments, controller ports, players
Operator direction (2026-10-01): first the existing Game Boy fly goes fully onto the framework
and the bus. A later project puts several flies on multi-controller consoles, one fly per
controller port. This slice does not build that, but the services and grants are scoped per
session, per agent and per port from the start, so multi-fly is configuration, not a redesign.
A single-fly deployment is the same design with one agent.
- **Scope** (`controlbus::Scope`): a session id and its agents, each an id and, where the
environment has controller ports, the port it plays on (`AgentScope { id, port }`). The live
fly is session `main`, agent `fly` on port 0, the Game Boy's one pad (`Scope::live`). A scope
refuses two agents with one id or on one port.
- **Session-scoped** families (read, chat, ops) are `fly.control.s.<session>.<family>`. Pause and
checkpoint act on a whole session: one coordinator steps every agent, and one save is one
generation. The chat ring is the session's stage. `read` holds the session's status, health,
metrics and event log.
- **Agent-scoped** families (status, sugar, reward) are
`fly.control.s.<session>.a.<agent>.<family>`, one service per fly. A sugar or reward pulse goes
into one brain. Each fly's own view is its `status` service. Adding a fly adds its three
services, and nothing else changes.
- **Ports.** A port is a property of an agent's binding, not part of a name, because a pulse
goes into a brain, not into a controller. A grant limited to a port
(`Agents::Port(n)`) is resolved to the agent bound to that port when the policy is built. The
policy is fixed for a router's lifetime, so rebinding ports is a session restart. A port nobody
plays on grants no agent service.
- **M sessions** on one router (several games, or one multiplayer game) have disjoint names, so
a grant on one session never names another's. `:7401` addresses the live scope only. A second
session gets native bus clients, or an edge of its own on another port with its own scope.
- **Environments.** Environment-scoped status is reserved as
`fly.control.s.<session>.e.<env>.read`. Environment *input* services (`Environment.Step` and
the like) are never in a control scope. An agent's decision reaches its environment through
the coordinator, never through control, and on a multi-controller console each fly's decoder
writes only its own port. Property 2 holds however many environments and ports share the
router.
- **Players.** A viewer who backs one fly gets `player_grants(scope, Agents::Port(n))` or
`Agents::Id(..)`: read the session, see and sugar that fly, nothing else
(`a_player_sugars_their_own_fly_and_no_other`). In a multiplayer game the players on the pads
are flies, and their presses come from their decoders. A human input path would be a new
contract, never a control grant.
### What in `docs/control-api.md` is single-fly
The contract is unchanged by this slice. These parts of it assume one fly per session. Each
would need a contract amendment before a second fly could be served over HTTP. The bus services
above are already addressed per agent, so the amendments are to the HTTP shapes, not the bus.
| Endpoint or rule | Why it is single-fly | Multi-fly direction |
| --- | --- | --- |
| `GET /status` | The feed header reshaped: one `buttons`, `rates`, `decoder`, `learning`, `game`, `milestone`, `sugar`, `version` | Per agent: each fly's `status` service. The session's `Control.Status` becomes a session shape listing its agents and ports |
| `POST /stimulate` | No agent field; addresses "the fly" | The agent's `sugar` service; over HTTP an `agent` (or `port`) field, absent meaning the only fly |
| sugar limits ("6 per minute globally, no overlap with an active pulse") | The overlap rule is per brain; the budget is per deployment | Overlap per agent; whether the budget is per fly or per session is a policy decision |
| `POST /reward` | No agent field | The agent's `reward` service; same field as `/stimulate` |
| `GET /events`, `events.jsonl` | `FeedEvent` has no agent: reward, sugar and macro events cannot say whose they are | An `agent` field on agent events, absent for session events |
| `POST /checkpoint` | One generation of one FLYSIM01 envelope, which is single-fly by format | A session checkpoint holding every agent. FLYSIM01 stays the format of record until RETIRE-01 |
| `GET /metrics` | Series carry no agent label (`fly_reward_*`, the rates) | An `agent` label on per-fly series |
| `[macros]`, `loop.game` | One mode and one game per deployment | Per environment |
| `POST /chat`, `/pause`, `/resume`, `/healthz` | Session-level already | None |
### Lifecycle and operations
- `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and
`control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With
control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8.
- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its
`ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for
`flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings
`:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own
counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`,
`_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`).
- The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and
reconnects every 500 ms. To a client that looks exactly like flysim restarting
(`tests/backpressure.rs`, `tests/serve.rs`).
- Watchdog. Check 1 reads flysim's own `/healthz` on `:9101` when `FLY_CONTROL_VIA=bus`, so an
edge outage never restarts the fly. Check 1b restarts the edge alone when `:7401` fails while
flysim is healthy. Every other `:7401` reader (`fly-runtime`, probation, shadow guard,
loop-recover, the stream check) goes through the edge unchanged.
- Switch and rollback: `infra/docs/runbook.md`, "Control over the bus".
- **Migration order.** This document's rule stands: the control API moves after the feed has
been on the bus in production for a full session. The switch exists independently of the
feed's, and when to throw it is the coordinator's call.

View file

@ -398,6 +398,19 @@ on-screen ticker cannot disagree with what the sim did.
slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed"). slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed").
`STATE_VERSION` stays 4. `STATE_VERSION` stays 4.
**`v7` -> `v8`** (2026-09-29, the damage reward). `pokered-unique8-v8`'s `migrates_from()` is
`["pokered-unique8-v7", "pokered-unique8-v6"]`: the live run is `v7`, and `v6` still composes,
because `v7`'s own step (the item seed on the first sample without `items:seeded`) is still in
this build and the damage state starts empty either way. The deploy that ships it sets
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`; naming `v7` does not admit a `v6` checkpoint, which
needs its own id. One optional field is added, `damageCounts` (the wild keys that have paid
damage), and one optional object inside a battle in flight, `battle.damage` (the per-battle
marks and what the battle has paid). A `v7` state has neither and restores with no wild key paid
and, if the checkpoint was taken mid-battle, every enemy Pokémon marked at the HP it has when
first read, so nothing it lost before the restore is paid. `STATE_VERSION` stays 4. The
compatibility string moves in segment 1 only: `.../pokered-unique8-v7/...` becomes
`.../pokered-unique8-v8/...`, every other segment byte-identical.
- **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away; - **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away;
`infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a `infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a
dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and

View file

@ -555,7 +555,7 @@ into this project.
| What | Where | Mode | | What | Where | Mode |
|---|---|---| |---|---|---|
| source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/helix-client-id`, `twitch/helix-client-secret`, `twitch/fly-pokemon-bot-token` | WSL box only | | source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/<app>-client-id`, `twitch/<app>-client-secret`, `twitch/<bot>-token` | WSL box only |
| stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` | | stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` |
| bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` | | bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` |
| bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` | | bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` |

View file

@ -155,6 +155,21 @@ which neither `gen_symbols.py` nor `resolve_wram.py` resolves, and a hand-writte
thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame
before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM. before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM.
### The damage reward's reads (2026-09-29)
**New 2026-09-29** (`damage`, `docs/rewards-learning.md`, "Damage rewards"). The two WRAM names were
resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit and
are bracketed by addresses `symbols.rs` already carried. The HRAM byte is the second hand-counted
HRAM address in the crate, after row 63's `hJoyLast`, and is held to the same standard: counted
from that pinned anchor and checked against the section's end, then pinned on the cartridge.
| what | symbol | address | notes | verified |
| --- | --- | --- | --- | --- |
| whose side is acting | `hWhoseTurn` | `$FFF3` | "0 on player's turn, 1 on enemy's turn" (`ram/hram.asm`). Counted from `hJoyLast` (`$FFB1`) with each `UNION` at its largest member; the nine bytes after it end at `$FFFE`, the end of HRAM. `ExecutePlayerMove` writes 0 before the fly's move and `MainInBattleLoop` 1 before the enemy's; `HandlePoisonBurnLeechSeed` picks whose HP to cut by it. MEM-01's memory image captures HRAM, so the session runtime reads the same byte. | survey (`tests/rom_damage.rs`, the row 67 state: every enemy HP drop with 0, every own HP drop with 1) |
| the move executing | `wPlayerMoveNum` | `$cfd2` | the first of the six move bytes `ExecutePlayerMove` loads; `STRUGGLE` (`$a5`) for a Pokémon with no PP. Bracketed by `wWalkCounter` and `wEnemyMonSpecies`. | survey (BUBBLE `$91` and TACKLE `$21` read on the frames their hits landed) |
| which enemy slot is out | `wEnemyMonPartyPos` | `$cfe8` | `battle_struct`'s third field (`macros/ram.asm`: Species, HP, PartyPos, aliasing BoxLevel); `$ff` until a trainer's first send-out, then the 0-based party slot. Bracketed by `wEnemyMonHP` and `wEnemyMonStatus`. | trace (`pokemon_red/tests.rs`), survey |
| (stale) the enemy | `wEnemyMonSpecies` ... `wEnemyMonMaxHP` | as above | **not cleared between battles**: `InitBattleVariables` leaves `wEnemyMon` alone, and a trainer battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData`. The first samples of a battle can hold the last battle's Pokémon at the HP it finished on; the damage rule marks a target only once it reads full. | disassembly, trace |
### Battle menu and cursor, own turn against forced switch ### Battle menu and cursor, own turn against forced switch
`HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it `HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it
@ -1024,3 +1039,67 @@ the latch keeps that A until the next list first asks. Measured on the Potion's
list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120 list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120
rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and
HRAM whose values never overlap between lost and answered frames. HRAM whose values never overlap between lost and answered frames.
## 15. The naming screen (2026-09-29, `docs/design/macros.md` 12.32)
Row 69. Two bytes of a `UNION` in `ram/wram.asm` that the reviewed list does not carry, pinned the
way `hJoyLast` is and read back from the code that stores them by
`row69_the_naming_bytes_are_where_the_cartridge_stores_them` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `wNamingScreenNameLength` | `$CEE9` | the letters typed; the operand of `PrintNicknameAndUnderscores`'s `ld [wNamingScreenNameLength], a` before `hlcoord 10, 2` |
| `wNamingScreenSubmitName` | `$CEEA` | non-zero once START or ED is taken; the operand of `.pressedStart`'s `ld [wNamingScreenSubmitName], a` |
**`state::naming_screen`** is the keyboard only when the menu bytes `DisplayNamingScreen` writes
(`wTopMenuItemY` 3, `wMaxMenuItem` 7, `wMenuWatchedKeys` `$ff`) **and** its figure are on screen:
the whole `TextBoxBorder` at (0, 4)-(19, 14) and a run of seven or ten underscores (`$76`, the raised
one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH - 1` or
`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for
`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before
`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first.
## 16. The list's scroll offset (2026-10-01, `docs/design/macros.md` 12.34)
Row 71. One byte the reviewed list does not carry. It is pinned the way `hJoyLast` is, and
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM) reads it back from the
code that uses it. Section 7's "cannot be pinned" applied to the symbol table. The pin comes from
the cartridge instead.
| name | where | what reads it |
| --- | --- | --- |
| `wListScrollOffset` | `$CC36` | entries scrolled off the top of a `DisplayListMenuID` window; the operand of `DisplayListMenuIDLoop.buttonAPressed`'s `ld a, [wCurrentMenuItem] / ld c, a / ld a, [wListScrollOffset] / add c / ld c, a`, found once in the cartridge |
**`BattleMenu::Bag`'s `cursor`** is now `wCurrentMenuItem + wListScrollOffset`, the bag entry
under the arrow, which is the sum the cartridge makes on A. In the live trap the arrow was on row 1
with an offset of 3, so it was on entry 4, the Poké Ball. `state::shop`'s buy and sell lists
report their cursor (and its `max`) as the entry the same way. The offset is added only while a
list is on screen, because the byte outlives every list. Purchases still use only the first three
rows (`MART_CURSOR_ROWS`, section 7).
## 17. The hidden-event tables (2026-10-02, `docs/design/macros.md` 12.35)
Row 73. Two ROM tables, read through `MemoryReader::read_rom` from the cartridge image the process
already holds, never through the bus and never by switching banks. Pinned the way
`ItemUsePtrTable` is, and read back from the code that uses them by
`row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `HiddenEventMaps` | `$11:$6A40` | one map id per byte to a `$ff` (85 maps at the pinned commit); the operand of `CheckForHiddenEvent`'s `ld hl, HiddenEventMaps`, followed by `ld a, [hli] / ld b, a / cp $ff` |
| `HiddenEventPointers` | `$11:$6A96` | one little-endian pointer per map of the list above, into the same bank; the operand of the routine's `ld hl, HiddenEventPointers`, followed by `add hl, de` |
Both are in `SECTION "Hidden Events Core"`, which `layout.link` places in bank `$11`. Each map's
list is six bytes an entry to a `$ff` (`hidden_event`): y, x, the routine's argument, and the
routine as `dba` (bank, then a little-endian address). The coordinates are in the same tile space as
`wXCoord`/`wYCoord`, like a sign's.
**`state::hidden_events`** answers the current map's entries as `HiddenEvent { x, y, index,
facing }`: `index` is the entry's position in the map's list, which is how `wHiddenEventIndex`
counts and the talked ledger's key (`TalkTarget::Hidden`); `facing` is the argument when it is a
`SPRITE_FACING_*` value (`$00`, `$04`, `$08`, `$0C`), the side a routine such as `BillsHousePC`
checks. It answers nothing for a map list with no end within 128 entries or an id above `$f7`, a
pointer outside `$4000..$8000`, a list longer than 64 entries (the Game Corner's 48 are the longest), a tile off the loaded map or a
routine address at `$8000` or above. Bill's house (`$58`) has one entry: (1, 4), argument `$04`,
`BillsHousePC` at `$07:$6B6E`.

View file

@ -1913,6 +1913,352 @@ a door is taken the way the cartridge takes it, and the map graph says what the
decoder, the reward catalog, the adapter version, the roles and the compatibility string are decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched. untouched.
### 12.30 A counter walked away from is not walked back to, a ball is bought with one button, and a closed bag is not the pad (2026-09-29, row 66)
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) to watch the fly shop,
buy Poké Balls and catch. On v0.6.5, 35 minutes in: `GO SHOP` done 33 times, `TALK` 5, `BUY BALL`
never dealt, `THROW BALL` 0, no catch. Three findings, two of them the pad.
**`GO SHOP` and the way out were a ring.** Row 62 (12.26) deals a service walk whenever the
cartridge says the service is needed, whatever the ledgers say. When the fly stands at the counter
and does not use it, that is a ring by construction: `GO SHOP` from the street to the Viridian
clerk, `GO OUT` or `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again,
because the bag still holds no ball. Reproduced with the connectome from a post-parcel checkpoint
of the Viridian mart (`survey-rank8-row66-viridian-mart`, saved by the offers survey): three laps in
eighteen brain seconds. A `GO SHOP` or `GO HEAL` that finishes facing the counter person now
records the building's counter (`TargetKey::Counter`, keyed by the building's map, because the
question is asked from the street, where none of the building's sprite slots means anything). For
the reached window the service walk toward that building is not dealt, from the street or inside.
That is 12.1's ledger doing for the service walk what it does for every other walk: a target
arrived at and faced is not walked to again at once. `TALK` at the counter, `HEAL` in a centre and
`BUY BALL` in a mart are unchanged by it. When the window closes the counter is a service again.
**A ball is one button (the operator's decision).** Even without the ring the fly did not buy.
A purchase took four choices in a row at the counter: `TALK`, a press at the greeting, `CONFIRM`
on BUY, and `BUY BALL` on the list. With the connectome the fly walked to the clerk every time and
never once chose `TALK` there. So `BUY BALL` is now also the mart's `HEAL`. On the overworld pad
inside a mart, one press walks to the clerk, talks, advances the greeting until BUY / SELL / QUIT
is drawn, buys the first row, answers the price box as 12.26's purchase does, and is `done` when
the wallet drops. It is offered only while it can work:
- in a mart whose first stock row is a Poké Ball (`geography::BALL_FIRST_MARTS`: Viridian, Pewter,
Cerulean, `data/items/marts.asm`). The script reads the stock once the counter is open and
refuses if the first row is anything else;
- while `service_needed` holds for the mart: no ball in the bag, 200 in the wallet, no Oak's parcel
(while it is carried the Viridian clerk's text table is the parcel's and he sells nothing). In
Viridian it is also not offered before Oak has the parcel (`EVENT_OAK_GOT_PARCEL`);
- with the clerk not in the blocked window. The talked and reached ledgers do not retire him, as
for the nurse.
The fly still chooses it, as it chooses `HEAL`. The open-counter `BUY BALL` is unchanged.
**After a catch the pad read the bag.** `wListMenuID` is written when a list opens and never
cleared. After a ball was thrown, every frame to the end of the battle read as an open battle bag:
"All right! WEEDLE was caught!", the Pokédex page, the nickname offer and the naming screen. The pad
was `BACK` and `THROW BALL`, a `THROW BALL` that threw nothing. Its A presses said YES to the
nickname and typed it, 6,900 frames from the catch to the battle's end on a stub survey. The bag
is now the bag only while its box, a `TextBoxBorder` at (4, 2)-(19, 12), is on screen: row 50's rule
for the move list. After the catch the pad is `NEXT`. `NEXT` answers the nickname offer with YES
and names the Pokémon with A's. Offering the offer's two answers inside a battle is a pad change
not made here.
ROM tests: `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` and
`row66_buy_ball_from_the_marts_floor_rings_up_a_ball` (`FLY_ROW66_MART_CHECKPOINT`),
`row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 66.
Nothing ranks a button or presses for the fly. The walk back is withheld for a window, a purchase
is one offer, and the bag is read off the screen. The decoder, the reward catalog, the adapter
### 12.31 A battle lost on repeat is the readout's choice when the pad offers the move that wins (2026-09-29, row 67)
Live on v0.6.5, rung 10, an hour and a half in the Pewter Gym (map 54): per 3,000 events `NEXT`
1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17, no battle won. The feed
read `battle` most of the time, but the fly was not in one battle. It was in a ring. It lost
29 battles in a row to the gym's Jr. Trainer (Diglett L11, Sandshrew L11), whited out to Pewter
(`wLastBlackoutMap` `$02`, money 0) and walked straight back in. Reproduced from the live
checkpoint (`FLY_ROW67_CHECKPOINT`).
- **The pad was right.** Squirtle L11 has TACKLE 35/35, TAIL WHIP 30/30 and BUBBLE 30/30, and
the trainer's Pokémon are Ground type. In a trainer battle with a party of one and no Potion,
the menu's pad is `MOVE 1`, `MOVE 2`, `MOVE 3`, which is every move with PP and an effect.
RUN, ITEM, SWITCH and THROW BALL each have nothing behind them there. Every turn advances.
In 932 own-turn frames, no move with PP and an effect was missing from the pad.
- **The choice was the readout's.** Per live battle, TAIL WHIP was 155 of 178 moves and BUBBLE
23. TAIL WHIP has an effect until the stage reaches -6, and 12.23 withholds it from there. Squirtle
faints at about the sixth turn, so the rule arrives as the battle ends (live: `22222233`).
A readout with no favourite wins with the same pad: uniform over it, the trainer is beaten on
all three seeds, and on the committed seed in the third battle. The live readout's favourite,
replayed, loses 17 of 17 battles.
- **PP never runs out.** Each loss spends about six TAIL WHIPs of 30, and the whiteout heals the party and
restores PP. The out-of-PP path is sound anyway: from the no-PP checkpoint, a trainer battle
with a party of one and every move at 0, the pad is `MOVE 1` alone (FIGHT's backstop, 12.8),
and "has no moves left!" and Struggle end the battle in 1,487 frames.
- **Nothing in the macros changes.** Moving the fly off TAIL WHIP would be ranking a move. The
one pad rule measured that would work, withholding a stat-lowering move once the target's
stage has moved, wins the first battle on both seeds (two stages: the second). It is a rule
about which move is good rather than one about what the cartridge refuses, so it waits for
the operator, like the reward options (`infra/docs/macros-traps.md` row 67).
- **What ships is detection.** The watchdog's check 10 gains `unwon-battles`: 24 or more `MOVE
n` decisions and no battle-won reward (`wildwin`, `trainer`, `badge`) in the ten-brain-minute
window, on two probes, with no new ground. Replayed on the live log, it flags from 14:01. The
existing rules first flag at 14:46, because a stray tile reward on a walk back reset
`unrewarded`. The recovery ladder acts on the flag as on any other, and a restart alone
does not change the readout.
Nothing is ranked, weighted or pressed for the fly. The decoder, the reward catalog, the adapter
version, the roles and the compatibility string are untouched.
### 12.32 A ball at low HP is the only attack, and the fly spells its catch's name (2026-09-29, row 69)
(12.31 is row 67.) Two operator decisions of 2026-09-29, after row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag, and every catch named
`AAAAAAAAAA` by `NEXT`'s A presses on the keyboard.
**"Throw on low HP only."** In a wild battle, when `THROW BALL` is on the pad and the wild
Pokémon's HP is low, the ball is the only attack-side button: `MOVE 1` to `MOVE 4` are withheld on
the top-level menu, and so are `SWITCH` and `RUN`, and `BACK` in the bag.
- **Low is the cartridge's number.** `ItemUseBall` (`engine/items/item_effects.asm`) computes
`W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, floored at each step, with a `BallFactor`
of 8 for a Great Ball and 12 for every other. The ball holds on HP when a random byte is at most
`W`, so at `W >= 255` HP stops mattering. For a Poké Ball that is HP at about a third of its
maximum (7 of a Weedle's 20), for a Great Ball about a half. Lower HP buys nothing more; what is
left is the catch rate and the status, which no press changes. So low is where the throw stops
getting better (`palette::ball_holds_on_hp`, `palette::throw_only`), for the ball
`THROW BALL` would throw.
- **What stays beside the ball.** `ITEM`, because it is dealt only for a Pokémon that is out,
under half its HP, with a Potion the cartridge would take: the one non-attack need that keeps
the thrower standing. `SWITCH` is about a healthier fighter; `RUN` forfeits the catch the pad
exists for, with the enemy at its weakest; `BACK` in the bag leads to a menu whose pad is the
same ball. `palette::WITHHELD_FOR_THE_THROW` is the list.
- **It cannot loop.** It applies only while `THROW BALL` itself is dealt, so every precondition
of that button still holds it: a wild battle, a ball, room in the party, a species the party does
not hold. A missed throw is an ordinary turn (`NEXT` between turns, the ball again on the next
own turn while one is left). With no ball left the button is off the pad and so is the rule, and
the moves are back. An enemy that faints ends the battle as always. A catch goes to the nickname
offer, which `NEXT` answers YES as before.
**"Let the fly name it."** The keyboard (`DisplayNamingScreen`) is a screen of its own. It reads
`Unknown` in or out of a battle (the detector checks it before `wIsInBattle`), and its pad is the
fly's **own buttons**: the D-pad moves over the letters, A types one (or ED, which hands the name
back, or the case switch), B deletes, START hands the name back. SELECT is not on the operator's
list and is masked. No macro is dealt while the fly spells.
- **Why raw buttons and not a macro per key.** A macro per key is new types, and a new type
re-deals every macro population (`docs/readout.md`). The fly's raw buttons are already decoded
every frame in macros mode, and the title already passes them through (section 2). The player's
and rival's names at the start of a game are the same screen before the game timer starts, so
they read `Title` and the fly has always typed them with these buttons; the nickname is now
consistent with them. `Observed::raw` carries the scene's mask and the layer presses
`raw_mask & raw` while nothing is bound and nothing runs.
- **The bound.** Once the name is full (`wNamingScreenNameLength` at the capacity the underscores
show, ten or seven; the cartridge moves the cursor onto ED itself then), or sixty brain seconds
after the keyboard opened (`palette::NAMING_BOUND_MS`), the raw buttons are shut and `CONFIRM`
is the only button. On the keyboard `CONFIRM` pulses START until the screen is gone
(`Step::Submit`), `blocked` after 160 frames. `CONFIRM` is not offered earlier: a macro group of
one always has a winner at its next decision, so a lone `CONFIRM` would hand back an empty name
within a second.
- **What the name is.** Whatever the fly typed stays. An empty name is the species' own name,
which is the cartridge (`AskName.declinedNickname`).
- **The reading.** Red has no "keyboard open" byte, so `state::naming_screen` is the construction
`yes_no_prompt` makes: the menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3,
`wMaxMenuItem` 7, every key watched), the keyboard's whole box at (0, 4)-(19, 14), and the
underscores at (10, 3). `wNamingScreenNameLength` (`$CEE9`) and `wNamingScreenSubmitName`
(`$CEEA`) are read from the operands of the cartridge's own instructions, like `hJoyLast`, and
pinned by the ROM tests.
- `game.scene` is `unknown` on the keyboard, `game.palette` is `[]` while the fly spells, and
`game.padEmptyMs` stays 0: the fly's own buttons are a pad.
ROM tests (`tests/rom_catch.rs`): `row69_at_low_hp_a_wild_battles_pad_is_the_ball`
(`FLY_ROW69_CHECKPOINT`), `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`
and `row69_a_fly_that_types_nothing_is_ended_by_the_bound` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 69.
Nothing presses for the fly on the keyboard but the bound's one button, dealt as a button and
chosen by the fly's own macro group. The decoder, the reward catalog, the adapter version, the
roles and the compatibility string are untouched.
### 12.33 The SHIFT offer's party list is the fly's turn, not a forced switch (2026-09-30, row 70)
Live on v0.7.0, rung 12, Mt. Moon 1F: the fly caught its first Pokémon (a Zubat). Minutes later, a
Lass's battle. Wartortle fainted to her Oddish, the forced switch sent out the Zubat, and the Zubat
knocked the Oddish out. With two Pokémon in the party, the cartridge's SHIFT battle style asks
"Will ZUBAT change POKéMON?" before the trainer's next one (`EnemySendOut`,
`engine/battle/core.asm`). The fly answered YES, and the game opened the party list. From then on,
the event log was `NEXT start/done` every 0.8 brain seconds for 58 brain minutes, and nothing
else happened until the ladder reset the run to rung 11.
- **The misread.** `EnemySendOut` opens that list with `wPartyMenuTypeOrMessageID =
BATTLE_PARTY_MENU`, the same value `ChooseNextMon` uses after a faint. `state::battle` took
BATTLE_PARTY_MENU alone as the forced switch, so the pad was the forced switch's `SWITCH, NEXT`.
`SWITCH` had no one to switch to, because the Wartortle had fainted. `NEXT`'s A landed on the
cursor, which the game parks on the Pokémon already out. The game printed "ZUBAT is already out!"
and reopened the list. The one press that leaves this list is B, which declines the offer:
`DisplayPartyMenu` returns carry and the trainer sends the next one out. No button on the pad
sent B.
- **The rule.** A battle party list is a forced switch only when BATTLE_PARTY_MENU is set **and
the active battler's HP is 0**. Both callers of `ChooseNextMon` (`HandlePlayerMonFainted`, and
the enemy's faint after a double knock-out) reach it only with `wBattleMonHP` at 0, so the faint
is what the forced switch has and the offer does not. On the offer's list it is the fly's turn,
and its pad is the party list's own answers, `SWITCH` and `BACK` (12.9). `SWITCH` is dealt only
when another Pokémon can go out. Nothing is chosen for the fly. It can still take the offer with
`SWITCH`, and `BACK` is the way out that the pad was missing.
- **Why it waited for a catch.** The offer needs a second Pokémon (`wPartyCount - 1 != 0`), so
with a party of one it never appeared. Every catch from now on makes it likelier.
Tests: `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, the second half of
`the_party_list_a_fainted_mon_forces_is_a_forced_switch`, and two ROM tests.
`row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` uses
`FLY_ROW70_CHECKPOINT`, the live trap. `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered`
uses `FLY_ROW70_FORCED_CHECKPOINT`, the rung-12 archive carried forward by the stub to the same
Lass with a Zubat caught.
### 12.34 The battle bag's cursor is the entry, not the window's row (2026-10-01, row 71)
Live on v0.7.3, rung 15, Route 25 (map 36): a wild Oddish L13 at 8 of 36, Wartortle L35 out, the
bag open. Row 69's rule saw the HP low enough for the ball and left `THROW BALL` alone on the pad.
Every start was `blocked`, 131 of 131 in ten minutes and about two hours in all. A flysim restart
restored the same battle with the same bag open, so the trap came straight back.
- **Not a trainer.** `wIsInBattle` was 1 (wild), so the cartridge would have taken the ball.
There were two Poké Balls in the bag, the party had room, the Oddish was a new species, and
Wartortle's moves had PP left. `THROW BALL` was a correct button that its script could not
carry out.
- **The misread.** The battle bag is a `DisplayListMenuID` list. Its window shows three entries,
the arrow moves over rows `0, 1, 2` (`wCurrentMenuItem`), and the list scrolls under the arrow.
The entry under the arrow is the row plus `wListScrollOffset`. `state::battle` reported the row
as the bag cursor. `THROW BALL` aims at the ball's bag index, here 4 (TM34, HELIX FOSSIL, NUGGET
and TM45 come first), and no row can ever be 4. The cursor step walked between rows 1 and 2, ran out
of budget and blocked, even though the arrow was on the ball (offset 3, row 1).
- **The rule.** The bag cursor is `wCurrentMenuItem + wListScrollOffset`, the same sum
`DisplayListMenuIDLoop` makes when A selects. `wListScrollOffset` (`$CC36`) is pinned from the
operand of that read and checked against the cartridge, the same way as `hJoyLast` (12.27).
Every UP or DOWN press then moves the entry by one, either by moving the arrow or by scrolling
the window, so the existing cursor step reaches any entry. `ITEM`'s Potion had the same limit
(fourth entry or later) and is fixed by the same change.
- **Why row 69 turned it into a trap.** Before row 69, a ball fourth or later in the bag was a
dead `THROW BALL` next to the moves. That cost a hold but did not trap the fly. Row 69 withholds
the moves, `SWITCH`, `RUN` and the bag's `BACK` at low HP, so the dead button became the only
one.
Other lists, checked: the mart's buy and sell lists are `DisplayListMenuID` lists too, and
`state::shop` now reports their cursor as the entry in the same way. The battle menu, the move
list, the party list and the start menu do not scroll. No macro navigates the PC's lists.
`MART_CURSOR_ROWS` (row 55) still limits purchases to the first three rows, because lifting it puts
new buttons on the pad and needs its own survey on the cartridge.
Tests: `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn` (state, a bag scrolled by
three), `a_mart_reports_which_of_its_screens_is_up` (a scrolled buy list, and a stale offset on the
counter menu), the catch test's check that its ball is in the window's first rows (it still
throws),
`row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`, the live trap) and
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM).
### 12.35 An errand is its people, then its things, and a hidden event is a thing (2026-10-02, row 73)
Live on v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. Scout B3 measured it from the live
checkpoint on six seeds (2.8 brain hours): `GO ROUTE` walked the fly into Bill's house, and inside
it `GO OBJECTIVE` or `GO OUT` walked it straight back out, 30 to 60 times per ten brain minutes.
`GO NPC` was chosen 0 times in about 600 starts in the house, and new tiles stopped (2527 to 2531
in 35 minutes). Rung 16 (MET BILL, `EVENT_GOT_SS_TICKET`) was never earned.
- **The place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`, because the house's id was
not derived. A fly on Route 25 was already "there", so inside the house `GO OBJECTIVE` was an
exit into the objective's own map, which is the same door as `GO OUT`. That is row 29's lab loop
again, one rung later.
- **The rung is an errand, not a conversation.** `scripts/BillsHouse.asm`: Bill (a Pokémon, a
person sprite) asks for help and walks into the teleporter, the cartridge hides his sprite; the
cell separator is started from the PC at (1, 4), pressed facing up; Bill then steps out of the
machine as a second sprite and hands over the ticket. Two people and a thing, in that order.
- **The PC is a hidden event.** `wNumSigns` is 0 in the house and the only sprite is Bill: the PC
is an entry of the cartridge's own hidden-event table (`data/events/hidden_events.asm`), which
`CheckForHiddenEvent` searches on every A in the overworld. No macro could aim at it and `TALK`
was never dealt in front of it, so even a fly that talked to Bill could not earn the rung.
What changed, all of it knowledge inside macros:
- **`PlaceKind::Errand`.** Rung 16's place is `errand(BILLS_HOUSE)` (`$58`, confirmed by Route
25's warp table and by the hidden-event map list). An errand's targets are the room's people,
drawn or off the screen, and once none is left untalked, its things: objects, signs and hidden
events. No step is named anywhere. The cartridge shows and hides the people as the errand moves
on, the talked ledger records what has been had, and what is left is the next step. People come
first because a thing pressed out of turn is in the talked ledger for the session: Bill's PC
pressed before he has asked prints the monitor and does nothing, and a PC recorded as talked to
would never be the next step again. Everything 12.5 and 12.22 give a person place applies: the
ways out are withheld while a target waits, `GO OBJECTIVE` aims at the four sides, facing a
target is the arrival and `TALK` is the press; the blocked ledger is the escape hatch.
- **Hidden events are read from the cartridge's table, not written down.** `state::hidden_events`
walks `HiddenEventMaps` and `HiddenEventPointers` in ROM bank `$11` through
`MemoryReader::read_rom`, the same read the move and item tables use: no WRAM is written and the
mapper's bank register is not touched. The two addresses are pinned from the operands of
`CheckForHiddenEvent`'s own `ld hl` instructions and checked on the cartridge
(`macros-wram.md` section 17); every read checks the table's shape and answers nothing for a
table that is not the one the disassembly describes, which narrows and never invents a tile. A
hard-coded `(1, 4)` would have been a number nobody can check from the running game; the table is
what the cartridge itself consults when the A is pressed.
- **A hidden event is only ever the errand's next step.** It is in `objective_targets` for an
errand and in `facing_target` (so `TALK` is dealt) only while it is that step. It is not added to
`GO ITEM`, `GO NPC` or `TALK` anywhere else. The table holds every PC, poster, trash can,
bookshelf and hidden item in Kanto; making them general targets would add a walk to most
buildings' pads and an entry to the talked ledger for each, which is a change to what the fly is
offered everywhere and not a fix for this trap. The day that is wanted it is one line in
`path::interactable_targets`, and it needs its own survey.
- **A hidden event's side.** Where the entry's argument is a `SPRITE_FACING_*` value it is the side
the routine checks before it does anything (`BillsHousePC` returns unless the player faces up),
so the walk's one aim is the tile on that side and only facing it from there is the arrival and
`TALK`'s precondition. An argument that is an item or a text id and happens to equal a facing
value only narrows the approach.
- **An errand is recoverable inside one session (row 73 review).** The talked ledger is the
session's and never forgot, but the cartridge re-shows people: Route 25's script resets Bill's
event once the fly has left, and a Bill whose bag was full never handed over the ticket. A
conversation had on the last visit then retired this one's and the rung was unreachable until a
restart. The palette now notes the room while the errand is the objective and, on the first
frame the fly stands anywhere else with that errand still the objective, forgets that room's
talked entries (`Talked::forget_map`). Other rooms' entries and a room that is not the errand
keep theirs. The bag-full case needs no extra rule: nothing is left to aim at, the exits return,
and the fly leaves and comes back.
- **A one-sided target nobody can stand in front of is not waited for.** If every tile a hidden
event can be pressed from is one the cartridge pushes the fly off (the pushed ledger, row 37),
the walk had no aim, so no walk ended `blocked` and the ways out stayed withheld for good. Such
a target leaves the errand's list at once (`palette::servable`), which returns the exits.
- **A hidden-event entry off its own map is skipped.** The Safari Zone gate lists a nugget
"inaccessible" at (10, 1) on an 8 x 6 map, and the rest houses a copied Pokecenter PC; one such
entry no longer voids the rest of the map's list.
The fly still chooses every press: `GO OBJECTIVE` to walk, `TALK` to press A, `YES`, `NO` or
`NEXT` in Bill's boxes. Nothing presses for it, no button is added to any pad, and the readout, the
catalog, the adapter and the compatibility string are unchanged. What the scene deals inside the
house is narrower than before, not wider: the ways out leave the pad while the errand waits.
**The road after the ticket (the third trap).** With the ticket the objective is rung 17,
Vermilion, south through Cerulean. Cerulean's ground is in three pieces, not two: the town's ends at
row 28 (the gap at (16, 28) opens onto a wall and the trainer-tips sign), and the south of the map,
the road to Route 5 and the east edge onto Route 9 are reached through the trashed house (`$3e`),
in by its front door at (27, 11) and out by the hole in its back wall onto (27, 9) in the Rocket's
yard. Scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's. The house was
off the map graph, so `GO OBJECTIVE` aimed at ground the town cannot reach (`blocked` at (17, 28))
and the fly rang between the town and its houses (0 of 6 seeds past row 28 in 43 brain minutes
each). The house is now on the graph and the south is `SPLIT`'s third piece of Cerulean, so the
objective walks into the house and out through the hole. Before the ticket a guard stands on the
tile in front of the door (`TOGGLE_CERULEAN_GUARD_2`, (27, 12)), which the ticket's own script hides; the objective only
points south after the ticket.
**Not fixed, predicted:** the road from Route 5 to Vermilion on the graph is Route 5, Saffron,
Route 6, as plain map edges. The cartridge's gate houses are guarded until the guard's drink is
given, and the way the game means is the Underground Path, whose houses are off the graph. No run
has reached Route 5's gate yet; it needs its own checkpoint and row.
Tests: `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`,
`a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`,
`a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`,
and on the cartridge `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it`,
`row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door`,
`row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket`,
`row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket`,
`row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` and
`row73_the_fly_takes_the_trashed_house_south_to_route_5`.
## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a
## priority to visit the shop at least once per area; make shop macros item purchases. same ## priority to visit the shop at least once per area; make shop macros item purchases. same
## for the Pokécenter. heal should be a macro.") ## for the Pokécenter. heal should be a macro.")
@ -1942,9 +2288,10 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
- **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's, - **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's,
untouched). untouched).
- **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come. - **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come.
- **Proof.** ROM-gated from the Viridian checkpoint: `GO SHOP` enters the Viridian mart and - **Proof.** ROM-gated: from the Viridian checkpoint `GO HEAL` enters the center and `HEAL`
`BUY POTION` buys one; `GO HEAL` enters the center and `HEAL` restores the party; the errand is restores the party; from the rung-11 Pewter checkpoint (a state where `GO SHOP` is dealt, since
not offered again in Viridian; trap hunt before/after. rows 62/66: money, no ball, no parcel) `GO SHOP` enters the mart and walks to its counter, and
is not dealt back from the street for the reached window; trap hunt before/after.
## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2 ## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2
## columns" … "four, one per move slot" … "2 cols.") ## columns" … "four, one per move slot" … "2 cols.")
@ -1993,7 +2340,9 @@ observe is not a precondition, it is a guess.
| Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad | | Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad |
| Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it | | Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it |
| Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged | | Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged |
| Unknown (the Pokédex, the trainer card, OPTION, a naming screen, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them | | Unknown (the Pokédex, the trainer card, OPTION, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them |
| Unknown, the naming screen (**12.32**) | the fly's own D-pad, A, B and START; **CONFIRM** alone once the name is full or after sixty brain seconds | new, row 69: read before the battle test, so a nickname typed in a battle is here too |
| Battle, own turn, main menu, a wild Pokémon at low HP with THROW BALL dealt (**12.32**) | THROW BALL, and ITEM for a hurt thrower | new, row 69: the moves, SWITCH and RUN withheld; the bag's BACK too |
| Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as | | Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as |
| Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands | | Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands |
| Battle, own turn, party list | SWITCH, BACK | unchanged | | Battle, own turn, party list | SWITCH, BACK | unchanged |
@ -2044,7 +2393,7 @@ measured where it cannot.
| a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one | | a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one |
| a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette | | a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette |
| the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt | | the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt |
| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`; a screen neither press leaves (the naming screen, row 14) is a genuine stall and still needs START, which is a contract change | | a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`. The naming screen (row 14), which neither press leaves, is read since **12.32** and its pad is the fly's own buttons, then `CONFIRM` (START) once the name is full or the bound runs |
| an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other | | an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other |
| the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read | | the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read |
| the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens | | the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens |

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

@ -105,7 +105,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` | | Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) | | The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies | `wire.rs::Location`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse | | Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) | | `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) | | Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
@ -187,9 +187,10 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` | | The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
| The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) | | The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) | | Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
| Sealing on send (amendment 2026-10-02, BUS-02): an `rpc.call`/`rpc.reply`/`publish` attachment naming the sender's own writer is sealed (its declared prefix, copied outside the state lock) before the command is admitted, the writer becomes the sender's hold, `recycle` reissues the staging file as a new writer, and a refused sealing send releases every writer it named | conforms | `router/state.rs::{sealing_attachments, finish_sealing_send}`, `router/mod.rs::read_loop` (`SealThenAdmit`), `store.rs::{seal_prefix, rename}`, `client/handles.rs::{ArtifactWriter::into_unsealed, Responder::reply_sealing}` | `tests/sealing.rs::{a_reply_seals_and_recycles_its_writers, a_refused_sealing_send_releases_its_writers}` (both), `tests/artifacts.rs::unsealed_artifacts_cannot_be_used` (both) |
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) | | A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) | | No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) | | Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` | | All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |
@ -345,7 +346,7 @@ behind "latest replaces only queued messages": the replacement never turns into
## The crate README's differences from the draft ## The crate README's differences from the draft
Each of the ten differences the crate lists, kept with the sentence that allows it or fixed. Each of the differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict | | README difference | Verdict |
| --- | --- | | --- | --- |
@ -359,6 +360,8 @@ Each of the ten differences the crate lists, kept with the sentence that allows
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) | | 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
| 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` | | 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` |
| 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) | | 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) |
| 11. Read locations in deliveries | Kept. The bus-v1 amendment of 2026-10-01 (BUS-01) |
| 12. Sealing sends, `recycle`, and no `rpc.responder.release` after an admitted reply | Kept. The bus-v1 amendment of 2026-10-02 (BUS-02); section 8.1's immutability holds because the sealed bytes are still a copy, and a reply the router admitted already ended the reply authority the release would give up |
## Measured on the dev VM ## Measured on the dev VM

View file

@ -207,7 +207,11 @@ roots, so an idempotent repeat may report zero. Queue/credit requests are intege
and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters. and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters.
call target is a service name; expectedIncarnation is its registration ID, not worker process ID. call target is a service name; expectedIncarnation is its registration ID, not worker process ID.
Location grants are `{storeId, relativePath}` resolved by the client beneath the configured Location grants are `{storeId, relativePath}` resolved by the client beneath the configured
local store root; absolute paths, parent traversal and symlink escapes are rejected. They local store root; absolute paths, parent traversal and symlink escapes are rejected (the
reference SDK caches a store's canonical directories per connection, BUS-02, and still checks
each file with an lstat and an `O_NOFOLLOW` open; a store directory replaced by a symlink after a
connection first used it is not re-checked by that connection, which the store's 0700 owner-only
directory makes a same-user act). They
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
committed into application schemas or source configuration. committed into application schemas or source configuration.
@ -523,3 +527,83 @@ 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.
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
a frame for an answer the router already knows when it delivers.
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
`artifact.open` would return for that artifact under that delivery's ownership. It is still
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
symlink checks, and never placed in an application body.
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
field, and the connection closes as for any malformed envelope.
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
client that prefers to ask.
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
that needs the bytes kept alive can keep a clone instead of taking a second hold.
**2026-10-02, BUS-02 (wire change; `contractDigest` changes).** A sending command may seal the
artifacts it attaches. Section 8.1 makes a producer seal (`artifact.seal`, one router round trip)
before any message may name the artifact, and section 5 allocates every artifact afresh
(`artifact.allocate`, another). A participant that replies with media every transition -- the
legacy world a frame, a memory image and an audio chunk, the agent a spike bitset and its feed
status -- paid both for every artifact of every transition, two of them on the transition's
critical path, for answers the router could give as it admits the reply.
- **Sealing attachments.** In `rpc.call`, `rpc.reply` and `publish`, an attachment's `ownerId` may
be the sender's own writer of `ref.artifactId`, still unsealed. Its `ref` is the reference the
sealed artifact will have: this store, generation 1, the allocation's content type, a null
digest, and a `byteLength` of at most the allocation -- the sealed artifact is the first
`byteLength` staging bytes. As part of admitting the command the router seals each such writer
exactly as `artifact.seal` would (section 8.1: the copy into a fresh sealed inode happens outside
the routing state lock, before anything is admitted, and the connection's later commands wait
for it), the writer becomes the sender's explicit hold on the sealed artifact (as after
`artifact.seal`), and only then is the command admitted as if its sender had sealed first. If a
seal fails, or the command is then refused, nothing is admitted and every writer the command
named is released (with whatever it sealed): the reply carries the refusal, `not-dispatched`.
- **Recycling.** Such a command's body may carry `recycle: true` (a body member of `rpc.call`,
`rpc.reply` and `publish` with at least one sealing attachment, refused otherwise). The router
then keeps each sealed writer's staging file and reissues it as a new writer -- a new
`artifactId`, a new hold `ownerId`, the same allocation and content type -- and the command's
reply value carries `writers: [{name, artifactId, generation, ownerId, writeLocation}]`, one per
attachment it sealed, named by attachment. A writer it cannot reissue (owner budget) is simply
left out. Section 8.1's immutability is unchanged: the sealed bytes are a copy, so a producer
writing into the recycled staging file reaches only the staging inode. A reissued writer is a
fresh allocation in content as well: the router overwrites the staging file with zeros before
the reply, so it reads as zeros and no artifact sealed from it -- a prefix, or the whole
allocation through `artifact.seal` -- can carry bytes of the artifact it was before (review N3,
2026-10-02). `recycle` in a body with no sealing attachment is refused, `false` included, and
one writer named by two attachments of the same command is refused (`INVALID_ENVELOPE`).
- Nothing else changes: deliveries, ownership roots, credits and quotas are those of the command
with pre-sealed attachments; a sealing attachment counts its sealed copy against the store quota
at admission, as `artifact.seal` counts it at the seal.
SDK changes of the same slice, no wire change: `ArtifactWriter::into_unsealed` and
`Responder::reply_sealing` (the client side of the above); a reply the router admitted spends the
call's reply authority, so the SDK no longer sends `rpc.responder.release` after one (it was a
no-op command on every call); the router encodes each frame once and forwards an admitted
payload as the bytes it re-encoded once at admission instead of deep-copying it per delivery.

View file

@ -176,6 +176,35 @@ window and last location as private readout state; report `stimulusRemainingMs`;
legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`, legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`,
which that contract leaves open. which that contract leaves open.
**2026-09-23 (AGENT-01 built, `feat/agent-legacy-worker`).** `LegacyAgentWorker`
(`fly-session/src/legacy_agent.rs`) serves the legacy profile under the launcher in all three
execution modes (`legacy-agent` subcommand). Its parity harness (`legacy_parity.rs`) drives
`NeuralAgent` directly in `Sim::step_frame` order from recorded inputs. On the committed toy
connectome, the worker's records match that reference exactly in every mode, including a
rollback and a restore, and are pinned as goldens. A gated FAFB run
(`FLY_AGENT01_FAFB=1`) shows the same on `gameboy-legacy-fafb-v783-v1`. The rate-role mapping
turned out to be the identity: the legacy names are already `Id`s. It is recorded in
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The
harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`.
**2026-09-29 (AGENT-01 rebased onto v0.6.5 and checked against FND-01's trace).** The rebase onto
main had no conflicts. Main changed nothing the worker reads except the adapter id in the
fixtures (v7). The toy goldens and the FAFB reference digest are unchanged. `FLY_TRACE` carries
the frames only as digests and not the `{boot, bound, location}` context, so it checks a worker
and cannot drive one. `legacy_parity::read_frame_trace` and `check_against_trace` hold a run's
records to it: ticks, clock, exact remainder, rates digest, spike-set digest and decision. The
script is checked too: the same sugar, frames, reward events and rollback.
`flysim/tests/agent_trace_parity.rs` is the host. It runs `LegacyFrame` on the ROM with the trace
on, records the missing inputs and checks the worker (in-process, thread and process) and the
direct reference against the trace:
- the toy connectome in raw mode from power-on, for every ROM run;
- `gameboy-legacy-fafb-v783-v1` in macros mode from stream checkpoints (`FLY_AGENT01_FAFB=1`),
with sugar and a ratchet rollback, the worker seeded from the checkpoint's agent state.
Both are identical. Found on the way: a `FLYSIM01` import must start `learning.updates` at the
legacy `plasticity.updates` (legacy-gameboy-v1 section 13, amendment of 2026-09-29).
**Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives;
reference-first composition/goldens; independently seeded agent state and shared immutable data. reference-first composition/goldens; independently seeded agent state and shared immutable data.
Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering.
@ -213,6 +242,64 @@ the frame order maps one to one (section 4), the legacy clock equals the rationa
(section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2 (section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2
and 12). The acceptance criteria below stand. and 12). The acceptance criteria below stand.
**2026-09-29: built on `port/env-01` (off main `9f2345d`).** `fly-session::legacy_env` is the
environment worker (`LegacyGameboyEnvironment`), launched by `Launcher::launch_legacy_environment`
and the `legacy-environment` subcommand in all three execution modes. It makes exactly the emulator
calls flysim's `LegacyFrame` makes, in the same order: `Environment.Initialize` runs the one-frame
setup scaffold with no button down (O[0] has `engineFrame` "1", no audio chunk);
`Environment.Advance` takes one complete `gameboy-joypad-v1` batch for the one port, runs one frame
and returns the `lcd` view, the `apu` chunk as `f32le` (`sample / 255`, unfiltered) and the
`gameboy-memory-inspection-v1` image; `Environment.SaveSlot` / `RestoreSlot` are
`gameboy-slots-v1` (a restore imports, releases the pad, shows the slot's frame, runs no frame and
moves to the new epoch at the same boundary); `State.Capture` / `StageRestore` / `ActivateRestore`
carry every slot and stage on a stopped replacement emulator. The joypad is the only write into a
running game. The coordinator now refuses `episodeRequest.kind = "rollback"` (task failure, epoch
fenced) unless the composition declares `legacy-ratchet-rollback-v1`
(`Coordinator::declare_rollback_policy`); with the policy declared it still pauses at the boundary,
because the rollback sequence is TASK-01's. Parity (`tests/legacy_env.rs`, harness
`legacy_env_parity`): records equal to the emulator driven directly, frame by frame (view, 64 KiB
image, WRAM, audio chunk, slot and capture state digests), in-process, thread and process, on a
toy cartridge the harness assembles (committed golden `fixtures/legacy-env/toy-cart.golden.json`)
and, with rom-env, on the real cartridge from the row-58 checkpoint; and the service's own
`FLY_TRACE`s (FND-01's harness; `FLY_ENV01_TRACE_DIR`) replayed through the worker reproduce every
recorded frame, WRAM and slot-state digest, including a ratchet slot save and a rollback. Not in
this slice: the shim's bulk read (MEM-01, behind the one seam `legacy_env::memory_image`), the
coordinator's save/rollback/`Agent.Rollback` sequence and the executor (TASK-01), and assembling
the FLYSIM01 export from the three halves (STATE-02; the world's half is
`Flysim01World::{manifest_entries, chunks}`).
**Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice:
- ~~*The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM,
`FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and
`export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The
legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image
would make every slot and capture differ from the service's bytes. The worker reads the image
between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as
the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare")
therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read
must keep that guard (or equivalent).~~
*Struck 2026-09-29 (ENV-01 review, R1):* superseded by MEM-01 (legacy-gameboy-v1 section 8
amendment). The register windows are not captured, so `legacy_env::memory_image` is MEM-01's
`Emulator::read_memory_image` with no guard, neutral by construction; the service traces still
match, and the toy golden's image digests were regenerated.
- *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no
boundary, world clock or audio position. The frame counter advances once per transition and
never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is
`k x stepDuration` and the audio position is that time's sample at the configured rate, rounded
down. The first chunk after the restore marks the discontinuity. The ratchet's one slot is the
composition's first declared slot (`best`).
- *Names.* The image travels as the attachment `inspection.memory`; the audio stream is `apu`;
the port is `p1`. `backendConfig` is the canonical JSON of `gameboy-backend-config-v1`
`{form, romDigest, portId, slots, audio {sampleRate, channels, bufferFrames}, setupFrames, view,
controllerSchema, inspectionSchema}`; `Environment.Initialize` naming any other document, and a
cartridge on disk that is not `romDigest`, are refused `INCOMPATIBLE_STATE` with nothing mutated.
The capture payload is flybrain-core's envelope with magic `FLYENV01`, and its participant
compatibility uses the state format `fly-gb-env-v1`.
- *`legacy-transient-reset` for the world is empty.* Everything the environment holds is restored:
emulator, frame on screen, joypad, frame counter, slots, clock and audio position. The reset
applies to the executor, the agent's readout transient and the task's transient observations.
**Implement:** binjgb environment, task-local memory inspector and identity/existing action **Implement:** binjgb environment, task-local memory inspector and identity/existing action
adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics. adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics.
@ -220,6 +307,553 @@ adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash
its own identity and public adapter selection. No console-specific state enters generic its own identity and public adapter selection. No console-specific state enters generic
session types. ROM-backed checks are optional explicit jobs, not required downloads. session types. ROM-backed checks are optional explicit jobs, not required downloads.
### MEM-01 — The boundary memory image (port slice)
**2026-09-29: built** on `port/mem-01` off v0.6.5 and awaiting review. It changes no live
behaviour: nothing in `flysim` calls the new read, and the compatibility string is unchanged. It
delivers the piece of ENV-01 above that reads "add the one read-only bulk memory read to the shim
and prove it mutates nothing", together with the executor-side reader that TASK-01 and the
CUT-01 shadow need.
- **Shim.** `fly_gb_read_memory_image(gb, out, 65536)` fills the buffer in address order.
`Emulator::read_memory_image{,_into}` wraps it. There is no new write path.
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 8 carries a dated amendment (2026-09-29):
VRAM, OAM and I/O are not captured and read `$FF`. binjgb's read of those windows runs a
catch-up that moves the exported state. Every memory byte is captured exactly.
- **Executor reader.** `flybrain_gb::{MemoryImage, Cartridge, ImageReader}`. `ImageReader`
implements `MemoryReader`. The palette, `MacroLayer`, `PokeState` and `PokemonRedReward` run
over it unchanged; this is the same code, not a port. The emulator's own bank reads now go
through the same `Cartridge::read_bank`.
- **Proof.** flybrain-gb `tests/rom_memory_image.rs` (ROM) checks three things. The exported
state is byte-identical before and after each bulk read over 4,200 boot frames. The image
equals the single and cached reads. Reading every frame leaves framebuffers, audio and state
frame-for-frame equal to a run that is never read. flysim `tests/rom_memory_image.rs` runs a
live arm and an image-only shadow arm (task and executor) from nine rom-env checkpoints for
3,000 frames each: 27,000 frames with about 5.5 M `MacroState` answers, deals, pads,
decisions, rewards, ledgers and rollbacks. It finds 0 mismatches and 0 reads outside the
captured ranges.
- **Cost.** A bulk read has a median of 0.31 ms per boundary, 1.9 % of a 16.74 ms frame or
about 209 MB/s of reading. This is the same cost as the 57,120 single reads it replaces. The
image is 3.91 MB/s at 59.7275 fps. A 64 KiB copy has a median of 5 µs, and the optional
SHA-256 digest a median of 0.36 ms. Means and p99 values are dominated by preemption: the
measurement ran on the shared 4-core build box at load 16.
**For ENV-01:** after `run_frame` and after a slot import, publish
`read_memory_image` as the `gameboy-memory-inspection-v1` artifact (`MEMORY_IMAGE_CONTENT_TYPE`,
65,536 bytes, digest optional, `romDigest` = `Cartridge::sha256_hex`). **For TASK-01:** build
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
### TASK-01 — The `pokered-macros-v1` task and executor (port slice)
**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 +
ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of
the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it
the live fly's whole composition -- agent, world, task and executor -- runs on the session
framework, from a fresh start or from a FLYSIM01 checkpoint.
- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one
object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds
any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide`
over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs
`PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's
decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe`
over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order;
there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is
retained until Phase C has read it.
- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the
coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the
agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A
declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with
`RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters
cover the backend and task config, the media, the decision schema, the world's state format and
per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's
`preStepStimulations` and reports every admission applied or aborted. `Coordinator::import`
installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are
kept for a parity run.
- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's
`legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves
go into each participant's own capture format, and the ordinary group restore installs them:
stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first,
because ENV-01 stages only on a replacement. The context the agent resumes with is computed
from the checkpoint's own memory image, and the coordinator holds the task to it after the
install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`.
- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's
`LegacyCheckpointer`).
- `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy
candidate order, holding each candidate to the legacy gate. Any refusal falls to the next
candidate; each attempt runs on a session of its own, because a refused install fences its
session. It is a fresh start when the stores are empty. After either, the startup durable
save is written and the intervals start.
- `advance` keeps the declared boundary order: the slot save (inside the step), the milestone
archive on a rank climb, the rollback (deferred by the coordinator until the host has
captured), a durable save after a rollback, then the interval saves.
- `shutdown_save` is the legacy shutdown's durable save.
- The session runtime writes no sugar journal yet: its admission is the coordinator's, and the
journal's boot header needs the edge.
- `lastEventId` carries the restored file's watermark; the runtime has no feed event log
before EDGE-01.
- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged,
against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the
next cut.
- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment.
**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session
writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built
from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the
executor's batch, the view, the image and the boundary actions. It is compared field by field with
the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list
order. Where the legacy side runs in the test, the ledgers are compared after every boundary as
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
counts and "nearer". Results: see the TASK-01 run report and the amendment below.
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
B1, N1 and N3.
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
past the 32 KiB `TypedValue` bound.
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
- The coordinator files those attachments as `task-ledger-<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.
### PERF-02 — The session's ticks on the release cpuset (port slice)
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. Pinning is only safe in a cpuset that is the sim's alone (a pinned worker cannot leave a CPU that something else hogs: 0.14x real time): the deploy makes it so with `flysim.slice` and `fly-cpu-confine` and writes `FLY_SESSION_PIN=0` when it cannot (`infra/docs/runbook.md`). The legacy loop and process mode are
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
workers against the sequential kernel on the real connectome. The service's periodic profile
line also prints the measurement spans (and the brain's phase split) when
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
### BUS-01 (port slice) — The live session's participants on the router
Not the framework guide's BUS-01 above (the router itself); the port plan reuses the name.
**2026-10-01: built** on `port/bus-01` off `main` (v0.7.5), awaiting review. Operator direction:
run the live session over the flybus router on Unix sockets, one emulator and one fly, because
multiplayer and more flies follow. The topology, its rules and the shadow procedure are
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 12 (amendment 2026-10-01) and section 18
(amendment of the same date); the wire change is [bus-v1](bus-v1.md) section 12 (2026-10-01).
- **Selecting it.** `FLY_SESSION_TRANSPORT=bus` / `flysim-session --transport bus` (process mode
by default; `FLY_SESSION_MODE=thread` and `in-process` too), `fly-runtime session --bus`
(`session-bus`) on the container, `fly-shadow --mode bus/process` and
`fly-shadow-run start --bus` / `check --bus` for its shadow. The local lane stays the default.
`SessionArm` names the four arms; `FLY_PARITY_ARMS` picks them for the parity suites (default
`local,bus/thread,bus/process`).
- **What it took.** Per-process CPU placement (`Launcher::place_process`,
`--host-cpus`/`--sweep-cpus`, `flybrain_core::pool::apply_placement`), the launcher's own clients
in memory in thread and process modes, `block_in_place` for a bus request's handler (without it a
slow `Agent.Initialize` could not be resolved and a process-mode session failed to boot on a
loaded box: "never resolved"), delivered read locations (bus-v1 amendment), writers allocated
ahead (`WriterPool`), no second hold on a worker's own seals, small store I/O in place, the
envelope encoded without copying its body, and the agent's feed status attached to a bus Commit
(the host's 30 Hz `Legacy.FeedStatus` call was a round trip of its own).
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`, as v0.7.5) are the same in every arm: the toy and FAFB parity suites
(`session_trace`, `service_parity`, `rollback_sequence`, `save_handoff`) ran `local`,
`bus/thread` and `bus/process`.
- **Measured, and not fast enough to go live.** The report `claude-bus-01` has the tables. On a
build box with the release CPU model and the release cpuset's shape (four CPUs, four sweep
threads), same frames, interleaved, unpaced: legacy 16.1 ms a frame, the lane 17.4,
`bus/thread` 25.1, `bus/process` 25.7 (`main`'s process mode: 30.4, so this slice took about a
third off the bus's cost). Paced at real time the lane holds 1.00 and the bus 0.69 to 0.71, with a
neighbour CPU busy or not. Every round trip through the router is 0.5 to 1 ms there (the
synthetic `fly-session measure` puts a bare `Worker.Status` at 0.5 ms whether the processes
share one CPU or four), and a transition needs at least five in sequence: Prepare; Advance and
its seals; Commit and its seals. That is a realtime factor of roughly 0.7 on the release
container, so the lane stays live and nothing is switched. Moving the router, the coordinator
and the world to a fifth CPU (`FLY_SESSION_AUX_CPUS`) made it 1.5 to 2 ms slower. What would close
it is a cheaper round trip, not more CPUs: the router's own per-message work (strict JSON parsed
and re-encoded per hop, the state lock, about three task hops a direction), and sealing a reply's
media in the reply itself (one round trip fewer for Advance and for Commit).
- **`fly_frame_work_*`** on `/metrics` (both runtimes): the loop's compute time per frame without
its pacing sleep, mean, p99 and max over the last 3,600 frames. It agrees with the unpaced
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
hides.
### BUS-02 (port slice) — A cheaper bus transition
**2026-10-02: built** on `port/bus-02` off `port/bus-01`, awaiting review. Goal: make the
session-over-flybus transport cheap enough to carry the live fly (operator: run on the bus with
real sockets, because more consoles and more flies follow). The wire change is [bus-v1](bus-v1.md)
section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched.
- **Where a bus transition's time went** (a build box with the release CPU model and the release
cpuset's shape, router traffic counted per frame, cross-process timestamps per hop). About 35
commands a transition went through the router -- three calls and their replies, but also five
`artifact.seal`, six `artifact.allocate`, five `artifact.retain`, four `artifact.release`, six
`delivery.consumed` and three no-op `rpc.responder.release` -- and the router encoded every frame
twice and deep-copied every payload three or four times. The session's host CPU (the dispatcher's
CPU, which the router, the coordinator and the world share) was about 96% busy in every arm, so
bus cost was frame time almost one for one.
- **What changed.** Sealing sends (bus-v1 amendment: a reply seals the writers it attaches and
recycles their staging files as new writers, so a reply's media cost no seal or allocate round
trip); result attachments kept as delivered instead of retained; no responder release after an
admitted reply; the router encodes each frame once and forwards an admitted payload as bytes;
seal copies with `copy_file_range`; client location resolution cached; the session's writer pool
keyed by capacity (4 KiB buckets) so the variable-length feed status no longer misses it. About
14 commands a transition remain (three calls, three replies, consumes, cache releases).
- **Measured.** Before/after tables in the run report `claude-bus-02`. Unpaced, same rounds:
`bus/process` 17.1-17.2 ms a frame before, 14.9-15.8 after; paced at 1.0, the frame-work metric
17.4 before, 15.0 after (the lane 12.5, legacy 10.7). The bus still costs 2.5 to 3.5 ms a frame
more than the lane on that box, short of the 1.5 ms target, so the lane stays live. Also found:
BUS-01's numbers had the bus store on a disk-backed directory; on tmpfs (as the release, under
`/run`) its own binaries were 2.5 ms a frame faster.
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`) in `local`, `bus/thread` and `bus/process` (the FAFB parity suites, all arms).
- **Review notes (2026-10-02).** The review approved with notes; since the feed and the control
API already run over flybus in production, the router and SDK changes carry live traffic, so
every note was treated as live-path correctness. A recycled writer's staging file is zero-filled
when the router reissues it (about 10 us a 92,160-byte reply on tmpfs), so no artifact sealed from it -- by prefix or
whole -- carries the previous artifact's bytes (N3). A sealing reply is sent with the worker's
result cache held, so a duplicate replays the sealed artifacts rather than racing the reply
with an unsealed writer (N2). A refused sealing reply is answered as the handler's own seal
failure was before this slice (`BACKEND_FAILURE`, mutation applied), cached the same way, and
logged (N1). A failed staging rename leaves no file (N5). `recycle` without a sealing
attachment is refused even when false, a writer named by two attachments is refused, and the
SDK checks `writers` on every sealing send's reply (N4). The store-directory cache is per
connection (N6). Two test races are closed: the fly-edge stall test waits for the feed topic,
and SERVE-01's parity accepts a refused `/stimulate` drained one frame late (N7). The review's
adversarial lifecycle tests are in `flybus/tests/sealing_lifecycle.rs`.
### 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.
### SHADOW-02 — The shadow on a build box (port slice)
**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
back to 0.999-1.0 the moment the shadow was stopped.
- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
pins; no path, no secret).
- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
byte that was on disk a minute ago). The box's verdict is written back only when it is this
run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
box): the release directory and binary hashes must equal its own; a new run id resets the mirror
and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
finished is never written again (`done`, and the relay then deletes the container's copy);
reports liveness (heartbeat fresh, verdict this run's and running or passed).
- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
stop while following is a `coverage` divergence; coverage reads the journal before listing the
traces. `shadow::release` holds the release hashing the binary and `check` share.
- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
`flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
`Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
`flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
`02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
section has the set-up.
**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
and `resync`, the run reset, the env allowlist.
**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
build box standing in for the release container, the remote shadow on another behind a real sshd
with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
the trace is on, so the trace's cost counts against it.
### 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.
@ -233,6 +867,244 @@ for new epoch metadata; corrupt any participant and installation fails as a grou
reply doesn't advance durable metadata; failure during activation cannot resume half a world. reply doesn't advance durable metadata; failure during activation cannot resume half a world.
Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery. Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery.
### STATE-02 — The legacy composition's checkpoints in `FLYSIM01` (port slice)
**2026-09-29: built** on `port/state-02` off `port/integration` and awaiting review. The operator's
decision of 2026-09-23 makes `FLYSIM01` the format of record until RETIRE-01, and the session
runtime exports it on every durable save ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16).
This slice is that export, the import back, the store policy and the restore selection. It adds
no `FLYSESS1` production file. Nothing in `flysim`'s frame, checkpoint bytes or compatibility
string changes.
- **One store, two runtimes.** `flysim`'s `store.rs` and `journal.rs` move unchanged into the new
crate `flysim-store`, which `flysim` re-exports (`flysim::store`, `flysim::journal`) and
`fly-session` links. Both runtimes write through the one `store::encode` and commit through the
one `Store`, so they share the envelope bytes, the generations, `manifest.json`, the
`milestone-<N>` archives, `keep_generations` rotation and the restore order by construction.
- **Export** (`fly-session::legacy_checkpoint`). A `FLYSIM01` file is assembled from its owners'
halves: the agent's `FLYAGT01` capture payload (the seven agent chunks, the remainder already the
accumulator's), the world's `FLYENV01` payload (emulator, frame on screen, joypad, frame
counter, cartridge digest, and slot `best` as `ratchetGame`/`ratchetFrame`), the task's
`{reward, ratchet}` and the host's `{generation, wallMs, compatibility, speed, rankSinceMs,
lastEventId}`. `runtime_state` builds the legacy `RuntimeState` field for field as
`Sim::snapshot_state` does.
- **Import.** `split`/`halves` read a `FLYSIM01` file back into those halves. `agent_payload` is
the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01`
payload a replacement agent stages, using the same encoder the worker's own capture uses
(`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms,
warmupOffset = 2500}`. `learning.updates` is the file's `reinforcements`. A file from before
that member starts at `plasticity.updates` once (`legacy_reinforcements`, section 13
amendment). The checkpoint id is the file's generation (`flysim01-g<N>`). No template worker
is involved. This fixes the four points the AGENT-01 review raised against the prototype:
template dependence, borrowed ids, no compatibility gate (the gate is `restore_from_store`'s,
below), and the count falling back on every round trip. The payload also carries the file's
`framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input.
`LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive,
and the two differ on the row 65 yard survey checkpoint (found here; see the section 13
amendment). `world_payload` is ENV-01's `FLYENV01` from
the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`.
`legacy_parity` now seeds its workers through this import.
- **`reinforcements`, an optional `FLYSIM01` manifest member.** `LegacyFrame` now counts
reinforcement calls the way the agent worker does: one per commit while the rule is enabled,
zero sums included. `Sim` writes the count, and `LegacyFrame::restore` reads it (falling back
to `plasticity.updates`), so the count survives every round trip in either runtime. Readers
that predate it ignore it. The member changes no behaviour and not the compatibility string,
but it does change legacy checkpoint bytes: a file written from now on is the old layout plus
this member.
- **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site:
- one generation counter over both stores, starting above the highest either has allocated;
- a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also
restarts the hot interval;
- a durable save for a climb, archived as `milestone-<rank>` when the rank is above every rank
this process has archived (`best_archived_rank`, per process as in the legacy loop);
- rank tracking as in `track_rank`;
- encoding and fsyncs on a writer thread.
- **Restore selection.** `restore_from_store` walks `store::restore_order`: hot latest, hot
previous, durable latest, durable previous, then the archives by descending rank, each as its
generation and then as its `milestone-<N>` file. It checks the legacy gate: the cartridge, and
`flybrain_gb::compatibility::decide` with `FLY_ACCEPT_ADAPTERS`. It moves to the next candidate
on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no
candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit
as `Sim::restore_or_warm_up` does.
- **The agent worker** now refuses a conflicting stage (a restore already staged, or a token
already activated) before it builds a replacement network (AGENT-01 review).
- **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header
records the runtime, start frame, brain ms, restore origin, generation and compatibility. The
journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a
`continues` line. `journal::clear` removes the journal. `flysim` writes the header at boot, and
`flysim --reset-to-milestone` clears the journal after it has copied both stores aside.
`read_segments` cuts the journal into per-process segments. `read` still returns input lines
only.
**Boundary order the session host must keep** (section 16, and section 11 step 6). At `Ready(k+1)`
the order is:
1. `Environment.SaveSlot`, if one is due.
2. The milestone capture, if the rank climbed.
3. The rollback, if one was requested.
4. The durable capture after the rollback, then the hot and durable interval saves.
The capture itself uses `State.Capture` on the world and the agent at the same committed
boundary, plus the task's ledger, `{reward, ratchet, slotFilled}` (`TaskHalf::to_ledger`). Wiring
it into the coordinator and the boot-time restore path is left to the legacy composition's
coordinator (TASK-01); this slice ships the pieces and proves them on the workers.
**Proof** (flysim `tests/state_02.rs`, `tests/state_02_store.rs`; `fly-session`
`legacy_checkpoint` unit tests):
- *legacy -> session -> legacy on 18 real checkpoints* (every distinct rom-env checkpoint, which
includes the row 64, row 65 and row 67 ones). Each file is split and the world is restored
into the real environment worker and captured again. The agent goes through the imported
`FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is
byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once.
Against the files themselves, every export differs only in named fields. All 18 gain
`reinforcements`, because the files predate it. Twelve written by adapters v5 or v6 also
differ in `reward`, which the adapter's import migrates. One survey checkpoint also differs in
a joypad byte of its emulator state that its own `buttons` field does not match; both runtimes
apply `buttons` on restore. Before the counter was added, six of the 18 were byte-identical to
the file.
- *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a
checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy
loop and the session runtime then each run 600 frames from it. World: 1,800 values identical
to `FLY_TRACE` (frame, WRAM). Agent: 600 transitions identical (ticks, clock, exact remainder,
rates, spikes, decision). The session runtime's export at the last boundary is byte-identical
to the legacy loop's checkpoint of that boundary. That export also survives session -> legacy
-> session unchanged: a fresh legacy loop restores it and checkpoints the same bytes, and a
fresh world and agent import it and export the same bytes.
- *The same with `gameboy-legacy-fafb-v783-v1` in macros mode* from the row 67 checkpoint, with
sugar and a ratchet rollback (`FLY_STATE02_FAFB=1`). Four checkpoints were run for 1,800 frames
each: rows 58, 64 and 67, and the row 65 yard survey. Each run has 5,400 world values and 1,800
agent transitions identical to the trace, with 2 sugar and 1 rollback. Each export is
byte-identical to the legacy checkpoint and survives session -> legacy -> session.
- *The tools, both ways* (`tests/state_02_store.rs`, the real `infra/bin` scripts and the real
binary). `fly-loop-reset --list` and `--print-state-compatibility` read a store the session
runtime wrote. `fly-reset-to-milestone` promotes its rung with the recovery budget back and
clears the journal. The legacy order and the session runtime then choose the same candidate,
and the session runtime carries on above every generation and archives its next climb. The
other way round, the session runtime restores a store the legacy writer wrote and the tool
reset, and it would save it as the same bytes.
**Not in this slice, and why:**
- *The coordinator hook and the boot-time restore.* Both need the legacy composition's
bootstrap, which is TASK-01's. The restore order is Initialize-free: stage and activate the
world, have the task install `{reward, ratchet}` and observe O[k] for the first context
(`{boot, bound, location: null}`), then build the agent's payload with that context
(`agent_payload`) and stage and activate it.
- *The task's per-frame half in the proofs.* The executor and the task's evaluation are TASK-01's.
The proofs take the joypad masks from the trace and the task's end-of-run `{reward, ratchet}`
from the legacy loop.
- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive
holds the post-capture ratchet and slot. It is excluded from the shadow comparison.
### SERVE-01 — The session runtime as the live service (port slice)
**2026-09-29: built** on `port/serve-01` off `port/task-01` and awaiting review. It makes the
session runtime a drop-in for the live `flysim` service, so CUT-01 can switch the stream over
with one command and roll back with one. It changes no live behaviour: the legacy loop's frame,
feed, checkpoint bytes and compatibility string are unchanged, and nothing runs the new binary
until `fly-runtime session` is run on a container.
- **One service shell, two runtimes** (`flysim::serve`). `flysim::run` is split: `serve(config,
sim)` binds the feed (`:7400`, or the feed bus that `fly-edge` serves), the control API
(`:7401`) and the metrics listener (`:9101`), handles SIGTERM/SIGINT/SIGHUP, and runs `sim` on
the calling thread with the `Shared` state, the snapshot slot and the command queue. The
legacy loop is `serve(config, Sim::boot + Sim::run)`. The pieces of a feed header that come
from the fly (`feed_rates`, `feed_learning`, `feed_game`, `feed_milestone`, `feed_sugar`) and
the chat admission (`admit_chat`) move out of `Sim` into free functions both runtimes call.
The feed codec, the bus publisher, the router, `/status`, `/events`, `/metrics` and the
WebSocket framing are therefore one copy of the code whichever runtime is behind them.
- **The service host** (`fly-legacy-session::service`, binary `flysim-session`). It reads
`flysim`'s own `Config` (so `/etc/fly/fly.env`, `FLY_ACCEPT_ADAPTERS` through STATE-02's
`RestoreGate`, the macro mode, speed, threads, chat, the store paths) and keeps `Sim`'s order
call site for call site: boot by TASK-01's `boot_unsaved` (the legacy candidate order and gate),
the boot event, the chat sidecar, the journal's boot header (`runtime: fly-session`), the
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,
the same filter on the environment's `v / 255`); the spike bitset is the OR of the commits'
`telemetry.spikes` since the last publish, which equals the legacy window exactly; `buttons`
is the executor's mask (the checkpoint's after an import, 0 after a rollback, as
`LegacyFrame` has it); the game, milestone and macro fields are the task's own adapter,
ratchet and macro layer (`PokeredTask::inspect`, `take_feed`). The numbers from inside the
network that no session message carries -- the plasticity statistics (`learning.changed`,
`learning.synapses`), the decoder's baselines and scores for `/status`, and the rates and pulse
at the boundary -- come from one declared extension of the legacy agent,
`Legacy.FeedStatus` (capability `legacy-feed-status-v1`): read-only, answered at a committed
`Ready(k)`, once per published snapshot, never in a trace. `Coordinator::read_agent_extension`
calls it without fencing the epoch; `Coordinator::media_bytes` reads the committed view and
audio chunk.
- **Sugar.** flysim's `RateLimiter` and clamp, over the pulse the network holds: the last commit's
`stimulusRemainingMs`, raised by each sugar admitted since (`network.stimulate` is a maximum),
so a second request in one drain is refused with the legacy `retryAfterMs`. The admission lands
in the next Prepare, which is the frame the legacy drain applies it before, and the journal
stamps it with that frame.
- **Long-running hygiene.** The coordinator kept every transition's trace, every phase change,
an audit line per step and every timing sample: about 120 KB/s of heap on the live fly
(the first soak's RSS). `Coordinator::trim_records` bounds them at each boundary; the timings
are logged once a minute as a `session profile` line and cleared.
- **Declared differences** (the rest is byte-equal, below): `POST /reward` is always 403
(`control.allow_reward` is forced off; the operator pulse has no session-framework
counterpart, `legacy-gameboy-v1` section 15); a fresh start publishes no audio for its setup
frame (the environment discards O[0]'s); `FLY_TRACE` and `FLY_PROFILE_SECONDS` are the legacy
loop's tools; only the Pokémon composition exists (another `FLY_GAME` is refused at start); the
toy connectome cannot run macros mode (AGENT-01 refuses a macro channel the dataset does not
track, and the toy tracks none).
- **Infra.** `flysim.service` stays the fly's one unit. `infra/bin/fly-runtime session|legacy|status`
switches the binary it runs with one drop-in (`flysim.service.d/10-runtime.conf`), so every
consumer that names `flysim.service` -- `fly.target`, `flyedge.service`'s `Requires=`, the
watchdog, `fly-loop-recover`'s sudoers-granted restart, `fly-loop-reset`,
`fly-reset-to-milestone`, the unstick rule -- works unchanged and the choice survives reboots and
deploys. It refuses a release without `flysim-session` or with a different compatibility
string, waits for `/healthz` and an advancing frame, and falls back to legacy by itself if the
session runtime does not come up. `flysim-session.service` is the standalone unit (flysim's
limits and cpuset, `Conflicts=flysim.service`, no `[Install]`) for rehearsals.
`build-flysim.sh`/`package-release.sh` ship `flysim-session` and `fly-session`; `05-deploy.sh`
installs `fly-runtime`, writes the standalone unit's cpuset drop-in and refuses a release
without `flysim-session` while the drop-in is present; tmpfiles creates `/run/fly/session`.
The runbook's "Switch the runtime" is the operator's page.
**Proof** (`fly-legacy-session/tests/service_parity.rs`, `journal_replay.rs`, rom-env; the SERVE-01
run report has the numbers). Both runtimes are started from the same seeded store behind
flysim's own control router and driven by one script of control requests, each landing before
the same frame: every running feed header is equal field by field (wall-clock fields excepted)
and every frame, audio and spike attachment byte for byte; every control response is equal
(`/stimulate` 202/429 with the same `retryAfterMs`, `/reward` 403, `/chat` 202/422,
`/checkpoint` the same generation, `/pause`, `/resume`, `/events`, 404s); the event log, the
journal and the final checkpoint are equal. Toy connectome raw mode, and the real connectome in
macros mode through a ratchet rollback, each in-process and as processes. A soak of both
runtimes side by side with the stage's decoder and the bridge's `HttpSimClient`
(`tools/runtime-soak.ts`), the hot/durable cadence sampled from the stores, and a `SIGKILL`
whose journal is replayed from the seed in the legacy loop onto the killed process's last hot
checkpoint.
Results (2026-09-29, the build boxes; the run report has the logs):
| Proof | Result |
| --- | --- |
| Toy raw, 120 frames, 19 scripted requests incl. two sugars in one drain | identical, in-process and process |
| Real connectome, macros, `rollback` checkpoint (ratchet rollback on frame 1), 120 frames | identical, both modes, before and after the TASK-01 fixes |
| Real connectome, macros, engage checkpoint (ledger thinned), 2400 frames, 46 macro and 2 reward events | identical, both modes |
| Real connectome, macros, row 64 (a 42 KB adapter ledger, TASK-01 B1), 1200 frames | identical, both modes |
| Soak, 35 min, both runtimes from the row 67 checkpoint, production configuration | 0 decode or schema errors, no 2 s stall, `/healthz` 100 %, event ids gapless, hot every 5 s and durable at 300 s on both (same intervals) |
| Soak, 36 min, the session killed -9 at +6 min | back in about 1 s from the hot checkpoint 3.5 s old, 1 `/healthz` 503, the feed client reconnected (533 ms gap), two journal segments |
| The killed process's journal, 17 sugars, replayed from the seed in the legacy loop | 18,838 frames onto its last hot checkpoint: agent, emulator, frame, adapter, ratchet equal |
| Feed over the bus (`FLY_FEED_VIA=bus`) with `fly-edge` | 3,050 snapshots through the edge, 0 errors |
Open for CUT-01: **speed.** Unpaced on a shared box the session ran 54-61 fps where the legacy
loop ran 68-118 (per frame p50: `Agent.Prepare` 7.8 ms, `Environment.Advance` 2.6,
`Agent.Commit` 1.6, publication 0.4; `Legacy.FeedStatus` 0.9 ms at 30 Hz). The live container
must be measured (SHADOW-01's cost run) before cutover. **Memory.** After `trim_records` the
session's RSS still grows about 5-8 MB an hour, tied to the saves (an unpaced run without saves
is flat); at `MemoryMax=4G` that is weeks, and a restart clears it, but it is not explained yet.
**Number form.** A checkpoint the session writes carries the adapter ledger's integral numbers
as `7580031` where the legacy loop writes `7580031.0` (the ledger crossed canonical JSON); equal
values, and both runtimes read both.
### PUBLISH-01 — Committed snapshots and observer isolation ### 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

@ -125,7 +125,8 @@ interface GameboyReadoutContext {
``` ```
`ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so `ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so
they are not `Id`s. The context is what the task hands the decoder with each Prepare (the they are not `Id`s (corrected 2026-09-23, AGENT-01: they are; see the section 13 amendment).
The context is what the task hands the decoder with each Prepare (the
`initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the `initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the
composition's `macroChannels`. composition's `macroChannels`.
@ -168,7 +169,8 @@ interface GameboyMemoryInspection {
} }
``` ```
- **The image.** Byte *i* is what `fly_gb_read_mem(i)` returns at this boundary, which is - **The image.** (Amended 2026-09-29, below: the register windows are not captured.) Byte *i*
is what `fly_gb_read_mem(i)` returns at this boundary, which is
what every task and executor read in the legacy loop sees through the per-frame read cache. what every task and executor read in the legacy loop sees through the per-frame read cache.
It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional, It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional,
because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At
@ -186,6 +188,38 @@ interface GameboyMemoryInspection {
- **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated. - **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated.
The executor reads it in Phase B, and the task reads old and new images in Phase C. The executor reads it in Phase B, and the task reads old and new images in Phase C.
**Amendment, 2026-09-29 (MEM-01).** The image captures the address space's *memory*, not its
*registers*. The two proofs this section demands contradicted each other for three windows: a
read of VRAM (`$8000-$9FFF`), OAM (`$FE00-$FE9F`) or I/O with the APU and wave RAM
(`$FF00-$FF7F`) goes through binjgb's lazy catch-up (`ppu_synchronize`, `timer_synchronize`,
`serial_synchronize`, `intr_synchronize`, `apu_synchronize`) before it answers. The catch-up
rewrites the subsystem's sync bookkeeping, so the exported state changes. On a boot run it
changed on 104 to 105 of 105 sampled boundaries for each window. A full 65,536-byte read
through `emulator_read_mem` is therefore not read-only by the state-comparison test. The amended
rule:
- **Captured**: `$0000-$7FFF` (ROM as mapped), `$A000-$FDFF` (cartridge RAM, work RAM and its
echo), `$FEA0-$FEFF` (the unused block) and `$FF80-$FFFF` (high RAM and `IE`). Byte *i* is
exactly what `fly_gb_read_mem(i)` returns at this boundary. binjgb reads each of these
straight out of an array, with no catch-up.
- **Not captured**: the three register windows above. They read `$FF` (binjgb's
`INVALID_READ_BYTE`), and the shim does not call `emulator_read_mem` for them.
- **Unchanged**: the artifact is still 65,536 bytes in address order,
`application/octet-stream`, with an optional digest. `gameboy-memory-inspection-v1` is
therefore unchanged, and so are its schema digest and the contract digest.
- **Why no task or executor loses anything**: none of them reads a register window. The Pokémon
adapter, scene detector and macro engine read WRAM, HRAM and ROM only. MEM-01's equivalence
harness (flysim `tests/rom_memory_image.rs`) counts every address the image-backed arm reads
over 27,000 frames from nine checkpoints and finds no read outside the captured ranges. A future
task that needs a register must amend this section first. A register cannot be captured
read-only through this shim.
The shim function is `fly_gb_read_memory_image(gb, out, 65536)`, and in Rust it is
`Emulator::read_memory_image{,_into}`. The executor's reader is `flybrain_gb::ImageReader`,
which pairs a `MemoryImage` with a `Cartridge`. `Cartridge::verified` refuses a ROM whose SHA-256
is not the environment's `contentDigest`. The emulator answers its own bank reads through the same
`Cartridge::read_bank`.
## 9. Environment ## 9. Environment
- **Initialize.** The backend configuration declares a setup scaffold of **one frame with no - **Initialize.** The backend configuration declares a setup scaffold of **one frame with no
@ -214,6 +248,22 @@ interface GameboyMemoryInspection {
FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary
completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16). completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16).
**Amendment, 2026-09-29 (ENV-01).** Two consequences of building this section, recorded in the
[implementation guide](implementation.md) ENV-01 entry: ~~the memory image cannot be taken with a
plain loop of `emulator_read_mem`, because reading OAM, VRAM, the serial and timer registers,
`IF`, `STAT` or `LY` advances binjgb's lazy synchronisation and changes what `export_state` writes
-- the environment reads it between an export and an import of the same bytes, so slots and
captures stay byte for byte the legacy loop's;~~ and a `FLYSIM01` world is restored at boundary
`emulatorFrame - 1`, its world time and audio position derived from that boundary, with the
ratchet's snapshot as the slot `best`.
*Struck 2026-09-29 (ENV-01 review, R1).* The first consequence is superseded by section 8's MEM-01
amendment of the same day: the register windows are not captured and read `$FF`, so the image is
MEM-01's one bulk read with no export/import guard around it, read-only by construction
(`legacy_env::memory_image`). With it the service's traces still reproduce every frame, WRAM and
slot-state digest (rollback 3,199, climb 3,156, r58 11,043 transitions), because the legacy
adapter and macros never read VRAM, OAM or I/O.
## 10. Executor `pokered-macros-v1` ## 10. Executor `pokered-macros-v1`
The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the
@ -238,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
@ -281,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
@ -326,6 +415,120 @@ 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.
**Amendment, 2026-10-01 (PERF-02): thread placement in the service.** Again nothing in the
declaration, the digest or the compatibility string changes, and no result can: placement chooses
the CPU a thread runs on, never what an index of a parallel phase computes.
- `flysim-session` (in-process and thread modes), before it spawns any thread, gives each of the
`RAYON_NUM_THREADS - 1` spawned sweep workers one CPU of the unit's cpuset to itself and confines
every other thread -- the dispatching runtime worker, the coordinator, the listeners, the
checkpoint writer -- to the rest (the first CPU, plus any beyond the sweep's). Process mode and
the legacy loop are unchanged. `FLY_SESSION_PIN=0` keeps every thread floating, as before. The infra keeps other processes off the pinned CPUs (`flysim.slice`, `fly-cpu-confine`) and sets it to `0` where it cannot.
- Why: the session's host threads sleep and wake around every transition, so the sweep workers
park and wake every transition too, and the scheduler often woke two of them onto one CPU while
a host thread held another: each parallel phase of that transition then took two shares' time.
On the release CPU model with a four-CPU cpuset the session's ticks ran 35% slower than the
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost
what the legacy loop's do.
**Amendment, 2026-10-01 (BUS-01): the composition on the router.** The operator's direction of
2026-10-01: run the live session's participants over the flybus router on Unix sockets, one
emulator and one fly today, because multiplayer and more flies follow. Nothing in the declaration,
the digest or the compatibility string changes, and no result can: the bus carries the same
domain calls, in the same order, to the same endpoints as the local lane. Traces, checkpoints and
the FAFB parity runs are identical in every arm (`local`, `bus/thread`, `bus/process`;
`fly_legacy_session::composition::SessionArm`).
*Selecting it.* `FLY_SESSION_TRANSPORT=bus` (or `flysim-session --transport bus`) puts every
participant on the router's sockets; `FLY_SESSION_MODE` then defaults to `process`, and `thread` and
`in-process` are also allowed (`in-process` on the bus is every participant a socket client from
the coordinator's own runtime). `local`, the default, is the PERF-01 lane and stays the release
configuration until a cutover onto the bus. `local` with a thread or a process is refused: those
have no lane. On the container, `fly-runtime session --bus` (`session-bus`) writes
`Environment=FLY_SESSION_TRANSPORT=bus` into the runtime drop-in, and `session --local` takes it out.
*The topology (process mode, the bus default).*
| Process | Runs | Bus client | Reached by |
| --- | --- | --- | --- |
| `flysim-session` (the unit's main process) | the router (one per session), the launcher's supervisor, the coordinator with the `pokered-macros-v1` task and executor, the service host (feed, control API, metrics, checkpoint writer, sugar journal) | `coordinator`, `launcher` | in memory: they live with the router |
| `fly-session legacy-agent` (child) | AGENT-01: the brain, its readout and its sweep pool | `legacy-fly`, registers `agent.fly` | `<session dir>/attempt-N/sockets/legacy-fly-<n>.sock`, launcher-bound |
| `fly-session legacy-environment` (child) | ENV-01: binjgb, the slot, the memory image | `legacy-world`, then `legacy-world-r2` for the restore's replacement world; registers `env.world` | `.../sockets/legacy-world[-r2]-<n>.sock`, launcher-bound |
- *Policy* (closed, `composition.rs`): the coordinator may call `agent.*` and `env.*` and owns
`session.*` (publish, topics, its query service); the supervisor may call `agent.*` and `env.*`
and register nothing; each participant may register exactly its own service and call nothing.
An identity is bound by the launcher before Hello, so a process cannot answer as another.
- *Media* stay artifacts in the router's store (`<session dir>/attempt-N/store`, tmpfs, `fly`
0700): the 92,160-byte frame, the 65,536-byte memory image, the audio chunk (about 6.4 KB a frame
of `f32le`) and the 17,407-byte spike bitset every transition, and the captures (MBs, every hot
save). Inline is not an option: bus-v1 section 8.1 forbids binary in a body, and the image alone
would not fit the 64 KiB envelope once encoded. A delivery names each attachment's read location
(bus-v1 section 12, 2026-10-01), so a read is a local file read; a worker seals into writers it
allocated after the previous step (`worker::WriterPool`). Over the bus the agent's Commit also
attaches its feed status (`legacy.feed-status`, the `Legacy.FeedStatus` result's bytes as of the
committed boundary), which the service host reads instead of making that call at every publish;
a rollback after the Commit makes it ask again.
- *One unit, restarted as a whole.* The session cannot survive the loss of a participant: its
state is split across them and is recovered only as a group (STATE-01), and the store's last save
is that group. So the children belong to `flysim.service` (the launcher spawns them; systemd's
default `KillMode=control-group` reaps them with the unit), a dead participant fails the step
within `ipc-v1` section 6's ten seconds, `flysim-session` exits, and `Restart=always` starts the
whole session again from the store -- what a crash of the in-process session does today. A
child also exits when its router connection closes. The router lives in the coordinator's
process for the same reason: its loss is the session's. One unit keeps `fly-runtime`'s one
drop-in switch, the `OnFailure=` fallback to legacy (three starts in ten minutes), the speed
probation, the watchdog and the unstick rule's restart unchanged; separate units would need
`BindsTo=` chains and three start limits for no recovery a group restore does not already give.
- *CPUs.* The unit's cpuset is unchanged (on the release container `flysim.slice`'s four CPUs).
The service splits it as PERF-02 does and hands the split out: the agent process pins its spawned
sweep workers one per CPU and keeps its other threads (its dispatcher is sweep worker 0) on the
remaining CPU (`fly-session ... --sweep-cpus 3,5,7 --host-cpus 1`); the service process and the
world process run on that same host CPU. The transaction is serial -- nothing overlaps Prepare
(PERF-01) -- so they take turns on it rather than contend. `FLY_SESSION_AUX_CPUS` moves the
service and the world elsewhere in the unit's cpuset; it was measured and does not pay
(implementation guide, BUS-01). `FLY_SESSION_PIN=0` floats everything, as before.
- *Each participant process has one async worker, and a long handler gives it up*
(`tokio::task::block_in_place` for `*.Initialize`, `State.*`, `Agent.Rollback`): the agent's
warm-up runs for seconds, and a Tokio worker blocked that long stranded the shell's own bus loop,
so `ipc-v1` section 6's resolution of a slow `Agent.Initialize` failed ("never resolved") and a
session could not boot on a loaded box. A step's handlers (milliseconds) run in place, so a bus
request crosses no thread inside a participant. The local lane is unchanged.
*N agents and M environments are configuration.* Nothing above assumes one of each: the
launcher starts any number of `LegacyAgentLaunch` and environment launches, each with its own
client id, service name and socket; the policy grants are per client; placements are per worker
id (`Launcher::place_process`), so each agent process pins its own sweep to its own CPUs; the
coordinator calls agents concurrently and assembles one batch over every declared port; the router
has no notion of a fly. What is one-of-each today is this composition (`LegacyConfig`, one
`PokeredTask`, `FLYSIM01`'s one agent and one world) and the service's CPU split (one agent's
plan), which a multi-agent composition replaces rather than extends.
## 13. Machine-readable parts ## 13. Machine-readable parts
| Where | What | | Where | What |
@ -351,6 +554,79 @@ stale files.
valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The
mapping belongs to the agent adapter. This contract does not choose it. mapping belongs to the agent adapter. This contract does not choose it.
**Amendment, 2026-09-23 (AGENT-01): the rate-role mapping `legacy-rate-role-id-v1`.** The
premise above is wrong. The session `Id` grammar is `^[a-z0-9][a-z0-9._-]{0,63}$`
([session RPC](ipc-v1.md) section 1, `flybus::wire::is_id`, `isId` in `@flybrain/session-types`),
and it admits `_`. Every role `data/fafb-v783` declares, including the 31 `macro_*` populations
merged after the fingerprint, and every role the kernel tracks, is already an `Id`; so is every
`ChannelName`, whose grammar is a subset. The mapping is therefore the identity:
- a legacy rate-role name `n` is published as `roleId = n` when `n` is an `Id`, and a `roleId`
names the rate role of the same spelling. The mapping is reversible by construction;
- a name that is not an `Id` has no `roleId`. The agent refuses to initialize over a dataset
that tracks one (`INCOMPATIBLE_STATE`), rather than invent an encoding no consumer could read
back. No shipped dataset has one;
- the published list keeps the kernel's tracked-role order and its bounds: at most 64
(`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. On `fafb-v783` it is 45 roles.
`gameboy::rate_role_id`, `rate_role_name` and `rate_role_ids` in `fly-session-types`, and
`rateRoleId`, `rateRoleName` and `rateRoleIds` in `@flybrain/session-types`, implement it.
`fixtures/gameboy-rate-roles.json` holds both languages to the same accepted and refused names and
records the FAFB tracked list, which `fly-session`'s gated FAFB test recomputes from the
committed dataset. The mapping changes no schema, digest or fixture digest.
**Amendment, 2026-09-23 (AGENT-01): what the legacy agent reports and captures.** These are
agent-adapter choices that the sections above leave open. `LegacyAgentWorker`
(`fly-session/src/legacy_agent.rs`) implements them:
- *Seed.* The kernel version `lif-1ms-f64-v2` hashes the LIF seed. Every seed except the legacy
default `22222` gives a different kernel version, so the profile pins the seed.
`Agent.Initialize` refuses any other seed (`INCOMPATIBLE_STATE`) before it builds a model. The
coordinator of this composition passes `22222`. It does not use a seed derived under
[seed-derivation-v1](seed-derivation-v1.md).
- *Learning telemetry.* `AgentTelemetry.learning` requires `changed <= updates`. The legacy
counters mean something else, so they map as follows. `updates` is the number of reinforcement
calls the agent has applied: one per commit while the rule is enabled, zero sums included.
`changed` is the legacy `plasticity.updates`: the reinforcements that moved at least one gain.
`signal` is `plasticity.signal`. The legacy per-synapse count (`LearningStats.changed`, the
gains away from 1.0) is not carried. It can still be read from a captured state.
`stimulusRemainingMs` is the network's `reward_remaining` after the operation.
*Amended 2026-09-29 (AGENT-01 rebase):* `FLYSIM01` records `plasticity.updates` but not the
reinforcement calls. An agent imported from a `FLYSIM01` agent state therefore starts
`updates` at that state's `plasticity.updates`, which is a lower bound on the calls made. Starting
it at zero makes the first telemetry violate `changed <= updates`: on the live fly `changed` is
in the thousands. `legacy_parity::legacy_reinforcements` is the rule. The import that ENV-01
or STATE-01 ships must apply it.
- *Spikes.* Each `Agent.Commit` reply carries the attachment `telemetry.spikes`, with content type
`application/x-fly-spike-bitset`. It uses the legacy feed's layout: bit *i* is neuron *i*,
`ceil(neurons/8)` bytes. It covers the transition's ticks: a neuron is set when its last spike
is at or after the brain time before that transition's Prepare ticked. The mapping of bit
*i* is the graph's `indexDigest`.
- *Graph.* `datasetDigest` is the SHA-256 of the schema-1 fingerprint string. `indexDigest` is the
SHA-256 of `fly-session/legacy-agent-index-v1`, the fingerprint, the neuron count and every
`macro_*` population's members. The macro populations are the profile's declared
`macro-roles-outside-fingerprint` exception. Two datasets that relabel them differently
therefore get the same fingerprint and different index digests.
- *Initialize.* The readout transient starts as it does in a fresh legacy process: no held
channel, no last location, and a blocked window from 0 ms. `initialDecisionContext.location`
is **not** taken as the last location. The legacy loop reads a location only at the end of a
frame, so the window first restarts on it at the first commit, as it does in the legacy loop.
- *Capture.* The `State.Capture` payload is a `flybrain-core` checkpoint envelope with magic
`FLYAGT01`. Its manifest and chunks are exactly `agent_to_chunks`, with the frame remainder
taken from the session accumulator, as `Sim::checkpoint` does. It adds one `session` member: the
accumulator, the context, the profile, the seed, the reinforcement count, the macro channels
and the decoder configuration digest. It does not carry the readout transient (section 14). It
is not FLYSIM01. Writing a FLYSIM01 export from it and from the environment's state is still
STATE-01/ENV-01 work (section 16).
- *Restore.* `State.StageRestore` builds a replacement network over the same dataset, imports
the state and refuses any mismatch between the state's clock and the accumulator.
`ActivateRestore` then installs the state and resets the readout transient, as a fresh legacy
process does. The visual drive is the restored `visualDrive` chunk. Legacy `try_restore`
instead re-projects the saved framebuffer, and the two are the same values (the parity
harness compares the full state after a restore).
- *Decision.* `macro` is the first channel in the context's `bound` order that the decode holds.
This is the channel the legacy macro layer's `asked` would start.
## 14. Restore `legacy-transient-reset` ## 14. Restore `legacy-transient-reset`
The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore
@ -377,6 +653,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
@ -400,6 +697,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)`
@ -428,6 +748,45 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat
checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01
says so. says so.
**Amendment, 2026-09-29 (STATE-02).** Six readings of this section, fixed by building it
([implementation guide](implementation.md) STATE-02):
- *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session
runtime writes through the legacy loop's own encoder and store, which now live in the crate
`flysim-store` that both link. For the same state it writes the same bytes, and it keeps the
same generations, `manifest.json`, `milestone-<N>` archives, rotation and restore order. The
owners of the fields are: the agent (the seven agent chunks, the remainder), the environment
(`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as
`ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`,
`wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`); the agent's reinforcement
count, `reinforcements`, is new (below).
- *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when
the rank is above every rank *this process* has archived. After a restart, the first climb
rewrites `milestone-<rank>` even if an older process had archived that rank. That is the
legacy behaviour, and the reset tools rely on the newest archive of a rung.
- *A restore is the legacy restore, candidate for candidate.* The candidate order is hot latest,
hot previous, durable latest, durable previous, then the archives by descending rank. The gate
is the cartridge and the compatibility decision. A refusal at any step, including a
participant's `State.StageRestore`, moves to the next candidate. If every candidate fails, the
runtime does not start. The world applies the recorded `buttons` on restore, as
`LegacyFrame::restore` does, so a file whose emulator state disagrees with its own `buttons`
restores to the same state in both runtimes, not to the file's bytes.
- *The visual drive after a `FLYSIM01` import is the framebuffer's projection* (a correction to
section 13's *Restore*, "the two are the same values"). They are the same on stream
checkpoints. On the row 65 yard survey checkpoint they are not: the first transition's rates
and spikes differed from the legacy loop's. The import therefore carries the framebuffer in
the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import,
as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores
exactly.
- *`learning.updates` is carried in `FLYSIM01`.* This corrects section 13's *Learning telemetry*
amendment, which started every import at `plasticity.updates` and so dropped the count on
every round trip. Both runtimes count reinforcement calls the same way and write the count
as the optional manifest member `reinforcements`. A file without it (every file from before
2026-09-29) starts at `plasticity.updates` once.
- *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is
rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it
(`flysim-store::journal`). It is not a checkpoint and nothing restores from it.
## 17. PROF-02b: MaleCNS bundles (later) ## 17. PROF-02b: MaleCNS bundles (later)
Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict
@ -435,3 +794,247 @@ 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`;
- `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.
**Amendment, 2026-09-30 (SHADOW-02): the shadow runs on a build box.** On the release container
the shadow cost the live fly real time: SCHED_IDLE on the page and encoder CPUs, sharing them with
the encoder and the browser and the memory bandwidth of flysim's NUMA node, it took about 27 ms a
frame, fell further behind every hour (so it could never meet the catch-up bound), and the live
realtime factor fell from 0.9998 to 0.93-0.98. It recovered to 0.999-1.0 the moment the shadow
stopped. The comparison itself is unchanged: the shadow is the same binary of the same release,
following the same trace. What moves is where it runs, and so how its inputs reach it and its
verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
- *The relay* (`fly-shadow relay`, the container's `flyshadow.service` with the drop-in
`fly-shadow-run start` writes) opens one ssh connection to the box and streams, every quarter
second: the new live saves of both stores, then the new bytes of every trace file of this run
(oldest first; a file's size read after the directory listing, so an older file is complete
when a newer one reaches the box), then the sugar journal as read before the listing. Trace files
that started before the run (`FLY_SHADOW_RUN_ID`, the start's Unix ms) and saves older than a
minute before it are not sent. A writer thread owns the link, so a stall never blocks the relay:
new saves are read as they appear and held in memory (256 MiB, about 8 minutes; a hot save lives
about ten seconds), trace bytes wait on disk, and a newer file and the journal wait until every
older file is complete on its way.
- *The ingest* (`fly-shadow ingest --root <dir>`) is the forced command of the relay's key on the
box (`authorized_keys` `restrict,command=`); the box holds no credential for the container. It
refuses a relay whose release directory or binary SHA-256 differ from its own, so the box runs the
container's release, installed from the same tarball at the same path, and the verdict's
`candidate` is exactly what `check` recomputes on the container. A new run id resets the mirror
and restarts the box's shadow (it exits with status 4; `--run-id-file`).
- *The heartbeat.* flysim's `<trace dir>/consumer` on the container is now the relay's. The relay
touches it only while it is healthy: connected; the box reported within 30 s that the shadow of
this run is alive (its own heartbeat fresh and its verdict this run's, running or passed); and
the box has acknowledged every byte that was on the container's disk a minute earlier. A dead box,
shadow or link, and a stalled sync, therefore stop the live trace exactly as a dead local shadow
does. The relay removes the file when it stops.
- *The verdict* on the container is the box's `verdict.json`, written back only when its new
`runId` member is this run's, with two changes: `lagTransitions` is the box's plus the live
trace not yet acknowledged by the box, so the catch-up bound covers the sync; and a `relay`
member (`relayedAt`, `remoteLagTransitions`, `unsyncedBytes`, `unsyncedTransitions`). A diverged
verdict brings `divergence.json` and the checkpoint files back, and the relay exits with status 3.
- *Coverage, tightened for both placements.* A trace that stops for want of a consumer
(`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage`
divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with
a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow
started, and the byte cap, end the verdict's window instead (`window.ends`): what was compared
before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). The coverage
check reads the sugar journal before it lists the trace directory (a process creates its trace
file before it writes its boot header, so a boot between the two reads could look untraced
the other way round).
- *`fly-shadow-run check`*, remote: in addition to everything above, `/srv/fly/shadow/relay.json`
must be less than a minute old and say `healthy`. `fly-shadow check` (the Rust rule) is
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
cost, which is a few file reads and one ssh stream.
**Amendment, 2026-10-01 (BUS-01): a shadow of the bus topology.** A cutover onto the bus is a
cutover into another topology, so it needs a shadow that ran it. `fly-shadow --mode` (and
`FLY_SHADOW_MODE`) names the topology as `SessionArm` does: `local` (the default, the in-process
lane; `in-process` is the same), `bus/thread`, `bus/process` (`bus`, `process`), `bus/in-process`.
`fly-shadow-run start --bus` sets `FLY_SHADOW_MODE=bus/process` in a drop-in of
`flyshadow.service` (`mode.conf`); in remote mode the relay forwards it with the rest of the live
composition's settings (it is in `FORWARDED_ENV`), so the box's shadow -- the same release, which
ships `fly-session` beside `fly-shadow` -- starts its agent and its world as child processes on its
own router's sockets. Its placement is the box's: the shadow places no thread. The verdict records
the topology (`candidate.executionMode`, and `candidate.transport`, new), and
`fly-shadow check --require-arm bus/process` (`fly-shadow-run check --bus`) refuses a verdict that
did not run it; a verdict from before this amendment, with no `transport`, counts as `local` when
it ran in process. The comparison, the window and every other rule of this section are unchanged.
The shadow follows the trace only the legacy loop writes (`FLY_TRACE_DIR`); the session runtime
ignores it. So the live fly runs the legacy runtime for the shadow's window, as it did for CUT-01:
`fly-shadow-run start` refuses while `flysim.service` runs the session runtime. The procedure for a
switch onto the bus is: `fly-runtime legacy`; `fly-shadow-run start --bus`; three hours of zero
divergence; `fly-shadow-run check --bus && fly-runtime session --bus` (the probation then judges
the bus topology). Shadowing the session runtime from its own trace is not built.

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

@ -177,7 +177,7 @@ Node 22, TypeScript, `tsx` for dev, `node --test` for tests. Deps: `@twurple/aut
One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim. One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim.
Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/fly-pokemon-client-{id,secret}`, matching the stream-key posture already documented. Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/<app>-client-{id,secret}`, matching the stream-key posture already documented.
Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope: Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope:

View file

@ -187,7 +187,8 @@ before. The Rust producer always sends all five, in both modes.
- **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in - **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in
brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound, brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound,
and while a macro is running, because a running macro owns the pad. It is **report only**: no on the naming screen, whose pad is the fly's own buttons (`docs/design/macros.md` 12.32), and
while a macro is running, because a running macro owns the pad. It is **report only**: no
producer acts on it and no consumer should, and nothing in the loop reads it back. It exists producer acts on it and no consumer should, and nothing in the loop reads it back. It exists
because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no
button waits — and on screen that is indistinguishable from a hang button waits — and on screen that is indistinguishable from a hang

View file

@ -178,8 +178,9 @@ achievements.
| Badge | +3 | each newly set badge bit | | Badge | +3 | each newly set badge bit |
That is the prototype's catalog as it shipped, kept here as history. The live one is That is the prototype's catalog as it shipped, kept here as history. The live one is
`docs/rewards-learning.md`: `pokered-unique8-v7` adds `boundary` (v5), `catch` (v6), and `talk` and `docs/rewards-learning.md`: `pokered-unique8-v8` adds `boundary` (v5), `catch` (v6), `talk` and
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23). `item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23), and `damage`
(v8, the operator's decision of 2026-09-29).
Every value is positive; there were no loss or blackout penalties. Values in a frame summed into Every value is positive; there were no loss or blackout penalties. Values in a frame summed into
`R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with `R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with

View file

@ -1,6 +1,6 @@
# Rewards and learning # Rewards and learning
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v7`. The code of record is The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v8`. The code of record is
`services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the `services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the
gates and the rules); this page says what each rule pays for and why it is allowed to. The gates and the rules); this page says what each rule pays for and why it is allowed to. The
prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules
@ -27,6 +27,7 @@ change what the fly can do.
| `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger | | `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger |
| `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger | | `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger |
| `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger | | `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger |
| `damage` | -- | +0.20 per whole Pokémon, in proportion; +0.05 knockout | 80 ms | HP the fly's own attack removed from the enemy (since v8): its share of the target's max HP, below the lowest HP that target has shown this battle; +0.05 when the hit knocks out a trainer's Pokémon; at most 0.50 a battle; a wild battle at 1, 1/2, 1/3 for its first three per `(map, species, level)`, then nothing |
Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")` Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")`
is `None` by test. The values in one frame sum into `R`, and the network reinforces once with is `None` by test. The values in one frame sum into `R`, and the network reinforces once with
@ -34,7 +35,8 @@ is `None` by test. The values in one frame sum into `R`, and the network reinfor
The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`: The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`:
`docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its `docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its
own shares the nearest one. It still reaches the page as an event with its own label. own shares the nearest one. It still reaches the page as an event with its own label. `damage` is
the one Pokémon kind with no counter at all ("Damage rewards" below says why).
Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on
`wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on `wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on
@ -177,6 +179,87 @@ half, 0.10, once, keyed under the building's id as it always was; walking out pa
person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no
building can be farmed. building can be farmed.
## Damage rewards
The operator's decision of 2026-09-29, chosen over a pad rule that would have withheld a stat move
once it had been used: pay the fly for the HP its own attack removes from the Pokémon it is
fighting. It is a catalog change, an operator decision like the catch and engagement rewards, not a
loop-review fix. It answers row 67 (`infra/docs/macros-traps.md`): the live fly lost the Pewter
Gym's Jr. Trainer 29 times running, choosing TAIL WHIP 155 times, BUBBLE 23 and TACKLE 0, and
nothing in the catalog paid for anything that happened inside a battle it did not win. The pad
offered every move; the readout's favourite was the one move that cannot win. The code is
`pokemon_red/damage.rs`.
**What counts as the fly's attack.** A drop in `wEnemyMonHP` on a sample where `hWhoseTurn`
(`$FFF3`) reads 0 and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit
(`engine/battle/core.asm`), `ApplyDamageToEnemyPokemon` subtracts the damage inside
`ExecutePlayerMove`, with `hWhoseTurn` 0, once per hit of a multi-hit move. Everything else that
lowers the enemy's HP lands with it 1: the enemy's poison and burn ticks and a Leech Seed on the
enemy (`HandlePoisonBurnLeechSeed` picks whose HP to cut *by* `hWhoseTurn`), its recoil, its
confusion self-hit, its own Explosion or Self-Destruct, and the HP it pays for a Substitute. A
Leech Seed on the fly heals the enemy, and HP going up never pays. Damage into an enemy Substitute
never touches `wEnemyMonHP`. `STRUGGLE` is the move the cartridge executes for a Pokémon with no
PP; the fly chose FIGHT, not the move, so it pays nothing (winning still pays what winning pays).
`tests/rom_damage.rs` pins the address on the cartridge from the live row 67 state: every drop of
the enemy's HP lands with `hWhoseTurn` 0 and every drop of the fly's own with 1.
**How much.** 0.20 per whole enemy Pokémon's max HP, paid in proportion on the sample the HP
drops -- BUBBLE for 10 of Diglett's 24 is 0.083, TACKLE for 4 of Sandshrew's 33 is 0.024. The hit
that knocks out a trainer's Pokémon adds 0.05 on the same event. At most **0.50 a battle**, which is
the `trainer` rule's own value: a battle's worth of damage is worth what winning it is, and the
Jr. Trainer's two Pokémon reach it exactly (2 x (0.20 + 0.05)). A wild knockout adds nothing here
because the `battle` rule already pays it, on the way out of the battle. Next to the rest of the
catalog: a wild battle's damage (0.20) is twice its knockout (0.10) and equal to a new area (0.20);
a trainer battle's (0.50) is the trainer's flag; a gym's is a sixth of the badge (3.0).
**What cannot be farmed.**
- *Heal.* Each target keeps the lowest HP it has shown this battle, and only HP below that pays. A
Potion, Recover, Rest or a drain lifts the HP; the same HP is not paid twice.
- *Switch.* A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that goes out
and comes back keeps its mark, and two Weedles of one level are two targets.
- *A stale enemy.* `InitBattleVariables` does not clear `wEnemyMon`, and a trainer battle sets
`wIsInBattle` a whole transition before `LoadEnemyMonData` runs, so the first samples of a
battle can hold the last battle's Pokémon at the HP it finished on -- in the row 67 ring, the
same trainer's Diglett in the same slot. A target is marked the first time it reads full HP,
which is how every enemy Pokémon enters a battle in this game, so the stale one neither pays nor
hides the real one's first hit.
- *The battle.* 0.50 at most, whatever the party size.
- *Wild Pokémon.* A wild battle pays at the wild-KO rule's scale, 1, 1/2, 1/3, for its first three
battles per `(map, species, level)` that paid any damage (`damageCounts`), then nothing; attacking
a wild Pokémon and running from it counts. A rollback blocks every key that has paid, the way it
blocks a paid wild KO or catch.
- *Trainers* keep no lifetime ledger. A trainer is fought again only after the fly has lost to it
(or after a rollback), and each of those battles is bounded by the cap. In the row 67 ring that
is the point: every lost battle pays for the hits that landed, and the hits that land are the
moves that win.
**Feed.** `damage` publishes on no counter (`RewardKind::from_adapter` is `None`). Every other
Pokémon kind shares the nearest counter, and the nearest here is `wildwin`, but the stage folds
that row into "N wild wins": false of a trainer battle, and false of a battle the fly goes on to
lose. A hit reaches the page as a reward event with its own label, `HIT #<species> FOR <n> HP`
(`... KO` for a knockout; the species is the cartridge's internal index, as `CAUGHT #<species>` is),
and the event log, `/status` and the checkpoint carry it; it is only left out of
`game.rewardCounts` and the ticker's per-kind copy, the way the platformer's `started` and `clear`
are. No feed kind was added. The stage rolls the hits up itself (`apps/stage/src/lib/ticker.ts`,
`hitCopy` in the game config): a reward with no `rewardKind` and that label folds into one
"damage dealt x<n>" row with the summed value, ` KO` once a hit in it felled a Pokémon, joined by
each hit within 45 s of the last; a later battle starts a new row (`apps/stage/mockups/row68-ticker-*.png`).
**Learning.** A payout reinforces the recent spike history with `m = tanh(R)` over a 5 s
eligibility trace ([plasticity](plasticity.md)). Measured on the cartridge from the row 67 state
(`tests/rom_damage.rs`), the HP drops 176 frames (2.9 s) after the `MOVE n` press when the fly
moves first and about 420 frames (7 s) when the Jr. Trainer's Pokémon does -- its attack and text
come first. So the choice's trace is at a half to a quarter when its hit is paid, and the previous
turn's choice, one turn (about 7.5 s) earlier still, at a tenth to a twentieth. That ratio is the
whole mechanism: nothing tells the readout which move to press. A hit is small (0.02 to 0.10), so what it can move per battle is small too; whether
the brain learns the attacking move inside a few brain hours is a measurement, not a promise, and
the first one is `infra/docs/macros-traps.md`, row 68.
**Migration.** `v7` -> `v8` adds `damageCounts` and, inside a battle in flight, `battle.damage`;
both are optional and a `v7` state restores with no wild key paid and its battle's Pokémon marked
where they stand. See `docs/design/flysim.md`, "Restoring across an adapter version".
## Gates ## Gates
Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other
@ -276,6 +359,15 @@ body picks the macro; the descending neurons press the buttons.**
## Honesty ## Honesty
The catalog now includes damage (v8). It is the first rule that pays for something inside a battle
the fly may still lose, and the closest the catalog has come to grading a *choice*: the moves are
all on the pad, and the one that lands pays. It is still a reward read out of WRAM after the frame,
not a press: nothing in the adapter picks a move, removes one from the pad or tells the readout
which is good, and a move pays only if the cartridge says it took HP off the enemy. The pad rule
the operator declined (withholding a stat move once used) would have been the doctrine change; this
one leaves the pad exactly as the scene deals it. It is also bounded on purpose: at most what winning
pays, per battle, and a wild Pokémon only three times.
The catalog now includes conversations and items (v7). Paying for a conversation is the closest The catalog now includes conversations and items (v7). Paying for a conversation is the closest
the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a
press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is

176
docs/scorecard.md Normal file
View file

@ -0,0 +1,176 @@
# The behavioural scorecard
A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what
they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a
release plays *better or worse* than the one before it across the places the fly actually is. The
scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real
connectome with the macro layer, reduced to one JSON per release and compared release against
release by a test over the paired runs, never by a single run.
It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The
ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly.
```sh
export FLY_ROM=/path/to/the-cartridge # read, never copied
cargo build --release -p fly-scorecard # from services/flysim
fly-scorecard list # the set, resolved, each checkpoint's rung
fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes
fly-scorecard summary card.json # one screen of markdown
fly-scorecard compare old.json new.json # exit 1 when a metric regressed
fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE)
```
`--runtime session` (the default) runs the session composition the release cut over to
(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame
(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a
card from one runtime is comparable with a card from the other. From the same checkpoint and seed
the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard
run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer.
## The set
`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds
its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the
newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked).
`list` prints the rung each one stands on, from its reward ledger. The set has two or three
states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join
the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from
the environment is named on stderr and, with `--strict`, an error.
## Seeds
A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed
therefore chooses how many frames the brain's readout is ignored before the measurement starts
(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise
generator still advances, the game sees no button, and from the first measured frame the readout
is the brain's own: the run sits on a different point of its own trajectory. The idle frames are
not measured. The same seed twice is the same run.
## What a run reports
One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by
`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames.
| group | what |
| --- | --- |
| rungs | start, end, gained, the brain minute of each climb; reported per brain hour |
| places | the adapter's exploration count, start and end |
| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch |
| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) |
| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) |
| ratchet | rollbacks, split by game over and stall |
| macros | starts, done, blocked, timeout, refused, by macro |
| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got |
| heals | GO HEAL and the nurse's HEAL |
| whiteouts | the whole party fainted (a rising edge) |
| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other |
| rewards, scenes | counts and totals by adapter kind; frames by scene |
The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe
memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about
time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds,
first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or
the whole run when it is shorter; and the first probe compares the exploration count with the
run's starting count, which the live check lacks after a boot.
## Compare
`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`)
has a direction (more is better, less is better, or info), an absolute tolerance and a relative
one. For each metric the pairs give one difference, signed so that positive means B is worse. B
**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip
permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over
the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most
alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of
releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the
same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent,
and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a
fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The
comparison also names its caveats (different lengths, different runtimes, fewer than eight
pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint.
**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one
checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs
(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled
compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its
own, without statistics: it **fails**, named as `trap@<checkpoint>`, when B is trapped on at least
two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm
(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is
trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled,
zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with
three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center
on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap,
so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243.
Identical suites never fail.
The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per
hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and
lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's
flagged windows are reported, never judged: healing more can follow losing more, and a fly that
fights for most of a run presses NEXT through battle text more than ten times in two minutes,
which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so
the number has no room to move).
## Cost and size
A run's brain minute costs about 75 CPU seconds however it is split, and the result does not
depend on the thread count (the same seed gives an identical report at one thread and at four).
The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet
ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one
job of four threads ran five times slower per brain minute than one-thread jobs did. So the
default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by
three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten
quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let
rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001.
`--resume` keeps the runs an interrupted suite had finished (`<out>.runs.jsonl`).
## What it does not do
- It does not rebuild session ledgers a restore starts empty (the trap hunt's
`FLY_TRAP_SEED_*`); a trap that needs them is that tool's.
- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a
per-run prediction; a release that is faster by a rung every few hours shows only across the
suite.
- It judges play against the previous release, not against a notion of good. A regression is
"worse than last time"; the absolute numbers say how good last time was.
## Releases and nightly
`tools/scorecard/overlay.sh <ref> <tree>` puts the tool on the tree of an older release (the crate,
the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that
predates it can be scored and its numbers are its own. The operator's nightly runner builds the
latest release tag on a build box, runs the suite, writes the card and a one-screen summary and
compares with the previous release's card.
## The v0.7.5 baseline
`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8,
compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on
the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box.
| headline | v0.7.5 |
| --- | ---: |
| rungs per brain hour | 1.50 (9 of 36 runs climbed) |
| empty-pad time | 6.96% of frames |
| watchdog probes suspected | 2.8% |
| ladder-worthy traps | 1 (one run, `r09-forest-catch`) |
| blocked macro finishes | 0.5% |
| buy ball / throw / catch | 10 / 10 / 8 |
| heals / whiteouts | 9 / 46 |
| battles won / lost | 33 / 45 |
| ratchet rollbacks | 1 |
What the card shows about v0.7.5, worth reading before the next release is compared with it:
- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a
battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won;
46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on
`r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle.
- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three
seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT
alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The
watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery
step would act on it.
- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15.

View file

@ -916,3 +916,137 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and
redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63, redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63,
64, 65 APPROVE-WITH-NOTES. 64, 65 APPROVE-WITH-NOTES.
- 2026-09-29 (v0.6.6, loop review + port foundation): the fly shops, throws and names what it
catches. Row 66: a counter walked away from is not walked back to for the ledger window (the
GO SHOP/GO OUT re-entry ring: 31 to 0), BUY BALL is one walk-talk-buy button like HEAL (the
operator's call; offered in a mart that sells balls, with no ball and 200 in the wallet), and a
closed battle bag is not the pad (post-catch presses typed the nickname). Row 67: the live fly
lost the Pewter Gym's Jr. Trainer 29 times in a row choosing TAIL WHIP (the pad offered every
move); a report-only `unwon-battles` watchdog reason lets the recovery ladder act 45 minutes
sooner, and the no-PP ROM test is fixed (Struggle is the cartridge's answer). Row 69 (the
operator's calls): in a wild battle at the catch formula's low-HP threshold with a ball in the
bag, THROW BALL is the only attack-side button; the naming screen takes the fly's own buttons
("AAAAAAAAAA" before), bounded by CONFIRM after a full name or 60 brain seconds. Port
foundation merged, dormant on the stream: AGENT-01, MEM-01, ENV-01, STATE-02 (the checkpoint
store is now the shared `flysim-store` crate; FLYSIM01 gains an optional `reinforcements`
field, downgrade-safe both ways). A PII guard scans lint, tag-release and pushes. Reviews: all
APPROVE-WITH-NOTES.
- 2026-09-29 (unreleased, the operator's decision, row 68): the fly is paid for the HP its own
attack removes in battle, the catalog's answer to row 67 (the Pewter Gym's Jr. Trainer lost on
repeat with TAIL WHIP six turns in seven). New kind `damage`: 0.20 per whole enemy Pokémon, in
proportion, +0.05 when it knocks out a trainer's Pokémon, at most 0.50 a battle; a wild battle at
1, 1/2, 1/3 per map/species/level. Only a drop on the fly's own turn (`hWhoseTurn` 0) by a move it
chose (not Struggle); a heal is never paid twice; no feed counter (a hit is not a "wild win").
Adapter `pokered-unique8-v8`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 migrates the
run (v6 still migrates when named). Survey, 3 starts x 120 brain minutes from the row 67
checkpoint: v8 beat the trainer in 2 of 3 (one run also won the Boulder Badge), v7 in 0 of 3, but
the move choice did not shift more under v8 than v7 (BUBBLE ~15% -> ~20% in both): no learned
preference is shown inside two hours (`infra/docs/macros-traps.md` row 68).
- 2026-09-30 (v0.6.7, the operator's call, reward catalog): the fly is paid for damage its own
attacks deal. Row 67 found the live fly losing the Pewter Gym's Jr. Trainer on repeat with TAIL
WHIP while BUBBLE was on the pad; the operator chose a reward over a pad rule. HP removed on the
fly's own turn (hWhoseTurn 0, not Struggle; poison/burn/Leech Seed/recoil/enemy moves never pay;
healed HP not re-paid) pays 0.20 per whole enemy mon, +0.05 for knocking out a trainer's mon,
capped at 0.50 per battle (a trainer beaten); wild battles diminish 1, 1/2, 1/3 per
map/species/level. Adapter pokered-unique8-v8, migrating v7 (compat differs in the adapter
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
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).
- 2026-09-30 (v0.7.1, loop review hotfix): row 70. The fly's first live catch (a Zubat, Mt. Moon)
gave it a second party member, and in the next trainer battle the cartridge's SHIFT-style offer
"Will ZUBAT change POKéMON?" opened the battle party list with the same menu id as a forced
switch after a faint. Read as forced, the pad was SWITCH (no healthy target) and NEXT ("ZUBAT is
already out!", the list again) for 58 brain minutes; the recovery ladder's rung-11 reset erased
the catch and, restores being deterministic, replayed the path back into the trap. A forced
switch now also requires the active battler at 0 HP; the offer is the fly's own turn with SWITCH
and BACK. ROM test from the live checkpoint: NEXT on all 6,000 frames before, BACK and the battle
continues after; a real post-faint switch unchanged. The ladder change (protect recent catches
from resets) is held back for a review finding. Review: APPROVE.
- 2026-10-01 (v0.7.2, loop review): row 70's recovery ladder. A milestone reset within 2 hours of a
new species becomes a restart (operator decision: a catch is worth up to 2 h of a trap, not more);
a reset's deterministic replay re-earns rewards the restored archive already had, so progress and
catch protection now count only reward names the ladder has not seen; a held reset does not climb;
the last-archive marker expires. Escape from a trap only the lower rung clears: 2.08 h (as v0.7.0),
3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at
most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK,
r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES.
- 2026-10-01 (v0.7.3, port slice SHADOW-02): the shadow moves off the release container. On the
container a light relay forwards the live trace, new saves and the sugar journal over one outbound
ssh link whose key can only run the receiver; a build box mirrors them and runs the unchanged
shadow on its own cores; the verdict comes back. Release binding by binary hashes; the relay's
heartbeat is fresh only while the link, the box's shadow and the sync are; any trace stop (no
consumer, byte cap, outage) ends the verdict window, so a pass needs 3 h of compared brain time
after the last loss. The guard and `check` stay on the container. The on-box shadow (v0.7.0)
slowed the live fly; the relay costs about 0.5% of a core. Reviews: BLOCK, BLOCK,
APPROVE-WITH-NOTES, APPROVE.
- 2026-10-01 (v0.7.4, loop review hotfix): row 71. On Route 24 (rung 15) the fly met a wild
Oddish at low HP with two Poké Balls in a bag that had grown to five items (TMs, HELIX FOSSIL,
NUGGET), so the ball was the fifth entry and the list scrolled. The macro state read the bag
cursor as the window row only, so THROW BALL could never reach the ball and was blocked every
time; row 69's low-HP rule left it the only card. A restart restores the open bag, so the ladder
could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge
computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before,
Oddish caught after. Review: APPROVE.
- 2026-10-01 (v0.7.5, port slice PERF-02): the first cutover (v0.7.3, after a 3 h shadow with zero
divergence) failed its speed probation at a median 0.959x real time and fell back to legacy on
its own. Cause: with exactly as many CPUs as sweep threads, the session's other threads woke each
frame and the scheduler often stacked two sweep threads on one CPU. flysim-session now pins each
sweep worker to its own CPU and its other threads to the remaining one (16.2 to 13.0 ms a frame on
a build box of the release CPU; legacy 10.5), and the sim gets its own slice: every other unit,
user session and `pct exec` shell is confined off its CPUs (a hog there collapsed a pinned
session). Results, traces and the compatibility string are unchanged. Reviews: two rounds,
APPROVE-WITH-NOTES; notes addressed.
- 2026-10-01 20:07Z (CUT-01, milestone M4): the stream runs on the session runtime. v0.7.5's remote
shadow compared 3 h of live brain time (645,560 transitions, 2,161 identical checkpoints) with
zero divergence; `check` allowed the switch; the 30-minute speed probation passed at a median
1.000x real time with no lag growth. Legacy stays one command away (`fly-runtime legacy`);
RETIRE-01 after a clean week.
- 2026-10-02 (v0.7.6, flybus groundwork, nothing switched): the control API as flybus RPC with
per-agent grants (CTRL-01, `FLY_CONTROL_VIA`), the video feed over the bus in production form
(EDGE-02, `fly-feed bus|direct`), the session's agent and world as processes on the router's
Unix sockets (BUS-01, `fly-runtime session --bus`), an optional aux cpu for bus threads off the
sim's cores, and a per-frame work metric for both runtimes. All default off; the live stream
is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural
scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the
parity test's idle-header race.
- 2026-10-02 07:13Z: the stream's video feed runs over flybus (`fly-feed bus`, one aux cpu for the
bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about
14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime
factor unchanged at about 1.0. Rollback: `fly-feed direct`.
- 2026-10-02 07:41Z: the control API runs over flybus too (`FLY_CONTROL_VIA=bus`): `:7401` is
served by the control edge calling flysim's RPC services under per-client grants. First 15
minutes: bus connected, calls flowing, no failures, no restarts, realtime factor about 1.0.
Both switches are in the host env, so a deploy keeps them. The session's agent and world stay
on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the
release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there.
- 2026-10-02 (v0.7.7, loop review): row 73. The scout found rung 16 unreachable: its place was
"on Route 25", so inside Bill's house the walks just left again, and Bill's PC is a hidden
object no macro could press. Rung 16 is now Bill's errand inside the house (people first, then
things; exits off the pad while the errand waits), and hidden objects are read from the
cartridge's own table and become a target only as that errand's next step. Cerulean's north half
joins the map graph through the trashed house. Trap hunts: rung 16 in 0 of 6 seeds before, 6 of 6
after; Route 5 from the ticket 0 of 6 before, 5 of 6 after. Review: APPROVE-WITH-NOTES; notes
fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a
wall-clock rate.
- 2026-10-02 (v0.7.8, groundwork for the GPU and the bus): the GPU brain steps a whole frame per
call with its state resident on the card (about 230 KB a frame crosses PCIe instead of 24 MB),
bit-exact against the CPU through rollback, restore and checkpoints; a dead GPU makes the process
CPU-only and the replacement restores the last checkpoint on the CPU (cuda feature, off; operator
decision: the live brain moves to the release host's Quadro after a 3 h shadow). Cheaper flybus
round trips (seal on reply, recycled zero-filled staging writers, frames encoded once); the
session's own transport stays on the in-process lane. No behaviour change on the live stream.

View file

@ -18,7 +18,10 @@ need pct
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \ PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \
ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \ ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo" fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo \
openssh-client"
# openssh-client (SHADOW-02): the remote shadow's relay dials OUT to a build box. The client only;
# the container still runs no sshd (below).
# Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage # Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl` # needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three # (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three

View file

@ -123,6 +123,22 @@ need pct
# /opt/fly/current, rather than half way through the deploy or at flysim's boot. # /opt/fly/current, rather than half way through the deploy or at flysim's boot.
FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \ FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
|| die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'" || die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'"
# Who serves the control API (docs/design/flybus.md, "Control over the bus"): the same.
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
# container is not in the env file unless the operator put it there, and this deploy writes the env
# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at
# their next start, so the feed stays served either way) but the mode would change at the next
# restart of flysim, which is not what anyone meant. Said once, loudly, here.
FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \
| tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then
log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \
"this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \
"If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both."
fi
# CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a # CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a
# `vgl` on a container that never had VirtualGL installed would only show up as # `vgl` on a container that never had VirtualGL installed would only show up as
@ -181,13 +197,26 @@ NEED_RELOAD=0
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}" RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}" ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the
# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing.
SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}"
case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac
SESSION_AUX_LIST=""
DEPLOY_CPUS="" DEPLOY_CPUS=""
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to
# flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
PARTITION_ACTIVE=0
if [ -n "${CPUSET:-}" ]; then if [ -n "${CPUSET:-}" ]; then
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \ deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)" "/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \ read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
PARTITION_ACTIVE=1
if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then
_aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1
read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split"
fi
log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim" log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim"
else else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \ log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -322,8 +351,9 @@ if [ -n "$RELEASE_TARBALL" ]; then
# #
# FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps # FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps
# the run. It names adapter version strings whose checkpoints the new build # the run. It names adapter version strings whose checkpoints the new build
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 for the deploy # may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 for the deploy
# that adds the engagement rewards (v7; v5 -> v6 was the catch reward's). # that adds the damage reward (v8; v6 -> v7 was the engagement rewards', v5 -> v6
# the catch reward's).
# It only applies when the adapter segment is the # It only applies when the adapter segment is the
# ONLY difference between the two strings and the new build's adapter says it # ONLY difference between the two strings and the new build's adapter says it
# can read that one; a dataset, kernel, emulator or state-format change is # can read that one; a dataset, kernel, emulator or state-format change is
@ -377,7 +407,7 @@ The difference is usually an adapter/ladder or dataset version bump. Three ways
* deploy a build whose string matches (check out the commit the running release was built from), or * deploy a build whose string matches (check out the commit the running release was built from), or
* if the ADAPTER VERSION is the only segment that differs and the new build documents a * if the ADAPTER VERSION is the only segment that differs and the new build documents a
migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6). The run is kept; flysim applies the same string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7). The run is kept; flysim applies the same
rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or
* accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which * accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which
archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and
@ -386,6 +416,53 @@ 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."
# BUS-01: on the bus transport flysim-session starts its participants from fly-session.
if ct_exec "$CTID" -- grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/fly-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime on the bus (fly-runtime session --bus) and this release has no fly-session worker. Run \`fly-runtime session --local\` in the container first. The 'current' symlink has NOT been moved."
fi
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
# The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's
# ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed.
# Refused when the env file asks for bus, and when the container is in bus mode now (an edge
# that is running keeps running, but the first time it restarts there is nothing to start; and
# the way back is `fly-feed direct`, which needs no binary of this release).
if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then
ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \
|| die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved."
log "05-deploy: the feed is on the bus; this release ships fly-edge"
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
@ -396,7 +473,7 @@ fi
# 2. systemd units # 2. systemd units
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging systemd units" log "05-deploy: converging systemd units"
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.slice "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
[ -f "$f" ] || continue [ -f "$f" ] || continue
name="$(basename "$f")" name="$(basename "$f")"
changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)" changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)"
@ -512,6 +589,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# so FLY_ENCODER-style flipping between backends across restarts keeps the # so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move. # checkpoint: the compatibility string this script gates on does not move.
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}"
# Where the session worker writes fly_brain_backend (which hardware runs the
# LIF tick, and the GPU fallback count): the same textfile directory as
# fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA").
echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom"
# On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the
# kill switch: POST /chat answers 403 and the feed header omits `chat`, so # kill switch: POST /chat answers 403 and the feed header omits `chat`, so
# the CHAT panel blanks without touching flybridge or the page. flysim reads # the CHAT panel blanks without touching flybridge or the page. flysim reads
@ -527,6 +608,21 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# refuses anything but "raw" for a game with no macros, reads the retired # refuses anything but "raw" for a game with no macros, reads the retired
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised # "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
# value outright. # value outright.
# PERF-02: flysim-session pins its sweep workers one per cpu of the cpuset it finds. That is only
# safe when the cpuset is the sim's alone: with the partition in force (section 3b) it is, and
# bin/fly-cpu-confine keeps every other process off it. Without it (no CPUSET, or a conf that does
# not match) the unit sees the container's whole cpuset, where a pinned worker would sit on a cpu
# anything can hog (measured 0.14x real time), so pinning is turned off: the threads float. The
# runtime reads the exact value 0 as off.
if [ "$PARTITION_ACTIVE" -eq 1 ]; then
echo "FLY_SESSION_PIN=1"
else
echo "FLY_SESSION_PIN=0"
fi
# EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set.
if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then
echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}"
fi
echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}" echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the # Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as # bus"). "direct" is the default and is flysim binding :7400 itself, as
@ -535,9 +631,17 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# never enables: see that unit's header for the switch. Written # never enables: see that unit's header for the switch. Written
# unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs. # unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs.
# Watchdog check 2 reads this line to know whose /metrics carries the # Watchdog check 2 reads this line to know whose /metrics carries the
# feed counters (flysim's :9101, or flyedge's loopback :9102). # feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
# Validated and lowercased above (feed_via_normalize). # Validated and lowercased above (feed_via_normalize).
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}" echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
# the bus"). "direct" is the default: flysim binds it. "bus" makes flysim
# register the control services on its embedded router and leave :7401 to
# flycontrol-edge.service, which this script never enables (runbook,
# "Control over the bus"). Written unconditionally; the watchdog reads it
# to know whose /healthz is flysim's own (check 1) and whether to watch
# the edge (check 1b). Validated and lowercased above.
echo "FLY_CONTROL_VIA=${FLY_CONTROL_VIA_EFFECTIVE}"
# How long a macro leaves a target alone after a walk to it aborted # How long a macro leaves a target alone after a walk to it aborted
# (macros.md section 12.1, the Viridian stall). Only written when it is set, # (macros.md section 12.1, the Viridian stall). Only written when it is set,
# because the default lives in the crate and a box that has not tuned it # because the default lives in the crate and a box that has not tuned it
@ -671,35 +775,52 @@ if [ -n "${CPUSET:-}" ]; then
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \ "Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
"leaves cpuset.cpus.effective empty and the unit unstartable." "leaves cpuset.cpus.effective empty and the unit unstartable."
else else
read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")"
log "05-deploy: cpuset partition — flysim=$sim_cpus, xvfb/flystage/flystage-web/pulse/mediamtx/flyedge=$page_cpus, flycast=$encoder_cpus" log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
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; likewise
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do # flycontrol-edge (CTRL-01).
case "$u" in # flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
flysim) cpus="$sim_cpus" ;; # (`fly-runtime session` runs it AS flysim.service, which already has them.)
flycast) cpus="$encoder_cpus" ;; # flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
*) cpus="$page_cpus" ;; # flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
esac # leave idle and never a cycle of the live fly's.
{ # flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit." # its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4." # using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
echo "[Service]" # everything else. See that script's header for the cgroup semantics and the ordering rule.
echo "AllowedCPUs=${cpus}" # A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
} > "$tmp_dropin" mapfile -t plan_lines <<< "$plan"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.service.d" for plan_line in "${plan_lines[@]}"; do
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.service.d/cpuset.conf" 0644 root:root)" read -r u cpus <<< "$plan_line"
case "$u" in *=) continue ;; esac
cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then if [ "$changed" = changed ]; then
NEED_RELOAD=1 NEED_RELOAD=1
log "05-deploy: ${u}.service.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload" log "05-deploy: ${u}.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
fi fi
done done
{
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
echo "$plan" | awk '$1 ~ /=$/ {print $1 $2}'
} > "$tmp_dropin"
changed="$(converge_file "$CTID" "$tmp_dropin" /etc/fly/cpuset.env 0644 root:root)"
[ "$changed" = changed ] && log "05-deploy: /etc/fly/cpuset.env changed — fly-cpu-confine applies it when flysim next (re)starts, by which time it runs in flysim.slice"
rm -f "$tmp_dropin" rm -f "$tmp_dropin"
fi fi
else else
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)" log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
fi fi
# No partition in force: nothing may stay confined by an earlier one, and the session runtime must
# not pin (fly.env above says FLY_SESSION_PIN=0). A confinement already applied lasts until the next
# boot or `fly-cpu-confine release`.
if [ "$PARTITION_ACTIVE" -ne 1 ]; then
ct_exec "$CTID" -- rm -f /etc/fly/cpuset.env
log "05-deploy: no cpuset partition: /etc/fly/cpuset.env removed, FLY_SESSION_PIN=0 in fly.env (sweep workers float); run \`fly-cpu-confine release\` if an earlier partition is still applied"
fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not # 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not
@ -707,10 +828,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-cpu-confine fly-feed 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.

View file

@ -26,7 +26,7 @@
# docs/design/stage-bridge.md section B1 has flybridge read # docs/design/stage-bridge.md section B1 has flybridge read
# TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate # TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate
# LoadCredentialEncrypted= values sourced from # LoadCredentialEncrypted= values sourced from
# twitch/fly-pokemon-client-{id,secret}. This script follows infra.md (the # twitch/<app>-client-{id,secret}. This script follows infra.md (the
# doc this task implements) and writes ONE twitch-app.cred containing both # doc this task implements) and writes ONE twitch-app.cred containing both
# values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own # values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own
# implementation (out of scope here, not yet written) will need to parse # implementation (out of scope here, not yet written) will need to parse
@ -118,9 +118,14 @@ fi
# docs/stream-mvp-plan.md's rollout order) — install only if both pass # docs/stream-mvp-plan.md's rollout order) — install only if both pass
# entries already exist, so running this before the Twitch app is # entries already exist, so running this before the Twitch app is
# registered is a clean no-op rather than a hard failure. # registered is a clean no-op rather than a hard failure.
BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-twitch/helix-client-id}" # The two entry NAMES come from the env file (BRIDGE_ID_KEY, BRIDGE_SECRET_KEY): a
BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-twitch/helix-client-secret}" # `pass` entry name identifies the operator's store, so it is not spelled here.
if command -v pass >/dev/null 2>&1 \ BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-}"
BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-}"
if [ -z "$BRIDGE_ID_KEY" ] || [ -z "$BRIDGE_SECRET_KEY" ]; then
log "06-secrets: WARNING: BRIDGE_ID_KEY / BRIDGE_SECRET_KEY are not set in the env file, skipping twitch-app." \
"Set both to the pass entry names of the Twitch app id and secret (infra/env/example.env) to install it."
elif command -v pass >/dev/null 2>&1 \
&& pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \ && pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \
&& pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then && pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then
log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}" log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}"

View file

@ -267,6 +267,12 @@ refuses to write the drop-ins until the conf actually carries
`CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves `CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves
`cpuset.cpus.effective` empty and the unit unstartable. `cpuset.cpus.effective` empty and the unit unstartable.
The sim's CPUs are also kept exclusive to it (PERF-02 review N1, `infra/docs/runbook.md` "The sim's
CPUs are exclusive to the sim"): the sim units run in `flysim.slice`, and `bin/fly-cpu-confine`
confines `system.slice`, `user.slice`, `init.scope` and `/.lxc` (`pct exec`) to the other CPUs when the sim starts.
Without a partition (`CPUSET` unset) none of this applies and the deploy turns the session
runtime's worker pinning off (`FLY_SESSION_PIN=0`).
`CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local `CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local
socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md` socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md`
section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three

188
infra/bin/fly-cpu-confine Executable file
View file

@ -0,0 +1,188 @@
#!/usr/bin/env bash
# infra/bin/fly-cpu-confine — keep every process that is not the sim off the sim's CPUs.
#
# Usage (INSIDE the container, as root):
# fly-cpu-confine apply confine system.slice, user.slice, init.scope and /.lxc (where `pct exec`
# lands) to the non-sim CPUs
# fly-cpu-confine release undo `apply` (all of them go back to the container's whole cpuset)
# fly-cpu-confine status what each of them is confined to, and where the sim runs
# fly-cpu-confine check list every process that is not in flysim.slice but may run on a
# sim CPU (exit 1 if there is one); this command's own process and its
# parents (the shell it was started from) are noted, not failed
#
# Why. The session runtime pins its sweep workers one per CPU (PERF-02). A pinned worker cannot
# leave its CPU, so any sustained CPU-bound process that may run there stalls every barrier:
# measured 0.14x real time with a plain busy loop (0.68x at nice 19; SCHED_IDLE is harmless).
# Priorities do not fix that; keeping the sim's CPUs to the sim does.
#
# How (cgroup v2). flysim.service and flysim-session.service run in flysim.slice, which has
# AllowedCPUs= the sim's CPUs (a drop-in written by 05-deploy.sh). Its siblings under the root
# cgroup are system.slice (every other service, cron, apt, sshd), user.slice (every login
# session) and init.scope (PID 1 and what it forks). `apply` sets AllowedCPUs= the NON-sim CPUs
# on those three, so nothing that systemd places anywhere else can reach a sim CPU. A child's
# cpuset is bounded by its parent's, so the sim must never sit under a slice that excludes its
# CPUs: that is why it has a slice of its own and is not left in system.slice.
#
# The CPU lists come from ${CPUSET_ENV} (written by 05-deploy.sh, from the same cpuset_partition
# call as the AllowedCPUs= drop-ins). No file means no partition: nothing is confined.
#
# `apply` is runtime-only (systemctl set-property --runtime) and is run by flysim.service and
# flysim-session.service's ExecStartPre, so it is re-applied after every boot and every restart
# and can never run while the sim still sits in system.slice: shrinking system.slice under a
# sim that has not been restarted into flysim.slice would silently make it float over the page
# CPUs. `apply` refuses (exit 3, nothing changed) if a sim unit is outside flysim.slice.
#
# `pct exec` / `pct enter` (lxc-attach) put their processes in the cgroup `/.lxc` (or `/.lxc-N`),
# a sibling of system.slice that systemd does not manage. It is written directly
# (cpuset.cpus), only if it already exists (a cgroup lxc owns is never created here), and a
# failure is a warning, never an error: it must not stop the sim from starting. If it cannot be
# written, `check` lists what is running there; run long operator jobs with
# `systemd-run --scope --slice=system.slice -- <cmd>` (or `... -- bash`).
set -euo pipefail
: "${CPUSET_ENV:=/etc/fly/cpuset.env}"
: "${SYSTEMCTL:=systemctl}"
: "${PROC_ROOT:=/proc}"
: "${CGROUP_ROOT:=/sys/fs/cgroup}"
: "${SIM_SLICE:=flysim.slice}"
: "${SIM_UNITS:=flysim.service flysim-session.service}"
CONFINED_UNITS="system.slice user.slice init.scope"
# existing lxc attach cgroups (/.lxc, /.lxc-N) that have a cpuset
lxc_cgroups() {
local d
for d in "$CGROUP_ROOT"/.lxc "$CGROUP_ROOT"/.lxc-*; do
[ -d "$d" ] && [ -e "$d/cpuset.cpus" ] && echo "$d"
done
return 0
}
# set_lxc CPUS — write CPUS into every lxc attach cgroup; warn, never fail.
set_lxc() {
local d
for d in $(lxc_cgroups); do
if ! echo "$1" > "$d/cpuset.cpus" 2>/dev/null; then
log "WARNING: cannot write ${d}/cpuset.cpus; processes started with pct exec stay unconfined (run long jobs with systemd-run --scope --slice=system.slice)"
fi
done
return 0
}
log() { echo "fly-cpu-confine: $*" >&2; }
# read_env — set SIM_CPUS and OTHER_CPUS from ${CPUSET_ENV}, or return 1 when there is no partition.
# Parsed as KEY=VALUE lines, never sourced.
read_env() {
SIM_CPUS="" OTHER_CPUS=""
[ -r "$CPUSET_ENV" ] || return 1
local k v
while IFS='=' read -r k v; do
case "$k" in
FLY_SIM_CPUS) SIM_CPUS="$v" ;;
FLY_OTHER_CPUS) OTHER_CPUS="$v" ;;
esac
done < "$CPUSET_ENV"
[ -n "$SIM_CPUS" ] && [ -n "$OTHER_CPUS" ]
}
# expand LIST — one cpu number per line for a list such as 1,3,5-7.
expand() {
echo "$1" | tr ',' '\n' | awk -F- 'NF==1 && $1 != "" {print $1} NF==2 {for (i=$1;i<=$2;i++) print i}'
}
sim_outside_slice() {
local u cg
for u in $SIM_UNITS; do
cg="$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
[ -n "$cg" ] || continue
case "$cg" in
"/${SIM_SLICE}/"*) ;;
*) echo "$u ($cg)"; return 0 ;;
esac
done
return 1
}
cmd="${1:-}"
case "$cmd" in
apply)
if ! read_env; then
log "no partition configured (${CPUSET_ENV} missing or empty): nothing confined"
exit 0
fi
if out="$(sim_outside_slice)"; then
log "REFUSING to confine: $out runs outside ${SIM_SLICE}; restart it first (it would float over the page cpus otherwise)"
exit 3
fi
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${OTHER_CPUS}"
done
set_lxc "$OTHER_CPUS"
log "system.slice, user.slice, init.scope and /.lxc confined to ${OTHER_CPUS}; ${SIM_SLICE} keeps ${SIM_CPUS}"
;;
release)
# Not `AllowedCPUs=` (empty): systemd leaves the cgroup's cpuset.cpus at its last value while
# the cpuset controller stays enabled for some other unit (here flysim.slice), so the slices
# would stay confined. Set the container's whole cpuset explicitly.
all_cpus="$(cat "${CGROUP_ROOT}/cpuset.cpus.effective" 2>/dev/null || true)"
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${all_cpus}"
done
set_lxc "$all_cpus"
log "system.slice, user.slice, init.scope and /.lxc released to the container's whole cpuset (${all_cpus:-unknown})"
;;
status)
for u in $CONFINED_UNITS $SIM_SLICE; do
echo "$u AllowedCPUs=$("$SYSTEMCTL" show -p AllowedCPUs --value "$u" 2>/dev/null || true)"
done
for d in $(lxc_cgroups); do
echo "${d#"$CGROUP_ROOT"} cpuset.cpus=$(cat "$d/cpuset.cpus" 2>/dev/null || true)"
done
for u in $SIM_UNITS; do
echo "$u ControlGroup=$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
done
;;
check)
if ! read_env; then
log "no partition configured: nothing to check"
exit 0
fi
sim="$(expand "$SIM_CPUS" | sort -n | tr '\n' ' ')"
bad=0
# this process and its parents (the pct exec shell chain) are not a CPU hog
self=" "
p="${SELF_PID:-$$}"
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#self}" -lt 400 ]; do
self="$self$p "
p="$(sed -n 's/^PPid:[[:space:]]*//p' "$PROC_ROOT/$p/status" 2>/dev/null || true)"
done
for d in "$PROC_ROOT"/[0-9]*; do
pid="${d##*/}"
[ -r "$d/status" ] || continue
cg="$(sed -n 's/^0:://p' "$d/cgroup" 2>/dev/null || true)"
case "$cg" in "/${SIM_SLICE}/"* | "/${SIM_SLICE}") continue ;; esac
# kernel threads have no cgroup of their own in this sense and are not a CPU hog
if [ -z "$(readlink "$d/exe" 2>/dev/null || true)" ]; then continue; fi
allowed="$(sed -n 's/^Cpus_allowed_list:[[:space:]]*//p' "$d/status")"
[ -n "$allowed" ] || continue
hit=""
for c in $(expand "$allowed"); do
for s in $sim; do [ "$c" = "$s" ] && hit="$hit$c,"; done
done
if [ -n "$hit" ]; then
case "$self" in *" $pid "*)
log "note: ${pid} ($(cat "$d/comm" 2>/dev/null)) is this check's own process chain in ${cg:-?} and may run on sim cpu ${hit%,}; not counted"
continue ;;
esac
echo "process $pid ($(cat "$d/comm" 2>/dev/null)) in ${cg:-?} may run on sim cpu ${hit%,}"
bad=1
fi
done
[ "$bad" -eq 0 ] && log "ok: only ${SIM_SLICE} can run on ${SIM_CPUS}"
exit "$bad"
;;
*)
sed -n '2,11p' "$0" >&2
exit 2
;;
esac

332
infra/bin/fly-feed Executable file
View file

@ -0,0 +1,332 @@
#!/usr/bin/env bash
# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself
# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over
# the bus"; the runbook's "Feed over the bus".
#
# Usage (INSIDE the container, as root):
# fly-feed status configured, running, the edge and its counters (any user)
# fly-feed bus [--no-restart] [--no-rollback]
# fly-feed direct [--no-restart] [--no-wait]
#
# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's
# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings
# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever
# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or
# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes
# hands at the start, so the stream is down for the length of a flysim restart, exactly like the
# unstick rule's) and waits until the page is on the feed again.
#
# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s):
# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it);
# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving);
# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the
# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit
# (a box that only serves the feed) the wait ends at 2.
# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
# only reports. `direct` is the safe terminal state: once the line says direct nothing, an
# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted
# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus`
# rolls back the same way as a failed one.
# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts
# flysim without blocking and does not wait for health or roll anything back: it is what the
# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up.
#
# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and
# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the
# next deploy writes `direct` back (the next flysim start would then follow it) and says so.
#
# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is
# selected, `fly-runtime`): a switch and its rollback are two.
#
# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}.
set -euo pipefail
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_EDGE_SERVICE:=flyedge.service}"
: "${FLY_PAGE_SERVICE:=flystage.service}"
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
: "${FLY_PROC_DIR:=/proc}"
: "${FLY_FEED_HEALTH_TIMEOUT:=300}"
: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}"
: "${FLY_FEED_LOCK:=/run/fly/feed.lock}"
: "${FLY_FEED_SAMPLE_SECONDS:=3}"
FEED_LOG="$FLY_FEED_LOG"
log() { echo "fly-feed: $*" >&2; }
die() { log "$*"; exit 1; }
record() {
if command -v logger >/dev/null 2>&1; then
logger -t fly-feed -- "$*" || true
fi
mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG"
}
usage() {
echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2
exit 2
}
# direct | bus | invalid:<value>. flysim reads the value case-insensitively; a missing line is direct.
configured() {
local value=""
if [ -f "$FLY_ENV_FILE" ]; then
value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)"
fi
value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')"
case "$value" in
""|direct) echo direct ;;
bus) echo bus ;;
*) echo "invalid:${value}" ;;
esac
}
# What the running flysim process started with (its environment, not the file): direct | bus |
# stopped | unknown.
running() {
local pid value
pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi
if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi
value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
case "$value" in
bus) echo bus ;;
*) echo direct ;;
esac
}
# The counters of whoever serves the feed in `via` mode.
metrics_url() {
if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi
}
# metric URL NAME -> the value of the first sample of NAME, or empty.
metric() {
curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true
}
# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these).
whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; }
# The page is on the feed: at least one client, and the frames counter moves over a sample.
page_on_feed() {
local url first second clients
url="$(metrics_url "$1")"
clients="$(metric "$url" fly_feed_clients)"
[ "$(whole "$clients")" -ge 1 ] || return 1
first="$(metric "$url" fly_frames_sent_total)"
sleep "$FLY_FEED_SAMPLE_SECONDS"
second="$(metric "$url" fly_frames_sent_total)"
[ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ]
}
page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; }
old_invocation=""
# Print to stdout, exiting quietly once the reader has gone (`fly-feed status | head -1`).
# Under `pct exec` SIGPIPE is ignored, so a write to a closed pipe fails with EPIPE and bash's
# printf/echo print "write error: Broken pipe": silence that one write and stop printing.
say() {
printf '%s\n' "$*" 2>/dev/null || exit 0
}
# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode.
healthy() {
local via="$1" deadline
deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT ))
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 --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
sleep 1
continue
fi
if ! page_unit_active; then
log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for"
return 0
fi
if page_on_feed "$via"; then
log "healthy (${via}): the page is on the feed and frames are moving"
return 0
fi
fi
sleep 1
done
return 1
}
# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner.
set_via() {
local value="$1" tmp
[ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)"
tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")"
awk -v v="$value" '
/^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next }
{ print }
END { if (!done) print "FLY_FEED_VIA=" v }
' "$FLY_ENV_FILE" >"$tmp"
chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp"
chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true
mv -f "$tmp" "$FLY_ENV_FILE"
}
locked=0
take_lock() {
[ "$locked" -eq 0 ] || return 0
mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true
exec 8>>"$FLY_FEED_LOCK"
flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching"
locked=1
}
restart_flysim() {
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
log "restarting ${FLY_SERVICE}"
# --no-block: a start that never becomes READY must not hold this process (and the lock);
# `healthy` proves it is talking to the new invocation.
systemctl restart --no-block "$FLY_SERVICE"
}
status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
say "configured: ${conf}"
say "running: ${run}"
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
say " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
fi
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
say "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
url="$(metrics_url "$run")"
if [ "$run" = bus ]; then
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
say "edge healthz: ok"
else
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
fi
say "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
fi
say "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
if [ -f "$FEED_LOG" ]; then say "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
rollback=1
wait_for_health=1
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-rollback) rollback=0 ;;
--no-wait) wait_for_health=0 ;;
*) usage ;;
esac
done
case "$command" in
status) status_report; exit 0 ;;
bus|direct) ;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})"
before="$(configured)"
[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching"
if [ "$command" = bus ]; then
[ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)"
fi
take_lock
running_before="$(running)"
if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then
log "already ${command}: fly.env says it and the running flysim started that way; nothing to do"
status_report
exit 0
fi
# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When
# the line already said bus (a deploy wrote it, the running flysim never started that way), the
# way back is direct: the state that worked.
back="$before"
if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi
# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never
# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it).
if [ "$command" = direct ]; then back=direct; fi
switching=0
restarted=0
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
set_via "$back" || true
if [ "$command" = direct ]; then
record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)"
else
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)"
fi
if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi
fi
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
switching=1
set_via "$command"
record "${command} (was ${before}; flysim was running ${running_before})"
if [ "$restart" -ne 1 ]; then
switching=0
log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it"
exit 0
fi
restarted=1
restart_flysim
if [ "$wait_for_health" -ne 1 ]; then
switching=0
record "${command}: flysim restart queued (--no-wait); health not checked"
log "restart queued; fly-feed status shows the result"
exit 0
fi
if healthy "$command"; then
switching=0
if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then
log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it"
systemctl stop "$FLY_EDGE_SERVICE" || true
fi
record "${command}: healthy"
log "the feed is served ${command}"
exit 0
fi
log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s"
if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then
set_via "$back"
switching=0
record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)"
restart_flysim
if healthy "$back"; then
log "rolled back to ${back}; it is healthy"
else
log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}"
fi
else
switching=0
record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})"
fi
exit 1

View file

@ -3,8 +3,12 @@
Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's
milestone, then to the rung below. It climbs one step per confirmed trap that outlives milestone, then to the rung below. It climbs one step per confirmed trap that outlives
the previous step, and starts over once the fly reaches a new best rung or has been the previous step, and starts over once the fly reaches a new best rung, makes lasting
quiet for QUIET seconds. A router model can delay a step, never deny it. progress after the last step that it had not made before (a reset's replay re-earns its
archive's rewards, which is not progress), or has been quiet for QUIET seconds. A milestone reset
never erases a species first owned within PROTECT seconds, and never repeats the last
reset's archive (a restore replays it exactly); either is a restart instead. A router model can
delay a step, never deny it.
""" """
import json import json
import os import os
@ -29,6 +33,9 @@ QUIET = 6 * 3600 # this long without a suspected report starts the ladder ov
HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent
DAY = 24 * 3600 DAY = 24 * 3600
MAX_RESETS = 2 # milestone resets per DAY MAX_RESETS = 2 # milestone resets per DAY
AGAIN = 12 * 3600 # after this long the last reset's archive may be restored again (row 70)
PROTECT = 2 * 3600 # a species owned this recently is not reset away (row 70)
SEEN = 2000 # lasting-progress names remembered, oldest dropped first (row 70 r3)
VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway
MODEL_BUDGET = 90 # seconds across all models in one decision MODEL_BUDGET = 90 # seconds across all models in one decision
VERIFY_TIMEOUT = 240 VERIFY_TIMEOUT = 240
@ -142,16 +149,19 @@ def rungs():
return sorted(found) return sorted(found)
def plan(level, rank, best, resets_left): def plan(level, rank, best, resets_left, last_reset=None):
"""(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart. """(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart.
Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best, Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best,
and never lower, so repeated days of a trap cannot walk the run down the ladder. and never lower, so repeated days of a trap cannot walk the run down the ladder. The archive
the last reset restored is not restored again (`last_reset`, cleared by a new best rung): a
restore is deterministic, so the same archive replays the same run into the same trap (row 70:
the second reset to rung 11 matched the first event for event).
""" """
if level == 0 or not resets_left or rank is None: if level == 0 or not resets_left or rank is None:
return "restart", None return "restart", None
target = rank if level == 1 else max(best, rank) - 1 target = rank if level == 1 else max(best, rank) - 1
if target > rank or target not in restorable_rungs(): if target > rank or target == last_reset or target not in restorable_rungs():
return "restart", None return "restart", None
return "reset", target return "reset", target
@ -226,7 +236,10 @@ def run(now=None, sleep=time.sleep, clock=None):
if level: if level:
log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank}) log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank})
state.update(bestRank=rank, level=0) state.update(bestRank=rank, level=0)
state.pop("lastReset", None)
level = 0 level = 0
if "lastReset" in state and now - state.get("lastResetAt", 0) >= AGAIN:
state.pop("lastReset", None)
last = state.get("lastSuspectedAt") last = state.get("lastSuspectedAt")
if level and last and now - last > QUIET: if level and last and now - last > QUIET:
log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank}) log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank})
@ -234,6 +247,46 @@ def run(now=None, sleep=time.sleep, clock=None):
state["resets"] = [at for at in state.get("resets", []) if now - at < DAY] state["resets"] = [at for at in state.get("resets", []) if now - at < DAY]
at = report.get("at") at = report.get("at")
# Row 70: lasting progress in the probe's window (a new rung, a species owned, a map entered,
# a trainer or badge beaten; the watchdog's window.progress). The ladder climbs for a trap that
# OUTLIVES its last step; one that follows real progress after that step is a new trap and
# starts again from a restart. A species owned is also kept from a milestone reset for PROTECT.
# A new trap means the old one let go: a clear probe more than SETTLE after the step, so a catch
# made while the fly stays flagged does not start the ladder over.
#
# Progress is measured against everything the ladder has seen before, not against the
# restored archive (row 70 review r3): a milestone reset restores the reward ledger, so the
# replay pays the archive's areas, trainers, species and rungs again, and counting those
# started the ladder over after every reset (a rung-12 replay re-earning an area and a
# species cost two extra steps and a three-hour hold before the rung below). The watchdog
# names each lasting reward (`window.progress.keys`, `kind:label`); only a name not in
# `progressSeen` is progress, and only a species not in it is protected (the replayed catch
# was the fly's before the reset too, and was protected then). A watchdog without names falls
# back to the counts.
progress = (report.get("window") or {}).get("progress") or {}
fresh = type(at) is int and 0 <= now - at <= 600
if fresh and report.get("suspected") == 0:
state["clearAt"] = max(at, state.get("clearAt", 0))
if fresh and type(progress) is dict:
keys = progress.get("keys")
if type(keys) is list:
seen = state.get("progressSeen")
seen = [key for key in seen if type(key) is str] if type(seen) is list else []
known = set(seen)
new = [key for key in dict.fromkeys(key for key in keys if type(key) is str) if key not in known]
state["progressSeen"] = (seen + new)[-SEEN:]
lasting, species = len(new), sum(key.startswith("pokedex:") for key in new)
else:
lasting, species = (progress.get(name) if type(progress.get(name)) is int else 0
for name in ("lasting", "species"))
if lasting > 0:
state["progressAt"] = max(at, state.get("progressAt", 0))
if species > 0:
state["speciesAt"] = max(at, state.get("speciesAt", 0))
since = state.get("actedAt", 0) + SETTLE
if level and state.get("progressAt", 0) > since and state.get("clearAt", 0) > since:
log({"at": now, "event": "ladder-reset", "why": "progress since the last step", "rank": rank})
state["level"] = level = 0
# The last probe that saw progress (new places, or a higher rung than the last probe), kept across # The last probe that saw progress (new places, or a higher rung than the last probe), kept across
# restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak. # restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak.
delta = (report.get("places") or {}).get("delta") delta = (report.get("places") or {}).get("delta")
@ -265,10 +318,25 @@ def run(now=None, sleep=time.sleep, clock=None):
return "waiting for next probe" return "waiting for next probe"
resets_left = MAX_RESETS - len(state["resets"]) resets_left = MAX_RESETS - len(state["resets"])
action, target = plan(level, rank, state.get("bestRank", 0), resets_left) action, target = plan(level, rank, state.get("bestRank", 0), resets_left, state.get("lastReset"))
if action == "restart" and level and now - acted < HOLD: protected = action == "reset" and now - state.get("speciesAt", -PROTECT) < PROTECT
# Only a catch-protected reset is held (the level keeps its slot, so it never drops a rung deeper
# while the window lasts, row 70). A step skipped because it would restore the archive just used
# does climb, so the ladder reaches the rung below promptly.
held_reset = protected
if protected:
action, target = "restart", None
# Restarts are at least HOLD apart, also when the ladder has started over since the last one.
if action == "restart" and (level or state.get("lastAction") == "restart") and now - acted < HOLD:
write_json(STATE, state) write_json(STATE, state)
return "holding: reset budget spent, next restart after the hold" if protected:
return "holding: a species owned within the protection window, next restart after the hold"
if not level:
return "holding: the last restart was under three hours ago"
return "holding: no reset to take, next restart after the hold"
if protected:
log({"at": now, "event": "protect", "why": "a species owned within the protection window",
"speciesAt": state["speciesAt"], "rank": rank})
stuck, model = verdict(report) stuck, model = verdict(report)
if stuck is False and state.get("vetoes", 0) < VETO_LIMIT: if stuck is False and state.get("vetoes", 0) < VETO_LIMIT:
@ -289,15 +357,18 @@ def run(now=None, sleep=time.sleep, clock=None):
notice(base, "countdown", now) notice(base, "countdown", now)
sleep(COUNTDOWN) sleep(COUNTDOWN)
started = int(clock()) started = int(clock())
# Recorded before acting, so a helper killed mid-step has still climbed and spent the reset. # Recorded before acting, so a helper killed mid-step has still climbed (unless held) and spent the reset.
state.update(level=level + 1, actedAt=started, lastAction=action, vetoes=0) state.update(level=level if held_reset else level + 1, actedAt=started, lastAction=action, vetoes=0)
state.pop("observedAt", None) state.pop("observedAt", None)
if action == "reset": if action == "reset":
state["resets"].append(started) state["resets"].append(started)
state.update(lastReset=target, lastResetAt=started)
write_json(STATE, state) write_json(STATE, state)
notice(base, "acting", started) notice(base, "acting", started)
ok = act(action, target) ok = act(action, target)
finished = int(clock()) finished = int(clock())
if action == "reset" and not ok:
state.pop("lastReset", None) # not known to have been restored, so it may be tried again
notice(base, "done" if ok else "failed", finished) notice(base, "done" if ok else "failed", finished)
state["actedAt"] = finished state["actedAt"] = finished
write_json(STATE, state) write_json(STATE, state)

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

@ -0,0 +1,501 @@
#!/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 the session's transport), and
# what flysim.service runs
# fly-runtime session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation]
# fly-runtime session-bus [...] the same as `session --bus`
# 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.
#
# The session's transport (BUS-01). `--local` (the default for a first switch) runs the session's
# participants in flysim-session's own process over the local lane. `--bus` runs them on the flybus
# router over Unix sockets: flysim-session (the router, the coordinator, the listeners) starts the
# agent and the world as child processes of the same unit (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release), in flysim.slice, on flysim's cpuset.
# The drop-in then carries `Environment=FLY_SESSION_TRANSPORT=bus`. Without either flag `session`
# keeps the transport the drop-in already has, so 05-deploy's `session --no-restart` refresh never
# changes it; `session --local` is the way back from the bus. Results, traces, checkpoints and the
# compatibility string are the same in both: only where the participants run changes. A switch onto
# the bus needs a shadow that ran the bus (`fly-shadow-run check --bus`), which the coordinator runs
# before this command, as for the first cutover. Everything below applies to both transports: one
# unit, OnFailure= falls back to LEGACY, the probation judges the session runtime either way.
#
# 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"
WORKER_BIN="${FLY_RELEASE_DIR}/fly-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 [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
exit 2
}
current() {
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
}
# The session's transport the drop-in selects: `bus` or `local` (also with no drop-in).
current_transport() {
if [ -f "$DROPIN" ] && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$DROPIN"; then
echo bus
else
echo local
fi
}
# `legacy`, `session` or `session-bus`, for the runtime log.
current_label() {
if [ "$(current)" = session ] && [ "$(current_transport)" = bus ]; then echo session-bus; else current; 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
if [ "$transport" = bus ]; then
cat >>"$tmp" <<EOF
# BUS-01: the participants are child processes on the session router's Unix sockets.
Environment=FLY_SESSION_TRANSPORT=bus
EOF
fi
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
transport=""
fallback_reason=""
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
if [ "$command" = session-bus ]; then command=session; transport=bus; fi
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-fallback) fallback=0 ;;
--no-probation) probe=0 ;;
--bus) [ "$command" = session ] || usage; transport=bus ;;
--local) [ "$command" = session ] || usage; transport=local ;;
*) usage ;;
esac
done
# No flag: keep the drop-in's transport (05-deploy's refresh); local for a first switch.
[ -n "$transport" ] || transport="$(current_transport)"
case "$command" in
status)
current
if [ "$(current)" = session ]; then echo " transport: $(current_transport)"; fi
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|session-bus|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}"
if [ "$transport" = bus ] && [ ! -x "$WORKER_BIN" ]; then
die "this release has no ${WORKER_BIN}: the bus transport starts its participants from it"
fi
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_label)"
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 "$(current_label) (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_label)"
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

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

@ -0,0 +1,630 @@
#!/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. The shadow runs on a
# build box (SHADOW-02, below); --local runs it on this container
# instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
# 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.
# --bus also requires that the shadow ran the bus topology (BUS-01)
# 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.
#
# THE BUS TOPOLOGY (BUS-01). `start --bus` runs the shadow's session the way `fly-runtime
# session --bus` runs the live one: the router, the coordinator and the task in the shadow's own
# process, the agent and the world as child processes (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release) on the router's Unix sockets. It sets
# FLY_SHADOW_MODE=bus/process in flyshadow.service's drop-in (mode.conf); a remote relay forwards it
# to the box (live.env), whose shadow reads it. The verdict records the topology
# (candidate.executionMode "process", candidate.transport "bus"), and `check --bus` refuses any
# verdict that did not run it. The live fly must run the LEGACY runtime while a shadow runs: only
# the legacy loop writes the trace (FLY_TRACE_DIR) the shadow follows, so `start` refuses while
# flysim.service runs the session runtime (fly-runtime status: session).
#
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
#
# 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
# /srv/fly/shadow/relay.json remote mode: the relay's health
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"
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
MODE_DROPIN="$REMOTE_DROPIN_DIR/mode.conf"
RUNTIME_DROPIN="${FLY_RUNTIME_DROPIN:-$DROPIN_DIR/10-runtime.conf}"
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
# restarts for the new run and the ingest hashes the release first).
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
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
}
# Remote mode's prerequisites, checked before anything changes.
check_remote() {
[ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
local target key known
target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
[ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
{ [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
{ [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
[ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
}
start() {
need_root
local mode=remote arm=""
for arg in "$@"; do
case "$arg" in
--local) mode=local ;;
--bus) arm=bus/process ;;
*) die "start: unknown option $arg" ;;
esac
done
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
# Only the legacy loop writes the trace the shadow follows (FLY_TRACE_DIR); the session runtime
# ignores it, and every process it ran would be a coverage divergence.
[ ! -f "$RUNTIME_DROPIN" ] || die "flysim.service runs the session runtime, which writes no trace for a shadow to follow. Switch the live fly to legacy for the shadow window first (fly-runtime legacy), then start the shadow"
if [ -n "$arm" ]; then
[ -x "$(dirname "$(readlink -f "$BIN")")/fly-session" ] || die "the bus topology needs fly-session beside $BIN"
fi
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
if [ "$mode" = remote ]; then
[ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
check_remote
fi
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" "$REMOTE_DROPIN_DIR"
if [ -n "$arm" ]; then
cat > "$MODE_DROPIN" <<EOF
# written by fly-shadow-run start --bus (BUS-01); removed by fly-shadow-run stop and by its guard.
# The shadow's session runs the bus topology; a remote relay forwards this to the box.
[Service]
Environment=FLY_SHADOW_MODE=$arm
EOF
log "the shadow runs the bus topology ($arm)"
else
rm -f "$MODE_DROPIN"
fi
if [ "$mode" = remote ]; then
local run_id
run_id="$(date +%s%3N)"
[ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
cat > "$REMOTE_DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
[Service]
EnvironmentFile=$REMOTE_ENV
Environment=FLY_SHADOW_RUN_ID=$run_id
ExecStart=
ExecStart=$BIN relay
CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=1G
EOF
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
else
rm -f "$REMOTE_DROPIN"
log "LOCAL shadow on this container (--local)"
fi
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
rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the
# relay writes it once the box's shadow of this run is alive and the sync is caught up).
for _ in $(seq 1 "$HEARTBEAT_WAIT"); 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 (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; }
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" "$REMOTE_DROPIN" "$MODE_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")"
if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
python3 - "$SHADOW_DIR/relay.json" <<'PY'
import json, sys
r = json.load(open(sys.argv[1]))
print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
PY
fi
[ -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() {
# `--bus` (BUS-01): the cutover goes onto the bus topology, so the shadow must have run it.
local -a pass=()
local arg
for arg in "$@"; do
case "$arg" in
--bus) pass+=(--require-arm bus/process) ;;
*) pass+=("$arg") ;;
esac
done
set -- "${pass[@]}"
# Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session
# runtime during the window, the verdict no longer covers what would be cut over.
if [ -f "$RUNTIME_DROPIN" ]; then
echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)"
exit 1
fi
# 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
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
local why rc=0 run_id=""
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
import datetime, json, sys
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
def refuse(msg):
print(msg); sys.exit(1)
try:
v = json.load(open(verdict_path))
except Exception:
v = {}
if mode == "local":
if v.get("runId") is not None:
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
sys.exit(0)
if not run_id:
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
try:
r = json.load(open(relay_path))
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
refuse("no readable relay.json (%s)" % e)
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
refuse("relay.json is %.0f s old" % age)
if r.get("runId") != run_id:
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
if v.get("runId") != run_id:
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
if v.get("window") is None:
refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
if r.get("coverageLost"):
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
if not r.get("healthy"):
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
ta = r.get("traceAgeSeconds")
if ta is None:
refuse("no live trace file of this run")
if ta > 90:
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
PY
)" || rc=$?
if [ "$rc" != 0 ]; then
echo "cutover refused: remote shadow: $why"
exit 1
fi
[ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string. fly.env is systemd's
# EnvironmentFile syntax (GAME_TITLE=Pokemon Red is valid there), so it is read as KEY=VALUE
# lines, as fly-runtime does, never sourced as shell.
local line key value env_file="${FLY_ENV_FILE:-/etc/fly/fly.env}"
if [ -f "$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#\"}"
export "${key}=${value}"
done <"$env_file"
fi
# 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 "${FLY_CURRENT_DIR:-/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 [--local]|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

@ -48,6 +48,9 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5). # encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}"
# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick.
: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}"
: "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
: "${FFMPEG:=/usr/bin/ffmpeg}" : "${FFMPEG:=/usr/bin/ffmpeg}"
@ -72,6 +75,7 @@ log_info() {
: "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10) : "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10)
: "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57) : "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57)
: "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58) : "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58)
: "${WD_LOOP_FIGHT_MIN:=24}" # this many MOVE n decisions with no battle won and no new ground, two probes running, is battles lost on repeat (row 67)
: "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}" : "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}"
mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR" mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR"
@ -155,7 +159,7 @@ write_textfile_metrics() {
{ {
echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)." echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)."
echo "# TYPE fly_watchdog_restarts_total counter" echo "# TYPE fly_watchdog_restarts_total counter"
for unit in flysim flystage flycast mediamtx flypush flystage-web; do for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")" echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
done done
# Check 7's own restart reason, kept as a separate labelset on the # Check 7's own restart reason, kept as a separate labelset on the
@ -173,6 +177,9 @@ write_textfile_metrics() {
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "# TYPE fly_watchdog_encoder_degraded gauge"
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)"
echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend."
echo "# TYPE fly_watchdog_backend_degraded gauge"
echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)"
# Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
# is -1 until the first probe completes, the same "unknown, not # is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or # broken" convention fly_watchdog_encoder_degraded uses; a value at or
@ -192,7 +199,7 @@ write_textfile_metrics() {
# convention as fly_watchdog_encoder_degraded), while the flag itself # convention as fly_watchdog_encoder_degraded), while the flag itself
# starts at 0, because a 0/1 flag carrying -1 reads as a loop to every # starts at 0, because a 0/1 flag carrying -1 reads as a loop to every
# alert expression that would ever use it. # alert expression that would ever use it.
echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked) or completing nothing, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this." echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked), completing nothing, earning nothing or winning no battle, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this."
echo "# TYPE fly_loop_suspected gauge" echo "# TYPE fly_loop_suspected gauge"
echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)." echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)."
@ -221,6 +228,12 @@ write_textfile_metrics() {
echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)." echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_rewards gauge" echo "# TYPE fly_loop_rewards gauge"
echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)" echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_fights MOVE n decisions (a move chosen in a battle) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_fights gauge"
echo "fly_loop_fights $(cat "${WD_RUN_DIR}/loop.fights" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_wins Battle-won reward events (rewardKind wildwin, trainer or badge) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_wins gauge"
echo "fly_loop_wins $(cat "${WD_RUN_DIR}/loop.wins" 2>/dev/null || echo -1)"
echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against." echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against."
echo "# TYPE fly_places_delta gauge" echo "# TYPE fly_places_delta gauge"
echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)" echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)"
@ -319,9 +332,30 @@ is_enabled() {
# ============================================================================ # ============================================================================
# Check 1: flysim — /healthz 200 and hot-state mtime age < 30s. # Check 1: flysim — /healthz 200 and hot-state mtime age < 30s.
# ============================================================================ # ============================================================================
# FLY_CONTROL_VIA from fly.env, lowercased ("direct" when absent).
control_via() {
local via=""
if [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_CONTROL_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
echo "${via:-direct}"
}
# flysim's own /healthz: :7401 when flysim serves it, and with FLY_CONTROL_VIA=bus
# (docs/design/flybus.md, "Control over the bus") flysim's read-only listener,
# which flysim serves itself in both modes -- so an edge that is down is check
# 1b's business and never restarts the fly.
flysim_health_url() {
if [ "$(control_via)" = "bus" ]; then
echo "${FLY_METRICS_URL}/healthz"
else
echo "${FLY_CONTROL_URL}/healthz"
fi
}
check_flysim() { check_flysim() {
local ok=1 local ok=1
if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then
ok=0 ok=0
fi fi
if [ -e "$FLY_STATE_HOT" ]; then if [ -e "$FLY_STATE_HOT" ]; then
@ -339,6 +373,24 @@ check_flysim() {
fi fi
} }
# ============================================================================
# Check 1b: flycontrol-edge -- only with FLY_CONTROL_VIA=bus. :7401/healthz
# answered by the edge while flysim's own /healthz is fine; when the edge does
# not answer, restart the edge (never flysim, never a reboot: the fly is fine
# and the edge holds no state). With flysim itself down, check 1 owns it.
# ============================================================================
check_control_edge() {
[ "$(control_via)" = "bus" ] || return 0
curl -fsS -o /dev/null "${FLY_METRICS_URL}/healthz" || return 0
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
record_ok flycontrol-edge
else
record_fail flycontrol-edge
log_err "flycontrol-edge: :7401 does not answer while flysim is healthy; restarting the edge"
restart_unit flycontrol-edge
fi
}
# ============================================================================ # ============================================================================
# Check 2: flystage — flysim's frames_sent_total / feed_clients from the # Check 2: flystage — flysim's frames_sent_total / feed_clients from the
# read-only metrics listener (infra.md section 5; not superseded by the # read-only metrics listener (infra.md section 5; not superseded by the
@ -350,25 +402,86 @@ check_flysim() {
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the # bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
# watchdog's own environment overrides both. # watchdog's own environment overrides both.
# ============================================================================ # ============================================================================
# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of
# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the
# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next
# restart, and judging the edge in that window would restart a flysim that is serving the feed
# itself. So: the running process when its environment can be read (flysim runs as the same user),
# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or
# no line, is direct.
feed_via() {
local via="" pid=""
pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)"
if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then
via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
elif [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then echo bus; else echo direct; fi
}
feed_metrics_url() { feed_metrics_url() {
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
echo "$FLY_FEED_METRICS_URL" echo "$FLY_FEED_METRICS_URL"
return return
fi fi
local via="" if [ "$(feed_via)" = "bus" ]; then
if [ -f "$FLY_ENV_FILE" ]; then
# Lowercased: flysim reads the value case-insensitively, so `Bus` is bus mode.
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then
echo "$FLY_EDGE_METRICS_URL" echo "$FLY_EDGE_METRICS_URL"
else else
echo "$FLY_METRICS_URL" echo "$FLY_METRICS_URL"
fi fi
} }
# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200
# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down
# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go:
# a flysim that has only just answered may not have published yet. After that:
# 2nd consecutive failure restart flyedge (the escalation's restart)
# 3rd and the page and the encoder (escalate's chain)
# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed
# direct --no-wait` (a restart of flysim, one stream gap, then the page
# is served again by the process that always worked). It is logged as
# an escalation and leaves FLY_FEED_VIA=direct until an operator
# switches again; this check then does nothing.
check_flyedge() {
if [ "$(feed_via)" != "bus" ]; then
record_ok flyedge
return 0
fi
if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
return 0
fi
if is_active flyedge.service \
&& curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
record_ok flyedge
return 0
fi
record_fail flyedge
local n
n="$(fail_count flyedge)"
# From the 4th consecutive failure on, whatever the time the failures were spread over (passes
# are skipped while flysim is down, so a flapping flysim stretches the run past any window): the
# fallback to direct comes first and a reboot is never the answer to an edge fault. Only
# n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on
# the next pass instead of falling through to it.
if [ "$n" -ge 4 ]; then
log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)"
inc_counter "escalations_total"
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"
record_ok flyedge
elif [ "$n" -ge 2 ]; then
escalate flyedge flystage flycast
fi
}
check_flystage() { check_flystage() {
local metrics frames clients ok=1 local metrics frames clients ok=1 chain=(flycast)
if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then
# The edge serves the page. While it is down or silent that is check 2a's to fix, and a
# restarted page would only reconnect to nothing (and count towards a reboot).
curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0
chain=(flyedge flycast)
fi
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)" metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
if [ -z "$metrics" ]; then if [ -z "$metrics" ]; then
ok=0 ok=0
@ -395,7 +508,7 @@ check_flystage() {
record_ok flystage record_ok flystage
else else
record_fail flystage record_fail flystage
escalate flystage flycast escalate flystage "${chain[@]}"
fi fi
} }
@ -603,6 +716,39 @@ check_encoder() {
"and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv"
} }
# ============================================================================
# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the
# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks
# for the card and the CPU is what runs, the GPU fell back (operator decision
# 2026-10-02: automatic, the stream keeps going, logged here, no paging).
#
# Like check 8 this takes NO remediation. A restart cannot repair a dead card
# and costs the run its in-memory state; the fallback is a CPU run from the
# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the
# card to a human. fly_brain_backend is not duplicated into this file's own
# .prom, for the reason check 8 gives.
# ============================================================================
check_backend() {
local wanted live fallbacks
if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then
# No session worker has written it (the legacy loop, a CPU deploy, or not started yet).
echo -1 > "${WD_RUN_DIR}/backend_degraded"
return 0
fi
wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
live="$(awk '/^fly_brain_backend\{/ && $NF == 1 {
if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \
"$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then
echo 1 > "${WD_RUN_DIR}/backend_degraded"
log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \
"Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'"
else
echo 0 > "${WD_RUN_DIR}/backend_degraded"
fi
}
# ============================================================================ # ============================================================================
# Check 9: capture freeze (infra/docs/capture-freeze.md). # Check 9: capture freeze (infra/docs/capture-freeze.md).
# #
@ -807,6 +953,22 @@ check_capture_freeze() {
# unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the # unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the
# window, on this probe AND the previous one. # window, on this probe AND the previous one.
# #
# Row 67: the Pewter Gym, one trainer lost ~30 times in a row. The readout
# chose TAIL WHIP six turns in seven, Squirtle fainted every time, the fly
# whited out to Pewter and walked straight back in: MOVE 2 / NEXT / GO
# OBJECTIVE / TALK / NO, seven names, every macro `done`. Two stray tile
# rewards (a new tile of the gym on a whiteout's walk back) reset the
# unrewarded rule for ~45 minutes. What the window never had was a battle WON.
# So the reward lines carry their rewardKind, and one more rule reads them,
# behind the same gate:
# unwon-battles — WD_LOOP_FIGHT_MIN+ `MOVE n` decisions and no reward of
# kind wildwin, trainer or badge in the window, on this
# probe AND the previous one.
# The feed has no HP (docs/feed-protocol.md), so "a battle that makes no
# progress" is read as moves chosen and nothing won. Measured on the live log:
# healthy windows had 13-46 MOVE starts and 1-4 wins (the one 22-move window
# with no win also had new ground); the trap had 30-39 and none.
#
# The tile rule is what separates a loop from a legitimately repeating # The tile rule is what separates a loop from a legitimately repeating
# explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer # explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer
# than the frame cap, not a trap), and the watchdog has no tile counter. The # than the frame cap, not a trap), and the watchdog has no tile counter. The
@ -857,7 +1019,7 @@ loop_status_fields() {
loop_macro_stream() { loop_macro_stream() {
[ -f "$FLY_EVENT_LOG" ] || return 0 [ -f "$FLY_EVENT_LOG" ] || return 0
tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \ tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)"' -R 2>/dev/null \ | jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward" or .kind == "milestone") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \
|| true || true
} }
@ -865,12 +1027,22 @@ loop_macro_stream() {
# #
# total US distinct US topCount US period US repeats US windowFrom US # total US distinct US topCount US period US repeats US windowFrom US
# windowTo US topName US block US tail US decisions US refused US blocked US # windowTo US topName US block US tail US decisions US refused US blocked US
# timeout US done US rewards # timeout US done US rewards US fights US wins US progress US species US keys
# #
# `total` counts start events inside the window, `decisions` starts plus # `total` counts start events inside the window, `decisions` starts plus
# refusals (the sequence, `distinct` and `topCount` are over decisions), and # refusals (the sequence, `distinct` and `topCount` are over decisions), and
# the next four count each outcome in the window, and `rewards` the reward # the next four count each outcome in the window, and `rewards` the reward
# events in it (row 58). `period`/`repeats` describe # events in it (row 58), `fights` the `MOVE n` decisions and `wins` the
# rewards of kind wildwin/trainer/badge (row 67). `progress` counts the lasting
# progress in the window (row 70): a `milestone` event (a new rung), or a reward of kind
# pokedex (a species owned for the first time), area (a map entered for the first time),
# trainer or badge -- each paid once per run, so a ring cannot earn them twice -- and
# `species` the pokedex ones alone. `keys` names each of them once as `kind:label`
# (`pokedex:OWNED #8`, `milestone:Reached MT. MOON`), RS-joined, at most 64: a milestone
# reset restores the reward ledger, so its replay pays the same rewards again, and only
# the names tell a replayed reward from a new one. They are reported, never read by a
# rule here: the recovery ladder uses them to tell a trap that follows real progress from
# one that outlived its last step. `period`/`repeats` describe
# the shortest repeating block at the END of the sequence (0/0 when nothing # the shortest repeating block at the END of the sequence (0/0 when nothing
# repeats), `block` is that block comma-joined, and `tail` is the last 12 # repeats), `block` is that block comma-joined, and `tail` is the last 12
# names for context. The window ends at the newest macro event's own brain # names for context. The window ends at the newest macro event's own brain
@ -879,14 +1051,29 @@ loop_analyze() {
awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" ' awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" '
# Reward lines are counted and nothing else: the window still ends at the # Reward lines are counted and nothing else: the window still ends at the
# newest macro event, as it always has. # newest macro event, as it always has.
$3 == "reward" { rms[++nr] = $1 + 0; next } $3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; rlbl[nr] = $2; next }
$3 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; rlbl[nr] = $2; next }
{ ms[++n] = $1 + 0; lbl[n] = $2 } { ms[++n] = $1 + 0; lbl[n] = $2 }
END { END {
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\n"; exit } if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\0370\0370\037\n"; exit }
to = ms[n]; from = to - win to = ms[n]; from = to - win
k = 0; distinct = 0; topn = 0; top = "" k = 0; distinct = 0; topn = 0; top = ""
starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0 starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) rewards++ fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) {
lasting = rkind[q] == "milestone" || rkind[q] == "pokedex" || rkind[q] == "area" \
|| rkind[q] == "trainer" || rkind[q] == "badge"
if (lasting) {
progress++
key = rkind[q] ":" rlbl[q]
gsub(/[\036\037]/, " ", key)
if (!(key in seenkey) && nkeys < 64) { seenkey[key] = 1; keys = keys (nkeys++ ? "\036" : "") key }
}
if (rkind[q] == "milestone") continue
rewards++
if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++
if (rkind[q] == "pokedex") species++
}
for (i = 1; i <= n; i++) { for (i = 1; i <= n; i++) {
if (ms[i] < from) continue if (ms[i] < from) continue
if (lbl[i] ~ / blocked$/) { blocked++; continue } if (lbl[i] ~ / blocked$/) { blocked++; continue }
@ -897,6 +1084,7 @@ loop_analyze() {
else continue else continue
name = lbl[i]; sub(/ (start|refused)$/, "", name) name = lbl[i]; sub(/ (start|refused)$/, "", name)
seq[++k] = name seq[++k] = name
if (name ~ /^MOVE [1-4]$/) fights++
if (!(name in cnt)) { cnt[name] = 0; distinct++ } if (!(name in cnt)) { cnt[name] = 0; distinct++ }
cnt[name]++ cnt[name]++
if (cnt[name] > topn) { topn = cnt[name]; top = name } if (cnt[name] > topn) { topn = cnt[name]; top = name }
@ -919,9 +1107,9 @@ loop_analyze() {
tailstr = "" tailstr = ""
start = k - 11; if (start < 1) start = 1 start = k - 11; if (start < 1) start = 1
for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j] for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j]
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\n", \ printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\n", \
starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \ starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \
k, refused, blocked, timeout, done, rewards k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys
}' }'
} }
@ -979,14 +1167,15 @@ check_loop() {
echo "$delta" > "${WD_RUN_DIR}/loop.places_delta" echo "$delta" > "${WD_RUN_DIR}/loop.places_delta"
local analysis total distinct topn period repeats win_from win_to top block tailstr local analysis total distinct topn period repeats win_from win_to top block tailstr
local decisions refused blocked timeouts completed rewards local decisions refused blocked timeouts completed rewards fights wins progress species keys
analysis="$(loop_macro_stream | loop_analyze)" analysis="$(loop_macro_stream | loop_analyze)"
IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \ IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \
decisions refused blocked timeouts completed rewards <<< "$analysis" decisions refused blocked timeouts completed rewards fights wins progress species keys <<< "$analysis"
total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}" total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}"
period="${period:-0}"; repeats="${repeats:-0}" period="${period:-0}"; repeats="${repeats:-0}"
decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}" decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}"
timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}" timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}"
fights="${fights:-0}"; wins="${wins:-0}"; progress="${progress:-0}"; species="${species:-0}"
echo "$distinct" > "${WD_RUN_DIR}/loop.distinct" echo "$distinct" > "${WD_RUN_DIR}/loop.distinct"
echo "$period" > "${WD_RUN_DIR}/loop.period" echo "$period" > "${WD_RUN_DIR}/loop.period"
echo "$repeats" > "${WD_RUN_DIR}/loop.repeats" echo "$repeats" > "${WD_RUN_DIR}/loop.repeats"
@ -994,6 +1183,8 @@ check_loop() {
echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked" echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked"
echo "$completed" > "${WD_RUN_DIR}/loop.done" echo "$completed" > "${WD_RUN_DIR}/loop.done"
echo "$rewards" > "${WD_RUN_DIR}/loop.rewards" echo "$rewards" > "${WD_RUN_DIR}/loop.rewards"
echo "$fights" > "${WD_RUN_DIR}/loop.fights"
echo "$wins" > "${WD_RUN_DIR}/loop.wins"
local prev_suspected=0 local prev_suspected=0
[ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" [ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
@ -1022,6 +1213,14 @@ check_loop() {
[ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1 [ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1
echo "$busy" > "$busy_file" echo "$busy" > "$busy_file"
# Battles lost on repeat (row 67), judged over two probes like the two
# above: moves chosen, no battle won, no new ground.
local unwon_file="${WD_RUN_DIR}/loop.prev_unwon" prev_unwon=0 unwon=0
[ -f "$unwon_file" ] && prev_unwon="$(cat "$unwon_file" 2>/dev/null || echo 0)"
case "${prev_unwon:-}" in ''|*[!0-9]*) prev_unwon=0 ;; esac
[ "$fights" -ge "$WD_LOOP_FIGHT_MIN" ] && [ "$wins" -eq 0 ] && [ "$grown" -eq 0 ] && unwon=1
echo "$unwon" > "$unwon_file"
local failed=$(( refused + blocked + timeouts )) local failed=$(( refused + blocked + timeouts ))
local suspected=0 reason="" local suspected=0 reason=""
if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then
@ -1051,6 +1250,11 @@ check_loop() {
# completes, none of them earns anything, and the ground stays put. # completes, none of them earns anything, and the ground stays put.
suspected=1 suspected=1
reason="unrewarded" reason="unrewarded"
elif [ "$unwon" -eq 1 ] && [ "$prev_unwon" -eq 1 ]; then
# Row 67: every macro completes and the odd tile reward keeps the
# window from reading unrewarded, but no battle is ever won.
suspected=1
reason="unwon-battles"
fi fi
fi fi
echo "$suspected" > "${WD_RUN_DIR}/loop.suspected" echo "$suspected" > "${WD_RUN_DIR}/loop.suspected"
@ -1083,6 +1287,11 @@ check_loop() {
--argjson timeouts "$timeouts" \ --argjson timeouts "$timeouts" \
--argjson completed "$completed" \ --argjson completed "$completed" \
--argjson rewards "$rewards" \ --argjson rewards "$rewards" \
--argjson fights "$fights" \
--argjson wins "$wins" \
--argjson progress "$progress" \
--argjson species "$species" \
--arg keys "${keys:-}" \
--argjson windowFrom "${win_from:-0}" \ --argjson windowFrom "${win_from:-0}" \
--argjson windowTo "${win_to:-0}" \ --argjson windowTo "${win_to:-0}" \
--argjson windowMs "$WD_LOOP_WINDOW_MS" \ --argjson windowMs "$WD_LOOP_WINDOW_MS" \
@ -1112,6 +1321,10 @@ check_loop() {
decisions: $decisions, decisions: $decisions,
outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused }, outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused },
rewards: $rewards, rewards: $rewards,
fights: $fights,
wins: $wins,
progress: { lasting: $progress, species: $species,
keys: (if $keys == "" then [] else ($keys | split("\u001e")) end) },
tail: (if $tail == "" then [] else ($tail | split(", ")) end) tail: (if $tail == "" then [] else ($tail | split(", ")) end)
}, },
dominant: { name: (if $dominant == "" then null else $dominant end), dominant: { name: (if $dominant == "" then null else $dominant end),
@ -1137,6 +1350,8 @@ check_loop() {
if [ "$suspected" -eq 1 ]; then if [ "$suspected" -eq 1 ]; then
if [ "$reason" = "unrewarded" ]; then if [ "$reason" = "unrewarded" ]; then
log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "unwon-battles" ]; then
log_err "loop suspected (unwon-battles): ${fights} moves chosen in battle and no battle won in the last ${mins} brain minutes, two probes running — ${decisions} decisions, ${rewards} reward event(s), top [${top}] x${topn}, tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — battles lost on repeat are a readout choice or a pad that offers no winning move. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then
log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "sequence" ]; then elif [ "$reason" = "sequence" ]; then
@ -1151,9 +1366,12 @@ check_loop() {
main() { main() {
check_flysim check_flysim
check_flyedge
check_control_edge
check_flystage check_flystage
check_flycast check_flycast
check_encoder check_encoder
check_backend
check_mediamtx check_mediamtx
check_flypush check_flypush
check_disk check_disk

147
infra/box/fly-shadow-remote-setup Executable file
View file

@ -0,0 +1,147 @@
#!/usr/bin/env bash
# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
# Idempotent: re-run it for every release the container runs.
#
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
#
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
# root-owned, and /opt/fly/current points to it: the shadow's verdict names
# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
# refuses a relay whose release differs.
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
# live fly's NUMA node.
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
# clearly faster than real time: see the runbook's "Which box".
#
# What it sets up:
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# ignores what the client asks for; the ingest writes nothing outside the mirror;
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
# run id the relay brings).
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
set -euo pipefail
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
log() { echo "fly-shadow-remote-setup: $*"; }
[ "$(id -u)" = 0 ] || die "run as root on the build box"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
from=""; cpus=""; threads=4
while [ $# -gt 0 ]; do
case "$1" in
--from) from="$2"; shift 2 ;;
--cpus) cpus="$2"; shift 2 ;;
--threads) threads="$2"; shift 2 ;;
*) die "unknown option $1" ;;
esac
done
here="$(cd "$(dirname "$0")" && pwd)"
ROOT=/srv/fly-shadow-remote
HOME_DIR=/srv/fly-shadow-remote-home
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
[ -f "$tarball" ] || die "no tarball $tarball"
[ -f "$rom" ] || die "no ROM $rom"
[ -f "$pubkey" ] || die "no public key $pubkey"
base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
key="$(head -n 1 "$pubkey")"
[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
# The release, exactly as 05-deploy installs it on the container (but root-owned here).
release="/opt/fly/releases/${version}"
if [ -f "$release/MANIFEST" ]; then
log "release $version already at $release"
else
install -d -m 0755 "$release"
tar -xzf "$tarball" -C "$release"
chown -R root:root "$release"
fi
(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
# The bare subcommand exits 2 (usage); under pipefail a pipe into grep would fail on that, so capture.
probe="$("$release/fly-shadow" ingest 2>&1 || true)"
printf '%s' "$probe" | grep -q 'needs --root' \
|| die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
log "/opt/fly/current -> $release"
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
if id flyshadow >/dev/null 2>&1; then
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
else
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
fi
if [ -e "$ROOT" ]; then
[ -d "$ROOT" ] || die "$ROOT is not a directory"
else
mkdir -m 0750 "$ROOT"
chown -h flyshadow:flyshadow "$ROOT"
fi
for d in trace hot durable out; do
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
if [ -e "$ROOT/$d" ]; then
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
else
mkdir -m 0750 "$ROOT/$d"
chown -h flyshadow:flyshadow "$ROOT/$d"
fi
done
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
install -d -o root -g root -m 0755 "$HOME_DIR"
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
log "authorized_keys: the relay key may run only the ingest"
# The cartridge and this box's paths.
rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
install -d -m 0755 /srv/fly/rom
install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
install -d -m 0755 /etc/fly
cat > /etc/fly/fly-shadow-remote.env <<ENV
# written by infra/box/fly-shadow-remote-setup (SHADOW-02): this box's paths for the remote shadow.
FLY_ROM=/srv/fly/rom/${rom_sha}.gb
FLY_DATASET=/opt/fly/current/data/fafb-v783
ENV
log "ROM sha256 $rom_sha (must equal the container's ROM_SHA256)"
# The units.
install -m 0644 "$here/flyshadow-remote.service" /etc/systemd/system/flyshadow-remote.service
install -m 0644 "$here/flyshadow-remote.path" /etc/systemd/system/flyshadow-remote.path
install -d -m 0755 /etc/systemd/system/flyshadow-remote.service.d
{
printf '# written by fly-shadow-remote-setup\n[Service]\nEnvironment=FLY_SHADOW_THREADS=%s\n' "$threads"
[ -n "$cpus" ] && printf 'AllowedCPUs=%s\n' "$cpus"
} > /etc/systemd/system/flyshadow-remote.service.d/10-cores.conf
log "${threads} threads${cpus:+ on CPUs $cpus}"
systemctl daemon-reload
systemctl enable --now flyshadow-remote.path
systemctl enable flyshadow-remote.service
# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
systemctl try-restart flyshadow-remote.service || true
log "ready: the container's fly-shadow-run start brings the first run id"

View file

@ -0,0 +1,13 @@
# infra/box/flyshadow-remote.path — installed on a BUILD BOX with flyshadow-remote.service
# (SHADOW-02). A new run id (the container's `fly-shadow-run start`, written by the ingest) starts
# the shadow when it is down: the first run, or after a divergence (exit 3 is not restarted). A
# running shadow restarts itself on the change (exit 4, Restart=always).
[Unit]
Description=Start the remote shadow for a new run (SHADOW-02)
[Path]
PathChanged=/srv/fly-shadow-remote/run-id
Unit=flyshadow-remote.service
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1,55 @@
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
#
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the
# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
# the SAME release (installed from the same tarball at the same /opt/fly/releases/<version> path,
# so the verdict's release and binary hashes are the container's), on this box's own cores, at
# normal priority.
#
# Its input is the mirror /srv/fly-shadow-remote, written by `fly-shadow ingest`, the forced
# command of the one key the container's relay (`fly-shadow relay`, flyshadow.service there) holds;
# the relay writes this shadow's verdict back to the container, where `fly-shadow-run check`, its
# guard and CUT-01 read it as before. REPORT-ONLY: it reads the mirror, writes <root>/out and its
# runtime directory, and serves nothing.
#
# The run: `fly-shadow-run start` on the container gives each run an id; the ingest writes it to
# <root>/run-id (after resetting the mirror). A running shadow sees the change within 5 s and exits
# with status 4, and Restart=always starts the new run; a shadow that is down (it diverged: exit 3,
# which is not restarted, so the diverged verdict stays) is started by flyshadow-remote.path.
[Unit]
Description=flyshadow-remote: the session runtime shadowing the live fly from a build box (SHADOW-02, report only)
ConditionPathExists=/opt/fly/current/fly-shadow
ConditionPathExists=/srv/fly-shadow-remote/run-id
[Service]
Type=simple
User=flyshadow
# The live composition's settings, as the relay forwarded them (game, macro mode, accepted
# adapters, pins; never a path or a secret), then this box's own paths: FLY_ROM (the cartridge,
# with the container's ROM_SHA256) and FLY_DATASET (the release's connectome).
EnvironmentFile=-/srv/fly-shadow-remote/live.env
EnvironmentFile=/etc/fly/fly-shadow-remote.env
Environment=FLY_TRACE_DIR=/srv/fly-shadow-remote/trace
Environment=FLY_STATE_HOT=/srv/fly-shadow-remote/hot
Environment=FLY_STATE=/srv/fly-shadow-remote/durable
Environment=FLY_SHADOW_DIR=/srv/fly-shadow-remote/out
Environment=FLY_SHADOW_WORK=/run/flyshadow-remote
RuntimeDirectory=flyshadow-remote
# 3 sweep threads (the SHADOW-01 measurements: 13-15 ms a frame against 16.7 ms of real time).
Environment=FLY_SHADOW_THREADS=3
# No lag back-off: the live fly is on another machine. The spool holds a long catch-up.
ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0 --spool-max-mib 4096
Restart=always
RestartSec=2
RestartPreventExitStatus=3
# Dedicated cores (fly-shadow-remote-setup --cpus writes AllowedCPUs= in a drop-in) at a weight
# above anything else on the box: a build must not starve the shadow.
CPUWeight=1000
Nice=-5
MemoryMax=6G
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

View file

@ -85,6 +85,16 @@ 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
# fly-control-edge (FLY_CONTROL_VIA=bus, CTRL-01): the control API served from
# flysim's control services on the bus. Same reasons, same place.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-control-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 +128,18 @@ 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))"
control_edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-control-edge"
[ -x "$control_edge_built" ] || die "expected binary not found after build: $control_edge_built"
control_edge_out="$(dirname "$OUT_PATH")/fly-control-edge"
cp "$control_edge_built" "$control_edge_out"
chmod 0755 "$control_edge_out"
log "built $control_edge_out ($(du -h "$control_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,14 @@
# 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)
# fly-control-edge (the control-bus edge, CTRL-01, likewise;
# flycontrol-edge.service stays inactive 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 +90,25 @@ 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
CONTROL_EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-control-edge"
if [ -x "$CONTROL_EDGE_BIN" ]; then
cp "$CONTROL_EDGE_BIN" "${release_dir}/fly-control-edge"
chmod 0755 "${release_dir}/fly-control-edge"
else
log "no fly-control-edge beside $FLYSIM_BIN; packaging without it (FLY_CONTROL_VIA=bus unavailable in this release)"
fi
for extra in flysim-session fly-shadow fly-session; do
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
if [ -x "$EXTRA_BIN" ]; then
cp "$EXTRA_BIN" "${release_dir}/${extra}"
chmod 0755 "${release_dir}/${extra}"
else
case "$extra" in
fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;;
*) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;;
esac
fi
done
cp -a "$STAGE_DIR" "${release_dir}/stage" cp -a "$STAGE_DIR" "${release_dir}/stage"
cp -a "$BRIDGE_DIR" "${release_dir}/bridge" cp -a "$BRIDGE_DIR" "${release_dir}/bridge"

View file

@ -38,6 +38,19 @@ branch="$(git rev-parse --abbrev-ref HEAD)"
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})" die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})"
fi fi
# A tag is published with its whole history, so the privacy scan runs first and fails
# closed: without the operator's private pattern list ($FLY_PII_PATTERNS) it cannot see
# host names, people's names, the channel or pass entry names, and a tag is not cut blind.
# It checks the tree being tagged and every line added since the previous tag.
log "running tools/pii-scan.sh (private pattern list required)"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --tree HEAD \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in the tree (or its private pattern list is missing) — see above"
prev_tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)"
pii_range="HEAD"
[ -z "$prev_tag" ] || pii_range="${prev_tag}..HEAD"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --range "$pii_range" \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in commits since ${prev_tag:-the root} (a tag publishes them even if a later commit removed them) — see above"
git fetch --tags >/dev/null 2>&1 \ git fetch --tags >/dev/null 2>&1 \
&& log "fetched tags from the remote" \ && log "fetched tags from the remote" \
|| log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state" || log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state"

View file

@ -6,17 +6,22 @@
# <unit>` and, on the 5-consecutive-failure escalation, a container # <unit>` and, on the 5-consecutive-failure escalation, a container
# reboot. This is the minimum NOPASSWD surface for exactly what # reboot. This is the minimum NOPASSWD surface for exactly what
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast, # bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
# mediamtx, flypush), plus reboot. No `systemctl stop`, no # mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
# `enable`/`disable`, no arbitrary unit name, and no units this script # `enable`/`disable`, no arbitrary unit name, and no units this script
# does not itself restart (xvfb, pulse, flystage-web are never touched by # does not itself restart (xvfb, pulse, flystage-web are never touched by
# fly-watchdog's checks, so they are not granted here). # fly-watchdog's checks, so they are not granted here).
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge.service
fly ALL=(root) NOPASSWD: /usr/sbin/reboot fly ALL=(root) NOPASSWD: /usr/sbin/reboot
# fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and # fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and
# resets to a milestone archive through this one root wrapper, which validates the rung, # resets to a milestone archive through this one root wrapper, which validates the rung,
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md). # stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset
# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on
# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait

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

@ -16,9 +16,35 @@ a ladder one step per trap that outlives the previous step:
their 10-brain-minute window lies after it. The helper waits that long after every step. their 10-brain-minute window lies after it. The helper waits that long after every step.
- **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a - **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a
restart, at most every three hours, until a reset is free again. The same three-hour spacing applies restart, at most every three hours, until a reset is free again. The same three-hour spacing applies
when a reset level finds no restorable rung and restarts instead. when a reset level finds no restorable rung and restarts instead, and between any two restarts in a
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, or after row, also when the ladder has started over in between.
six hours with no suspected report. - **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, after
six hours with no suspected report, or when the fly makes new lasting progress more than
20 minutes after the last step and a clear probe shows the old trap let go (row 70). Lasting
progress is the watchdog's `window.progress`: a rung reached, a species owned, a map entered, or
a trainer or badge beaten, each named in `window.progress.keys` as `kind:label` (`pokedex:OWNED
#41`). A ring cannot earn them twice, but a milestone reset restores the reward ledger, so its
replay pays the archive's rewards again. Progress is therefore measured against every name the
ladder has seen (`progressSeen` in the state file, the last 2,000), not against the restored
archive: a replay re-earning what the run had before the reset is not progress, and the ladder
climbs on to the rung below as it did before row 70. A trap that follows new progress is a new
trap, and it starts again from a restart. A catch made while the fly stays flagged is not a new
trap. With a watchdog that reports no names, the counts are used as before.
Names the ladder never saw (before this version was deployed, or while an older one ran) count
as new once.
- **Protected catches:** a milestone reset never erases a species first owned in the last two hours
(`PROTECT`, a `pokedex:` name not seen before). A species a reset's replay owns again was the fly's
before the reset and was protected then, so it does not open a second window. Within that window the step is a restart, spaced by
the hold like a spent budget, and `history.jsonl` records a `protect` event. A reset turned into a
restart this way does not climb the ladder: the level keeps its slot and the reset comes, at the
same rung, once the window ends. Evolution also counts as a species owned.
- **No archive twice in a row:** a reset never restores the same archive as the last reset,
until a new best rung is reached or twelve hours have passed (`AGAIN`; a trap no restart clears
is reset again in bounded time, no later than before this rule). Such a step does climb, so the rung below is reached promptly. A restore is deterministic, so the same archive replays the
same run into the same trap. Row 70's second reset to rung 11 matched the first one event for
event: the same Zubat caught, the same trap an hour later, and the catch erased. That step is
a restart instead. A reset that fails does not mark its archive: it is not known to have been
restored, so the next reset may try it again.
A milestone step only uses an archive the running build can restore. `fly-loop-reset --list` A milestone step only uses an archive the running build can restore. `fly-loop-reset --list`
compares each archive's compatibility string with `flysim --print-compatibility` and accepts an compares each archive's compatibility string with `flysim --print-compatibility` and accepts an

View file

@ -3370,3 +3370,428 @@ gives these results:
- **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest - **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest
of the window (65e). of the window (65e).
- **branch**: all six leave with no empty pad, and three win the Cascade Badge. - **branch**: all six leave with no empty pad, and three win the Cascade Badge.
## 2026-09-29, row 66: shop, Poké Balls and catching from the rung-8 restart
### What was found
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) on v0.6.5 to watch
shopping and catching. In the first 35 minutes: `GO SHOP` done 33, `TALK` 5, `BUY BALL` never
dealt, `THROW BALL` 0, no catch. The sequences after `GO SHOP` were `GO SHOP`, `GO OUT`, `GO SHOP`,
`GO OUT` (`docs/design/macros.md` 12.30).
### Reproduction
- `survey-rank8-row66-viridian-mart.checkpoint` (`FLY_ROW66_MART_CHECKPOINT`, not committed) was
saved by the offers survey (`FLY_PROBE_SAVE_MART=2a`, `FLY_PROBE_SAVE_AFTER=3000`) from
`survey-rank7-row62` on the frame the fly walked into the Viridian mart after delivering the
parcel: 793 in the wallet, no ball.
- The connectome from it (`trap_hunt`, `FLY_TRAP_LOG_MACROS=1`): `GO SHOP` from the door to the
clerk, `GO OBJECTIVE` out of the door, `GO SHOP` from the street. Three laps in 18 brain seconds.
`TALK` was on the pad at the counter every time and was never chosen.
- A catch on the stub survey (`FLY_PROBE_SCREEN_*` dumps): from "All right! WEEDLE was caught!"
to the end of the battle, 6,900 frames under a pad of `BACK` and `THROW BALL`. `THROW BALL`'s A
said YES to the nickname and typed AAAAAAAAAA.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 66 | row 62's service walk is dealt again whenever the service is needed, with no window, so a fly that walks away from the counter is walked straight back | the Viridian mart after the parcel, no ball, money for one | `a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window`, `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` | **fixed**: a completed `GO SHOP` / `GO HEAL` facing the counter records `TargetKey::Counter` on the building's map. The service walk toward it is withheld for the reached window |
| 66b | a purchase took four choices in a row at the counter (`TALK`, the greeting, `CONFIRM`, `BUY BALL`). The connectome never chose `TALK` there | any mart | `buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought`, `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | **operator decision, built**: `BUY BALL` is also one button from the mart's floor, like `HEAL`. It walks to the clerk, talks, opens BUY, buys the first row and is done when paid. It is offered only in Viridian (after Oak has the parcel), Pewter and Cerulean, with no ball, 200 in the wallet, no parcel, and the clerk not blocked |
| 66c | `wListMenuID` outlives the battle bag, so every frame after a throw read as an open bag | a catch (the Pokédex page, the nickname, the naming screen) and the text after any throw or potion | `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends`, the state unit test | **fixed**: the bag is the bag only while its box (4, 2)-(19, 12) is drawn |
| 66d | after a catch, `NEXT` says YES to the nickname offer and names the Pokémon with A's | every catch | -- | **left, named**: offering the box's two answers in a battle is a pad change for the operator |
| 66e | the connectome did not choose `THROW BALL` in any wild battle with a ball (35 decisions over seven battles, three runs) | Viridian Forest with a ball bought by 66b | -- | **left, the fly's**: dealt as designed (12.9). Whether to make throwing likelier is the operator's |
| 66f | whiteouts halve the wallet: 3,175 to 793 to 396 to 0 on one stub run before Pewter | early fights lost | -- | **left**: the cartridge's rule. It is why the restart rung matters |
| 66g | `rom_catch`'s `BALL` is the button's tag (`MB·BALL`), not its channel, so the lean sets a rate nobody reads | the test's drive | -- | **left, documented**: that drive is the one that catches from `FLY_CATCH_CHECKPOINT`. Both tests now retry from idle offsets, because one ball misses about two throws in three |
### Before and after
ROM tests (rom-env sourced):
| test | v0.6.5 | branch |
| --- | --- | --- |
| `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` (10,000 frames, the drive declines the counter) | 31 street `GO SHOP`s, 31 walks back in. **Fails** | 0 and 0. Passes |
| `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | `BUY BALL` never dealt on the floor, no ball. **Fails** | dealt, started, done. One ball, 793 to 593, at f491. Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | `THROW BALL` dealt on 666 frames after the catch, pad `BACK`/`THROW BALL`. **Fails** | 0, pad `NEXT`, battle over 1,463 frames after the catch. Passes |
With the connectome (`trap_hunt`, one sweep thread). `FLY_TRAP_SEED` seeds only the palette, and
three seeds from one checkpoint were byte-identical. So the runs vary the starting state: three
post-parcel Viridian mart entrances saved from stub seeds 1, 3 and 5, and the Pewter gym
(`survey-rank11-row59`, 1,606 in the wallet). A decision is a macro start whose pad held the
button.
| run | brain min | counter `TALK` dealt / chosen | floor `BUY BALL` dealt / chosen / done | balls bought | `THROW BALL` dealt / chosen |
| --- | ---: | ---: | ---: | ---: | ---: |
| base, Viridian mart (s1 entrance) | 5 | 4 / 0 | -- | 0 | 0 / 0 |
| branch, Viridian mart (s1 entrance) | 5 | 1 / 0 | 2 / 0 / 0 | 0 | 0 / 0 |
| branch, Viridian mart (s3 entrance) | 5 | 3 / 0 | 3 / 1 / 1 | 1 (431 to 231) | 4 / 0 |
| branch, Viridian mart (s5 entrance) | 5 | 3 / 0 | 4 / 1 / 1 | 1 (1,587 to 1,387) | 16 / 0 |
| branch, Pewter gym, then the Pewter mart | 10 | 1 / 0 | 4 / 1 / 1 | 1 (1,606 to 1,406) | 15 / 0 |
`TALK` at a counter: 0 of 12 decisions on either arm. The floor `BUY BALL`: chosen 3 of 13, and
done (paid) all 3 times. The ring: 4 mart entries in 16 brain seconds on base, one visit on the
branch.
## 2026-09-29, row 67: the Pewter Gym trainer, lost on repeat
### What was live
v0.6.5, macros mode, reset to rung 8 at 12:16Z and back at PEWTER CITY by 13:40. The fly
entered the Pewter Gym (map 54) at 13:41, talked to the guide (#3) and to the Jr. Trainer
(#2). For the next hour and a half the pad read `battle` most of the time.
Per 3,000 events: `NEXT` 1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17,
`GO FRONTIER` 13, `TALK` 7. There was no battle-won reward, only two tile rewards on map 54. Check
10 stayed clear.
### Reproduction (the pulled checkpoint, hot generation 230739)
- The checkpoint is on the walk back, not in a battle: Pewter City (18, 13), `wIsInBattle` 0,
`wLastBlackoutMap` `$02`, money 0, no badge, `EVENT_BEAT_PEWTER_GYM_TRAINER_0` clear. The party
is one Squirtle L11, 34/34: TACKLE 35/35, TAIL WHIP 30/30, BUBBLE 30/30.
- The opponent is `wTrainerClass` `$05` (Jr. Trainer♂) #1, `wEnemyPartyCount` 2: Diglett L11 and
Sandshrew L11, both Ground (`wEnemyMonType1` `$04`).
- Driven with the real palette and the live readout's measured favourite (TAIL WHIP 87%, else
BUBBLE), the cycle is the live one. `GO OBJECTIVE` into the gym, then `TALK` and the guide's
YES/NO. Then the trainer's challenge starts the battle. The own-turn pad is `MOVE 1, MOVE 2, MOVE 3`
on every turn, and each turn resolves in about 530 frames. Squirtle falls 34 → 29 → 24 → 19
→ 11 → 6 → 0 while Diglett's DEFENSE falls to -6. Then `wIsInBattle` `$ff`, `wBattleResult` 1,
the whiteout to Pewter (13, 26) with PP back to 30, and the walk back. One battle takes about
4,500 frames.
- Live, per battle (29 battles, from the event log): TAIL WHIP 155, BUBBLE 23, TACKLE 0, and 5 to 8
moves each. Where TAIL WHIP ran out of effect before the faint, 12.23 withheld it and the fly
pressed BUBBLE (`22222233`).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 67 | a readout that favours TAIL WHIP loses every battle against a trainer it could beat; the whiteout heals the party, so PP never runs out and the ring never ends | the Pewter Gym's Jr. Trainer, Squirtle alone | `row67_the_gym_trainer_is_beaten_from_what_the_pad_deals` | **left, the fly's**: the pad offers every move with PP and an effect on every own-turn frame (0 missing in 932) and a uniform choice wins. Options for the operator below |
| 67b | check 10 did not flag: a stray tile reward (a new gym tile on a walk back) every ~20 minutes reset `unrewarded`, and battles are not a sequence of four names | a whiteout ring with a walk in it | `lint.sh` check 10 case 8 | **fixed**: `unwon-battles` (24+ `MOVE n`, no `wildwin`/`trainer`/`badge` reward, two probes, no new ground) |
| 67c | the no-PP ROM test asserted "more than one button" on a trainer battle whose only honest button is `MOVE 1` (12.8's backstop); it was red on main and skipped without `FLY_NOPP_CHECKPOINT` | the no-PP checkpoint | `macros_mode_ends_a_turn_with_no_move_left_on_the_cartridge` | **fixed (test)**: at least one button, and the battle ends (Struggle, 1,487 frames) |
### The options, measured
From the live checkpoint, 60,000 frames per arm (16.7 brain minutes), real palette. The driver
is harness choice, not the fly's:
| arm | trainer battles (L lost, W won) | trainer beaten | Brock beaten |
| --- | --- | --- | --- |
| live favourite (TAIL WHIP 87%), seed 1 | LLLLLLLLL | no | no |
| live favourite, seed 2 | LLLLLLLL | no | no |
| uniform over the pad, seeds 1 / 2 / 3 | LLW / LLLLW / LLLW | f32,940 / f46,293 / f41,030 | seed 1 |
| BUBBLE whenever dealt | W | f12,234 | yes |
| TACKLE whenever dealt | LLLLLW | f59,253 | no |
| live favourite, stat-down move withheld once the target's stage is -1 or lower, seeds 1 / 2 | W / W | f9,165 / f9,304 | yes / yes |
| the same at -2, seeds 1 / 2 | LW / LW | f17,053 / f19,033 | yes / yes |
| the same at -3, seed 1 | LLLLLW | f54,551 | no |
- **Withhold a move with no effect on this target** (12.23's rule): it already applies, and TAIL
WHIP has an effect until -6. The fly faints at about that turn, so the rule changes nothing here.
- **Withhold a stat-lowering move once it has done something**: the -1 arm wins the first battle
on both seeds and then beats Brock. It is a pad rule about which move is good, not about what
the cartridge refuses, so it is a doctrine change for the operator. It would also hide GROWL,
SAND-ATTACK and similar moves after one use in every battle.
- **Reward damage dealt**: this is a reward-catalog change, out of scope for loop review, and it
cannot be measured without the brain. Nothing in the current catalog separates BUBBLE from
TAIL WHIP until a battle is won, and none is.
- **Watchdog detection plus the recovery ladder**: shipped (67b). Replayed probe by probe on the
live log with uniqueLocations proxied from the tile rewards, base check 10 first flags at 14:46
(`unrewarded`). The branch flags `unwon-battles` at 14:01, 14:16, 14:21, 14:36 and 14:41; a
tile reward at 14:06 and 14:26 clears one probe each. The healthy windows before the gym
(13 to 46 `MOVE n`, 1 to 4 wins each) are not flagged. The ladder's restart does not change the
readout, and a reset to PEWTER CITY replays the same gym. Only the reset to the rung below adds
forest battles, and whether that is enough was not measured.
## 2026-09-29, row 69: throw on low HP only, and the fly names its catch
### What was asked
Two operator decisions after row 66 (`docs/design/macros.md` 12.32). Row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag (66e), and every catch named
`AAAAAAAAAA`: `NEXT` answered the nickname offer YES and its A presses typed on the keyboard (66d).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 69 | at low HP the ball sat beside four moves, `SWITCH` and `RUN`, and the fly never chose it (66e) | a wild battle with a ball, the enemy at a third of its HP | `row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack` and four more unit tests, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` (`FLY_ROW69_CHECKPOINT`) | **operator decision, built**: with `THROW BALL` dealt and `ItemUseBall`'s HP factor saturated (`W >= 255`), the moves, `SWITCH`, `RUN` and the bag's `BACK` are withheld; `ITEM` stays for a hurt thrower |
| 69b | the keyboard read as the battle's between-turns frame, so `NEXT` typed the name (66d) | every catch | `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`, `the_naming_screen_is_its_menu_and_its_box_and_its_underscores` | **operator decision, built**: the keyboard reads `Unknown` and its pad is the fly's own D-pad, A, B and START |
| 69c | a keyboard nobody ends is a stall: B never leaves it and A stops typing at ten letters | a fly that does not press ED or START | `row69_a_fly_that_types_nothing_is_ended_by_the_bound`, `row69_confirm_on_the_keyboard_presses_start_until_it_closes` | **fixed**: once the name is full or sixty brain seconds have run, `CONFIRM` alone, which presses START until the keyboard closes (`blocked` after 160 frames) |
| 69d | row 66's `unknown_pads_with_no_box` counted the bound's `CONFIRM` on the keyboard, which is drawn without the text font | the rung-10 Pewter gym drive, which buys a ball and catches | `the_fly_reaches_the_pewter_gym_from_the_rung_ten_checkpoint` | **fixed in the test**: the keyboard is a drawn screen |
| 69e | the catch checkpoint's lead one-shots every forest Pokémon, so no wild HP is ever low there | `FLY_CATCH_CHECKPOINT` | -- | **left, named**: the low-HP ROM test uses a rung-9 Route 2 checkpoint (rung-9 A below: a Bulbasaur at 5/30, one ball) as `FLY_ROW69_CHECKPOINT` |
### Before and after
ROM tests (rom-env sourced, the build box), a69a258 against the branch:
| test | a69a258 | branch |
| --- | --- | --- |
| `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | 664 low-HP frames with the ball dealt, pad `MOVE 1`, `MOVE 2`, `MOVE 3`, `THROW BALL`. **Fails** | 58 frames, pad `THROW BALL` alone, thrown. Passes |
| `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends` | keyboard 511 frames, 11 `NEXT` starts, 0 raw frames, name `AAAAAAAAAA`. **Fails** | keyboard 1,516 frames, no macro, 1,516 frames of the fly's buttons, 7 letters at most, name `RIJ?`, closed by the fly (ED). Passes |
| `row69_a_fly_that_types_nothing_is_ended_by_the_bound` | `NEXT` types ten A's and ED. **Fails** | nothing typed; `CONFIRM` dealt once at the bound, span 3,587 frames, name empty (the species' own). Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | passes | passes (battle over 2,468 frames after the catch) |
With the connectome (`trap_hunt`, one sweep thread, 15 brain minutes, macro log). The runs vary the
starting state, as row 66's did: four rung-9 checkpoints with one ball each.
| checkpoint (lead, balls) | arm | wild battles with a ball | `THROW BALL` dealt frames / chosen | the throw's pad (frames) | catches | keyboard | rung, tiles, windows flagged |
| --- | --- | ---: | ---: | ---: | ---: | --- | --- |
| rung-9 A, Route 2 (Bulbasaur 5/30, 1) | a69a258 | 5 | 414 / 0 | -- | 0 | -- | 10, 520, 40 |
| | branch | 2 | 96 / 1, at low HP from the pad `THROW BALL` alone | 32 | 1 | 16.8 brain s, A 32, B 30, longest 1, name empty (the species'), ended by the fly (ED) | 10, 482, 51 |
| rung-9 B, Route 2 (Wartortle 9/70, 1) | a69a258 | 1 | 32 / 1, at full HP on the first frame | 0 | 1 | `NEXT` | 9, 300, 46 |
| | branch | 1 | 32 / 1, the same throw | 0 | 1 | 28.1 brain s, A 55, B 52, longest 1, name empty, ended by the fly (ED) | 9, 236, 43 |
| rung-9 C, the forest (`FLY_CATCH_CHECKPOINT`, Wartortle 18/70, 1) | both, identical | 1 | 32 / 1, at full HP, missed | 0 | 0 | -- | 9, 278, 18 |
| rung-9 D, the forest (the no-PP state, Bulbasaur 6/34, 1) | both, identical | 2 | 282 / 0 | 0 (never low with the ball dealt) | 0 | -- | 9, 285, 21 |
- **Throws and catches.** Three balls thrown in four runs on the branch, two catches; on a69a258
two thrown and one catch. The one run where they differ is the one whose wild HP passed a third
with the ball dealt: the fly threw from the throw's pad at once and caught. Two of the throws
were the fly's own choice from the ordinary pad on a battle's first frame, on both arms.
- **Names.** Both keyboards were ended by the fly's own A on ED, in 17 and 28 brain seconds, well
inside the bound. The brain's A and B fire at nearly the same rate there, so each letter it typed
it deleted again and both names came out empty, which the cartridge turns into the species'
name. That is the fly's spelling, kept as it is.
- **Stalls.** None from this row. Every run ends its battles; no keyboard reached the bound. The
flagged windows are `NEXT` runs through battle text on both arms (and on the branch's rung-9 A run
five `GO ROUTE, GO HEAL` windows, row 62's tug, 65h). The branch's rung-9 B run covers fewer tiles
after the keyboard because its frames after the catch differ from a69a258's (the keyboard took
28 brain seconds instead of `NEXT`'s few), not because anything waited: 635 macros started, 633
done, one refusal and one timeout, against 803, 802, one and one.
## 2026-09-29, row 68: the damage reward, the catalog's answer to row 67
Row 67 (the Pewter Gym's Jr. Trainer lost on repeat, TAIL WHIP 155 / BUBBLE 23 / TACKLE 0) is a
readout choice, not a pad fault. The operator chose a catalog change over a pad rule: `damage`,
adapter `pokered-unique8-v8` (`docs/rewards-learning.md`, "Damage rewards"). It pays for the HP the
fly's own attack removes; it does not touch the pad.
### The survey
The real brain, macros mode, from the row 67 checkpoint, 120 brain minutes per arm, `v7` (main)
against `v8` (the rule), on the stream's own frame (`LegacyFrame`). The palette seed turned out not
to diversify a run (seeds 1, 2 and 3 were identical per arm), so the three pairs are three starts:
the checkpoint as it is, and the checkpoint with the game run 7 and 19 frames ahead of the brain.
Each pair is identical until the first damage payout.
| start | arm | trainer battles | won | BUBBLE share, first 40 / last 40 min | damage paid | rung |
| --- | --- | ---: | ---: | --- | ---: | --- |
| +0 | v7 | 68 | 0 | 14% / 17% | -- | 10 |
| +0 | v8 | 58 | 3 (Jr. Trainer at 101 min, Brock at 107, a Route 3 trainer at 112) | 15% / 20% | 6.01 | **11, BOULDER BADGE** |
| +7 | v7 | 65 | 0 | 16% / 21% | -- | 10 |
| +7 | v8 | 67 | 0 | 14% / 14% | 3.41 | 10 |
| +19 | v7 | 60 | 0 | 15% / 24% | -- | 10 |
| +19 | v8 | 59 | 1 (Jr. Trainer at 119.6 min) | 16% / 22% | 6.74 | 10 |
TACKLE stayed at 0 to 2 choices a run in every arm.
**What it shows.** The rule fires where it should: every `v8` arm was paid for BUBBLE's hits and
nothing for TAIL WHIP's, 3.4 to 6.7 over two hours, capped per battle. `v8` beat the trainer in 2
of 3 starts and `v7` in 0 of 3 (and the live run 0 of 29). **What it does not show** is the
mechanism the rule is for: the move choice did not move more under `v8` than under `v7`. BUBBLE
drifted from about 15% to about 20% in both arms, and TAIL WHIP stayed near 80% everywhere. So
inside two brain hours the wins are not explained by a learned preference; a paid hit also changes
the brain's activity (the PAM stimulation) and the trajectory, and three starts cannot tell a small
real effect from luck. Learning is too slow to show in this window, or not happening, and the
survey cannot say which.
**Status: shipped as the operator decided, not a fix.** The trap is still possible under it: one of
three `v8` starts never won. Row 67's watchdog check 10 (`unwon-battles`, on its branch) is the
detector, and the pad rule the operator declined is the lever that still exists.
## 2026-09-30, row 70: Mt. Moon, the SHIFT offer's party list, and the ladder that took the catch
### What was live
On v0.7.0 with adapter v8, the ladder reset the run to rung 11 at 16:54Z. The rung-11 archive
replayed deterministically: Route 3's trainers, Mt. Moon (rung 12) at 17:40, a Poké Ball bought,
thrown, and a Zubat caught at 17:47 (`OWNED #41`, `CAUGHT #107`). At 17:52 a Lass's battle on 1F
started. From then on the log was `NEXT start/done` every 0.8 brain seconds and nothing else: no
reward and no other macro for 58 brain minutes. Check 10 flagged `dominant`/`sequence` (`NEXT`
100%). At 18:50 the ladder, at level 2 since the 16:54 reset, reset the run to rung 11 again and
erased the catch. The replay after that reset matched the one before it event for event (the same
`brainMs`), so it was heading into the same trap at about 19:48.
### Reproduction (durable generation 250877, pulled from the reset's archive)
`wIsInBattle` 2 and the Lass (`wTrainerClass` 3), with Oddish beaten and Bellsprout L11 next.
Wartortle L19 was at 0/58, Zubat L8 at 24/26 and out. The party list was open with
`wPartyMenuTypeOrMessageID` = BATTLE_PARTY_MENU and the cursor on the Zubat. The screen read
"ZUBAT is already out!". The seam read `forced_switch`, so the pad was `SWITCH, NEXT`, and `SWITCH`
had no healthy Pokémon to go to. Driven from the checkpoint on v0.7.0, the pad was `NEXT` on
6,000 of 6,000 frames: 125 `NEXT` starts, every one "already out" and the list again.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 70 | the SHIFT style's "Will <mon> change POKéMON?" offer opens the party list with BATTLE_PARTY_MENU, which the seam read as `ChooseNextMon`'s forced switch. Its pad `SWITCH, NEXT` had no B; `NEXT` on the Pokémon already out rings forever | any trainer battle with two or more Pokémon in the party, the fly answering YES (the first catch made it possible) | `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` (`FLY_ROW70_CHECKPOINT`), `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` (`FLY_ROW70_FORCED_CHECKPOINT`) | **fixed**: forced switch = BATTLE_PARTY_MENU **and** the active battler at 0 HP (`docs/design/macros.md` 12.33). The offer is the fly's turn, and its pad is `SWITCH` (when someone can go out) and `BACK` |
ROM tests on the build box (rom-env sourced):
| test | v0.7.0 | branch |
| --- | --- | --- |
| `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` | 6,000 frames in the list, `NEXT` on all of them, `BACK` on none, never left. **Fails** | `BACK` from f3. "LASS sent out BELLSPROUT!", then the fly's turn at f194. Passes |
| `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` | passes | 881 forced frames, all read as forced, `SWITCH` on all of them, `BACK` on none. The Zubat goes out, and the fly's turn comes at f1,102. Passes |
The stub reaches row 70 by itself. From the live rung-12 archive (Mt. Moon's mouth, one ball),
three uniform-stub seeds each catch a Zubat within 4,000 frames and meet the same Lass. There
Wartortle faints at f27,361, f34,656 and f35,284.
### The watchdog and the ladder: every act was on a real trap
The day's six acts, replayed probe by probe through check 10 and the ladder from the live logs
(open loop; uniqueLocations proxied from the tile rewards). The base replay reproduces the live
history: restarts at 05:55, 08:55 and 11:55, and resets to rung 11 at 16:50 and 18:49 (live:
16:54 and 18:50).
| live act | window | what the fly was doing |
| --- | --- | --- |
| restarts 05:57, 08:58, 11:59 (map 59) | `unwon-battles`, 05:50 to 13:50 | Row 67 again, against a Lass on Mt. Moon 1F. `MOVE 2` (TAIL WHIP) on six turns in seven, BUBBLE doing 5 to 8 to her Oddish, 34 to 48 moves per window, no battle won, whiteout and back. Beaten after the 11:59 restart (13:54, then the other 1F trainers, B2F's and the Super Nerd) |
| reset to 11, 16:54 (map 61, B2F) | `unrewarded`, 15:05 to 16:50 | A wild encounter every ~20 s, `RUN` every time (220), `GO FRONTIER`/`GO WARP` between them, and no new tile or reward for 1 h 50 min. The battles were ending and the fly was moving between them, but on ground it had already covered. Mechanism not established: no checkpoint from before 16:54 survives (row 64/65 territory, B2F's far side) |
| reset to 11, 18:50 (map 59) | `dominant`/`sequence`, 17:59 on | Row 70's list: `NEXT` alone for 58 brain minutes |
So check 10 read no cave as a trap. Healthy cave windows (17:04 to 17:54: Route 3 and Mt. Moon
battles won, a catch, new areas) peaked at 94% `NEXT`, and the tile gate kept them clear. Two
suggested relaxations are **not** supported by the evidence:
- "Battles ending and the fly moving between them": the 16:54 window was exactly that for
1 h 50 min, with nothing new.
- Counting the damage reward's KO as a win: the Lass ring had 45 KOs of her first Pokémon in
eight hours and never won.
The watchdog's flags are unchanged. Every replayed log (rows 58, 60 to 64, 67, 70) flags on the
same probes with the same reasons, base and branch.
What went wrong was the ladder. It stayed at level 3 to 4 from the morning's ring through a
rung-11 reset and a full, rewarded climb back to Mt. Moon. The 18:50 reset then restored the
same rung-11 archive as the 16:54 one. A restore is deterministic: the replay after it matched
the one before event for event (1,138 of 1,138, same `brainMs`). So the reset erased the catch
and walked back into the same list about an hour later. It also could not have helped: row 70's
trap is in the game state, not the ledgers, so neither a restart nor a replay clears it.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 70b | the ladder never started over after real progress. A trap after a reset and a rewarded climb back was treated as the old trap outliving its step | a reset, then progress, then any trap | `test_progress_after_the_last_step_starts_the_ladder_over`, `test_progress_while_a_step_settles_does_not_start_the_ladder_over` | **fixed**: `window.progress` in loop.json (report only; `lint.sh` check 10 case 9). New lasting progress more than `SETTLE` after the step, once a clear probe shows the trap let go, returns the ladder to level 0 (see 70f) |
| 70c | a reset restored the same archive as the last reset, which replays deterministically into the same trap | level 2 and above, where every step targets the rung below the best | `test_the_last_resets_archive_is_not_restored_again`, `test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it` | **fixed**: that step is a restart |
| 70d | a reset erased a catch made an hour earlier | any reset after a catch | `test_a_species_owned_recently_is_never_reset_away`, `test_a_probe_that_owns_a_species_starts_the_protection` | **fixed**: within two hours of a species first owned, a reset is a restart (held three hours apart) |
| 70f | (review r3) a reset's replay counted as progress. The restored reward ledger pays the archive's areas, trainers, species and rung again, so 70b started the ladder over after every reset, and a replayed catch opened a second protection window. A trap only the rung below escapes took 5.6 h (6.8 h after a catch) to reach it, against 2.1 h in v0.7.0 | a reset whose replay re-earns rewards, then traps | `test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over`, `test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected`, `test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over`, `test_a_trap_only_the_rung_below_escapes_is_reached_promptly`, `test_restarts_are_a_hold_apart_in_every_closed_loop` | **fixed**: `window.progress.keys` names each lasting reward (`lint.sh` check 10 case 9); progress and protection count only names the ladder has not seen (`progressSeen`). 2.1 h (3.3 h after a catch). Restarts stay three hours apart, and a failed reset does not mark its archive |
| 70e | the B2F wander: `RUN` from every encounter, walks on covered ground, nothing new for 1 h 50 min | Mt. Moon B2F after the Super Nerd | -- | **left, named**: no checkpoint survived. The next occurrence should be pulled before any reset |
Ladder replay of the day (the same logs and the same start state, base against branch):
- **Base**: restarts at 01:30, 05:55, 08:55, 11:55 and 15:10; resets to 11 at 16:50 and 18:49.
- **Branch**: restarts at 01:30, 05:55, 07:15, 10:30, 13:30 and 15:10; a reset to 12 (the
current rung, not 11) at 16:50; a restart at 18:04.
- 07:15: AREA 60 at 06:48 started the ladder over.
- 18:04: the climb after 16:50 started the ladder over.
- After 18:04, no reset. The Zubat was owned at 17:46 and rung 12 was the last reset's
archive, so the branch holds to restarts three hours apart.
- **Review r3** (names, from a live-like 00:00 state, then the post-16:54 log with the state carried
over): restarts at 01:30, 05:55, 08:55, 11:55 and 15:10, as live; a reset to 12 at 16:50 (the
13:54 to 14:20 trainers were new, so the ladder had started over). After 16:54 the Route 3
trainers, AREA 59, OWNED #8 and the rung are the replay's and do not count; OWNED #41 (the
Zubat, 17:46) is new, so a restart at 18:04 and then the protection hold through 18:54, no reset.
The replay is open loop: the log after 16:50 is what the base's reset produced.
## 2026-10-01, row 71: Route 25, a ball past the bag's window
### What was live
v0.7.3 legacy, adapter v8, rung 15 (NUGGET BRIDGE), map 36 (Route 25), two badges. After the
Route 25 trainers, a wild battle began. The pad held `THROW BALL` alone and every start was
`blocked`: 131 of 131 in ten minutes, about two hours in all. A flysim restart restored a hot
generation from inside the same battle with the same bag open, so the trap came back at once. The
coordinator then reset the run to milestone 15.
### Reproduction (hot generation 263767, inside the trap)
- The state: `wIsInBattle` 1 (wild, not a trainer), a wild Oddish L13 at 8/36, Wartortle L35 at
21/105 with PP left (only GROWL at 0).
- The bag: TM34, HELIX FOSSIL, NUGGET, TM45, POKé BALL x2. Party of 2, Oddish not in it.
- The bag was open with `wListScrollOffset` 3, so the window showed TM45, POKé BALL and CANCEL,
with the arrow on row 1, the ball.
- Row 69's rule (enemy HP low for the ball) withheld everything but the ball.
- `THROW BALL` aims at bag index 4. The seam reported the window row (0..2) as the cursor, so the
cursor step walked between rows 1 and 2 until its budget ran out.
The hypotheses in the brief were all checked:
- **A trainer battle.** No, it is wild.
- **No balls in the bag.** No, there are two.
- **The ball counted wrong.** Its index was right; the cursor reading was wrong.
- **RUN, or PP.** Not involved.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 71 | the battle bag's cursor was read as the window's row, so a bag entry past the third could never be reached; with row 69's low-HP rule, `THROW BALL` alone on the pad and blocked for ever | any wild battle against a species not in the party at low HP, with the ball fourth or later in the bag (`ITEM`'s Potion likewise, without the trap) | `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn`, `row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`), `row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` | **fixed**: cursor = `wCurrentMenuItem + wListScrollOffset` (`$CC36`, pinned from the cartridge; `docs/design/macros.md` 12.34). The mart's lists read the same way; `MART_CURSOR_ROWS` stays |
| test | 390d118 | branch |
| --- | --- | --- |
| `row71_a_ball_past_the_bags_window_is_thrown` | 11 starts, 10 `blocked`, nothing thrown in 3,000 frames. **Fails** | thrown, Oddish caught (`wCapturedMonSpecies`) by f350, 0 `blocked`. Passes |
| `a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_label`, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | pass | pass (balls in the window's first rows, unscrolled) |
Trap hunt, 10 brain minutes with the real connectome from the trap checkpoint:
- **390d118:** 33 of 33 windows flagged, 1 tile, `THROW BALL` 131 starts and 131 `blocked`. That
matches the live count exactly.
- **Branch:** 1 of 33 flagged. That window is the opening battle text, with 71 tiles in it. The
ball is thrown on the first hold and the Oddish is caught at 0.10 min. The fly ends the keyboard
itself, and the run reaches 91 tiles.
The watchdog and the ladder flagged the trap correctly. The restart could not help, because the
trap is in the game state and the hot checkpoint is inside it (row 70's lesson again). Only a reset
or the fix ends it.
## 2026-10-02, row 73: Route 25 and Bill's house, a PC no macro could press, and Cerulean's south
### What was live
v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. After row 71's battle trap was fixed the fly kept a
busy ring with no progress: `GO ROUTE` into Bill's house (`$58`, door (45, 3)), `GO OBJECTIVE` or
`GO OUT` straight back out. Scout B3 measured it from the live checkpoint: on six seeds (2.8
brain hours) the pad in the house was always `GO OBJECTIVE, GO OUT, GO NPC, GO FRONTIER`, `GO OUT`
16-51 and `GO OBJECTIVE` 16-60 starts per ten brain minutes, `GO NPC` 0 in about 600 starts, and
new tiles 2527 to 2531 in 35 minutes. Rung 16 was never earned.
### Mechanism
- **Rung 16's place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`. A fly on Route 25 was
already there, so in the house `GO OBJECTIVE` was an exit into the objective's map: the same
door as `GO OUT`.
- **The errand's middle step was unpressable.** The ticket is Bill's errand
(`scripts/BillsHouse.asm`): talk to Bill as a Pokémon, press the cell separator's PC at (1, 4)
facing up, talk to Bill when he steps out. The PC is a hidden event (`wNumSigns` 0, one sprite),
and no macro aimed at hidden events or dealt `TALK` in front of one. Scout B3 confirmed the
press on the cartridge by hand.
- **After the ticket, the town is two pieces.** Cerulean's town ground ends at row 28; Route 5 is
on the ground behind the trashed house (`$3e`), in by its front door and out by the hole in its
back wall. The house was off the map graph, so `GO OBJECTIVE` toward Vermilion ended `blocked`
at (17, 28) and the fly rang between the town and its houses (scout: 0 of 6 seeds past row 28 in
43 brain minutes each, from a carry-forward made by scripted presses).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 73 | rung 16's place was Route 25, so inside Bill's house `GO OBJECTIVE` and `GO OUT` were both the door; the errand's PC is a hidden event no macro could press; after the ticket, Cerulean's south was off the graph | rung 15 on Route 25 (live), and any fly with the ticket in Cerulean | `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`, `a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`, `a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`; `row73_*` in `rom_macros_mode.rs` (`FLY_ROW73_DOOR_CHECKPOINT`, `FLY_ROW73_PC_CHECKPOINT`, `FLY_ROW71_CHECKPOINT`, `FLY_ROW73_SOUTH_CHECKPOINT`, `FLY_ROW73_TRASHED_CHECKPOINT`, `FLY_ROW73_TICKET_CHECKPOINT`) | **fixed**: rung 16 is `errand(BILLS_HOUSE)`, people then things; hidden events read from the cartridge's own table (`$11:$6A40`/`$6A96`), only ever as the errand's next step, faced from the side the entry names (`docs/design/macros.md` 12.35, `macros-wram.md` 17); Cerulean's third piece and the trashed house on the graph |
| 73a | the road from Route 5 to Vermilion is plain map edges through Saffron, whose gates are guarded until the drink; the Underground Path's houses are off the graph | a fly on Route 5 with rung 17 next | none yet | **left**: predicted, not reached by the scout; the branch hunt's flies reach Route 5's gate (`$46`) and the Underground Path house (`$47`). Needs its own checkpoint and row |
| test (stub rotation) | 74a3c12 | branch |
| --- | --- | --- |
| `row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door` | no ticket in 36,000 frames, out of the house and the Route 24/25 ring. **Fails** | ticket at 4,743 frames, never out of the house. Passes |
| `row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket` | no ticket in 36,000 frames. **Fails** | ticket at 2,116 frames. Passes |
| `row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket` | no ticket in 216,000 frames (60 brain minutes), 1,019 times into the house and 1,019 out. **Fails** | ticket at 9,876 frames. Passes |
| `row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` | aims at the town's bottom row (unreachable). **Fails** | the house's front door, then the hole in its back wall. Passes |
| `row73_the_fly_takes_the_trashed_house_south_to_route_5` | trashed house 54,442; ticket carry-forward not in 48,000 (63,880). **Fails** | 52,081 and 27,067. Passes |
| `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` | does not compile (new seam) | passes |
Trap hunt, real connectome, 15 brain minutes per seed, six seeds per arm. The palette seed does not
make runs differ (row 68), so the seeds are the game run 0, 7, 19, 41, 97 and 211 frames ahead of
the brain before the first hold (scout B3's `FLY_TRAP_AHEAD`, a scratch patch, not committed):
| from | arm | rung 16 | distinct (map, tile) | Bill's-house ring (`GO ROUTE` / `GO OUT` / `GO OBJECTIVE` at net 0) | reached Route 5 |
| --- | --- | --- | --- | --- | --- |
| live row-71 checkpoint (rung 15, Route 25) | 74a3c12 | 0 of 6 | 83-105 | 36-47 / 18-22 / 18-27 per seed | 0 of 6 |
| live row-71 checkpoint | branch | **6 of 6**, at 2.0-2.3 brain minutes | 200-517 | 2-24 / 3-30 / none at net 0 (the walks go somewhere) | 3 of 6 inside the 15 minutes |
| ticket carry-forward (rung 16, Bill's house) | 74a3c12 | (has it) | 328-400 | -- | 0 of 6 (ends in the town, the bike shop or the centre) |
| ticket carry-forward | branch | (has it) | 273-439 | -- | **5 of 6**; four of them on into Route 5's gate (`$46`) or the Underground Path house (`$47`) |
The two-minute window flags do not measure this trap: the ring crosses more than four tiles, so
the base arm flags only the opening battle text (1 of 53), and the branch arm's flags (28-49 of 53)
are `NEXT` runs inside long battles it now reaches -- the Rocket in the yard behind the trashed
house and Route 24/5 trainers (one battle 23,954 frames and 462 macros; the base's ticket seed 19
has the same 17,235-frame battle). Every one ended; none is a ring. Route 5 is counted from the
hunt's text-box maps and its final map, so it is a floor.

View file

@ -282,7 +282,7 @@ pct exec $CTID -- /opt/fly/bin/fly-reset-to-milestone $N
# (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5. # (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5.
# (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's # (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's
# adapter so the gate and flysim both migrate instead of refusing: # adapter so the gate and flysim both migrate instead of refusing:
FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 infra/05-deploy.sh <release-env> <release-tarball> FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 infra/05-deploy.sh <release-env> <release-tarball>
# The gate logs "the adapter version is the only difference, and it is named; the run is KEPT # The gate logs "the adapter version is the only difference, and it is named; the run is KEPT
# and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the # and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the
# same rule at restore. Anything else about the string differing is still a refusal. # same rule at restore. Anything else about the string differing is still a refusal.
@ -443,6 +443,612 @@ 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.
- **The session on the bus (BUS-01).** `fly-runtime session --bus` (or `session-bus`) runs the
session's participants on the flybus router over Unix sockets: `flysim-session` (the router, the
coordinator, the listeners) starts `fly-session legacy-agent` and `fly-session legacy-environment`
as children of the same unit, in `flysim.slice`, on flysim's CPUs. The drop-in gains
`Environment=FLY_SESSION_TRANSPORT=bus`; `fly-runtime status` prints `session` and then
` transport: bus`. `fly-runtime session` without a flag (05-deploy's refresh) keeps the transport
the drop-in has; `fly-runtime session --local` goes back to the in-process lane, and
`fly-runtime legacy` to legacy. The fallback, the probation, the watchdog and the unstick rule's
restart are the same on either transport: one unit, restarted as a whole, children included
(`ps -o pid,args --ppid $(systemctl show -p MainPID --value flysim)` lists them). A deploy
refuses a release without `fly-session` while the drop-in says `bus`. **Before switching onto the
bus, run a shadow of it** (Shadow run below): with the live fly on legacy (`fly-runtime legacy`),
`fly-shadow-run start --bus`, three hours, then `fly-shadow-run check --bus && fly-runtime
session --bus`. Watch `fly_frame_work_mean_ms` and `fly_frame_work_p99_ms` on `/metrics` (the
loop's compute time per frame, without its pacing sleep, over the last 3,600 frames; the budget
at real time is 16.74 ms): they show the headroom that a realtime factor of 1.0 hides.
- **Per-frame compute time, both runtimes.** `/metrics` exports `fly_frame_work_mean_ms`,
`fly_frame_work_p99_ms`, `fly_frame_work_max_ms` and `fly_frame_work_frames` for the legacy loop
and the session runtime alike: everything one running iteration does except the pacing sleep.
Headroom is `1 - mean / 16.74` at real time.
## Feed over the bus (EDGE-02)
`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before
EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`,
`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way
(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes,
on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the
capture never see the difference.
**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the
env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it
says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not
failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the
edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s
stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by
hand, and flysim and the edge cannot disagree.
```
pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters
pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy)
pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back
```
### The live procedure
Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`),
`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is
claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`,
`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch
restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the
restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run
continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit
(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes
of two other restarts.
```
# 1. Before: the baseline to compare with (keep the output).
pct exec $CTID -- /opt/fly/bin/fly-feed status
pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "'
pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's
# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints
# "healthy (bus): the page is on the feed and frames are moving", exit 0.
pct exec $CTID -- /opt/fly/bin/fly-feed bus
# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this
# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the
# env file's value; flysim applies it at its next restart.)
# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day.
pct exec $CTID -- /opt/fly/bin/fly-feed status
```
What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes
`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner
kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`),
waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while
`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with
`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA`
back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback`
leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM
or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted
`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and
`/var/lib/fly/feed.log`.
### What to watch
| Where | Healthy in bus mode | Wrong looks like |
| --- | --- | --- |
| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` |
| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) |
| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` |
| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare |
| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy |
| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back |
| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` |
| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer |
The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that
changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed
counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers
`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then
the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the
fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly
those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator
switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather
than restarting a page that has nothing to connect to, and its chain ends with the edge and the
encoder.
### Rolling back
- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own
feed, stops a lingering edge. It needs nothing from the release (it works on one without
`fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so
count it against the start limit.
- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and
`fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both
runtimes.
- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while
the env file says `bus` or the container is in bus mode: `fly-feed direct` and set
`FLY_FEED_VIA=direct` in the env file first, then roll back or deploy.
- A reboot keeps whatever `fly.env` says.
### What the rehearsal measured
Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome,
macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real
stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed`
and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so
**real-time factor is not comparable between the two runs**; the numbers below are the ones load does
not move much. The live switch is the real A/B: take the step 1 baseline and compare.
| Measure | direct | bus |
| --- | --- | --- |
| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs |
| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) |
| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) |
| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs |
| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run |
| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both |
| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box |
| Page | 0 decode errors | 0 decode errors, gaps only under that load |
Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM
restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once)
each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and
sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of
flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores
from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the
feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after
the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge
back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to
direct with the page connected again. The live restart is longer than these 6 s by the real
restore and warm-up; use the unstick rule's usual time.
### Notes
- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and
`fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*`
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
counters.
- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and
the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking
pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the
operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as
`FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to
the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about
1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the
critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof
flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the
deploy, restart flysim, and only then `fly-feed bus`.
- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A
reboot empties it; a crashed flysim's directory is removed by the next one.
- **Control (`:7401`)** stays in flysim and is not part of this switch.
## 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, remote shadow + guard, one flysim restart
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (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
```
- **A shadow of the bus topology (BUS-01).** `start --bus` runs the box's shadow session with its
agent and world as child processes on its router's sockets (`FLY_SHADOW_MODE=bus/process`, which
the relay forwards); `check --bus` also requires that the verdict ran that topology
(`candidate.transport` `bus`, `executionMode` `process`). The live fly must be on the legacy
runtime for any shadow: only the legacy loop writes the trace, and `start` refuses otherwise.
- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
further behind every hour. `start` refuses without the remote configuration below; `start --local`
runs it on the container anyway. In remote mode `flyshadow.service` on the container is the
*relay* (`fly-shadow relay`, from a drop-in `start` writes): normal scheduling off flysim's CPUs,
a few file reads and one outbound ssh stream that carries the trace, the new saves and the sugar
journal to the box and brings the box shadow's verdict back to `/srv/fly/shadow/verdict.json`.
The guard, `check` and CUT-01 see the unit and the files they always did. Set-up below
("Remote shadow set-up").
- **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`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this
run's id: the start's Unix ms);
2. starts `flyshadow.service` and waits for its heartbeat (remote: up to 5 minutes, while the
box resets its mirror, restarts its shadow for the new run and reports it alive);
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);
- remote: `/srv/fly/shadow/relay.json` is less than a minute old and `healthy` (connected, the
box's shadow of this run alive, the sync caught up), and the verdict is this run's (`runId`);
its `lagTransitions` counts the live trace not yet on the box as well;
- 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);
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
a trace that is not being written while the shadow claims to follow refuses the check (a paused
flysim refuses too, until it runs);
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
refuse (safe, not silent). Run NTP on both;
- 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 (remote: the box deletes its copy, and the relay then deletes
the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that
stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
gap, never a skip. The shadow discards the brain time and saves compared before it
(`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
`coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
new window has compared the required time.
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
would have to restart while the stopped trace is still the newest file and reach its stop before
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
one.
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
and the run is lost (safe: start a new run as above); do not rely on the fast case.
`coverageLost` is synced to disk before the chunk with the stop is forwarded.
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
counts against it; if the guard trips on a remote run, the trace alone is too much for the live
fly's headroom. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
- **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-ins, 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. Remote, the box's shadow keeps running idle until
the next `start`, which resets its mirror and restarts it for the new run.
- **Remote divergence**: the box's shadow stops (exit 3); the relay brings `divergence.json` and
both checkpoint files back to `/srv/fly/shadow/`, writes the diverged verdict and exits with
status 3 (the unit stays stopped, the guard stops itself). Pull the files from the container as
for a local divergence.
### Remote shadow set-up (SHADOW-02)
Once per build box, and again for every release the container runs. The real values (the box's
address, the key's path) go in the operator's private files, never in this repository. Nothing
on the build box can reach the release container: the container dials out.
1. **The relay's key**, on the release container (as root, claimed):
`install -d -o root -g fly -m 0750 /etc/fly/shadow-remote`, then
`ssh-keygen -t ed25519 -N '' -C fly-shadow-relay -f /etc/fly/shadow-remote/id_ed25519` and
`chown fly:fly /etc/fly/shadow-remote/id_ed25519*`. The private half never leaves the container.
The container needs an ssh client (`openssh-client`; `02-base.sh` installs it) and no sshd.
2. **The box** (as root on the box): copy the release tarball the container runs, the cartridge,
`infra/box/` and the public key there, then
`infra/box/fly-shadow-remote-setup flybrain-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
`/etc/fly/shadow-remote/known_hosts` on the container (`ssh-keyscan` from the host, checked by
hand).
3. **The container's remote file**, `/etc/fly/shadow-remote.env` (root, 0600):
`FLY_SHADOW_REMOTE=flyshadow@<box address>`,
`FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
it and runs in remote mode.
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
after an hour. The ingest refuses a relay whose release directory or binaries
differ from the box's (another release on the container: re-run step 2 with its tarball);
`journalctl -u flyshadow` on the container shows it.
Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
with `--cpus` and `--threads`; keep other heavy work (bx) off that box
for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
## 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; on a build box
# (Remote shadow set-up above, once per box and release):
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).
## Control over the bus (CTRL-01)
`FLY_CONTROL_VIA` picks who serves `http://127.0.0.1:7401`: `direct` (the default; flysim binds
it) or `bus`. In bus mode flysim registers the control API as RPC services on its embedded flybus
router, and `flycontrol-edge.service` serves the same HTTP bytes on `:7401` by calling them
(`docs/design/flybus.md`, "Control over the bus"). Clients do not change: the bridge, the stage's
health wait, the watchdog, `fly-runtime`, the probation and shadow guards, `fly-loop-recover`,
the stream check and `curl` still talk to `:7401`. It works under either runtime, independently
of `FLY_FEED_VIA`. Claim the container in the host log first, as for any host work.
**Prerequisites.** The release ships `fly-control-edge` (`ls /opt/fly/current/fly-control-edge`).
The env file has `FLY_CONTROL_VIA=bus`, deployed with `05-deploy.sh`. The deploy only rewrites
`/etc/fly/fly.env` and pushes the unit; it neither enables the edge nor restarts flysim, so the
box keeps serving `:7401` directly until step 2.
```
# 1. Before: what the switch must preserve.
pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint'
pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from
# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of
# flysim.service, started with it because fly.env says bus) binds :7401 once they answer.
# Between the two, :7401 refuses connections, exactly as during any flysim restart.
# There is nothing to enable: the unit has no [Install] section.
pct exec $CTID -- systemctl restart flysim.service
# 3. Verify.
pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"...
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"}
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status' # the frame moves
pct exec $CTID -- curl -s 127.0.0.1:9103/metrics | grep -E '^fly_control_edge_(bus_connected|calls_total|call_failures_total)'
pct exec $CTID -- journalctl -u flysim -b --since -5min | grep -E 'control services registered|bus listening'
pct exec $CTID -- ls /run/fly/bus/control-edge.sock /run/fly/bus/control/
pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridge: sim reachable
```
- **Healthy looks like:** `fly_control_edge_bus_connected 1`, `calls_total` rising (the bridge and
the watchdog poll it), `call_failures_total` flat, no `fly-watchdog:` restart lines, and the next
real channel-points sugar fulfilled as before. Do not fire a test sugar or chat line on the live
stream to prove it; both are visible on screen.
- **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a
dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails
while flysim is healthy (the sudoers file grants exactly that restart).
- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=`
on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode
and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start`
(`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all
bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge
unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer.
**Rollback** (any time, no release change):
```
pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env
pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz
# then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back.
```
- **Rolling back to a release from before CTRL-01 while in bus mode** is safe. The older flysim
does not know `FLY_CONTROL_VIA`, so it binds `:7401` itself. The edge unit's
`ConditionPathExists=` keeps it inactive on a release without the binary, and the older
watchdog reads `:7401` as before. Switch to direct first anyway, so the env file says what
runs.
- **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port
cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim
was not restarted after the deploy. Restart flysim (step 2).
- **Upgrading a container that had the edge enabled** (before this wiring): an
old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but
run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true.
## 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
@ -492,6 +1098,78 @@ not a constant, and live in the operator's infra repo
ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh` ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh`
checks it against both the current shape and the earlier, narrower one. checks it against both the current shape and the earlier, narrower one.
### The sim's CPUs are exclusive to the sim (PERF-02 review N1)
The session runtime pins its sweep workers one per CPU. A pinned worker cannot leave its CPU, so
any sustained CPU-bound process that is allowed on a worker's CPU stalls every barrier: measured
**0.14x real time** with a plain busy loop (0.68x at nice 19; `SCHED_IDLE` was harmless; the
floating, unpinned runtimes held 0.86-0.94x under the same hog). Priorities cannot fix that, so
the partition above is completed by making the sim's CPUs exclusive:
- `flysim.service` and `flysim-session.service` run in **`flysim.slice`** (`units/flysim.slice`),
whose `AllowedCPUs=` is the sim's set (`flysim.slice.d/cpuset.conf`, written by `05-deploy.sh` from
`lib/common.sh`'s `cpuset_dropin_plan`, the same call that writes every other drop-in).
- `bin/fly-cpu-confine apply` sets `AllowedCPUs=` the **non-sim** CPUs on `system.slice` (every
other service, cron, apt, sshd), `user.slice` (every login session) and `init.scope`, and writes
the same list to `/sys/fs/cgroup/.lxc/cpuset.cpus` (where `pct exec` / `pct enter` processes land,
see below). It runs as
both sim units' `ExecStartPre` (root, failure never blocks the start), so it is re-applied after
every boot and every restart. The lists come from `/etc/fly/cpuset.env`, which the deploy writes.
- The slice is named without a dash on purpose: systemd nests `a-b.slice` under `a.slice`, and a
child's cpuset is bounded by its parent's (cgroup v2: effective cpus = own cpus intersected with
the parent's, and the parent's when that is empty). `flysim.slice` sits beside `system.slice`
under the root slice, so nothing above it excludes its CPUs.
- **Ordering rule.** Shrinking `system.slice` under a flysim that still sits in `system.slice` (a
unit started before this change, not yet restarted) would leave its own `AllowedCPUs=` outside the
parent's set and silently make it float over the page CPUs. So `apply` refuses (exit 3, nothing
changed) while a sim unit's cgroup is not under `/flysim.slice/`. A deploy therefore changes
nothing on a running sim; the confinement starts with the next `flysim` (re)start, which is the
first moment it is safe. `fly-cpu-confine status` shows the result.
- `fly-recap` and `fly-retention` also run at `CPUSchedulingPolicy=idle`, which the review measured
harmless beside the pinned workers (defence in depth for the batch jobs).
- **No partition, no pinning.** With `CPUSET` unset (or the container conf not matching it) there
is no confinement, so `05-deploy.sh` writes `FLY_SESSION_PIN=0` to `/etc/fly/fly.env` and the
session runtime's threads float, as before PERF-02. With the partition in force it writes
`FLY_SESSION_PIN=1`. (The runtime treats exactly `0` as off.)
- **`pct exec` / `pct enter`:** `lxc-attach` puts its processes in the cgroup `/.lxc` (or
`/.lxc-N`), a sibling of `system.slice` that systemd does not manage. `apply` writes the non-sim
list into the `cpuset.cpus` of every such cgroup that already exists (it never creates one; lxc
owns it). Where that file is not writable it logs a warning and carries on: `apply` never fails
the sim's start. In that case run long operator jobs through
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`. A `.lxc-N` created
after `apply` is not covered until the next sim start. `fly-cpu-confine check` lists every
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one); its own
process and the shell chain it was started from are printed as a note and not counted, so it
exits 0 on a healthy container when run through `pct exec`.
- **After the first deploy (once):** restart the sim so the confinement is applied, then read it.
`apply` is refused while flysim still runs outside `flysim.slice`, so nothing changes until then.
```
pct exec <ctid> -- systemctl restart flysim.service
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine status # system.slice, user.slice, init.scope and /.lxc = the non-sim cpus; flysim.slice = the sim's; flysim ControlGroup under /flysim.slice/
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine check # exit 0: "ok: only flysim.slice can reach ..."
pct exec <ctid> -- systemctl show -p AllowedCPUs flycast.service xvfb.service # still the drop-in values
```
Then watch the probation RTF. A `check` that names a process is a hog to move or stop.
- **If lag grows on the session runtime**: `fly-cpu-confine check`, then `top -H` for a stray hog on
the sim's CPUs. `FLY_SESSION_PIN=0` (a drop-in) restores floating.
- `fly-cpu-confine release` undoes the runtime confinement (until the next sim start); it sets
`system.slice`, `user.slice`, `init.scope` and `/.lxc` back to the container's whole cpuset
explicitly, because systemd keeps the old mask for an empty `AllowedCPUs=` while the cpuset
controller stays on for another unit. (Tested in `tests/lint.sh` against a fake cgroup tree.)
- **Rollback by re-running an older infra tree's `05-deploy.sh`** (rather than the symlink flip in
"Roll back a release", which is fine): an infra tree older than this change has no
`Slice=flysim.slice`, so flysim restarts into `system.slice`, which is still confined to the
non-sim CPUs. Its `AllowedCPUs=` then does not intersect that set and it floats over the page and
encoder CPUs while the sim's own CPUs sit idle (the slow shape again, not a black stream). After
such a rollback run `pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine release` (or reboot), then
restart flysim.
Verified on a real-systemd box (4 CPUs, the sim as a unit in `flysim.slice` on 3 of them, 3 sweep
threads, paced at 0.55x): confined or not, with no hog the session holds 0.55; five busy loops (three
as system services, two from a user shell) unconfined sit on the sim's CPUs and the session drops to
0.37; confined by the unit's own `ExecStartPre`, every loop samples on CPU 0 only, the sim's threads
keep their CPUs and the session holds 0.54-0.55.
### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition ### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition
`FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into `FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into
@ -504,13 +1182,49 @@ loud which backend is configured. Two separate switches, deliberately:
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed | | build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* | | run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file: backend from flysim's own log, not from the env file:
```sh ```sh
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend'
``` ```
The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables
(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without
the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with
`BACKEND_FAILURE`; a build with it logs `LIF backend cuda:<n> attached, device-owned state` when
the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the
card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual
drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the
feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too.
**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no
paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches
a dead card in a loop:
- A CUDA error on a frame whose host state was current (the first frame after a start or a
restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there.
- Any other CUDA error mid-run fails the agent (the device held the only current copy of the
membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on
the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact,
so the CPU run equals one that never had a GPU.
- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and
a CPU worker, not a failed `Agent.Initialize`.
- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still
dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU.
Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure,
with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs),
`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the
textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and
`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises
`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It
takes no remediation and pages no one (a restart cannot fix a dead card and would cost the
run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host,
and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2`
(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0`
and redeploy if the card is not coming back soon.
It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`. targets, `sm_75`.
@ -622,13 +1336,17 @@ pct exec <ctid> -- cat /run/fly/wd/loop.json | jq .
| `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window | | `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window |
| `fly_loop_done` | macros that ended `done` in the window | | `fly_loop_done` | macros that ended `done` in the window |
| `fly_loop_rewards` | reward events in the window | | `fly_loop_rewards` | reward events in the window |
| `fly_loop_fights` | `MOVE n` decisions (a move chosen in a battle) in the window |
| `fly_loop_wins` | battle-won reward events (`wildwin`, `trainer`, `badge`) in the window |
The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+ The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+
times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused, times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused,
blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row
(`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row (`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row
(`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other (`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other
names, every macro `done`) — **and** no growth in the exploration count. A decision is a `start` or a names, every macro `done`), or 24+ `MOVE n` decisions and no battle won on two probes in a row
(`unwon-battles`, row 67: one Pewter Gym trainer lost thirty times, whiteout and back, with a
stray tile reward now and then keeping `unrewarded` quiet) — **and** no growth in the exploration count. A decision is a `start` or a
`refused`: a refused press starts nothing, which is why counting starts alone read row 57's `refused`: a refused press starts nothing, which is why counting starts alone read row 57's
pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and
one name. A one name. A
@ -745,6 +1463,50 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
whichever container got there first lock the card out from under the other. whichever container got there first lock the card out from under the other.
## GPU on a build box (dev and benchmarks)
A build box is a container with the host's `/dev/nvidia*` device nodes passed through but no
userspace driver installed — used for the `cuda` feature tests and the GPU benchmarks. The
release container follows the lockstep runbook above; this path is only for build boxes,
no root, no system install, one userspace per test run.
**Get the host's module version** — the .run must match exactly:
```sh
ssh the host cat /proc/driver/nvidia/version # the "Kernel Module" line
# or: ssh the host cat /sys/module/nvidia/version
```
**Install under your home.** Download the matching `NVIDIA-Linux-x86_64-<ver>.run`, verify
its SHA256 against the checksum NVIDIA publishes, and `--extract-only`:
```sh
VER=580.76.05 # whatever the host module reports
mkdir -p ~/tmp/nvidia-$VER && cd ~/tmp/nvidia-$VER
U=https://download.nvidia.com/XFree86/Linux-x86_64/$VER/NVIDIA-Linux-x86_64-$VER.run
curl -fSLO $U && curl -fSLO $U.sha256sum
sha256sum -c NVIDIA-Linux-x86_64-$VER.run.sha256sum # must print OK
sh NVIDIA-Linux-x86_64-$VER.run --extract-only --target ~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
```
**Use it only for the test run.** Prepend the extracted directory to `LD_LIBRARY_PATH`
(`libcuda.so`, `libnvidia-ptxjitcompiler.so`) and `PATH` (`nvidia-smi`); the kernel
modules are the host's, so nothing else is needed:
```sh
NV=~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH FLY_CARGO_FEATURES=cuda \
cargo test --release -p flybrain-core --features cuda
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH \
cargo run --release -p flybrain-core --features cuda --example cuda_bench
```
**Shared card.** The build box shares the GPU with the LLM workload. Before and after each
timing run, `nvidia-smi` for other compute processes on the device; re-run flagged timings
(benchmarks yield to the other workload — a contended run is not a measurement).
**Never on the release container** — that path is the lockstep one above.
## The host reboot order ## The host reboot order
Fly containers have no special reboot ordering requirement relative to each other Fly containers have no special reboot ordering requirement relative to each other

View file

@ -49,7 +49,7 @@ a credential. Full list:
| # | shape matched | path | commits (first → last touching) | verdict | | # | shape matched | path | commits (first → last touching) | verdict |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/fly-pokemon-key`), not a secret. | | 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/<channel>-key`), not a secret. |
| 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. | | 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. |
| 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. | | 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. |
| 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. | | 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. |

4
infra/env/README.md vendored
View file

@ -53,6 +53,8 @@ requires `CTID`, `HOSTNAME`, `IP`, `GAME` and `PUSH_TARGET`; `ROLE` defaults to
Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app
id/secret arrive as the systemd credential `twitch-app`, installed by id/secret arrive as the systemd credential `twitch-app`, installed by
`infra/06-secrets.sh` from `pass` on the operator box; the OAuth tokens live in the `infra/06-secrets.sh` from `pass` on the operator box, reading the two entry **names** from
`BRIDGE_ID_KEY` and `BRIDGE_SECRET_KEY` in the real env file (it skips `twitch-app` with a
warning when they are unset); the OAuth tokens live in the
container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and
the ROM it describes is never committed, copied into the repo, or shown on stream. the ROM it describes is never committed, copied into the repo, or shown on stream.

37
infra/env/example.env vendored
View file

@ -138,6 +138,12 @@ RAYON_THREADS=3
# cpuset_partition (default 2 when unset). flycast gets its own group rather # cpuset_partition (default 2 when unset). flycast gets its own group rather
# than sharing the page group — see lib/common.sh's cpuset_partition header. # than sharing the page group — see lib/common.sh's cpuset_partition header.
ENCODER_CORES=2 ENCODER_CORES=2
# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in
# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when
# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the
# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs
# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`.
SESSION_AUX_CPUS=0
# --- CUDA LIF backend ------------------------------------------------------- # --- CUDA LIF backend -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what # 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
@ -216,6 +222,11 @@ TWITCH_CHANNEL=<twitch-channel>
# never is. 06-secrets.sh reads it on the operator box and installs it as a # never is. 06-secrets.sh reads it on the operator box and installs it as a
# systemd credential. # systemd credential.
PASS_KEY=twitch/<channel>-key PASS_KEY=twitch/<channel>-key
# The `pass` entries holding the Twitch app client id and secret (names only).
# 06-secrets.sh installs them together as the twitch-app credential; unset means
# it skips twitch-app with a warning.
BRIDGE_ID_KEY=twitch/<app>-client-id
BRIDGE_SECRET_KEY=twitch/<app>-client-secret
# --- flybridge (services/bridge/src/config.ts) ------------------------------ # --- flybridge (services/bridge/src/config.ts) ------------------------------
# 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads # 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads
@ -316,9 +327,21 @@ FLY_MACRO_MODE=raw
# Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the # Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the
# bus"). direct: flysim binds it, as always. bus: flysim publishes every # bus"). direct: flysim binds it, as always. bus: flysim publishes every
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves # snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
# the same bytes; enable that unit by hand (its header has the steps). # the same bytes. This line (written into fly.env by every deploy) is the only
# Watchdog check 2 follows this setting to the edge's counters by itself. # switch: flysim.service wants the edge, which starts only in bus mode.
# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts
# flysim, checks the page is back, rolls back by itself) and put the same value
# here afterwards, or the next deploy warns that it writes the old one back.
# Watchdog check 2 follows the running mode to the edge's counters by itself.
# Runbook: "Feed over the bus".
FLY_FEED_VIA=direct FLY_FEED_VIA=direct
# --- control path -------------------------------------------------------------
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,
# "Control over the bus"). direct: flysim binds it, as always. bus: flysim
# registers the control services on its embedded bus (/run/fly/bus) and
# flycontrol-edge.service serves the same bytes; enable that unit by hand
# (infra/docs/runbook.md, "Control over the bus"). Independent of FLY_FEED_VIA.
FLY_CONTROL_VIA=direct
# How long a macro leaves a target alone after a walk to it aborted "blocked" or # How long a macro leaves a target alone after a walk to it aborted "blocked" or
# "timeout" (macros.md section 12.1). Session state, so a restart offers every # "timeout" (macros.md section 12.1). Session state, so a restart offers every
# target once more. Unset means the default, 10. # target once more. Unset means the default, 10.
@ -335,9 +358,13 @@ FLY_FEED_VIA=direct
# two strings AND the new build's adapter declares a migration from that one. A # two strings AND the new build's adapter declares a migration from that one. A
# dataset, kernel, plasticity, emulator or state-format difference is still a # dataset, kernel, plasticity, emulator or state-format difference is still a
# refusal. Set it for the one deploy that needs it and leave it out afterwards; # refusal. Set it for the one deploy that needs it and leave it out afterwards;
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The v0.6.0 # 05-deploy writes it into /etc/fly/fly.env only while it is set. The deploy
# deploy (pokered-unique8-v7, the engagement rewards) is the one that needs: # of pokered-unique8-v8 (the damage reward) over the live v7 run needs:
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 # FLY_ACCEPT_ADAPTERS=pokered-unique8-v7
# and, to keep the milestone archives written before v0.6.0 restorable as
# fallbacks and fly-reset-to-milestone targets, also names v6 (v8 reads both):
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7,pokered-unique8-v6
# (v0.6.0's, pokered-unique8-v7 over v6, needed pokered-unique8-v6.)
# --- push mode -------------------------------------------------------------- # --- push mode --------------------------------------------------------------
# local: flypush.service stays disabled, everything else identical to prod. # local: flypush.service stays disabled, everything else identical to prod.

View file

@ -168,6 +168,19 @@ feed_via_normalize() {
esac esac
} }
# control_via_normalize VALUE — FLY_CONTROL_VIA as feed_via_normalize does FLY_FEED_VIA:
# lowercased (empty means "direct"), or return 1 for anything but direct|bus. flysim refuses
# anything else at boot; 05-deploy.sh refuses it at deploy and writes the lowercased word, which
# the watchdog reads to know who serves :7401 (docs/design/flybus.md, "Control over the bus").
control_via_normalize() {
local via
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
case "$via" in
direct|bus) printf '%s\n' "$via" ;;
*) return 1 ;;
esac
}
cpuset_partition() { cpuset_partition() {
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}" local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
@ -189,6 +202,69 @@ cpuset_partition() {
echo "$sim_cpus $page_cpus $encoder_cpus" echo "$sim_cpus $page_cpus $encoder_cpus"
} }
# cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's
# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's
# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu.
cpuset_aux_split() {
local page="$1" count="$2" n
n="$(echo "$page" | awk -F, '{print NF}')"
if [ "$count" -ge "$n" ]; then
die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS."
fi
echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)"
}
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service,
# flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine:
#
# flysim.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the
# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it);
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
# slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
# flycast the encoder CPUs;
# flyshadow page + encoder (never the sim's);
# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS);
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
# of CPUSET that is not the sim's, in CPUSET order.
#
# One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
# cpuset_partition does.
cpuset_dropin_plan() {
local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
local out
out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
read -r sim page enc <<< "$out"
if [ "$aux_count" -gt 0 ]; then
# not `read <<< "$(...)"`: die inside the substitution would only end the subshell
out="$(cpuset_aux_split "$page" "$aux_count")" || return 1
read -r page aux <<< "$out"
fi
slice_cpus="$sim"
[ -n "$aux" ] && slice_cpus="${sim},${aux}"
echo "flysim.slice $slice_cpus"
for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $slice_cpus"
echo "FLY_OTHER_CPUS= ${page},${enc}"
[ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux"
return 0
}
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to
# /etc/systemd/system/UNIT-NAME.d/cpuset.conf ([Slice] for a .slice, [Service] otherwise).
cpuset_dropin_text() {
local unit="$1" cpus="$2" label="$3" section="Service"
case "$unit" in *.slice) section="Slice" ;; esac
echo "# generated by infra/05-deploy.sh from CPUSET in ${label} — do not hand-edit."
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[${section}]"
echo "AllowedCPUs=${cpus}"
}
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# operator-box guard # operator-box guard
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -1,33 +1,32 @@
# infra/tests/de-pii-allow.txt — the mentions infra/tests/lint.sh's de-PII # infra/tests/de-pii-allow.txt — the mentions tools/pii-scan.sh (run by
# guard (section 5) is allowed to find. # infra/tests/lint.sh section 5, infra/build/tag-release.sh and the pre-push hook)
# is allowed to find.
# #
# Format, whitespace-separated: # Format, whitespace-separated:
# #
# <path> <pattern-name> # reason # <path> <pattern-name> # reason
# #
# <path> is a repo-relative path, a directory prefix ending in `/`, or a glob. # <path> is a repo-relative path, a directory prefix ending in `/`, or a glob.
# <pattern-name> is one of the guard's own names (host-proxmox, host-backup, # <pattern-name> is a pattern name: a generic one from tools/pii-scan.sh
# host-llm, operator-name, lan-address, container-id, host-root-path, # (`tools/pii-scan.sh --list`), one from the operator's private pattern list
# home-path, twitch-account, claim-log-name, forge-name, infra-repo-name, # (operator-name, forge-name, ...), or `*` for every pattern.
# mac-address, email-address, pass-entry-path), or `*` for every pattern.
# #
# EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead — # EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead —
# the rules and the per-file verdicts live in the operator's infra repo. # the rules and the per-file verdicts live in the operator's infra repo.
# An entry here says "this string is not identifying", not "this is grandfathered". # An entry here says "this string is not identifying", not "this is grandfathered".
# #
# The literals in the comments below are spelled with one bracketed character, for # Comments below describe what a mention is, never the private string itself: an
# the same reason lint.sh spells its patterns that way: an allowlist that carried the # allowlist that carried the plaintext would be the leak it is meant to prevent.
# plaintext would be the leak it is meant to prevent.
# --- chat-username fixtures ------------------------------------------------- # --- chat-username fixtures -------------------------------------------------
# Lowercase `"alex"` is the chat-username fixture the sanitizer, deny-list, # A lowercase first name is the chat-username fixture the sanitizer, deny-list,
# rate-limiter, ticker and store tests are written against; the de-PII sprint # rate-limiter, ticker and store tests are written against; the de-PII sprint
# leaves test fixture names alone. The guard's operator-name pattern is # leaves test fixture names alone. The operator-name pattern is case-sensitive
# case-sensitive precisely so capitalised `Al[e]x` in prose still fails, and # precisely so the capitalised name in prose still fails, and the real handle
# `al[e]x_camilo` (the real handle shape) was replaced with `fly_fan_42`. These # was replaced with `fly_fan_42`. These entries exist only for the few places a
# entries exist only for the few places a fixture is lowercase-with-a-boundary # fixture is lowercase-with-a-boundary that the pattern would still catch via
# that the case-sensitive pattern would still catch via another alternative. # another alternative.
apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file
@ -35,12 +34,12 @@ services/flysim/crates/flysim/src/eventlog.rs operator-name # ticker fixture in
services/bridge/tests/ operator-name # lowercase chat-username fixtures services/bridge/tests/ operator-name # lowercase chat-username fixtures
# --- container-side paths --------------------------------------------------- # --- container-side paths ---------------------------------------------------
# `/ro[o]t/nvidia.run`, `/ro[o]t/virtualgl.deb` and `/ro[o]t/nv.run` are paths INSIDE # `nvidia.run`, `virtualgl.deb` and `nv.run` under root's home are paths INSIDE
# a container: root's home on a stock Debian guest, not an operator-chosen # a container: root's home on a stock Debian guest, not an operator-chosen
# location, and not specific to this network. Host-side staging paths are # location, and not specific to this network. Host-side staging paths are
# parameterised instead (HOST_STAGE_DIR / `<host-stage>`). # parameterised instead (HOST_STAGE_DIR / `<host-stage>`).
infra/02-base.sh host-root-path # /ro[o]t/nvidia.run and /ro[o]t/virtualgl.deb are inside the guest infra/02-base.sh host-root-path # the two installer paths under root's home are inside the guest
docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ro[o]t/... which is procfs, not /root docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ root links, which are procfs
# --- documentation examples ------------------------------------------------- # --- documentation examples -------------------------------------------------
# A made-up MAC in a worked example of the compatibility string. Real MACs are # A made-up MAC in a worked example of the compatibility string. Real MACs are
@ -51,11 +50,16 @@ services/flysim/crates/flybrain-gb/src/compatibility.rs mac-address # aa:bb:...
# Third-party addresses and handles: upstream projects, not this network. # Third-party addresses and handles: upstream projects, not this network.
# (None currently; keep the section so the next one lands in the right place.) # (None currently; keep the section so the next one lands in the right place.)
apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit
infra/tests/lint.sh email-address # `lint@ex[a]mple.invalid`, the git identity for the throwaway test repos infra/tests/lint.sh email-address # the example.invalid git identity for the throwaway test repos
infra/tests/pii-scan-test.sh email-address # same example.invalid identity for the scanner's throwaway repos
# --- publish pack ------------------------------------------------------------ # --- publish pack ------------------------------------------------------------
NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred
LICENSES.md operator-name # same copyright line, mirrored LICENSES.md operator-name # same copyright line, mirrored
.forgejo/workflows/ci.yml forge-name # the product name of the CI runner (F[o]rgejo Actions), not the operator's forge .forgejo/workflows/ci.yml forge-name # the product name of the CI runner, not the operator's forge
.github/workflows/ci.yml forge-name # a comment naming the F[o]rgejo copy of this workflow .github/workflows/ci.yml forge-name # a comment naming the sibling copy of this workflow
infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path
infra/tests/de-pii-allow.txt forge-name # this file names the .f[o]rgejo/ workflow directory in the two entries above infra/tests/de-pii-allow.txt forge-name # this file names that workflow directory in the entry above
# --- fixtures ----------------------------------------------------------------
apps/stage/tests/unit/query.test.ts private-address # made-up address in a feed-URL parsing fixture
services/bridge/tests/ secret-assignment # fake client id/secret fixtures ("test-client-secret-DO-NOT-LOG")

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

File diff suppressed because it is too large Load diff

180
infra/tests/pii-scan-test.sh Executable file
View file

@ -0,0 +1,180 @@
#!/usr/bin/env bash
# infra/tests/pii-scan-test.sh — tests for tools/pii-scan.sh and tools/install-hooks.sh.
#
# Everything runs in throwaway repos under a temp dir, against a throwaway private pattern
# list. The fake identifying values are assembled at run time from pieces, so no complete
# fake value (and no real one) appears in this file for the tree scan to trip over.
set -euo pipefail
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
T="$(mktemp -d)"
trap 'rm -rf "$T"' EXIT
FAILS=0
ok() { echo "ok - $*"; }
bad() { echo "FAIL - $*"; FAILS=$((FAILS + 1)); }
# expect RC DESC -- CMD...: run CMD, capture output in $OUT, check the exit code
# the tree scan covers TRACKED files (git grep), like the guard it replaced
track() { git -C "$W" add -A; }
expect() {
local want="$1" desc="$2"; shift 3
local rc=0
OUT="$("$@" 2>&1)" || rc=$?
if [ "$rc" -eq "$want" ]; then ok "$desc"; else bad "$desc (exit $rc, wanted $want)"; printf '%s\n' "$OUT" | sed 's/^/ /'; fi
}
contains() { case "$OUT" in *"$1"*) ok "$2" ;; *) bad "$2 (missing '$1')"; printf '%s\n' "$OUT" | sed 's/^/ /' ;; esac; }
not_contains() { case "$OUT" in *"$1"*) bad "$2 (output leaks '$1')" ;; *) ok "$2" ;; esac; }
# --- fake private values, built from pieces -------------------------------------------
HOST="zorb""lequin" # a "host name"
PERSON="Quen""tavius" # a "person"
SECRET="fk""Q7pL2xV9""mZ4rT8wY""1nB6" # a "router key"
LAN="192.168"".77.21"
MAIL="someone""@""example.org"
mkdir -p "$T/private"
printf 'FAKE_ROUTER_KEY=%s\nSHORT=abc\n' "$SECRET" > "$T/private/router.env"
cat > "$T/private/patterns.txt" <<EOF
# test list
house-host -i ${HOST}
operator-name - \\b${PERSON}\\b
@values $T/private/router.env
EOF
export FLY_PII_PATTERNS="$T/private/patterns.txt"
# --- a throwaway repo with the scanner in it ------------------------------------------
W="$T/work"
git init -q -b main "$W"
git -C "$W" config user.name lint
git -C "$W" config user.email lint@example.invalid
mkdir -p "$W/tools" "$W/infra/tests" "$W/src"
cp "$REPO/tools/pii-scan.sh" "$REPO/tools/install-hooks.sh" "$W/tools/"
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
echo "hello" > "$W/src/a.txt"
git -C "$W" add -A && git -C "$W" commit -qm "init"
SCAN="$W/tools/pii-scan.sh"
expect 0 "clean tree passes" -- "$SCAN" --tree
contains "private list loaded" "private list is reported loaded"
expect 0 "--list prints names" -- "$SCAN" --list
contains "house-host" "--list includes private names"
not_contains "$HOST" "--list never prints a private regex"
# generic pattern
echo "feed at ws://${LAN}:7400" > "$W/src/b.txt"
track
expect 1 "LAN address in the tree fails" -- "$SCAN" --tree
contains "lan-address: src/b.txt:1:" "finding names the pattern and the location"
not_contains "$LAN" "the address itself is not echoed"
git -C "$W" rm -qf src/b.txt
# private noun, case-insensitive
echo "ssh root@$(echo "$HOST" | tr a-z A-Z).example" > "$W/src/c.txt"
track
expect 1 "private host name fails" -- "$SCAN" --tree
contains "house-host: src/c.txt:1:" "private name reported by its pattern name"
not_contains "$HOST" "private host name is not echoed"
git -C "$W" rm -qf src/c.txt
# case-sensitive private pattern: lowercase fixture passes, capitalised fails
echo "user: $(echo "$PERSON" | tr A-Z a-z)" > "$W/src/d.txt"
track
expect 0 "case-sensitive pattern ignores the lowercase fixture" -- "$SCAN" --tree
echo "by ${PERSON}" > "$W/src/d.txt"
track
expect 1 "case-sensitive pattern catches the capitalised name" -- "$SCAN" --tree
git -C "$W" rm -qf src/d.txt
# literal secret value from @values
echo "KEY=${SECRET}" > "$W/src/e.env"
track
expect 1 "a literal secret value fails" -- "$SCAN" --tree
contains "secret-value:FAKE_ROUTER_KEY: src/e.env:1:" "value finding names the env KEY"
not_contains "${SECRET:0:6}" "secret value is fully redacted"
git -C "$W" rm -qf src/e.env
# credential shape
echo "export STREAM_KEY=\"live_123456""7_abcdefghijABCDEFGHIJ123\"" > "$W/src/f.sh"
track
expect 1 "stream-key shape fails" -- "$SCAN" --tree
contains "secret-twitch" "stream key reported as secret-twitch"
git -C "$W" rm -qf src/f.sh
# allowlist
echo "contact ${MAIL}" > "$W/src/g.txt"
track
expect 1 "e-mail address fails" -- "$SCAN" --tree
printf 'src/g.txt email-address # upstream licence contact\n' >> "$W/infra/tests/de-pii-allow.txt"
expect 0 "allowlisted path/name pair passes" -- "$SCAN" --tree
printf 'src/ house-host # a different name does not excuse\n' >> "$W/infra/tests/de-pii-allow.txt"
echo "${LAN}" > "$W/src/g2.txt"
track
expect 1 "an allow entry excuses only its own pattern name" -- "$SCAN" --tree
git -C "$W" rm -qf src/g.txt src/g2.txt
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
# fail closed / open
expect 2 "--require-private without the list exits 2" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --require-private --tree
contains "private pattern list not found" "missing list is named"
expect 0 "without --require-private a missing list is a NOTE" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --tree
contains "NOTE: no private pattern list" "NOTE printed"
printf 'broken-line\n' > "$T/private/broken.txt"
expect 2 "a malformed private list is an error, not a silent pass" -- env FLY_PII_PATTERNS="$T/private/broken.txt" "$SCAN" --tree
# range: added then removed is still published history
base="$(git -C "$W" rev-parse HEAD)"
echo "on ${HOST} today" > "$W/src/h.txt"; git -C "$W" add -A; git -C "$W" commit -qm "add h"
git -C "$W" rm -q src/h.txt; git -C "$W" commit -qm "remove h"
expect 0 "tree is clean after the removal" -- "$SCAN" --tree
expect 1 "range still finds the line a commit added" -- "$SCAN" --range "${base}..HEAD"
contains "house-host:" "range finding names the pattern"
contains "src/h.txt:1" "range finding names path and line"
git -C "$W" commit -q --allow-empty -m "deploy to ${HOST}"
expect 1 "range scans commit messages" -- "$SCAN" --range "HEAD~1..HEAD"
contains "<commit-message>:1" "message finding is marked"
git -C "$W" reset -q --hard "$base"
git -C "$W" status --porcelain | grep -q . && bad "work repo not clean before the hook tests" || true
# --- pre-push hook ---------------------------------------------------------------------
git init -q --bare "$T/pub.git"
git init -q --bare "$T/priv.git"
git -C "$W" remote add github "$T/pub.git"
git -C "$W" remote add origin "$T/priv.git"
expect 0 "install-hooks installs" -- "$W/tools/install-hooks.sh"
[ -x "$W/.git/hooks/pre-push" ] && ok "hook is executable" || bad "hook missing"
expect 0 "install-hooks is idempotent" -- "$W/tools/install-hooks.sh"
expect 0 "clean push to github is accepted" -- git -C "$W" push -q github main
echo "at ${LAN}" > "$W/src/i.txt"; git -C "$W" add -A; git -C "$W" commit -qm "i"
expect 1 "push with PII to github is refused" -- git -C "$W" push -q github main
contains "refusing to publish" "hook explains the refusal"
expect 0 "push to a private remote is not scanned" -- git -C "$W" push -q origin main
git -C "$W" rm -q src/i.txt; git -C "$W" commit -qm "rm i"
expect 1 "removing it in a later commit does not unblock the push" -- git -C "$W" push -q github main
git -C "$W" reset -q --hard github/main
git -C "$W" tag -a v9.9.9 -m "release for ${HOST}"
expect 1 "annotated tag message is scanned" -- git -C "$W" push -q github v9.9.9
contains "<tag-message>" "tag finding is marked"
git -C "$W" tag -d v9.9.9 >/dev/null
git -C "$W" tag -a v9.9.8 -m "release"
expect 0 "clean annotated tag is accepted" -- git -C "$W" push -q github v9.9.8
git -C "$W" commit -q --allow-empty -m "clean"
expect 1 "push is refused when the private list is missing" -- env FLY_PII_PATTERNS="$T/nope" git -C "$W" push -q github main
git -C "$W" checkout -q -b old "$base"
rm -f "$W/tools/pii-scan.sh"
echo "x ${HOST}" > "$W/src/j.txt"; git -C "$W" add -A; git -C "$W" commit -qm "j"
expect 1 "a branch without tools/pii-scan.sh is scanned by the hook's own copy" -- git -C "$W" push -q github old
printf 'exit 0\n' > "$T/other-hook"
git -C "$W" checkout -q main
cp "$T/other-hook" "$W/.git/hooks/pre-push"
expect 1 "install-hooks refuses to clobber a foreign hook" -- "$W/tools/install-hooks.sh"
# --- review-pii-guard N2/N3 (2026-09-29) ----------------------------------------------
printf 'broken - (unclosed\n' > "$T/private/bad-patterns.txt"
expect 2 "an invalid private regex refuses to scan (never 'clean')" -- env FLY_PII_PATTERNS="$T/private/bad-patterns.txt" "$SCAN" --tree
printf '++ %s\n' "$LAN" > "$W/src/plusplus.txt"
git -C "$W" add -A && git -C "$W" commit -qm "a line that starts with ++"
expect 1 "an added line starting '++ ' is still scanned" -- "$SCAN" --range HEAD~1..HEAD
git -C "$W" rm -qf src/plusplus.txt && git -C "$W" commit -qm "drop it"
echo "==="
if [ "$FAILS" -eq 0 ]; then echo "pii-scan-test: ALL PASSED"; else echo "pii-scan-test: ${FAILS} FAILED"; exit 1; fi

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

@ -117,6 +117,143 @@ class RecoveryTests(unittest.TestCase):
self.confirm(T0, rank=13) self.confirm(T0, rank=13)
self.assertEqual(self.acts, [("restart", None)]) self.assertEqual(self.acts, [("restart", None)])
# Row 70: the rung-11 reset replayed the run exactly (1,138 of 1,138 events), caught the Zubat
# again and walked into the same trap; the next step reset to rung 11 again and erased the catch.
def test_progress_after_the_last_step_starts_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 4, "bestRank": 12, "resets": [], "actedAt": T0 - 7200})
# an area and a species inside the windows of probes well after the step
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 2, "species": 0}})
self.assertIn("flysim restarted", self.confirm(T0))
self.assertEqual(self.acts, [("restart", None)])
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("progress since the last step", [event.get("why") for event in history])
def test_progress_while_a_step_settles_does_not_start_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 1500})
self.tick(T0 - 1400, suspected=0, window={"progress": {"lasting": 3, "species": 0}})
self.confirm(T0)
self.assertEqual(self.acts, [("reset", 11)])
def test_a_species_owned_recently_is_never_reset_away(self):
owned = T0 - 1200
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [],
"actedAt": T0 - recover.HOLD - 300, "speciesAt": owned})
self.assertIn("flysim restarted", self.confirm(T0))
self.assertEqual(self.acts, [("restart", None)])
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("protect", [event.get("event") for event in history])
# the hold still spaces the restarts, and says why
self.assertIn("protection window", self.confirm(T0 + 300 + recover.SETTLE + 10))
# the protection lasts PROTECT from the species; then the ladder resets as before
self.assertIn("reset to rung 11", self.tick(owned + recover.PROTECT + 60))
def test_a_probe_that_owns_a_species_starts_the_protection(self):
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
self.assertEqual(recover.load(recover.STATE, {}).get("speciesAt"), T0)
self.assertEqual(recover.load(recover.STATE, {}).get("progressAt"), T0)
def test_the_last_resets_archive_is_not_restored_again(self):
acted = T0 - recover.HOLD - 100
recover.write_json(recover.STATE, {"level": 3, "bestRank": 12, "resets": [acted],
"actedAt": acted, "lastReset": 11, "lastResetAt": acted})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
def test_a_protected_reset_does_not_climb_but_the_archive_just_used_does(self):
# protected: the restart keeps the level's slot, so the reset comes at the same rung later
owned = T0 - 600
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0,
"speciesAt": owned})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 1)
# the archive just restored: a restart that climbs, and the marker is forgotten after AGAIN
self.acts.clear()
reset_at = T0 - recover.HOLD - 100
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [reset_at], "actedAt": reset_at,
"lastReset": 12, "lastResetAt": reset_at})
self.confirm(T0 + 1000)
self.assertEqual(self.acts, [("restart", None)])
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
self.acts.clear()
self.tick(reset_at + recover.AGAIN + 60)
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
def test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.confirm(T0)
self.assertEqual(recover.load(recover.STATE, {}).get("lastReset"), 11)
self.tick(T0 + 300 + recover.SETTLE + 10, suspected=0, rank=13)
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
# Row 70 review r3: a reset restores the reward ledger, so its replay pays the archive's rewards
# again. Progress is a reward name the ladder has not seen before, not a count.
def test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over(self):
seen = ["area:AREA 59", "pokedex:OWNED #8", "trainer:BEAT ROUTE 3 TRAINER 0", "milestone:Reached MT. MOON"]
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": seen})
replay = {"progress": {"lasting": 4, "species": 1, "keys": seen}}
self.tick(T0 - 3000, suspected=0, window=replay)
state = recover.load(recover.STATE, {})
self.assertNotIn("progressAt", state)
self.assertNotIn("speciesAt", state) # the replayed catch was protected before the reset
self.assertEqual(state["progressSeen"], seen)
self.confirm(T0)
self.assertEqual(self.acts, [("reset", 11)])
def test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": ["area:AREA 59"]})
self.tick(T0 - 3000, suspected=0,
window={"progress": {"lasting": 2, "species": 1, "keys": ["area:AREA 59", "pokedex:OWNED #41"]}})
state = recover.load(recover.STATE, {})
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
self.assertEqual(state["progressSeen"], ["area:AREA 59", "pokedex:OWNED #41"])
self.assertIn("flysim restarted", self.confirm(T0))
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("progress since the last step", [event.get("why") for event in history])
def test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over(self):
acted = T0 - recover.HOLD - 600
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": acted,
"clearAt": acted + 60})
catch = {"progress": {"lasting": 1, "species": 1, "keys": ["pokedex:OWNED #41"]}}
self.assertIn("flysim restarted", self.confirm(T0, window=catch))
self.assertEqual(self.acts, [("restart", None)]) # the rung-11 reset, held for the new species
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
def test_without_reward_names_the_counts_still_count(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": ["pokedex:OWNED #8"]})
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
state = recover.load(recover.STATE, {})
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
def test_the_names_remembered_are_bounded(self):
recover.write_json(recover.STATE, {"progressSeen": [f"area:AREA {n}" for n in range(recover.SEEN)]})
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA X"]}})
seen = recover.load(recover.STATE, {})["progressSeen"]
self.assertEqual((len(seen), seen[0], seen[-1]), (recover.SEEN, "area:AREA 1", "area:AREA X"))
# a malformed list is ignored item by item
self.tick(T0 + 300, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": [{}, ["x"], 3]}})
self.assertEqual(recover.load(recover.STATE, {})["progressSeen"][-1], "area:AREA X")
def test_restarts_stay_a_hold_apart_after_the_ladder_starts_over(self):
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": T0 - 3600,
"lastAction": "restart"})
self.tick(T0 - 2000, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA 60"]}})
self.assertIn("last restart was under three hours ago", self.confirm(T0))
self.assertEqual(self.acts, [])
self.assertIn("flysim restarted", self.tick(T0 - 3600 + recover.HOLD))
def test_a_failed_reset_does_not_block_its_archive(self):
recover.act.side_effect = lambda action, target: self.acts.append((action, target)) or False
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.assertIn("reset FAILED", self.confirm(T0))
state = recover.load(recover.STATE, {})
self.assertNotIn("lastReset", state)
self.assertEqual((state["level"], len(state["resets"])), (3, 1)) # it still climbed and spent the reset
def test_quiet_hours_start_the_ladder_over(self): def test_quiet_hours_start_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0, recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0,
"lastSuspectedAt": T0 - recover.QUIET - 1}) "lastSuspectedAt": T0 - recover.QUIET - 1})
@ -268,6 +405,139 @@ BUILD = "lif-1ms-f64-v2/pokered-unique8-v7/abc/fly-kc-mbon-rstdp-v2"
@unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root") @unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root")
class ClosedLoopTests(unittest.TestCase):
"""Row 70 review L1: a trap no restart clears, every reset replaying it exactly (closed loop)."""
M = 60
R11 = dict(events=[(20, "pokedex"), (21, "trainer"), (35, "trainer"), (44, "area"), (46, "milestone"),
(52, "pokedex")], trap=58, rank_after=[(46, 12)], start_rank=11)
R12 = dict(events=[(7, "pokedex")], trap=12, rank_after=[], start_rank=12)
R10 = dict(events=[(30, "area"), (60, "milestone"), (90, "milestone"), (100, "pokedex")], trap=110,
rank_after=[(60, 11), (90, 12)], start_rank=10)
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
for name, value in (("REPORT", "loop.json"), ("STATE", "s.json"), ("HISTORY", "h.jsonl"),
("NOTICE", "n.json")):
patcher = patch.object(recover, name, root / value)
patcher.start()
self.addCleanup(patcher.stop)
for name, value in (("restorable_rungs", lambda: {9, 10, 11, 12}), ("verdict", lambda report: (None, None))):
patcher = patch.object(recover, name, value)
patcher.start()
self.addCleanup(patcher.stop)
self.env = patch.dict("os.environ", {}, clear=False)
self.env.start()
self.addCleanup(self.env.stop)
for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"):
recover.os.environ.pop(key, None)
def simulate(self, archives, hours, species_before=None, names=True):
"""The fly is trapped from T0; returns [(hours, action, target)]. A reset replays its archive.
Every lasting reward has a name (window.progress.keys): the fly earned each archive's rewards
once before the trap, in clear probes the ladder saw, and a replay pays the same names again.
"""
M = self.M
sim = dict(events=[(T0 - species_before * M, "pokedex", "pokedex:pre")] if species_before else [],
rank=12, rank_changes=[], trap_from=T0, now=T0, acts=[])
history = [f"{k}:{rung}/{o}" for rung, a in sorted(archives.items()) for o, k in a["events"]]
for i in range(0, len(history), 3) if names else ():
recover.REPORT.write_text(json.dumps({
"at": T0 - 86400 + i * 300, "suspected": 0, "action": "none", "milestone": {"rank": 12},
"window": {"progress": {"lasting": 3, "species": 0, "keys": history[i:i + 3]}}}))
recover.run(now=T0 - 86400 + i * 300 + 5, sleep=lambda s: None)
seen = recover.load(recover.STATE, {}).get("progressSeen")
def act(action, target):
sim["acts"].append((sim["now"], action, target))
if action == "reset":
a = archives[target]
sim["rank"] = a["start_rank"]
sim["events"] = [(sim["now"] + o * M, k, f"{k}:{target}/{o}") for o, k in a["events"]]
sim["rank_changes"] = [(sim["now"] + o * M, r) for o, r in a["rank_after"]]
sim["trap_from"] = None if a["trap"] is None else sim["now"] + a["trap"] * M
return True
recover.write_json(recover.STATE, dict({"bestRank": 12, "rank": 12, "level": 0},
**({"progressSeen": seen} if seen else {})))
recover.HISTORY.write_text("")
with patch.object(recover, "act", side_effect=act):
t = T0
while t < T0 + hours * 3600:
for change in list(sim["rank_changes"]):
if change[0] <= t:
sim["rank"] = change[1]
sim["rank_changes"].remove(change)
win = [(k, name) for at, k, name in sim["events"] if t - 600 <= at <= t]
trapped = sim["trap_from"] is not None and t - sim["trap_from"] >= 600
recover.REPORT.write_text(json.dumps({
"at": t, "suspected": 1 if trapped else 0, "action": "none", "reason": "dominant",
"sequence": ["NEXT"], "milestone": {"rank": sim["rank"], "label": "X"}, "map": 59,
"window": {"progress": dict({
"lasting": sum(k in ("pokedex", "area", "trainer", "badge", "milestone") for k, _ in win),
"species": sum(k == "pokedex" for k, _ in win)},
**({"keys": [name for _, name in win]} if names else {}))}}))
sim["now"] = t + 5
recover.run(now=t + 5, sleep=lambda s: None)
t += 300
return [((at - T0) / 3600, action, target) for at, action, target in sim["acts"]]
def test_a_restart_proof_trap_is_reset_in_bounded_time_and_again(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 72, species_before=6)
resets = [a for a in acts if a[1] == "reset"]
# v0.7.0 resets again at 24.75 h; the ladder is no worse, and keeps resetting
self.assertTrue(resets and resets[0][0] <= 25, acts)
self.assertTrue(len([a for a in resets if a[0] <= 25]) >= 1, acts)
self.assertTrue(len(resets) >= 3, acts)
gaps = [b[0] - a[0] for a, b in zip(resets, resets[1:])]
self.assertTrue(all(g <= 25 for g in gaps), acts)
# the first step is a restart; the catch stays protected for 2 h
self.assertEqual(acts[0][1], "restart")
self.assertTrue(all(a[0] >= 2 - 0.2 for a in resets[:1]), acts)
def test_the_held_reset_is_the_rung_12_one_not_a_deeper_rung(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24, species_before=6)
self.assertEqual([a[2] for a in acts if a[1] == "reset"][:1], [12], acts)
def test_a_trap_the_rung_12_archive_escapes_ends_there(self):
clean = dict(self.R12, trap=None)
acts = self.simulate({11: self.R11, 12: clean, 10: self.R10, 9: self.R10}, 24, species_before=6)
self.assertEqual([a[1:] for a in acts if a[1] == "reset"], [("reset", 12)], acts)
self.assertEqual(len(acts), 2, acts)
def test_without_a_catch_the_ladder_resets_early(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24)
self.assertLessEqual(next(a[0] for a in acts if a[1] == "reset"), 1, acts)
def test_a_trap_only_the_rung_below_escapes_is_reached_promptly(self):
# review r2 N1: the rung-12 replay re-earns progress, then traps; only rung 11 escapes.
# v0.7.0 reset to 11 at 2.08 h; holding the level on the archive just used took 24.75 h, and
# counting the replay's area and species as progress took 5.58 h (6.83 h after a catch).
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
archives = {11: dict(self.R11, trap=None), 12: late12, 10: self.R10, 9: self.R10}
for species_before, bound in ((None, 2.1), (6, 2.1 + 2)): # a catch 6 min before the trap: +2 h at most
with self.subTest(species_before=species_before):
self.setUp()
acts = self.simulate(archives, 96, species_before=species_before)
resets = [a for a in acts if a[1] == "reset"]
self.assertEqual([a[2] for a in resets], [12, 11], acts)
self.assertLessEqual(resets[-1][0], bound, acts)
def test_restarts_are_a_hold_apart_in_every_closed_loop(self):
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
for archives in ({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10},
{11: self.R11, 12: late12, 10: self.R10, 9: self.R10}):
for species_before in (None, 6):
self.setUp()
acts = self.simulate(archives, 72, species_before=species_before)
restarts = [a[0] for a in acts if a[1] == "restart"]
self.assertTrue(all(b - a >= 3 - 1e-6 for a, b in zip(restarts, restarts[1:])), acts)
resets = [a[0] for a in acts if a[1] == "reset"]
self.assertTrue(all(sum(1 for y in resets if x <= y < x + 24) <= 2 for x in resets), acts)
class WrapperTests(unittest.TestCase): class WrapperTests(unittest.TestCase):
"""infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives.""" """infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives."""

View file

@ -13,3 +13,7 @@ ExecStart=/opt/fly/bin/fly-recap
Nice=19 Nice=19
IOSchedulingClass=idle IOSchedulingClass=idle
CPUWeight=20 CPUWeight=20
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
CPUSchedulingPolicy=idle

View file

@ -11,3 +11,7 @@ Environment=FLY_MEDIA_DIR=/srv/fly/media
ExecStart=/opt/fly/bin/fly-retention ExecStart=/opt/fly/bin/fly-retention
Nice=15 Nice=15
IOSchedulingClass=idle IOSchedulingClass=idle
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
CPUSchedulingPolicy=idle

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,56 @@
# infra/units/flycontrol-edge.service — pushed to /etc/systemd/system/flycontrol-edge.service.
#
# The control API (http://127.0.0.1:7401, docs/control-api.md) served from
# flysim's control services on the bus (docs/design/flybus.md, "Control over
# the bus"; services/flysim/crates/fly-control-edge). Whether it runs is decided
# by one line, FLY_CONTROL_VIA in /etc/fly/fly.env (05-deploy.sh writes it from
# the env file's FLY_CONTROL_VIA, default `direct`):
#
# direct flysim binds 127.0.0.1:7401 itself. ExecCondition= below fails, so
# this unit starts as "skipped" (inactive, no failure, no restart).
# bus flysim registers the control services on its router and leaves
# :7401 to this unit.
#
# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
# never disagree. This unit is in no target and has no [Install] section:
# `systemctl enable` has nothing to do. The switch and the way back are
# infra/docs/runbook.md, "Control over the bus": edit FLY_CONTROL_VIA, run
# 05-deploy.sh, restart flysim.
#
# Ordering: flysim owns the router (/run/fly/bus, shared with the feed when
# that rides the bus too), so it starts first and the edge follows it.
# Requires= makes an explicit stop or restart of flysim stop or restart the
# edge with it (and Wants= on the other side brings it back after a plain
# start). A crash-restart of flysim is covered by the edge itself: it unbinds
# :7401 and reconnects every 500 ms, so to every client it looks exactly like
# flysim restarting. The edge holds no state.
[Unit]
Description=flycontrol-edge: the control API served from flysim's control services on the bus
After=flysim.service
Requires=flysim.service
# A release that predates fly-control-edge has no binary; stay cleanly
# inactive rather than restart-looping.
ConditionPathExists=/opt/fly/current/fly-control-edge
[Service]
Type=simple
User=fly
# FLY_CONTROL_VIA, FLY_BUS_DIR and the rest of flysim's configuration: the
# edge reads the same file, so the two cannot disagree about the port or the bus.
EnvironmentFile=/etc/fly/fly.env
Environment=FLY_CONTROL_BIND=127.0.0.1:7401
Environment=FLY_BUS_DIR=/run/fly/bus
# Its own /metrics and /healthz. Loopback only.
Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127.0.0.1:9103
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
# "skip": the unit goes inactive without failing and without being restarted.
ExecCondition=/bin/sh -c 'case "$$FLY_CONTROL_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
ExecStart=/opt/fly/current/fly-control-edge
Restart=always
RestartSec=2
# Small JSON requests; an /events page is the largest thing it ever holds.
MemoryMax=128M

View file

@ -1,30 +1,41 @@
# infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service. # infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service.
# #
# The feed WebSocket served from flysim's feed bus (docs/design/flybus.md, # The feed WebSocket served from flysim's feed bus (docs/design/flybus.md,
# "Feed over the bus"; services/flysim/crates/fly-edge). DISABLED BY DEFAULT: # "Feed over the bus"; services/flysim/crates/fly-edge). Whether it runs is
# it is in no target's Wants=/Requires= and 07-enable.sh does not enable it. # decided by one line, FLY_FEED_VIA in /etc/fly/fly.env (05-deploy.sh writes it
# With FLY_FEED_VIA=direct (the default, written into /etc/fly/fly.env by # from the env file's FLY_FEED_VIA, default `direct`):
# 05-deploy.sh) flysim binds 127.0.0.1:7400 itself and this unit has nothing
# to do. To move the feed onto the bus on one container:
# #
# 1. FLY_FEED_VIA=bus in the env file, then 05-deploy.sh (rewrites fly.env); # direct flysim binds 127.0.0.1:7400 itself. ExecCondition= below fails, so
# 2. systemctl enable --now flyedge.service; systemctl restart flysim.service # this unit starts as "skipped" (inactive, no failure, no restart).
# (flysim stops binding :7400, the edge binds it once the first snapshot # bus flysim publishes on its feed bus and leaves :7400 to this unit.
# is on the bus);
# 3. nothing for the watchdog: check 2 reads FLY_FEED_VIA from fly.env and
# follows the feed counters to this unit's loopback /metrics.
# #
# Back: FLY_FEED_VIA=direct, deploy, systemctl disable --now flyedge.service, # flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
# restart flysim. # rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
# never disagree. This unit is in no target and has no [Install] section:
# `systemctl enable` has nothing to do.
#
# Switching a running container (infra/bin/fly-feed, "Feed over the bus" in
# docs/runbook.md; it is the whole procedure, with a health check and its own
# rollback):
#
# fly-feed bus FLY_FEED_VIA=bus in fly.env, restart flysim, wait for
# the edge and a client
# fly-feed direct the way back
# #
# Ordering (docs/design/flybus.md, amendment "Feed store lifecycle"): flysim # Ordering (docs/design/flybus.md, amendment "Feed store lifecycle"): flysim
# owns the router and its store under /run/fly/bus, so it starts first and # owns the router and its store under /run/fly/bus, so it starts first and the
# the edge follows it. Requires= makes an explicit stop or restart of flysim # edge follows it. Requires= makes an explicit stop or restart of flysim stop
# (the unstick rule's `systemctl restart flysim.service` included) stop or # or restart the edge with it. A crash-restart of flysim is covered by the edge
# restart the edge with it. A crash-restart of flysim is covered by the edge # itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, so
# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, # nothing here has to be restarted by hand. The edge holds no state; the store
# so nothing here has to be restarted by hand. The edge holds no state; the # is flysim's and a new router removes the previous one's directory.
# store is flysim's and a new router removes the previous one's directory. #
# CPUs: 05-deploy.sh writes this unit's cpuset drop-in on the page CPUs, never
# flysim's (the sim's CPUs are the sim's alone, docs/runbook.md "CPU partition").
# The router and the publisher run inside flysim, on its own two-thread bus
# runtime.
[Unit] [Unit]
Description=flyedge: the feed WebSocket served from flysim's feed bus Description=flyedge: the feed WebSocket served from flysim's feed bus
After=flysim.service After=flysim.service
@ -42,15 +53,17 @@ User=fly
EnvironmentFile=/etc/fly/fly.env EnvironmentFile=/etc/fly/fly.env
Environment=FLY_FEED_BIND=127.0.0.1:7400 Environment=FLY_FEED_BIND=127.0.0.1:7400
Environment=FLY_BUS_DIR=/run/fly/bus Environment=FLY_BUS_DIR=/run/fly/bus
# Its own read-only /metrics and /healthz, for watchdog check 2 in bus mode. # Its own read-only /metrics and /healthz: watchdog check 2 reads them in bus mode (over
# Loopback only: nothing off the container needs the edge's counters. # loopback), and so can the metrics dashboard, as a second target beside flysim's :9101, which
Environment=FLY_EDGE_METRICS_ADDR=127.0.0.1:9102 # reads 0 for the feed counters in bus mode. Same exposure as :9101 (the container's network).
Environment=FLY_EDGE_METRICS_ADDR=0.0.0.0:9102
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
# "skip": the unit goes inactive without failing and without being restarted.
ExecCondition=/bin/sh -c 'case "$$FLY_FEED_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
ExecStart=/opt/fly/current/fly-edge ExecStart=/opt/fly/current/fly-edge
Restart=always Restart=always
RestartSec=2 RestartSec=2
# A few snapshots in flight and a WebSocket per client; the store itself is # A few snapshots in flight and a WebSocket per client; the store itself is
# flysim's (tmpfs, bounded by feedbus::limits at 32 MiB). # flysim's (tmpfs, bounded by feedbus::limits at 32 MiB).
MemoryMax=256M MemoryMax=256M
[Install]
WantedBy=fly.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,66 @@
# 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
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
Slice=flysim.slice
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
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

@ -14,6 +14,15 @@
[Unit] [Unit]
Description=flysim: the fly brain, emulator, and control/feed APIs Description=flysim: the fly brain, emulator, and control/feed APIs
After=network.target After=network.target
# Every start of flysim starts the feed edge when fly.env says FLY_FEED_VIA=bus, and skips it in
# direct mode (units/flyedge.service decides): a stop and start of flysim (fly-loop-reset,
# fly-reset-to-milestone) would otherwise leave the stage with nothing on :7400, because
# flyedge.service's Requires= stops the edge with flysim but does not bring it back.
# Every start of flysim starts the control edge when fly.env says FLY_CONTROL_VIA=bus, and skips
# it in direct mode (units/flycontrol-edge.service decides): a stop and start of flysim
# (fly-loop-reset, fly-reset-to-milestone) would otherwise leave :7401 dead, because the edge's
# Requires= stops it with flysim but does not bring it back.
Wants=flyedge.service flycontrol-edge.service
StartLimitIntervalSec=300 StartLimitIntervalSec=300
StartLimitBurst=5 StartLimitBurst=5
@ -79,6 +88,16 @@ RestartSec=2
# bandwidth-bound sweep that is fighting its own SMT siblings. # bandwidth-bound sweep that is fighting its own SMT siblings.
Nice=-5 Nice=-5
CPUWeight=400 CPUWeight=400
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
Slice=flysim.slice
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
# The encoder, the browser and the sim must not share physical cores. # The encoder, the browser and the sim must not share physical cores.
# AllowedCPUs is per-host and per-container (PVE picks the container's # AllowedCPUs is per-host and per-container (PVE picks the container's
# cpuset at `pct create` time and it is NOT a set of whole cores — on this # cpuset at `pct create` time and it is NOT a set of whole cores — on this

11
infra/units/flysim.slice Normal file
View file

@ -0,0 +1,11 @@
# infra/units/flysim.slice — the sim's own slice (PERF-02 review N1).
# Named without a dash on purpose: systemd nests a slice named a-b.slice under a.slice, and a child's
# cpuset is bounded by its parent's; flysim.slice sits directly under the root slice, beside system.slice.
# flysim.service and flysim-session.service run here. 05-deploy.sh writes the drop-in
# flysim.slice.d/cpuset.conf (AllowedCPUs= the sim's CPUs) when the container has a cpuset
# partition; bin/fly-cpu-confine keeps every other slice off those CPUs. Nothing else belongs in
# this slice.
[Unit]
Description=The live sim (its CPUs are exclusive to it)
[Slice]

View file

@ -14,8 +14,8 @@ import { digestOf, fail } from './canonical';
import { readRational, readSchemaRef } from './common'; import { readRational, readSchemaRef } from './common';
import { Reader, readArtifactRef, requireUnique, u64 } from './reader'; import { Reader, readArtifactRef, requireUnique, u64 } from './reader';
import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar'; import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar';
import { isDigest } from './scalar'; import { isDigest, isId } from './scalar';
import { type AssetRef, readAssetRef } from './workers'; import { type AssetRef, MAX_RATE_ROLES, readAssetRef } from './workers';
import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions'; import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions';
export const PROFILE_ID = 'gameboy-legacy-fafb-v783-v1'; export const PROFILE_ID = 'gameboy-legacy-fafb-v783-v1';
@ -93,7 +93,10 @@ export const PAYLOAD_SCHEMAS: readonly SchemaRef[] = [
/** The legacy profile document's AssetRef digest: SHA-256 of its canonical JSON. */ /** The legacy profile document's AssetRef digest: SHA-256 of its canonical JSON. */
export const PROFILE_DIGEST = '41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878'; export const PROFILE_DIGEST = '41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878';
/** `ChannelName`: a decoder channel or rate-role name. Not an Id: legacy names carry '_'. */ /**
* `ChannelName`: a decoder channel or rate-role name, `^[a-z][a-z0-9_]{0,63}$`. A subset of the
* `Id` grammar (which admits '_'); see `rateRoleId` below (amendment 2026-09-23).
*/
export function isChannelName(value: unknown): value is string { export function isChannelName(value: unknown): value is string {
return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value); return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value);
} }
@ -558,3 +561,40 @@ export function decoderConfigForm(config: DecoderConfigLike): unknown {
export function decoderConfigDigest(config: DecoderConfigLike): Digest { export function decoderConfigDigest(config: DecoderConfigLike): Digest {
return digestOf(decoderConfigForm(config)); return digestOf(decoderConfigForm(config));
} }
// Rate roles: legacy-rate-role-id-v1 (amendment 2026-09-23, AGENT-01) ----------------------
/**
* The mapping from a legacy rate-role name to `AgentGraph.rateRoles` / `rates[].roleId`.
*
* The contract left it open on the premise that `command_0`, `macro_go_item` and the rest are
* not `Id`s; they are, because the `Id` grammar `^[a-z0-9][a-z0-9._-]{0,63}$` admits '_'. So the
* mapping is the identity on the `Id` grammar and a name outside it has no roleId: the agent
* refuses such a dataset. `fly-session-types/src/gameboy.rs` is the twin and
* `fixtures/gameboy-rate-roles.json` holds both to it.
*/
export const RATE_ROLE_MAPPING = 'legacy-rate-role-id-v1';
/** The roleId of a legacy rate-role name: the name itself, when it is an Id. */
export function rateRoleId(name: string): Id {
if (!isId(name)) {
fail(`${RATE_ROLE_MAPPING}: rate role ${JSON.stringify(name)} is not an Id and has no roleId`);
}
return name;
}
/** The legacy rate-role name a roleId stands for: the inverse of `rateRoleId`. */
export function rateRoleName(roleId: string): string {
if (!isId(roleId)) fail(`${RATE_ROLE_MAPPING}: ${JSON.stringify(roleId)} is not a roleId`);
return roleId;
}
/** Maps a tracked-role list in order, holding it to `AgentGraph.rateRoles`' bounds. */
export function rateRoleIds(names: readonly string[]): Id[] {
const ids = names.map(rateRoleId);
if (ids.length > MAX_RATE_ROLES) {
fail(`${RATE_ROLE_MAPPING}: ${ids.length} tracked rate roles; AgentGraph.rateRoles holds at most ${MAX_RATE_ROLES}`);
}
requireUnique(ids, 'rateRoles');
return ids;
}

View file

@ -174,3 +174,24 @@ test('the decoderConfigDigest vectors are what the TypeScript oracle preset comp
assert.equal(example.decoderConfigDigest, cases[1]!.digest); assert.equal(example.decoderConfigDigest, cases[1]!.digest);
assert.deepEqual(example.executor.macroChannels, cases[1]!.macroChannels); assert.deepEqual(example.executor.macroChannels, cases[1]!.macroChannels);
}); });
test('legacy-rate-role-id-v1 is the identity on the Id grammar and refuses the rest', () => {
const file = fixtures.load('gameboy-rate-roles.json') as Record<string, any>;
assert.equal(file.mapping, gameboy.RATE_ROLE_MAPPING);
assert.ok(file.accepted.length > 0);
for (const { name, roleId } of file.accepted as { name: string; roleId: string }[]) {
assert.equal(gameboy.rateRoleId(name), roleId, name);
assert.equal(gameboy.rateRoleName(roleId), name, `${roleId} maps back`);
}
for (const { name } of file.refused as { name: string }[]) {
assert.throws(() => gameboy.rateRoleId(name), `${JSON.stringify(name)} has no roleId`);
assert.throws(() => gameboy.rateRoleName(name));
}
const tracked = file.fafbTrackedRoles as string[];
assert.deepEqual(gameboy.rateRoleIds(tracked), tracked);
for (const role of tracked.filter((r) => r.startsWith('macro_'))) {
assert.ok(gameboy.isChannelName(role));
}
assert.throws(() => gameboy.rateRoleIds(Array.from({ length: 65 }, (_, i) => `role_${i}`)));
assert.throws(() => gameboy.rateRoleIds(['command_0', 'command_0']));
});

View file

@ -244,7 +244,7 @@ The unit itself lives in `infra/`, not here (W4 in `docs/stream-mvp-plan.md`). W
provide: provide:
- `LoadCredentialEncrypted=twitch-client-id:...` and `...twitch-client-secret:...`, sourced from - `LoadCredentialEncrypted=twitch-client-id:...` and `...twitch-client-secret:...`, sourced from
`pass` (`twitch/fly-pokemon-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files `pass` (`twitch/<app>-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files
`src/config.ts` reads. `src/config.ts` reads.
- A writable, persistent directory for `TOKENS_FILE`, `REDEMPTION_STATE_FILE` and - A writable, persistent directory for `TOKENS_FILE`, `REDEMPTION_STATE_FILE` and
`NOTICE_STATE_FILE` (default `/var/lib/flybridge/`), owned by the service user. `NOTICE_STATE_FILE` (default `/var/lib/flybridge/`), owned by the service user.

View file

@ -416,6 +416,23 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "fly-control-edge"
version = "0.1.1"
dependencies = [
"anyhow",
"axum",
"clap",
"flybus",
"flysim",
"serde_json",
"tempfile",
"tokio",
"tower",
"tracing",
"tracing-subscriber",
]
[[package]] [[package]]
name = "fly-edge" name = "fly-edge"
version = "0.1.1" version = "0.1.1"
@ -435,12 +452,60 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "fly-legacy-session"
version = "0.1.1"
dependencies = [
"anyhow",
"axum",
"clap",
"fly-control-edge",
"fly-edge",
"fly-session",
"flybrain-core",
"flybrain-gb",
"flybus",
"flysim",
"futures-util",
"serde_json",
"tempfile",
"tokio",
"tokio-tungstenite",
"toml",
"tower",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "fly-scorecard"
version = "0.1.1"
dependencies = [
"anyhow",
"clap",
"fly-legacy-session",
"fly-session",
"flybrain-core",
"flybrain-gb",
"flysim",
"libc",
"serde",
"serde_json",
"tempfile",
"tokio",
]
[[package]] [[package]]
name = "fly-session" name = "fly-session"
version = "0.1.1" version = "0.1.1"
dependencies = [ dependencies = [
"flate2",
"fly-session-types", "fly-session-types",
"flybrain-core",
"flybrain-gb",
"flybus", "flybus",
"flysim-store",
"libc",
"serde_json", "serde_json",
"tempfile", "tempfile",
"tokio", "tokio",
@ -464,11 +529,13 @@ dependencies = [
"cudarc", "cudarc",
"flate2", "flate2",
"indexmap", "indexmap",
"libc",
"libm", "libm",
"ryu-js", "ryu-js",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tempfile",
] ]
[[package]] [[package]]
@ -500,10 +567,12 @@ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
"clap", "clap",
"fly-session",
"fly-session-types", "fly-session-types",
"flybrain-core", "flybrain-core",
"flybrain-gb", "flybrain-gb",
"flybus", "flybus",
"flysim-store",
"futures-util", "futures-util",
"jsonschema", "jsonschema",
"serde", "serde",
@ -519,6 +588,19 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "flysim-store"
version = "0.1.1"
dependencies = [
"anyhow",
"flybrain-core",
"flybrain-gb",
"serde",
"serde_json",
"tempfile",
"tracing",
]
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.2.0" version = "0.2.0"

View file

@ -1,13 +1,17 @@
[workspace] [workspace]
resolver = "3" resolver = "3"
members = [ members = [
"crates/fly-control-edge",
"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",
"crates/flybrain-gb", "crates/flybrain-gb",
"crates/flybus", "crates/flybus",
"crates/flysim", "crates/flysim",
"crates/flysim-store",
"crates/fly-scorecard",
] ]
[workspace.package] [workspace.package]

View file

@ -0,0 +1,35 @@
[package]
name = "fly-control-edge"
version.workspace = true
edition = "2024"
rust-version.workspace = true
license.workspace = true
publish = false
description = "The control API (:7401) served from flysim's control services on the bus (FLY_CONTROL_VIA=bus)."
[lib]
name = "fly_control_edge"
path = "src/lib.rs"
[[bin]]
name = "fly-control-edge"
path = "src/main.rs"
[dependencies]
# The HTTP layer, the request/reply types and the bus encoding are flysim's own modules (`api`,
# `control`, `controlbus`), so the edge writes the :7401 bytes with the code flysim uses in direct
# mode and cannot disagree with the services about the encoding.
flysim = { path = "../flysim" }
flybus = { path = "../flybus" }
anyhow = "1.0"
axum = "0.8"
clap = { version = "4.5", features = ["derive"] }
serde_json = { workspace = true }
tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "time", "signal", "macros"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies]
tempfile = "3"
tower = { version = "0.5", features = ["util"] }

View file

@ -0,0 +1,462 @@
//! `fly-control-edge`: the control API on `:7401`, answered by flysim's control services on the
//! bus (CTRL-01, `docs/design/flybus.md`, "Control over the bus").
//!
//! With `FLY_CONTROL_VIA=bus` flysim (either runtime) does not bind `control.bind`. It registers
//! the control services on its embedded router (`flysim::controlbus`), and this process serves the
//! HTTP surface of `docs/control-api.md` to the bridge, the stage, the infra scripts and the
//! operator's `curl` by calling them. The HTTP layer is flysim's own `api::router_with`, so the
//! routes, the 404s, the extractors, the headers and the body encoding are the code direct mode
//! runs; this crate only adds a [`BusBackend`] that carries each request across the bus.
//!
//! Lifecycle (as `fly-edge` for the feed):
//!
//! - the control port is bound only once the control services answer, so before that a client
//! is refused exactly as it is by a flysim that has not started;
//! - when the bus goes away (flysim stopped or restarted) the edge unbinds the port, again what a
//! stopped flysim looks like, and reconnects every `retry` until a router answers.
//!
//! Failures on the bus side map onto the 503s direct mode answers for the same failure (the
//! words are `flysim::control::unavailable`), so a client cannot tell which side was in trouble.
use std::io::Write as _;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use anyhow::{Context, Result, anyhow};
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::get;
use flybus::{BusError, Client, ClientConfig, Dispatch, ErrorCode};
use flysim::api::ControlBackend;
use flysim::control::{COMMAND_TIMEOUT, ControlReply, ControlRequest, unavailable};
use flysim::controlbus::{self, Role, Scope};
use flysim::feedbus;
use flysim::metrics::metric;
use tokio::sync::oneshot;
/// How much longer than the services' own [`COMMAND_TIMEOUT`] the edge waits before it gives up
/// on a timed request and cancels it. The services answer a wedged loop with their own 503 at
/// [`COMMAND_TIMEOUT`]; this guard only covers a bus or a host that stopped answering at all.
pub const DEADLINE_MARGIN: Duration = Duration::from_secs(2);
/// What the edge needs to know, from flysim's own configuration.
#[derive(Debug, Clone)]
pub struct EdgeConfig {
/// `feed.bus_dir`: the router's sockets and store root.
pub bus_dir: PathBuf,
/// `control.bind`, the port flysim leaves alone in bus mode.
pub control_bind: SocketAddr,
/// `FLY_CONTROL_EDGE_METRICS_ADDR`: the edge's own `/metrics` and `/healthz`, when set.
pub metrics_bind: Option<SocketAddr>,
/// Delay between attempts to reach the bus.
pub retry: Duration,
/// The session and agents whose services `:7401` addresses.
pub scope: Scope,
}
impl EdgeConfig {
pub fn from_flysim(config: &flysim::config::Config, metrics_bind: Option<SocketAddr>) -> Self {
Self {
bus_dir: config.feed.bus_dir.clone(),
control_bind: config.control.bind,
metrics_bind,
retry: Duration::from_millis(500),
scope: Scope::live(),
}
}
}
/// The edge's counters.
#[derive(Debug, Default)]
pub struct EdgeMetrics {
/// 1 while connected and serving.
pub connected: AtomicU64,
/// Requests carried across the bus.
pub calls: AtomicU64,
/// Requests that ended in a bus failure rather than a reply (each a 503 or 403 to the
/// client).
pub call_failures: AtomicU64,
/// Requests the edge cancelled at its own deadline.
pub cancelled: AtomicU64,
/// Serving sessions ended by the bus going away.
pub bus_lost: AtomicU64,
/// Sessions that reached the bus but could not bind the control port.
pub bind_failures: AtomicU64,
}
impl EdgeMetrics {
pub fn render(&self) -> String {
let mut out = String::with_capacity(1_024);
for (name, kind, help, value) in [
(
"fly_control_edge_bus_connected",
"gauge",
"1 while the edge is connected to the control bus and serving.",
&self.connected,
),
(
"fly_control_edge_calls_total",
"counter",
"Control requests carried across the bus.",
&self.calls,
),
(
"fly_control_edge_call_failures_total",
"counter",
"Control requests that ended in a bus failure instead of a reply.",
&self.call_failures,
),
(
"fly_control_edge_cancelled_total",
"counter",
"Control requests the edge cancelled at its own deadline.",
&self.cancelled,
),
(
"fly_control_edge_bus_lost_total",
"counter",
"Serving sessions ended by the control bus going away.",
&self.bus_lost,
),
(
"fly_control_edge_bind_failures_total",
"counter",
"Times the bus was reachable but the control port could not be bound.",
&self.bind_failures,
),
] {
metric(&mut out, name, kind, help, value.load(Ordering::Relaxed));
}
out
}
}
/// A [`ControlBackend`] that answers each request by calling the control services on the bus.
#[derive(Clone)]
pub struct BusBackend {
client: Client,
scope: Scope,
metrics: Arc<EdgeMetrics>,
}
impl BusBackend {
pub fn new(client: Client, scope: Scope, metrics: Arc<EdgeMetrics>) -> BusBackend {
BusBackend {
client,
scope,
metrics,
}
}
/// The bus connection.
pub fn client(&self) -> &Client {
&self.client
}
/// The service a request goes to: the session's, or the first agent's for the agent-scoped
/// families (`:7401` addresses the one live fly; a second fly has no HTTP surface).
fn service(&self, family: controlbus::Family) -> String {
let agent = self.scope.agent_ids().next().unwrap_or("");
self.scope.service(family, agent)
}
/// Carry one request across the bus and wait for its reply, under the edge's deadline.
pub async fn call(&self, request: ControlRequest) -> ControlReply {
self.metrics.calls.fetch_add(1, Ordering::Relaxed);
let deadline = if request.waits_for_a_write() {
None
} else {
Some(COMMAND_TIMEOUT + DEADLINE_MARGIN)
};
let (family, method, mut payload) = controlbus::encode_request(&request);
let service = self.service(family);
// A body over the envelope travels as an artifact, so a large request gets the answer
// direct mode gives it.
let sealed = match controlbus::take_out_of_line_request(&mut payload) {
None => None,
Some(bytes) => match seal(&self.client, &bytes, "application/json").await {
Ok(artifact) => Some(artifact),
Err(error) => return self.failed(&error),
},
};
let attachments: Vec<(&str, &flybus::Artifact)> = sealed
.iter()
.map(|artifact| (controlbus::REQUEST_ARTIFACT, artifact))
.collect();
let mut pending = match self
.client
.call(&service, None, method, payload, &attachments)
.await
{
Ok(pending) => pending,
Err(error) => return self.failed(&error),
};
let result = match deadline {
None => pending.result().await,
Some(deadline) => match tokio::time::timeout(deadline, pending.result()).await {
Ok(result) => result,
Err(_) => {
// Cancelled before dispatch, the loop never sees it; dispatched, it may still
// act, exactly as a direct request whose caller timed out.
let state = pending.cancel().await;
self.metrics.cancelled.fetch_add(1, Ordering::Relaxed);
tracing::warn!(method, ?state, "a control call passed the edge's deadline");
return ControlReply::error(503, unavailable::TIMED_OUT);
}
},
};
let result = match result {
Ok(result) => result,
Err(error) => return self.failed(&error),
};
let artifact = if controlbus::has_body_artifact(result.outcome()) {
match result.artifact(controlbus::BODY_ARTIFACT) {
Ok(artifact) => match artifact.read_all().await {
Ok(bytes) => Some(bytes),
Err(error) => return self.failed(&error),
},
Err(error) => return self.failed(&error),
}
} else {
None
};
match controlbus::decode_reply(result.outcome(), artifact) {
Ok(reply) => reply,
Err(error) => {
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
tracing::warn!(%error, method, "an undecodable control reply");
ControlReply::error(502, format!("the control service answered badly: {error}"))
}
}
}
fn failed(&self, error: &BusError) -> ControlReply {
self.metrics.call_failures.fetch_add(1, Ordering::Relaxed);
tracing::debug!(%error, "a control call failed on the bus");
bus_failure(error)
}
}
impl ControlBackend for BusBackend {
fn handle(
&self,
request: ControlRequest,
) -> impl std::future::Future<Output = ControlReply> + Send {
let backend = self.clone();
async move { backend.call(request).await }
}
}
async fn seal(
client: &Client,
bytes: &[u8],
content_type: &str,
) -> Result<flybus::Artifact, BusError> {
let mut writer = client
.artifacts()
.allocate(bytes.len() as u64, content_type)
.await?;
writer
.write_all(bytes)
.map_err(|error| BusError::new(ErrorCode::StoreFailure, error.to_string()))?;
writer.seal().await
}
/// The reply a client gets for a request the bus did not deliver, in the words direct mode uses
/// for the same failure.
pub fn bus_failure(error: &BusError) -> ControlReply {
match error.code {
// The service's queue and in-flight slots are full: the direct API's full command queue.
ErrorCode::Backpressure => ControlReply::error(503, unavailable::QUEUE_FULL),
// Nobody is serving it: before dispatch the loop never saw it, as a closed command queue.
ErrorCode::NoService if error.dispatch == Dispatch::NotDispatched => {
ControlReply::error(503, unavailable::STOPPED)
}
ErrorCode::NoService | ErrorCode::CallGone | ErrorCode::RouterLost => {
ControlReply::error(503, unavailable::DROPPED)
}
ErrorCode::NotAuthorized => ControlReply::error(
403,
format!("not authorized on the control bus: {}", error.message),
),
code => ControlReply::error(
503,
format!("the control bus refused the request: {}", code.as_str()),
),
}
}
/// Serve until the process is stopped. Only a metrics listener that cannot bind is fatal;
/// everything about the bus is retried.
pub async fn run(config: EdgeConfig, metrics: Arc<EdgeMetrics>) -> Result<()> {
config.scope.validate()?;
if let Some(addr) = config.metrics_bind {
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("binding the edge metrics listener on {addr}"))?;
let app = axum::Router::new()
.route("/metrics", get(prometheus))
.route("/healthz", get(healthz))
.with_state(Arc::clone(&metrics));
tokio::spawn(async move {
if let Err(error) = axum::serve(listener, app).await {
tracing::error!(%error, "the edge metrics listener stopped");
}
});
}
let mut last: Option<&'static str> = None;
loop {
let end = session(&config, &metrics).await;
match &end {
SessionEnd::BusLost => {
tracing::warn!("the control bus went away; :7401 unbound, reconnecting");
}
SessionEnd::Unreachable(error) if last != Some(end.kind()) => {
tracing::info!(error = format!("{error:#}"), "waiting for the control bus");
}
SessionEnd::BindFailed(error) if last != Some(end.kind()) => {
// The bus is fine; the port is not ours. Most likely flysim is still in direct
// mode and holds it (FLY_CONTROL_VIA is not bus), or another process does.
tracing::warn!(
error = format!("{error:#}"),
"the bus is up but the control port cannot be bound; retrying"
);
}
_ => {}
}
last = match end {
SessionEnd::BusLost => None,
other => Some(other.kind()),
};
tokio::time::sleep(config.retry).await;
}
}
enum SessionEnd {
Unreachable(anyhow::Error),
BindFailed(anyhow::Error),
BusLost,
}
impl SessionEnd {
fn kind(&self) -> &'static str {
match self {
Self::Unreachable(_) => "unreachable",
Self::BindFailed(_) => "bind",
Self::BusLost => "lost",
}
}
}
async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
(
[(
axum::http::header::CONTENT_TYPE,
"text/plain; version=0.0.4",
)],
metrics.render(),
)
}
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
if metrics.connected.load(Ordering::Relaxed) == 1 {
(StatusCode::OK, "ok")
} else {
(
StatusCode::SERVICE_UNAVAILABLE,
"waiting for the control bus",
)
}
}
/// Connect as [`controlbus::EDGE`] and wait until the control services answer.
pub async fn connect(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> Result<BusBackend> {
let client = Client::connect_unix(
controlbus::socket_path(&config.bus_dir, Role::Edge),
ClientConfig::new(controlbus::EDGE, feedbus::store_root(&config.bus_dir)),
)
.await
.map_err(|error| anyhow!("connecting to the control bus: {error}"))?;
let backend = BusBackend::new(client, config.scope.clone(), Arc::clone(metrics));
// The host registers its services right after the router starts; until it has, a call is
// NO_SERVICE. Bind :7401 only once one is answered, whatever it answers.
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Healthz);
let service = backend.service(family);
for _ in 0..20 {
match backend
.client
.call(&service, None, method, payload.clone(), &[])
.await
{
Ok(mut pending) => match pending.result().await {
Ok(_) => return Ok(backend),
Err(error) if error.code == ErrorCode::NoService => {}
Err(error) => return Err(anyhow!("the control services did not answer: {error}")),
},
Err(error) if error.code == ErrorCode::NoService => {}
Err(error) => return Err(anyhow!("calling the control services: {error}")),
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(anyhow!(
"the control services are not registered on the bus"
))
}
async fn session(config: &EdgeConfig, metrics: &Arc<EdgeMetrics>) -> SessionEnd {
let backend = match connect(config, metrics).await {
Ok(backend) => backend,
Err(error) => return SessionEnd::Unreachable(error),
};
let listener = match tokio::net::TcpListener::bind(config.control_bind).await {
Ok(listener) => listener,
Err(error) => {
metrics.bind_failures.fetch_add(1, Ordering::Relaxed);
return SessionEnd::BindFailed(anyhow::Error::new(error).context(format!(
"binding the control listener on {}",
config.control_bind
)));
}
};
serve(config, metrics, backend, listener).await;
SessionEnd::BusLost
}
/// Serve `listener` until the bus connection closes.
async fn serve(
config: &EdgeConfig,
metrics: &EdgeMetrics,
backend: BusBackend,
listener: tokio::net::TcpListener,
) {
tracing::info!(control = %config.control_bind, bus = %config.bus_dir.display(), "serving the control API from the bus");
metrics.connected.store(1, Ordering::Relaxed);
let client = backend.client.clone();
let (stop, stopped) = oneshot::channel::<()>();
let server = tokio::spawn(async move {
let result = axum::serve(listener, flysim::api::router_with(backend))
.with_graceful_shutdown(async move {
let _ = stopped.await;
})
.await;
if let Err(error) = result {
tracing::error!(%error, "the control listener stopped");
}
});
while client.closed().is_none() {
tokio::time::sleep(Duration::from_millis(100)).await;
}
metrics.connected.store(0, Ordering::Relaxed);
metrics.bus_lost.fetch_add(1, Ordering::Relaxed);
let _ = stop.send(());
if tokio::time::timeout(Duration::from_secs(5), server)
.await
.is_err()
{
tracing::warn!("the control listener took more than 5 s to stop");
}
}

View file

@ -0,0 +1,81 @@
//! `fly-control-edge`: serve the control API (`:7401`) from flysim's control services on the bus.
//!
//! ```sh
//! FLY_CONTROL_VIA=bus flysim-session &
//! fly-control-edge
//! ```
//!
//! Configured through the same environment as flysim (`FLY_CONTROL_BIND`, `FLY_BUS_DIR`, or
//! `--config flysim.toml`), plus `FLY_CONTROL_EDGE_METRICS_ADDR` for its own `/metrics` and
//! `/healthz`. `infra/units/flycontrol-edge.service` runs it with no arguments.
use std::sync::Arc;
use anyhow::{Context, Result};
use clap::Parser;
use fly_control_edge::{EdgeConfig, EdgeMetrics};
#[derive(Debug, Parser)]
#[command(
name = "fly-control-edge",
about = "The control API, served from flysim's control services on the bus.",
version
)]
struct Args {
/// Path to `flysim.toml`, read for `[control]` and `[feed] bus_dir`. Environment overrides
/// apply as they do for flysim.
#[arg(long, value_name = "PATH")]
config: Option<std::path::PathBuf>,
}
fn main() -> Result<()> {
let args = Args::parse();
init_tracing();
let config = flysim::config::Config::load(args.config.as_deref())?;
let metrics_bind = match std::env::var("FLY_CONTROL_EDGE_METRICS_ADDR") {
Ok(value) if !value.is_empty() => Some(value.parse().with_context(|| {
format!("FLY_CONTROL_EDGE_METRICS_ADDR: {value:?} is not a host:port address")
})?),
_ => None,
};
let edge = EdgeConfig::from_flysim(&config, metrics_bind);
if config.control.via != flysim::config::ControlVia::Bus {
tracing::warn!(
"FLY_CONTROL_VIA is not \"bus\": flysim serves the control API itself and binds {}; \
this edge will wait for control services that are not there",
edge.control_bind
);
}
tracing::info!(config = ?edge, "fly-control-edge starting");
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("fly-control-edge")
.enable_all()
.build()
.context("building the tokio runtime")?;
runtime.block_on(async move {
let metrics = Arc::new(EdgeMetrics::default());
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.context("installing the SIGTERM handler")?;
tokio::select! {
result = fly_control_edge::run(edge, metrics) => result,
_ = tokio::signal::ctrl_c() => { tracing::info!("SIGINT: shutting down"); Ok(()) }
_ = terminate.recv() => { tracing::info!("SIGTERM: shutting down"); Ok(()) }
}
})
}
/// Logs to stderr, like flysim, under `FLY_CONTROL_EDGE_LOG` (or `RUST_LOG`).
fn init_tracing() {
use tracing_subscriber::EnvFilter;
let filter = EnvFilter::try_from_env("FLY_CONTROL_EDGE_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,313 @@
//! Backpressure, cancellation and the edge's lifecycle.
//!
//! - a family whose service is full refuses with the direct API's "queue is full" 503, and the
//! other families keep answering;
//! - a call cancelled before dispatch never reaches the loop; a caller that goes away, or a call
//! past the edge's deadline, leaves no call on the router;
//! - the edge unbinds `:7401` when the bus goes away and binds it again when a router is back.
mod common;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use axum::http::{Method, StatusCode};
use common::{exchange, rig};
use flybus::{CancelState, Client, ClientConfig, Policy, Router, RouterConfig};
use flysim::control::{ControlRequest, unavailable};
use flysim::controlbus::{self, Family, Role, Scope};
use serde_json::json;
async fn until(what: &str, mut check: impl FnMut() -> bool) {
let started = Instant::now();
while !check() {
assert!(
started.elapsed() < Duration::from_secs(30),
"timed out waiting for {what}"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_full_service_is_a_503_and_the_other_families_still_answer() {
let rig = rig(|_| {}).await;
rig.sim.hold.store(true, Ordering::SeqCst);
let slots =
(controlbus::SERVICE_CONFIG.max_in_flight + controlbus::SERVICE_CONFIG.max_queued) as usize;
// The first 16 fill the service's in-flight slots and reach the (wedged) loop; only then
// the next 16 fill its queue. (Sent as one burst, the queue bound can be met before the
// router has dispatched the first ones: a bounded queue refuses what it cannot hold at that
// instant, which is the point, but not what this test counts.)
let in_flight = controlbus::SERVICE_CONFIG.max_in_flight as usize;
let mut pauses = Vec::new();
for batch in [in_flight, slots - in_flight] {
for _ in 0..batch {
let edge = rig.edge.clone();
pauses.push(tokio::spawn(async move {
edge.call(ControlRequest::Pause).await
}));
}
until("the in-flight pauses", || rig.sim.received("pause") == in_flight).await;
}
let started = Instant::now();
while (rig.bus.router.stats().calls as usize) < slots {
if started.elapsed() > Duration::from_secs(30) {
let mut finished = Vec::new();
for pause in pauses.iter_mut().filter(|p| p.is_finished()) {
finished.push(format!("{:?}", pause.await.unwrap()));
}
panic!(
"not every pause admitted: {:?}, received {}, finished {finished:?}",
rig.bus.router.stats(),
rig.sim.received("pause")
);
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
// One more is refused at once, in the direct API's words.
let started = Instant::now();
let refused = exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]).await;
assert_eq!(refused.status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(refused.json(), json!({"error": unavailable::QUEUE_FULL}));
assert!(
started.elapsed() < Duration::from_secs(1),
"a full service made the caller wait"
);
// Reads, sugar and chat are other services: they answer while ops is saturated.
let status = exchange(rig.via_edge(), &Method::GET, "/status", None, &[]).await;
assert_eq!(status.status, StatusCode::OK);
let healthz = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
assert_eq!(healthz.status, StatusCode::OK);
// A queued pause cancelled before dispatch never reaches the loop.
let operator = Client::connect_unix(
controlbus::socket_path(&rig.config.bus_dir, Role::Operator),
ClientConfig::new(
Role::Operator.participant(),
flysim::feedbus::store_root(&rig.config.bus_dir),
),
)
.await
.unwrap();
// Let the loop go: the held pauses are dropped (503 "dropped"), the queued ones answered.
rig.sim.hold.store(false, Ordering::SeqCst);
rig.sim.release_held();
for pause in pauses {
let reply = pause.await.unwrap();
// The 16 the wedged loop dropped answer "dropped"; the 16 queued ones were answered.
assert!(
reply.status == 200 || reply.json_error() == Some(unavailable::DROPPED),
"{reply:?}"
);
}
let answered = rig.sim.received("pause");
assert_eq!(answered, slots);
// Wedge it again with 16 of the operator's own in flight; the 17th waits in the queue and
// is cancelled there.
rig.sim.hold.store(true, Ordering::SeqCst);
let (family, method, payload) = controlbus::encode_request(&ControlRequest::Pause);
let service = Scope::live().service(family, "");
let mut holders = Vec::new();
for _ in 0..controlbus::SERVICE_CONFIG.max_in_flight {
holders.push(
operator
.call(&service, None, method, payload.clone(), &[])
.await
.unwrap(),
);
}
until("the in-flight pauses", || {
rig.sim.received("pause") == slots + controlbus::SERVICE_CONFIG.max_in_flight as usize
})
.await;
let queued = operator
.call(&service, None, method, payload.clone(), &[])
.await
.unwrap();
assert_eq!(
queued.cancel().await.unwrap(),
CancelState::CancelledBeforeDispatch
);
rig.sim.hold.store(false, Ordering::SeqCst);
rig.sim.release_held();
for mut holder in holders {
let _ = holder.result().await;
}
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(
rig.sim.received("pause"),
slots + controlbus::SERVICE_CONFIG.max_in_flight as usize,
"the cancelled pause reached the loop"
);
until("no calls left on the router", || {
rig.bus.router.stats().calls == 0
})
.await;
}
trait ErrorText {
fn json_error(&self) -> Option<&str>;
}
impl ErrorText for flysim::control::ControlReply {
fn json_error(&self) -> Option<&str> {
match &self.body {
flysim::control::ReplyBody::Json(value) => value["error"].as_str(),
flysim::control::ReplyBody::Text(_) => None,
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_client_that_goes_away_leaves_no_call_behind() {
let rig = rig(|_| {}).await;
rig.sim.hold.store(true, Ordering::SeqCst);
// An HTTP client that gives up on a pause (which waits for a durable write, so has no
// deadline of its own): axum drops the handler, the edge drops the pending call.
let gave_up = tokio::time::timeout(
Duration::from_millis(300),
exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]),
)
.await;
assert!(gave_up.is_err());
until("the dropped call to be dispatched", || {
rig.sim.received("pause") == 1
})
.await;
// The host still holds it (the loop has it), so the router keeps the correlation until the
// host answers; then the detached result is discarded and nothing is left.
rig.sim.hold.store(false, Ordering::SeqCst);
rig.sim.release_held();
until("no calls left on the router", || {
rig.bus.router.stats().calls == 0
})
.await;
// And the edge is fine afterwards.
let ok = exchange(rig.via_edge(), &Method::POST, "/resume", None, &[]).await;
assert_eq!(ok.status, StatusCode::OK);
}
/// A host that registered the services but never answers: the edge gives up at its own deadline,
/// cancels, and answers the direct API's timeout 503.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_edge_cancels_at_its_deadline_when_the_host_never_answers() {
let dir = tempfile::tempdir().unwrap();
let scope = Scope::live();
let mut config = RouterConfig::new(dir.path());
config.policy = controlbus::policy(Policy::closed(), &scope);
let router = Router::new(config).unwrap();
let silent = Client::connect(
router.connect_in_memory_as(controlbus::HOST),
ClientConfig::new(controlbus::HOST, router.store_root()),
)
.await
.unwrap();
let name = scope.service(Family::Sugar, controlbus::LIVE_AGENT);
let mut service = silent
.register(&name, controlbus::SERVICE_CONFIG)
.await
.unwrap();
let held = tokio::spawn(async move {
let mut kept = Vec::new();
while let Some(request) = service.next().await {
kept.push(request);
}
});
let edge_client = Client::connect(
router.connect_in_memory_as(controlbus::EDGE),
ClientConfig::new(controlbus::EDGE, router.store_root()),
)
.await
.unwrap();
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
let backend = fly_control_edge::BusBackend::new(edge_client, scope, Arc::clone(&metrics));
let started = Instant::now();
let reply = exchange(
flysim::api::router_with(backend),
&Method::POST,
"/stimulate",
Some("application/json"),
&serde_json::to_vec(&json!({"by": "v", "source": "chat"})).unwrap(),
)
.await;
let waited = started.elapsed();
assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(reply.json(), json!({"error": unavailable::TIMED_OUT}));
let deadline = flysim::control::COMMAND_TIMEOUT + fly_control_edge::DEADLINE_MARGIN;
assert!(
waited >= deadline && waited < deadline + Duration::from_secs(2),
"{waited:?}"
);
assert_eq!(metrics.cancelled.load(Ordering::Relaxed), 1);
held.abort();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_edge_unbinds_when_the_bus_goes_and_binds_again_when_it_is_back() {
let mut rig = rig(|_| {}).await;
// The edge process connects as the edge participant, which the router admits once.
rig.close_edge().await;
let addr = common::free_port();
let config = fly_control_edge::EdgeConfig {
control_bind: addr,
..rig.config.clone()
};
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
let edge = tokio::spawn(fly_control_edge::run(config, Arc::clone(&metrics)));
until("the edge to bind", || {
metrics.connected.load(Ordering::Relaxed) == 1
})
.await;
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
let served = common::raw_http(addr, request).await.unwrap();
assert!(
served.starts_with(b"HTTP/1.1 200"),
"{}",
String::from_utf8_lossy(&served)
);
// flysim stops: its router goes, and the port with it.
rig.host.take();
rig.bus.router.shutdown();
until("the edge to notice", || {
metrics.bus_lost.load(Ordering::Relaxed) == 1
})
.await;
let started = Instant::now();
while common::raw_http(addr, request).await.is_some() {
assert!(
started.elapsed() < Duration::from_secs(10),
":7401 stayed bound"
);
tokio::time::sleep(Duration::from_millis(20)).await;
}
// flysim is back: a new router on the same directory, the services registered again.
let scope = Scope::live();
let uses = flysim::bus::Uses {
feed: false,
control: true,
};
let bus = flysim::bus::start(&rig.config.bus_dir, uses, &scope)
.await
.unwrap();
let _host = controlbus::serve(&bus.router, rig.state.clone(), &scope)
.await
.unwrap();
until("the edge to bind again", || {
metrics.connected.load(Ordering::Relaxed) == 1
})
.await;
let served = common::raw_http(addr, request).await.unwrap();
assert!(
served.starts_with(b"HTTP/1.1 200"),
"{}",
String::from_utf8_lossy(&served)
);
edge.abort();
}

View file

@ -0,0 +1,320 @@
#![allow(dead_code)]
//! A control rig: flysim's control state with a scripted stand-in for the loop behind it, the
//! embedded router with the control services registered, and the edge connected over its socket.
//! Every request can be sent to both sides — `direct` (flysim's own `:7401` router) and `edge`
//! (the same router over the bus) — and the answers compared byte for byte.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::body::Body;
use axum::http::{HeaderMap, Method, Request, StatusCode};
use fly_control_edge::{BusBackend, EdgeConfig, EdgeMetrics};
use flysim::AppState;
use flysim::bus::{EmbeddedBus, Uses};
use flysim::chat::{ChatRefusal, RejectReason};
use flysim::controlbus::{ControlHost, Scope};
use flysim::eventlog::{EventLog, EventRing, NewEvent};
use flysim::ratelimit::Refusal;
use flysim::simloop::{Command, Shared, booting_snapshot};
use flysim::snapshot::{FeedEventKind, FeedStatus, MacroMode, Snapshot};
use tokio::sync::{mpsc, watch};
use tower::ServiceExt;
/// The stand-in loop: answers every command deterministically from what the request says, so
/// the same request gets the same answer however often (and from whichever side) it is sent.
#[derive(Default)]
pub struct FakeSim {
/// Commands received, by kind.
pub received: Mutex<Vec<&'static str>>,
/// Hold every command without answering (a wedged loop).
pub hold: AtomicBool,
/// Answer `/checkpoint` with a failure.
pub fail_checkpoint: AtomicBool,
/// Held commands: kept so their reply channels stay open.
pub held: Mutex<Vec<Command>>,
pub answered: AtomicU64,
}
impl FakeSim {
pub fn received(&self, kind: &str) -> usize {
self.received
.lock()
.unwrap()
.iter()
.filter(|k| **k == kind)
.count()
}
pub fn release_held(&self) {
self.held.lock().unwrap().clear();
}
fn answer(&self, command: Command) {
let kind = match &command {
Command::Stimulate { .. } => "stimulate",
Command::Reward { .. } => "reward",
Command::Chat { .. } => "chat",
Command::Checkpoint { .. } => "checkpoint",
Command::Pause { .. } => "pause",
Command::Resume { .. } => "resume",
Command::Shutdown { .. } => "shutdown",
};
self.received.lock().unwrap().push(kind);
if self.hold.load(Ordering::SeqCst) {
self.held.lock().unwrap().push(command);
return;
}
self.answered.fetch_add(1, Ordering::SeqCst);
match command {
Command::Stimulate { by, reply, .. } => {
let answer = match by.as_str() {
"pulse" => Err(Refusal::PulseActive {
retry_after_ms: 250,
}),
"spent" => Err(Refusal::RateLimited {
retry_after_ms: 41_500,
}),
"drop" => return,
"hang" => {
self.held.lock().unwrap().push(Command::Stimulate {
duration_ms: None,
by,
source: String::new(),
reply,
});
return;
}
_ => Ok(41),
};
let _ = reply.send(answer);
}
Command::Reward { reply, .. } => {
let _ = reply.send(42);
}
Command::Chat {
by, text, reply, ..
} => {
let answer = if text.contains("http") {
Err(ChatRefusal::Rejected(RejectReason::Url))
} else if by == "fast" {
Err(ChatRefusal::RateLimited {
retry_after_ms: 1_999,
})
} else {
Ok(43)
};
let _ = reply.send(answer);
}
Command::Checkpoint { reply } => {
let answer = if self.fail_checkpoint.load(Ordering::SeqCst) {
Err("disk full".to_owned())
} else {
Ok(12)
};
let _ = reply.send(answer);
}
Command::Pause { reply } => {
let _ = reply.send(FeedStatus::Paused);
}
Command::Resume { reply } => {
let _ = reply.send(FeedStatus::Running);
}
Command::Shutdown { reply } => {
let _ = reply.send(());
}
}
}
}
pub struct Rig {
pub state: AppState,
pub sim: Arc<FakeSim>,
pub snapshots: watch::Sender<Arc<Snapshot>>,
pub bus: EmbeddedBus,
pub host: Option<ControlHost>,
pub edge: BusBackend,
pub metrics: Arc<EdgeMetrics>,
pub config: EdgeConfig,
pub dir: tempfile::TempDir,
_log: EventLog,
}
/// A snapshot with a few fields that are not the boot defaults, so `/status` has content.
fn snapshot() -> Snapshot {
let mut snapshot = booting_snapshot(4_242, 1_757_000_000_000, MacroMode::Raw);
let header = &mut snapshot.header;
header.status = FeedStatus::Running;
header.realtime_factor = 1.0312;
header.uptime_seconds = 612.5;
header.brain_ms = 3_600_250.0;
header.frame = 215_089;
header.population_rate = 12.375;
header.learning.signal = -0.125;
snapshot
}
/// The rig, with `configure` applied to flysim's configuration.
pub async fn rig(configure: impl FnOnce(&mut flysim::config::Config)) -> Rig {
rig_with(
configure,
Uses {
feed: false,
control: true,
},
)
.await
}
pub async fn rig_with(configure: impl FnOnce(&mut flysim::config::Config), uses: Uses) -> Rig {
let dir = tempfile::tempdir().unwrap();
let mut config = flysim::config::Config::default();
config.feed.bus_dir = dir.path().join("bus");
config.control.via = flysim::config::ControlVia::Bus;
configure(&mut config);
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, mut command_rx) = mpsc::channel::<Command>(flysim::simloop::COMMAND_QUEUE);
let (snapshots, receiver) = watch::channel(Arc::new(snapshot()));
let state = AppState {
shared: Arc::clone(&shared),
commands,
snapshots: receiver,
};
// A short event log, so `/events` has pages to turn.
let mut log = EventLog::open(&dir.path().join("events"), state.shared.events.clone()).unwrap();
for index in 0..7u64 {
log.append(
1_000 + index,
index as f64 * 0.5,
NewEvent::new(FeedEventKind::System, format!("event {index}")).value(index as f64),
);
}
state.shared.beat();
let sim = Arc::new(FakeSim::default());
{
let sim = Arc::clone(&sim);
tokio::spawn(async move {
while let Some(command) = command_rx.recv().await {
sim.answer(command);
}
});
}
let scope = Scope::live();
let bus = flysim::bus::start(&config.feed.bus_dir, uses, &scope)
.await
.unwrap();
let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope)
.await
.unwrap();
let edge_config = EdgeConfig {
retry: Duration::from_millis(50),
..EdgeConfig::from_flysim(&config, None)
};
let metrics = Arc::new(EdgeMetrics::default());
let edge = fly_control_edge::connect(&edge_config, &metrics)
.await
.unwrap();
Rig {
state,
sim,
snapshots,
bus,
host: Some(host),
edge,
metrics,
config: edge_config,
dir,
_log: log,
}
}
impl Rig {
pub fn direct(&self) -> axum::Router {
flysim::api::router(self.state.clone())
}
/// Close the rig's own edge connection, so an edge process can connect as the edge (the
/// router admits one live connection per participant).
pub async fn close_edge(&self) {
self.edge.client().clone().close().await;
}
pub fn via_edge(&self) -> axum::Router {
flysim::api::router_with(self.edge.clone())
}
}
/// One HTTP exchange as the bytes a client sees: status, every header, body.
#[derive(Debug, PartialEq, Eq)]
pub struct Exchange {
pub status: StatusCode,
pub headers: Vec<(String, Vec<u8>)>,
pub body: Vec<u8>,
}
impl Exchange {
pub fn json(&self) -> serde_json::Value {
serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
}
}
pub async fn exchange(
router: axum::Router,
method: &Method,
uri: &str,
content_type: Option<&str>,
body: &[u8],
) -> Exchange {
let mut request = Request::builder().method(method.clone()).uri(uri);
if let Some(content_type) = content_type {
request = request.header("content-type", content_type);
}
let request = request.body(Body::from(body.to_vec())).unwrap();
let response = router.oneshot(request).await.unwrap();
let status = response.status();
let headers = sorted(response.headers());
let body = axum::body::to_bytes(response.into_body(), 64 << 20)
.await
.unwrap()
.to_vec();
Exchange {
status,
headers,
body,
}
}
fn sorted(headers: &HeaderMap) -> Vec<(String, Vec<u8>)> {
let mut out: Vec<(String, Vec<u8>)> = headers
.iter()
.map(|(name, value)| (name.as_str().to_owned(), value.as_bytes().to_vec()))
.collect();
out.sort();
out
}
/// A free loopback port (bound, read, released).
pub fn free_port() -> std::net::SocketAddr {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap()
}
/// A raw HTTP/1.1 exchange over TCP: the whole response, with the `date` header line removed
/// (the one header that differs from second to second). `None` when nothing listens.
pub async fn raw_http(addr: std::net::SocketAddr, request: &str) -> Option<Vec<u8>> {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let mut stream = tokio::net::TcpStream::connect(addr).await.ok()?;
stream.write_all(request.as_bytes()).await.ok()?;
let mut out = Vec::new();
stream.read_to_end(&mut out).await.ok()?;
let text = String::from_utf8_lossy(&out).into_owned();
let kept: Vec<&str> = text
.split("\r\n")
.filter(|line| !line.to_ascii_lowercase().starts_with("date:"))
.collect();
Some(kept.join("\r\n").into_bytes())
}

View file

@ -0,0 +1,388 @@
//! The grant table refuses what it should, over the router's real sockets.
//!
//! - each native role calls exactly its families, and a refused call never reaches the loop;
//! - no role can register a service (so none can stand in for the control host), publish,
//! subscribe or manage a topic;
//! - a socket is bound to its role: claiming another identity on it is refused at hello;
//! - on a router shared with a service that does take input (an environment's, say), no control
//! participant can call it: "nothing can press buttons" holds for the grant table, not only for
//! the list of control methods;
//! - per-agent scoping: a player may sugar their own fly and not another.
mod common;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use axum::http::{Method, StatusCode};
use common::{exchange, rig, rig_with};
use flybus::{
BusError, Client, ClientConfig, Dispatch, ErrorCode, Grants, Pattern, Policy, Retained, Router,
RouterConfig, ServiceConfig,
};
use flysim::bus::Uses;
use flysim::control::ControlRequest;
use flysim::controlbus::{self, Family, Role, Scope};
use serde_json::{Map, json};
fn request_of(family: Family) -> ControlRequest {
match family {
Family::Read | Family::Status => ControlRequest::Status,
Family::Sugar => ControlRequest::Stimulate {
body: Some(json!({"by": "viewer", "source": "points"})),
},
Family::Reward => ControlRequest::Reward {
body: Some(json!({"value": 1.0, "by": "op", "source": "operator"})),
},
Family::Chat => ControlRequest::Chat {
body: Some(json!({"by": "viewer", "text": "hi"})),
},
Family::Ops => ControlRequest::Resume,
}
}
async fn call(
client: &Client,
scope: &Scope,
family: Family,
agent: &str,
) -> Result<Map<String, serde_json::Value>, BusError> {
let (encoded_family, method, payload) = controlbus::encode_request(&request_of(family));
// An agent's status service answers the same method the session's read does.
if family != Family::Status {
assert_eq!(encoded_family, family);
}
let service = scope.service(family, agent);
let result = client
.call_and_wait(&service, None, method, payload, &[])
.await?;
Ok(result.outcome().clone())
}
fn assert_refused(result: Result<impl std::fmt::Debug, BusError>, what: &str) {
let error = result.expect_err(what);
assert_eq!(error.code, ErrorCode::NotAuthorized, "{what}: {error}");
assert_eq!(error.dispatch, Dispatch::NotDispatched, "{what}");
}
async fn connect_role(
bus_dir: &std::path::Path,
role: Role,
claimed: &str,
) -> Result<Client, BusError> {
Client::connect_unix(
controlbus::socket_path(bus_dir, role),
ClientConfig::new(claimed, flysim::feedbus::store_root(bus_dir)),
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn each_role_calls_exactly_its_families_and_nothing_else() {
let rig = rig_with(
|_| {},
Uses {
feed: true,
control: true,
},
)
.await;
rig.close_edge().await;
let bus_dir = rig.config.bus_dir.clone();
let scope = Scope::live();
for role in Role::ALL {
let client = connect_role(&bus_dir, role, role.participant())
.await
.unwrap();
for family in Family::ALL {
let before = rig.sim.received.lock().unwrap().len();
let result = call(&client, &scope, family, controlbus::LIVE_AGENT).await;
if role.families().contains(&family) {
let outcome = result.unwrap_or_else(|e| panic!("{role:?} {family:?}: {e}"));
assert!(outcome["status"].as_u64().is_some(), "{role:?} {family:?}");
} else {
assert_refused(result, &format!("{role:?} {family:?}"));
assert_eq!(
rig.sim.received.lock().unwrap().len(),
before,
"{role:?} {family:?}: a refused call reached the loop"
);
}
}
// Nobody but the in-process host may register anything, a control name least of all.
for name in [
scope.service(Family::Ops, ""),
scope.service(Family::Sugar, controlbus::LIVE_AGENT),
"fly.control.s.main.buttons".to_owned(),
"anything".to_owned(),
] {
assert_refused(
client
.register(&name, ServiceConfig::default())
.await
.map(|_| ()),
&format!("{role:?} registering {name}"),
);
}
// No topics: not the feed, not a new one.
assert_refused(
client
.subscribe(flysim::feedbus::TOPIC, flybus::SubscriptionConfig::latest())
.await
.map(|_| ()),
&format!("{role:?} subscribing to the feed"),
);
assert_refused(
client
.declare_topic("fly.control.events", Retained::None)
.await
.map(|_| ()),
&format!("{role:?} declaring a topic"),
);
assert_refused(
client
.publish(flysim::feedbus::TOPIC, Map::new(), &[])
.await
.map(|_| ()),
&format!("{role:?} publishing on the feed"),
);
client.close().await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_socket_admits_only_its_own_role() {
let rig = rig(|_| {}).await;
let bus_dir = rig.config.bus_dir.clone();
for (socket, claimed) in [
(Role::Stage, Role::Operator.participant()),
(Role::Bridge, controlbus::HOST),
(Role::Watchdog, controlbus::EDGE),
(Role::Edge, Role::Operator.participant()),
] {
let result = connect_role(&bus_dir, socket, claimed).await;
assert!(
result.is_err(),
"{claimed} was admitted on {socket:?}'s socket"
);
}
// No socket is bound to the host.
assert!(
!bus_dir.join("control").join("flysim-control.sock").exists()
&& std::fs::read_dir(bus_dir.join("control")).unwrap().count() == Role::NATIVE.len()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn on_a_shared_router_no_control_participant_can_reach_an_input_service() {
let dir = tempfile::tempdir().unwrap();
let scope = Scope::live();
// An environment that takes input lives on the same router as the control services.
let input = "fly.env.s.main.input";
let policy = controlbus::policy(
Policy::closed().client(
"env",
Grants {
register: vec![Pattern::exact(input)],
..Grants::default()
},
),
&scope,
);
let mut config = RouterConfig::new(dir.path());
config.policy = policy;
let router = Router::new(config).unwrap();
let env = Client::connect(
router.connect_in_memory_as("env"),
ClientConfig::new("env", router.store_root()),
)
.await
.unwrap();
let mut service = env.register(input, ServiceConfig::default()).await.unwrap();
let pressed = Arc::new(std::sync::atomic::AtomicU64::new(0));
{
let pressed = Arc::clone(&pressed);
tokio::spawn(async move {
while let Some(request) = service.next().await {
pressed.fetch_add(1, Ordering::SeqCst);
let _ = request.reply(Map::new(), &[]).await;
}
});
}
for role in Role::ALL {
let client = Client::connect(
router.connect_in_memory_as(role.participant()),
ClientConfig::new(role.participant(), router.store_root()),
)
.await
.unwrap();
for method in ["Environment.Step", "Control.Stimulate", "Press"] {
let mut payload = Map::new();
payload.insert("buttons".into(), json!(1));
assert_refused(
client
.call(input, None, method, payload, &[])
.await
.map(|_| ()),
&format!("{role:?} calling {input} {method}"),
);
}
client.close().await;
}
assert_eq!(pressed.load(Ordering::SeqCst), 0);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_player_sugars_their_own_fly_and_no_other() {
// Two flies on two controller ports; one player backs the fly on port 1 and another is
// granted by id. Single-fly is the same table with one agent.
let dir = tempfile::tempdir().unwrap();
let scope = Scope {
session: "arena".to_owned(),
agents: vec![
controlbus::AgentScope::new("fly-a", Some(1)),
controlbus::AgentScope::new("fly-b", Some(2)),
],
};
let policy = controlbus::policy(Policy::closed(), &scope)
.client(
"player-a",
controlbus::player_grants(&scope, controlbus::Agents::Port(1)),
)
.client(
"player-b",
controlbus::player_grants(&scope, controlbus::Agents::Id("fly-b")),
);
let mut config = RouterConfig::new(dir.path());
config.policy = policy;
let router = Router::new(config).unwrap();
let rig = rig(|_| {}).await;
let _host = controlbus::serve(&router, rig.state.clone(), &scope)
.await
.unwrap();
let player = Client::connect(
router.connect_in_memory_as("player-a"),
ClientConfig::new("player-a", router.store_root()),
)
.await
.unwrap();
let other = Client::connect(
router.connect_in_memory_as("player-b"),
ClientConfig::new("player-b", router.store_root()),
)
.await
.unwrap();
assert_eq!(
call(&other, &scope, Family::Sugar, "fly-b").await.unwrap()["status"],
json!(202)
);
assert_refused(
call(&other, &scope, Family::Sugar, "fly-a").await,
"player-b sugar on fly-a",
);
assert_eq!(
call(&player, &scope, Family::Status, "fly-a").await.unwrap()["status"],
json!(200)
);
assert_refused(
call(&player, &scope, Family::Status, "fly-b").await,
"status of fly-b",
);
let outcome = call(&player, &scope, Family::Sugar, "fly-a").await.unwrap();
assert_eq!(outcome["status"], json!(202));
assert_eq!(outcome["body"], json!({"eventId": 41}));
assert_eq!(
call(&player, &scope, Family::Read, "").await.unwrap()["status"],
json!(200)
);
assert_refused(
call(&player, &scope, Family::Sugar, "fly-b").await,
"sugar on fly-b",
);
assert_refused(
call(&player, &scope, Family::Reward, "fly-a").await,
"reward on fly-a",
);
assert_refused(call(&player, &scope, Family::Chat, "").await, "chat");
assert_refused(call(&player, &scope, Family::Ops, "").await, "ops");
// The live session's names are not the arena's.
assert_refused(
call(&player, &Scope::live(), Family::Read, "").await,
"another session's read",
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_method_the_service_does_not_have_is_a_404_and_reaches_nothing() {
let rig = rig(|_| {}).await;
let operator = connect_role(
&rig.config.bus_dir,
Role::Operator,
Role::Operator.participant(),
)
.await
.unwrap();
let scope = Scope::live();
for (family, method) in [
(Family::Read, "Control.Pause"),
(Family::Sugar, "Control.Press"),
(Family::Ops, "Control.Buttons"),
(Family::Chat, "Control.Stimulate"),
] {
let result = operator
.call_and_wait(
&scope.service(family, controlbus::LIVE_AGENT),
None,
method,
Map::new(),
&[],
)
.await
.unwrap();
assert_eq!(
result.outcome()["status"],
json!(404),
"{family:?} {method}"
);
}
assert!(rig.sim.received.lock().unwrap().is_empty());
}
/// An HTTP edge holding a narrower role answers what the role may not do with a 403, and the
/// loop never sees it.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_edge_on_a_narrow_role_refuses_over_http() {
let rig = rig(|_| {}).await;
let stage = connect_role(&rig.config.bus_dir, Role::Stage, Role::Stage.participant())
.await
.unwrap();
let backend = fly_control_edge::BusBackend::new(stage, Scope::live(), Arc::clone(&rig.metrics));
let router = || flysim::api::router_with(backend.clone());
let ok = exchange(router(), &Method::GET, "/healthz", None, &[]).await;
assert_eq!(ok.status, StatusCode::OK);
for (uri, body) in [
("/stimulate", json!({"by": "v", "source": "chat"})),
("/chat", json!({"by": "v", "text": "hi"})),
("/pause", json!({})),
("/checkpoint", json!({})),
] {
let refused = exchange(
router(),
&Method::POST,
uri,
Some("application/json"),
&serde_json::to_vec(&body).unwrap(),
)
.await;
assert_eq!(refused.status, StatusCode::FORBIDDEN, "{uri}");
assert!(
refused.json()["error"]
.as_str()
.unwrap()
.starts_with("not authorized on the control bus"),
"{uri}"
);
}
assert!(rig.sim.received.lock().unwrap().is_empty());
}

View file

@ -0,0 +1,427 @@
//! Every `docs/control-api.md` endpoint through the edge equals direct, byte for byte.
//!
//! Each case is sent twice, to flysim's own `:7401` router (`control.via = direct`) and to the
//! same router over the bus (`fly-control-edge`'s [`BusBackend`]), and the status, every header
//! and the body bytes must be equal. The stand-in loop answers each command from what the request
//! says, so both sends get the same answer. The last test does it over real TCP sockets against
//! the running edge, where the whole HTTP response must be equal but for its `date` line.
mod common;
use std::sync::atomic::Ordering;
use std::time::Duration;
use axum::http::{Method, StatusCode};
use common::{exchange, rig};
use serde_json::json;
/// `(method, uri, content type, body)`.
type Case = (Method, &'static str, Option<&'static str>, Vec<u8>);
fn json_case(method: Method, uri: &'static str, body: serde_json::Value) -> Case {
(
method,
uri,
Some("application/json"),
serde_json::to_vec(&body).unwrap(),
)
}
fn bare(method: Method, uri: &'static str) -> Case {
(method, uri, None, Vec::new())
}
fn raw(method: Method, uri: &'static str, body: &str) -> Case {
(
method,
uri,
Some("application/json"),
body.as_bytes().to_vec(),
)
}
/// The cases every configuration runs: each endpoint, its validation and its refusals.
fn cases() -> Vec<Case> {
use Method as M;
vec![
bare(M::GET, "/status"),
bare(M::GET, "/status.json"),
bare(M::GET, "/healthz"),
bare(M::GET, "/metrics"),
// /events: the page, its parameters and the lenient defaults.
bare(M::GET, "/events"),
bare(M::GET, "/events?since=3"),
bare(M::GET, "/events?since=0&limit=2"),
bare(M::GET, "/events?since=99"),
bare(M::GET, "/events?since=abc&limit=abc"),
bare(M::GET, "/events?since=&limit="),
bare(M::GET, "/events?limit=0"),
bare(M::GET, "/events?since=-1&limit=100000"),
bare(M::GET, "/events?since=1&since=2"),
bare(M::GET, "/events?unknown=1"),
// /stimulate: accepted, both refusals, every malformed shape.
json_case(
M::POST,
"/stimulate",
json!({"by": "viewer", "source": "points"}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "viewer", "source": "chat", "durationMs": 300}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "op", "source": "operator", "durationMs": null}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "pulse", "source": "points"}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "spent", "source": "chat"}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "viewer", "source": "bridge"}),
),
json_case(M::POST, "/stimulate", json!({"by": "viewer"})),
json_case(M::POST, "/stimulate", json!({"source": "points"})),
json_case(
M::POST,
"/stimulate",
json!({"by": "viewer", "source": "points", "durationMs": -5}),
),
json_case(
M::POST,
"/stimulate",
json!({"by": "viewer", "source": "points", "durationMs": "400"}),
),
json_case(M::POST, "/stimulate", json!([1, 2, 3])),
raw(M::POST, "/stimulate", "{not json"),
raw(M::POST, "/stimulate", "\"a string\""),
bare(M::POST, "/stimulate"),
(
M::POST,
"/stimulate",
Some("text/plain"),
b"{\"by\":\"v\",\"source\":\"chat\"}".to_vec(),
),
(M::POST, "/stimulate", None, vec![0xff, 0xfe, 0x00]),
// The loop dropped the request: the 503 both sides answer.
json_case(
M::POST,
"/stimulate",
json!({"by": "drop", "source": "chat"}),
),
// /reward: 403 unless enabled; its validation once it is.
json_case(
M::POST,
"/reward",
json!({"value": 0.5, "by": "op", "source": "operator"}),
),
json_case(
M::POST,
"/reward",
json!({"value": "x", "by": "op", "source": "operator"}),
),
bare(M::POST, "/reward"),
// /chat: accepted, both refusals, the body rules.
json_case(
M::POST,
"/chat",
json!({"by": "viewer_two", "text": "go fly go"}),
),
json_case(
M::POST,
"/chat",
json!({"by": "bot", "text": "hello", "bot": true}),
),
json_case(
M::POST,
"/chat",
json!({"by": "viewer", "text": "see http://x.example"}),
),
json_case(M::POST, "/chat", json!({"by": "fast", "text": "again"})),
json_case(
M::POST,
"/chat",
json!({"by": "viewer", "text": "hi", "bot": "yes"}),
),
json_case(M::POST, "/chat", json!({"by": "viewer"})),
json_case(M::POST, "/chat", json!({"text": 5})),
raw(M::POST, "/chat", "]"),
bare(M::POST, "/chat"),
// /checkpoint, /pause, /resume.
bare(M::POST, "/checkpoint"),
bare(M::POST, "/pause"),
bare(M::POST, "/resume"),
json_case(M::POST, "/pause", json!({"ignored": true})),
// Everything that is not a route is the same 404, the wrong method on a route included.
bare(M::GET, "/stimulate"),
bare(M::POST, "/status"),
bare(M::PUT, "/pause"),
bare(M::DELETE, "/checkpoint"),
json_case(M::POST, "/button", json!({"button": "a"})),
bare(M::GET, "/joypad"),
bare(M::POST, "/memory"),
bare(M::GET, "/"),
bare(M::GET, "/status/"),
]
}
async fn compare_all(
configure: impl FnOnce(&mut flysim::config::Config),
cases: &[Case],
) -> Vec<(String, StatusCode)> {
let rig = rig(configure).await;
let mut seen = Vec::new();
for (method, uri, content_type, body) in cases {
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
assert_eq!(
direct,
edge,
"{method} {uri}: direct {} {:?} vs edge {} {:?}",
direct.status,
String::from_utf8_lossy(&direct.body),
edge.status,
String::from_utf8_lossy(&edge.body)
);
seen.push((format!("{method} {uri}"), direct.status));
}
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
seen
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn every_endpoint_through_the_edge_equals_direct() {
let seen = compare_all(|_| {}, &cases()).await;
// The cases reach every status code control-api.md names, so the comparison is not of
// twenty identical 200s.
let codes: std::collections::BTreeSet<u16> = seen.iter().map(|(_, s)| s.as_u16()).collect();
for code in [200, 202, 400, 403, 404, 422, 429, 503] {
assert!(codes.contains(&code), "no case answered {code}: {seen:?}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn with_reward_enabled_and_chat_disabled_too() {
let seen = compare_all(
|config| {
config.control.allow_reward = true;
config.chat.enabled = false;
},
&cases(),
)
.await;
let status = |what: &str| seen.iter().find(|(w, _)| w == what).unwrap().1;
assert_eq!(status("POST /chat"), StatusCode::FORBIDDEN);
assert_eq!(status("POST /reward"), StatusCode::ACCEPTED);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_failed_checkpoint_an_unhealthy_loop_and_a_timeout_match_too() {
let rig = rig(|_| {}).await;
rig.sim.fail_checkpoint.store(true, Ordering::SeqCst);
for (method, uri, body) in [
(Method::POST, "/checkpoint", Vec::new()),
// The loop takes the command but never answers: both sides wait COMMAND_TIMEOUT and 503.
(
Method::POST,
"/stimulate",
serde_json::to_vec(&json!({"by": "hang", "source": "chat"})).unwrap(),
),
] {
let direct = exchange(rig.direct(), &method, uri, Some("application/json"), &body).await;
let edge = exchange(
rig.via_edge(),
&method,
uri,
Some("application/json"),
&body,
)
.await;
assert_eq!(direct, edge, "{method} {uri}");
assert!(
direct.status.is_server_error(),
"{method} {uri}: {}",
direct.status
);
}
// A loop that has not advanced for 2 s.
tokio::time::sleep(Duration::from_millis(2_100)).await;
let direct = exchange(rig.direct(), &Method::GET, "/healthz", None, &[]).await;
let edge = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await;
assert_eq!(direct, edge);
assert_eq!(direct.status, StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_large_events_page_rides_as_an_artifact_and_still_matches() {
let rig = rig(|_| {}).await;
// Enough events that the page is far over one envelope.
let mut log = flysim::eventlog::EventLog::open(
&rig.dir.path().join("more-events"),
rig.state.shared.events.clone(),
)
.unwrap();
for index in 0..2_000u64 {
log.append(
2_000 + index,
index as f64,
flysim::eventlog::NewEvent::new(
flysim::snapshot::FeedEventKind::Reward,
format!("a reasonably long reward label number {index}"),
)
.value(0.25),
);
}
let uri = "/events?since=0&limit=4096";
let direct = exchange(rig.direct(), &Method::GET, uri, None, &[]).await;
let edge = exchange(rig.via_edge(), &Method::GET, uri, None, &[]).await;
assert!(
direct.body.len() > flysim::controlbus::INLINE_MAX,
"{} bytes",
direct.body.len()
);
assert_eq!(direct, edge);
// The artifact is released once read.
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(rig.bus.router.stats().artifacts, 0);
}
/// A request body over flybus's 65,536-byte envelope (N2): the edge carries it as an artifact and
/// the answer is the one direct mode gives, whatever it is, for every body endpoint.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_request_body_over_the_envelope_gets_directs_answer() {
let rig = rig(|_| {}).await;
let mut cases = Vec::new();
for size in [49_000usize, 70_000, 300_000] {
let text = "x".repeat(size);
for uri in ["/chat", "/stimulate", "/reward"] {
cases.push(json_case(
Method::POST,
uri,
json!({"by": "viewer", "source": "points", "text": text, "message": text, "reason": text}),
));
}
}
// Over the limit and not JSON at all: direct's 400 either way.
cases.push(raw(Method::POST, "/chat", &"{".repeat(100_000)));
let mut codes = Vec::new();
for (method, uri, content_type, body) in &cases {
let direct = exchange(rig.direct(), method, uri, *content_type, body).await;
let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await;
assert_eq!(
direct,
edge,
"{method} {uri} ({} bytes): direct {} {:?} vs edge {} {:?}",
body.len(),
direct.status,
String::from_utf8_lossy(&direct.body),
edge.status,
String::from_utf8_lossy(&edge.body)
);
assert!(
!String::from_utf8_lossy(&edge.body).contains("INVALID_ENVELOPE"),
"{uri}: {:?}",
String::from_utf8_lossy(&edge.body)
);
codes.push(direct.status.as_u16());
}
eprintln!("large-body statuses: {codes:?}");
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
// Every request artifact was released once read.
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(rig.bus.router.stats().artifacts, 0);
}
/// Request bodies that ride as artifacts, larger ones first (BUS-02 review N3): each artifact is
/// exactly its own body, never a tail of the one before -- a stale byte past a smaller body's end
/// would make it a different request (or not JSON), and its answer would differ from direct's.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_smaller_request_body_after_a_larger_one_is_exactly_its_own() {
let rig = rig(|_| {}).await;
for (size, fill) in [(300_000usize, 'a'), (120_000, 'b'), (70_000, 'c'), (66_000, 'd')] {
for uri in ["/chat", "/stimulate"] {
let text = fill.to_string().repeat(size);
let (method, uri, content_type, body) = json_case(
Method::POST,
uri,
json!({"by": "viewer", "source": "points", "text": text, "message": text}),
);
let direct = exchange(rig.direct(), &method, uri, content_type, &body).await;
let edge = exchange(rig.via_edge(), &method, uri, content_type, &body).await;
assert_eq!(direct, edge, "{uri} ({} bytes, {fill:?})", body.len());
}
}
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
tokio::time::sleep(Duration::from_millis(200)).await;
let stats = rig.bus.router.stats();
assert_eq!((stats.artifacts, stats.store_bytes), (0, 0), "every request artifact released");
}
/// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's,
/// `date` aside, for a request of every kind.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn over_tcp_the_edge_answers_the_same_bytes_as_flysim() {
let rig = rig(|_| {}).await;
rig.close_edge().await;
// flysim's own listener, as direct mode binds it.
let direct_addr = common::free_port();
let listener = tokio::net::TcpListener::bind(direct_addr).await.unwrap();
let router = rig.direct();
tokio::spawn(async move { axum::serve(listener, router).await });
// The edge process's loop, on another port.
let edge_addr = common::free_port();
let config = fly_control_edge::EdgeConfig {
control_bind: edge_addr,
..rig.config.clone()
};
let metrics = std::sync::Arc::new(fly_control_edge::EdgeMetrics::default());
let edge = tokio::spawn(fly_control_edge::run(
config,
std::sync::Arc::clone(&metrics),
));
let mut waited = 0;
while metrics.connected.load(Ordering::Relaxed) == 0 {
tokio::time::sleep(Duration::from_millis(20)).await;
waited += 1;
assert!(waited < 250, "the edge never bound");
}
let body = r#"{"by":"viewer","source":"points","durationMs":300}"#;
let chat = r#"{"by":"viewer","text":"see http://x.example"}"#;
for request in [
"GET /status HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
"GET /events?since=2&limit=3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
format!(
"POST /stimulate HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
),
format!(
"POST /chat HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{chat}",
chat.len()
),
"POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
"POST /reward HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
"GET /buttons HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(),
] {
let direct = common::raw_http(direct_addr, &request).await.unwrap();
let via_edge = common::raw_http(edge_addr, &request).await.unwrap();
assert_eq!(
String::from_utf8_lossy(&direct),
String::from_utf8_lossy(&via_edge),
"{request}"
);
assert!(direct.starts_with(b"HTTP/1.1 "), "{}", String::from_utf8_lossy(&direct));
}
edge.abort();
}

View file

@ -0,0 +1,90 @@
//! `flysim::serve` with `control.via = bus`: flysim leaves the control port alone, registers the
//! control services on its embedded router, and the edge process serves the port from them.
//! This is the wiring both runtimes share (`flysim` and `flysim-session` both run `serve`).
mod common;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use flysim::config::{Config, ControlVia};
use flysim::simloop::Command;
use flysim::snapshot::FeedStatus;
#[test]
fn serve_in_control_bus_mode_leaves_the_port_to_the_edge() {
let dir = tempfile::tempdir().unwrap();
let mut config = Config::default();
config.feed.bind = common::free_port();
config.control.bind = common::free_port();
config.control.via = ControlVia::Bus;
config.feed.bus_dir = dir.path().join("bus");
let control_bind = config.control.bind;
let stop = Arc::new(AtomicBool::new(false));
let serving = {
let config = config.clone();
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
flysim::serve(
config,
move |shared, _snapshots, mut commands, _notifier| {
// A stand-in loop: beats, answers pauses, stops when told.
while !stop.load(Ordering::SeqCst) {
shared.beat();
while let Ok(command) = commands.try_recv() {
if let Command::Pause { reply } = command {
let _ = reply.send(FeedStatus::Paused);
}
}
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
},
)
})
};
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
// The router's sockets appear; flysim never binds the control port.
let started = Instant::now();
while !dir.path().join("bus/control-edge.sock").exists() {
assert!(started.elapsed() < Duration::from_secs(20), "no control socket");
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(common::raw_http(control_bind, request).await.is_none(), "flysim bound :7401");
for role in ["stage", "bridge", "watchdog", "operator"] {
assert!(dir.path().join(format!("bus/control/{role}.sock")).exists(), "{role}");
}
// The feed is still direct: no feed socket.
assert!(!dir.path().join("bus/edge.sock").exists());
let edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None);
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
let edge = tokio::spawn(fly_control_edge::run(edge_config, Arc::clone(&metrics)));
let started = Instant::now();
while metrics.connected.load(Ordering::Relaxed) == 0 {
assert!(started.elapsed() < Duration::from_secs(20), "the edge never bound");
tokio::time::sleep(Duration::from_millis(20)).await;
}
let health = common::raw_http(control_bind, request).await.unwrap();
assert!(health.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&health));
let pause = "POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
let paused = String::from_utf8(common::raw_http(control_bind, pause).await.unwrap()).unwrap();
assert!(paused.starts_with("HTTP/1.1 200"), "{paused}");
assert!(paused.ends_with("{\"status\":\"paused\"}"), "{paused}");
// flysim stops: the edge lets go of the port.
stop.store(true, Ordering::SeqCst);
let started = Instant::now();
while common::raw_http(control_bind, request).await.is_some() {
assert!(started.elapsed() < Duration::from_secs(20), ":7401 stayed bound");
tokio::time::sleep(Duration::from_millis(20)).await;
}
edge.abort();
});
serving.join().unwrap().unwrap();
}

Some files were not shown because too many files have changed in this diff Show more