Compare commits

..

No commits in common. "main" and "v0.7.5" have entirely different histories.
main ... v0.7.5

137 changed files with 1007 additions and 18012 deletions

View file

@ -136,8 +136,7 @@ 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.
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
(`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
"Feed over the bus").
(`docs/design/flybus.md`, "Feed over the bus").
- 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`
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,

View file

@ -6,12 +6,6 @@ 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
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 |
|---|---|---|
| `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,9 +1,7 @@
# flybus: the communications bus
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
`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
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default**.
Written 2026-09-22, amended 2026-09-23 (EDGE-01, below). Index only; the
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
the draft is the [conformance report](session-framework/bus-conformance.md).
@ -63,13 +61,13 @@ allocate/seal/read with quotas and router restarts, plus the conformance suites
## Wiring still pending
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
- ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
over the bus". The "no button endpoint" guarantee is a grant table there.
- **flysim control services.** The control endpoints as RPC services with grants, so the
"no button endpoint" structural guarantee is expressed as a grant table.
- **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
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
contracts byte for byte.
the feed it exists (`fly-edge`), and they keep the WebSocket contract unchanged. The
control API (:7401) is the next slice and stays in flysim until then.
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" 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
@ -190,252 +188,3 @@ Accepted for now and written down rather than fixed:
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
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

@ -1077,29 +1077,3 @@ report their cursor (and its `max`) as the entry the same way. The offset is add
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

@ -2155,110 +2155,6 @@ 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
## 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.")
@ -2288,10 +2184,9 @@ 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,
untouched).
- **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 HEAL` enters the center and `HEAL`
restores the party; from the rung-11 Pewter checkpoint (a state where `GO SHOP` is dealt, since
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.
- **Proof.** ROM-gated from the Viridian checkpoint: `GO SHOP` enters the Viridian mart and
`BUY POTION` buys one; `GO HEAL` enters the center and `HEAL` restores the party; the errand is
not offered again in Viridian; trap hunt before/after.
## 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.")

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` |
| 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) |
| 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) |
| 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) |
| 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) |
| 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,10 +187,9 @@ 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 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) |
| 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) |
| 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; 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) |
| 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) |
| 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` |
@ -346,7 +345,7 @@ behind "latest replaces only queued messages": the replacement never turns into
## The crate README's differences from the draft
Each of the differences the crate lists, kept with the sentence that allows it or fixed.
Each of the ten differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict |
| --- | --- |
@ -360,8 +359,6 @@ Each of the differences the crate lists, kept with the sentence that allows it o
| 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` |
| 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

View file

@ -207,11 +207,7 @@ 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.
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
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
local store root; absolute paths, parent traversal and symlink escapes are rejected. They
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
committed into application schemas or source configuration.
@ -538,72 +534,3 @@ before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for par
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

@ -495,97 +495,6 @@ 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

View file

@ -456,79 +456,6 @@ the CPU a thread runs on, never what an index of a parallel phase computes.
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
| Where | What |
@ -1017,24 +944,3 @@ verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
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

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

@ -1011,42 +1011,3 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
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

@ -123,22 +123,6 @@ need pct
# /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:-}")" \
|| 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
# `vgl` on a container that never had VirtualGL installed would only show up as
@ -197,11 +181,6 @@ NEED_RELOAD=0
# ---------------------------------------------------------------------------
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
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=""
# 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.
@ -213,10 +192,6 @@ if [ -n "${CPUSET:-}" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(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"
else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -433,11 +408,6 @@ The 'current' symlink has NOT been moved; the running release is untouched."
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" \
@ -452,17 +422,6 @@ The 'current' symlink has NOT been moved."
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"
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
else
@ -589,10 +548,6 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move.
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
# 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
@ -619,10 +574,6 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
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}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as
@ -631,17 +582,9 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# never enables: see that unit's header for the switch. Written
# 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
# feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
# feed counters (flysim's :9101, or flyedge's loopback :9102).
# Validated and lowercased above (feed_via_normalize).
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
# (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
@ -775,12 +718,11 @@ if [ -n "${CPUSET:-}" ]; then
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
"leaves cpuset.cpus.effective empty and the unit unstartable."
else
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")"
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day
# it is enabled it serves the page from the page's CPUs, never from flysim's; likewise
# flycontrol-edge (CTRL-01).
# it is enabled it serves the page from the page's CPUs, never from flysim's.
# flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
# (`fly-runtime session` runs it AS flysim.service, which already has them.)
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
@ -828,7 +770,7 @@ fi
# ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /opt/fly/bin"
ct_exec "$CTID" -- mkdir -p /opt/fly/bin
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone 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
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
done

View file

@ -1,332 +0,0 @@
#!/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,10 +3,8 @@
# 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 status print `legacy` or `session`, and what flysim.service runs
# fly-runtime session [--no-restart] [--no-fallback] [--no-probation]
# fly-runtime legacy [--no-restart]
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
#
@ -14,19 +12,6 @@
# 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}:
#
@ -106,7 +91,6 @@ 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}"
@ -136,7 +120,7 @@ stop_shadow() {
}
usage() {
echo "usage: fly-runtime status | session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
echo "usage: fly-runtime status | session [--no-restart] [--no-fallback] [--no-probation] | legacy [--no-restart] | fallback [reason]" >&2
exit 2
}
@ -144,20 +128,6 @@ 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') $*"
@ -206,12 +176,6 @@ 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"
}
@ -375,33 +339,26 @@ 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) ;;
session|legacy) ;;
fallback)
[ "$(id -u)" -eq 0 ] || die "run as root"
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
@ -415,9 +372,6 @@ esac
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"
@ -427,7 +381,7 @@ if [ "$command" = session ]; then
flysim-session: ${session_compat}"
fi
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
before="$(current)"
if [ -f "$DROPIN" ]; then
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
cp -f "$DROPIN" "$prev_dropin"
@ -436,7 +390,7 @@ if [ "$command" = session ]; then
switching=1
rm -f "$FELLBACK_FILE"
write_dropin
record "$(current_label) (was ${before}); compatibility ${session_compat}"
record "session (was ${before}); compatibility ${session_compat}"
if [ "$restart" -ne 1 ]; then
systemctl daemon-reload
switching=0
@ -484,7 +438,7 @@ fi
# legacy
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
before="$(current)"
switch_target=legacy
switching=1
rm -f "$DROPIN"

View file

@ -12,8 +12,7 @@
# 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)
# into the release /opt/fly/current points to, onto flysim-session
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
# without the trace if the live fly pays for the shadow
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
@ -54,17 +53,6 @@
# 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
@ -97,8 +85,6 @@ 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}"
@ -289,21 +275,14 @@ check_remote() {
start() {
need_root
local mode=remote arm=""
local mode=remote
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"
@ -332,17 +311,6 @@ start() {
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)"
@ -392,7 +360,7 @@ EOF
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"
rm -f "$DROPIN" "$REMOTE_DROPIN"
systemctl daemon-reload
log "stopped the shadow: $1"
}
@ -508,22 +476,6 @@ 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).

View file

@ -48,9 +48,6 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${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 ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
: "${FFMPEG:=/usr/bin/ffmpeg}"
@ -159,7 +156,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 "# TYPE fly_watchdog_restarts_total counter"
for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do
for unit in flysim flystage flycast mediamtx flypush flystage-web; do
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
done
# Check 7's own restart reason, kept as a separate labelset on the
@ -177,9 +174,6 @@ 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 "# TYPE fly_watchdog_encoder_degraded gauge"
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
# is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or
@ -332,30 +326,9 @@ is_enabled() {
# ============================================================================
# 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() {
local ok=1
if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then
if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
ok=0
fi
if [ -e "$FLY_STATE_HOT" ]; then
@ -373,24 +346,6 @@ check_flysim() {
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
# read-only metrics listener (infra.md section 5; not superseded by the
@ -402,86 +357,25 @@ check_control_edge() {
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
# 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() {
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
echo "$FLY_FEED_METRICS_URL"
return
fi
if [ "$(feed_via)" = "bus" ]; then
local via=""
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"
else
echo "$FLY_METRICS_URL"
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() {
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
local metrics frames clients ok=1
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
if [ -z "$metrics" ]; then
ok=0
@ -508,7 +402,7 @@ check_flystage() {
record_ok flystage
else
record_fail flystage
escalate flystage "${chain[@]}"
escalate flystage flycast
fi
}
@ -716,39 +610,6 @@ check_encoder() {
"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).
#
@ -1366,12 +1227,9 @@ check_loop() {
main() {
check_flysim
check_flyedge
check_control_edge
check_flystage
check_flycast
check_encoder
check_backend
check_mediamtx
check_flypush
check_disk

View file

@ -85,9 +85,6 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
# without a rebuild. It lands next to OUT_PATH, where package-release.sh
# looks for it.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
# 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
@ -128,12 +125,6 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
cp "$edge_built" "$edge_out"
chmod 0755 "$edge_out"
log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
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"

View file

@ -14,8 +14,6 @@
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
# left one beside FLYSIM_BIN; flyedge.service stays
# inactive on a release without it)
# 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
@ -90,13 +88,6 @@ if [ -x "$EDGE_BIN" ]; then
else
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
fi
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

View file

@ -6,22 +6,17 @@
# <unit>` and, on the 5-consecutive-failure escalation, a container
# reboot. This is the minimum NOPASSWD surface for exactly what
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
# mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
# mediamtx, flypush), plus reboot. No `systemctl stop`, no
# `enable`/`disable`, no arbitrary unit name, and no units this script
# does not itself restart (xvfb, pulse, flystage-web are never touched by
# 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 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 mediamtx.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-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,
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
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

@ -3736,62 +3736,3 @@ Trap hunt, 10 brain minutes with the real connectome from the trap checkpoint:
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

@ -518,178 +518,6 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
(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)
@ -705,12 +533,6 @@ pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0
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
@ -979,76 +801,6 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy
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)
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
@ -1182,49 +934,13 @@ 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 |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file:
```sh
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
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`.
@ -1463,50 +1179,6 @@ 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
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
Fly containers have no special reboot ordering requirement relative to each other

22
infra/env/example.env vendored
View file

@ -138,12 +138,6 @@ RAYON_THREADS=3
# 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.
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 -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
@ -327,21 +321,9 @@ FLY_MACRO_MODE=raw
# 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
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
# the same bytes. This line (written into fly.env by every deploy) is the only
# 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".
# the same bytes; enable that unit by hand (its header has the steps).
# Watchdog check 2 follows this setting to the edge's counters by itself.
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
# "timeout" (macros.md section 12.1). Session state, so a restart offers every
# target once more. Unset means the default, 10.

View file

@ -168,19 +168,6 @@ feed_via_normalize() {
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() {
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
@ -202,56 +189,31 @@ cpuset_partition() {
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
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] — 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.slice the sim's CPUs (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;
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge 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
local cpuset="$1" rayon="$2" encoder="${3:-2}" sim page enc u
read -r sim page enc <<< "$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
echo "flysim.slice $sim"
for u in flysim flysim-session; do echo "${u}.service $sim"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge; do echo "${u}.service $page"; done
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $slice_cpus"
echo "FLY_SIM_CPUS= $sim"
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

View file

@ -459,6 +459,9 @@ else
grep -qE '^ConditionPathExists=/opt/fly/current/fly-edge$' "$EDGE_UNIT" \
&& pass "flyedge.service stays inactive on a release without fly-edge" \
|| fail "flyedge.service needs ConditionPathExists=/opt/fly/current/fly-edge (a release before it has none)"
grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$EDGE_UNIT" \
&& pass "flyedge.service keeps its metrics on loopback" \
|| fail "flyedge.service FLY_EDGE_METRICS_ADDR must be a 127.0.0.1 address"
fi
# Every unit a target's Wants=/Requires= names, with backslash continuations joined and
# comments dropped: fly.target spreads both lists over several physical lines, and the
@ -507,89 +510,6 @@ if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR
else
pass "07-enable.sh and verify.sh leave flyedge.service alone"
fi
# ---------------------------------------------------------------------------
# 3b2b. The control bus edge (CTRL-01, docs/design/flybus.md, "Control over the
# bus"). flycontrol-edge.service is off unless the operator switches a
# container to FLY_CONTROL_VIA=bus, follows flysim when on, and the deploy
# writes the default. The watchdog's use of FLY_CONTROL_VIA is driven for real
# further down, next to check 2's.
# ---------------------------------------------------------------------------
echo "--- flycontrol-edge.service: follows flysim in bus mode, skipped in direct mode ---"
CEDGE_UNIT="$INFRA_DIR/units/flycontrol-edge.service"
if [ ! -f "$CEDGE_UNIT" ]; then
fail "units/flycontrol-edge.service is missing"
else
grep -qE '^After=.*\bflysim\.service\b' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service orders itself After=flysim.service" \
|| fail "flycontrol-edge.service must be After=flysim.service: flysim owns the router"
grep -qE '^Requires=.*\bflysim\.service\b' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service Requires=flysim.service" \
|| fail "flycontrol-edge.service must Require flysim.service"
grep -qE '^ExecStart=/opt/fly/current/fly-control-edge$' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service runs the release's fly-control-edge" \
|| fail "flycontrol-edge.service ExecStart must be /opt/fly/current/fly-control-edge"
grep -qE '^ConditionPathExists=/opt/fly/current/fly-control-edge$' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service stays inactive on a release without fly-control-edge" \
|| fail "flycontrol-edge.service needs ConditionPathExists=/opt/fly/current/fly-control-edge"
grep -qE '^Environment=FLY_CONTROL_BIND=127\.0\.0\.1:7401$' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service binds the contract's loopback :7401" \
|| fail "flycontrol-edge.service FLY_CONTROL_BIND must be 127.0.0.1:7401 (docs/control-api.md)"
# N1 (review of CTRL-01): Requires= alone stops the edge with flysim but never starts it
# again, so fly-loop-reset's stop and start left :7401 dead. flysim Wants= it, and the
# unit's own ExecCondition= decides by FLY_CONTROL_VIA (EDGE-02's pattern for flyedge).
grep -qE '^Wants=.*\bflycontrol-edge\.service\b' "$INFRA_DIR/units/flysim.service" \
&& pass "flysim.service Wants=flycontrol-edge.service (every flysim start brings the edge up in bus mode)" \
|| fail "flysim.service must Want flycontrol-edge.service: a stop and start of flysim (fly-loop-reset) would leave :7401 dead"
if grep -qE '^\[Install\]' "$CEDGE_UNIT"; then
fail "flycontrol-edge.service has an [Install] section; flysim's Wants= is what starts it"
else
pass "flycontrol-edge.service has no [Install] section"
fi
cond="$(sed -nE "s/^ExecCondition=\/bin\/sh -c '(.*)'\$/\1/p" "$CEDGE_UNIT")"
if [ -z "$cond" ]; then
fail "flycontrol-edge.service needs an ExecCondition= on FLY_CONTROL_VIA"
else
# Run the condition as systemd would ($$ is systemd's escape for a literal $).
cond="${cond//\$\$/\$}"
cond_bad=""
for v in "" direct Direct junk; do
FLY_CONTROL_VIA="$v" sh -c "$cond" && cond_bad="$cond_bad [$v->runs]"
done
env -u FLY_CONTROL_VIA sh -c "$cond" && cond_bad="$cond_bad [unset->runs]"
for v in bus Bus BUS; do
FLY_CONTROL_VIA="$v" sh -c "$cond" || cond_bad="$cond_bad [$v->skipped]"
done
[ -z "$cond_bad" ] \
&& pass "flycontrol-edge.service ExecCondition= runs only for FLY_CONTROL_VIA=bus (any case); direct, unset and junk skip" \
|| fail "flycontrol-edge.service ExecCondition= wrong for:$cond_bad"
fi
grep -qE '^Environment=FLY_CONTROL_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$CEDGE_UNIT" \
&& pass "flycontrol-edge.service keeps its metrics on loopback" \
|| fail "flycontrol-edge.service FLY_CONTROL_EDGE_METRICS_ADDR must be a 127.0.0.1 address"
fi
if target_pulls "$INFRA_DIR/units/fly.target" | grep -qx 'flycontrol-edge.service'; then
fail "fly.target pulls flycontrol-edge.service in; flysim.service Wants= it, the condition decides"
else
pass "fly.target does not pull flycontrol-edge.service in"
fi
if grep -E '^(ALWAYS_ON_UNITS|APP_UNITS)=' "$INFRA_DIR/07-enable.sh" "$INFRA_DIR/verify.sh" | grep -q 'flycontrol-edge'; then
fail "07-enable.sh or verify.sh lists flycontrol-edge.service as always-on"
else
pass "07-enable.sh and verify.sh leave flycontrol-edge.service alone"
fi
grep -qE '^ echo "FLY_CONTROL_VIA=\$\{FLY_CONTROL_VIA_EFFECTIVE\}"$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes FLY_CONTROL_VIA into fly.env" \
|| fail "05-deploy.sh must write FLY_CONTROL_VIA (validated) into fly.env"
grep -qE '^fly ALL=\(root\) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge\.service$' "$INFRA_DIR/config/fly-sudoers" \
&& pass "the watchdog may restart flycontrol-edge.service" \
|| fail "config/fly-sudoers must let the watchdog restart flycontrol-edge.service (check 1b)"
cv_out="$(bash -c "source '$INFRA_DIR/lib/common.sh' >/dev/null 2>&1; for v in '' direct Bus BUS http; do control_via_normalize \"\$v\" || echo refused; done" 2>&1)"
if [ "$(echo $cv_out)" = "direct direct bus bus refused" ]; then
pass "control_via_normalize: empty/direct -> direct, Bus/BUS -> bus, anything else refused"
else
fail "control_via_normalize: got '$(echo $cv_out)'"
fi
# ---------------------------------------------------------------------------
# 3b3. The shadow run (SHADOW-01, infra/units/flyshadow.service).
#
@ -815,77 +735,7 @@ rs_start "no remote file (the shadow runs on a build box; --local to override)"
rs_start "a remote file without its key" "FLY_SHADOW_REMOTE=user@box
FLY_SHADOW_REMOTE_KEY=$cs_tmp/missing-key
FLY_SHADOW_REMOTE_KNOWN_HOSTS=$cs_tmp/missing-known"
# BUS-01: only the legacy loop writes the trace, so `start` refuses while flysim.service runs the
# session runtime; `--bus` needs the release's fly-session worker beside fly-shadow.
bs_start() { # name, expect (refuse|proceed), runtime drop-in (yes|no), worker (yes|no), args...
local name="$1" expect="$2" rt="$3" worker="$4" rc=0 out
shift 4
: > "$cs_tmp/systemctl.log"
rm -f "$cs_tmp/10-runtime.conf" "$cs_tmp/fly-session"
[ "$rt" = yes ] && printf '[Service]\nExecStart=/opt/fly/current/flysim-session\n' > "$cs_tmp/10-runtime.conf"
[ "$worker" = yes ] && { printf '#!/bin/sh\nexit 0\n' > "$cs_tmp/fly-session"; chmod +x "$cs_tmp/fly-session"; }
out="$(PATH="$cs_tmp/bin:$PATH" CS_DIR="$cs_tmp" CS_SHADOW_CPUS="0 2" CS_SIM_CPUS="1 3" \
FLY_SHADOW_DIR="$cs_tmp/shadow" FLY_SHADOW_BIN="$cs_tmp/fly-shadow" \
FLY_SHADOW_CPUSET_DROPIN="$cs_tmp/dropin.conf" FLY_SHADOW_REMOTE_ENV="$cs_tmp/no-remote.env" \
FLY_SHADOW_REMOTE_DROPIN_DIR="$cs_tmp/flyshadow.d" FLY_RUNTIME_DROPIN="$cs_tmp/10-runtime.conf" \
FLY_SHADOW_BASELINE_SECONDS=30 FLY_METRICS_URL=http://127.0.0.1:1 \
"$INFRA_DIR/bin/fly-shadow-run" start "$@" 2>&1)" || rc=$?
case "$expect" in
refuse)
if [ "$rc" -ne 0 ] && ! grep -qE '^(start|restart|daemon-reload)' "$cs_tmp/systemctl.log" \
&& [ ! -e "$cs_tmp/flyshadow.d/mode.conf" ]; then
pass "fly-shadow-run start refuses, $name: ${out#fly-shadow-run: }"
else
fail "fly-shadow-run start must refuse and start nothing, $name (rc=$rc): $out"
fi ;;
proceed)
if echo "$out" | grep -q 'stub install reached'; then
pass "fly-shadow-run start proceeds, $name"
else
fail "fly-shadow-run start must proceed, $name (rc=$rc): $out"
fi ;;
esac
}
bs_start "the live fly on the session runtime (no trace to follow)" refuse yes yes --local
bs_start "--bus without fly-session in the release" refuse no no --local --bus
bs_start "--bus with fly-session, live on legacy" proceed no yes --local --bus
rm -rf "$cs_tmp"
# BUS-01: `check --bus` asks fly-shadow for a verdict that ran the bus topology.
if command -v python3 >/dev/null 2>&1; then
cb_tmp="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-checkbus.XXXXXX")"
mkdir -p "$cb_tmp/bin" "$cb_tmp/shadow"
printf '#!/bin/sh\ncase "$1" in is-active) exit 0 ;; esac\nexit 0\n' > "$cb_tmp/bin/systemctl"
printf '#!/bin/sh\necho "$*" > "%s/args"\n' "$cb_tmp" > "$cb_tmp/fly-shadow"
chmod +x "$cb_tmp/bin/systemctl" "$cb_tmp/fly-shadow"
printf '{"rtfMean":1,"rtfSd":0,"lagRate":0,"samples":60,"margin":0.05}\n' > "$cb_tmp/shadow/baseline.json"
printf '{"status":"pass"}\n' > "$cb_tmp/shadow/verdict.json"
PATH="$cb_tmp/bin:$PATH" FLY_SHADOW_DIR="$cb_tmp/shadow" FLY_SHADOW_BIN="$cb_tmp/fly-shadow" \
FLY_SHADOW_REMOTE_DROPIN_DIR="$cb_tmp/none.d" FLY_ENV_FILE="$cb_tmp/none.env" \
"$INFRA_DIR/bin/fly-shadow-run" check --bus >/dev/null 2>&1 || true
if grep -q -- '--binary flysim-session --require-arm bus/process$' "$cb_tmp/args" 2>/dev/null; then
pass "fly-shadow-run check --bus requires a verdict that ran bus/process (fly-shadow check --require-arm)"
else
fail "fly-shadow-run check --bus must pass --require-arm bus/process to fly-shadow check ($(cat "$cb_tmp/args" 2>/dev/null))"
fi
# BUS-01 review N1: `check` (plain and --bus) refuses while the live fly runs the session
# runtime, which writes no trace for the shadow to follow, and never asks fly-shadow.
printf '[Service]\nExecStart=/opt/fly/current/flysim-session\n' > "$cb_tmp/10-runtime.conf"
for ck_args in "" "--bus"; do
rm -f "$cb_tmp/args"
ck_rc=0
# shellcheck disable=SC2086
ck_out="$(PATH="$cb_tmp/bin:$PATH" FLY_SHADOW_DIR="$cb_tmp/shadow" FLY_SHADOW_BIN="$cb_tmp/fly-shadow" \
FLY_SHADOW_REMOTE_DROPIN_DIR="$cb_tmp/none.d" FLY_ENV_FILE="$cb_tmp/none.env" \
FLY_RUNTIME_DROPIN="$cb_tmp/10-runtime.conf" \
"$INFRA_DIR/bin/fly-shadow-run" check $ck_args 2>&1)" || ck_rc=$?
if [ "$ck_rc" -ne 0 ] && echo "$ck_out" | grep -q 'runs the session runtime' && [ ! -e "$cb_tmp/args" ]; then
pass "fly-shadow-run check${ck_args:+ $ck_args} refuses while the live fly runs the session runtime"
else
fail "fly-shadow-run check${ck_args:+ $ck_args} must refuse while the session runtime drop-in exists (rc=$ck_rc): $ck_out"
fi
done
rm -rf "$cb_tmp"
fi
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute
# old), of this run (the drop-in's id, the verdict's too), without coverageLost (review B1: flysim
# stopped its trace for want of a consumer) and with a live trace written in the last 90 s.
@ -1155,50 +1005,6 @@ if fly_runtime && [ ! -f "$rt_dropin" ]; then
else
fail "fly-runtime legacy must remove the drop-in and succeed"
fi
# BUS-01: the bus transport. `session-bus` (= `session --bus`) adds FLY_SESSION_TRANSPORT=bus to
# the drop-in and needs the release's fly-session worker; a flag-less `session` (05-deploy's
# refresh) keeps the transport; `session --local` is the way back; status says which.
rt_status() { env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null; }
RT_ARGS=(session-bus)
if ! fly_runtime && [ ! -f "$rt_dropin" ]; then
pass "fly-runtime session-bus refuses a release without the fly-session worker"
else
fail "fly-runtime session-bus must refuse without \$FLY_RELEASE_DIR/fly-session and write nothing"
fi
printf '#!/usr/bin/env bash\nexit 0\n' > "$rt_dir/release/fly-session"
chmod +x "$rt_dir/release/fly-session"
if fly_runtime && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$rt_dropin" \
&& grep -qx "ExecStart=$rt_dir/release/flysim-session" "$rt_dropin" \
&& grep -qx 'OnFailure=fly-runtime-fallback.service' "$rt_dropin" \
&& [ "$(rt_status | head -n1)" = session ] \
&& rt_status | grep -qx ' transport: bus' \
&& tail -n1 "$rt_dir/runtime.log" | grep -q 'session-bus (was legacy)'; then
pass "fly-runtime session-bus: the drop-in adds FLY_SESSION_TRANSPORT=bus (fallback and probation unchanged); status: session, transport bus"
else
fail "fly-runtime session-bus: drop-in/status/log wrong ($(tr '\n' ' ' < "$rt_dropin" 2>/dev/null); $(tail -n1 "$rt_dir/runtime.log"))"
fi
RT_ARGS=(session --no-restart)
if fly_runtime && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$rt_dropin"; then
pass "fly-runtime session --no-restart (05-deploy's refresh) keeps the bus transport"
else
fail "fly-runtime session --no-restart must keep the drop-in's transport"
fi
RT_ARGS=(session --local)
if fly_runtime && [ -f "$rt_dropin" ] && ! grep -q 'FLY_SESSION_TRANSPORT' "$rt_dropin" \
&& rt_status | grep -qx ' transport: local' \
&& tail -n1 "$rt_dir/runtime.log" | grep -q 'session (was session-bus)'; then
pass "fly-runtime session --local takes the session off the bus (status: transport local)"
else
fail "fly-runtime session --local must drop FLY_SESSION_TRANSPORT from the drop-in"
fi
RT_ARGS=(legacy --bus)
if ! fly_runtime && [ -f "$rt_dropin" ]; then
pass "fly-runtime legacy --bus is refused (usage)"
else
fail "fly-runtime legacy --bus must be refused"
fi
rm -f "$rt_dir/release/fly-session"
RT_ARGS=(legacy); fly_runtime || fail "fly-runtime legacy after the bus tests failed"
RT_ARGS=(session)
if ! fly_runtime RT_COMPAT_FLYSIM_SESSION=other && [ ! -f "$rt_dropin" ]; then
pass "fly-runtime session refuses when the two compatibility strings differ"
@ -1591,430 +1397,9 @@ else
feed_url_case "BUS" "FLY_FEED_VIA=BUS" "" "http://edge"
feed_url_case "quoted bus" 'FLY_FEED_VIA="bus"' "" "http://edge"
feed_url_case "explicit override wins" "FLY_FEED_VIA=bus" "http://other" "http://other"
# Check 1 reads flysim's own /healthz: :7401 when flysim serves it, flysim's read-only
# listener when the control edge does (FLY_CONTROL_VIA=bus), so an edge outage never
# restarts the fly (CTRL-01).
health_url_case() {
local label="$1" env_line="$2" want="$3" got
printf '%s\n' "$env_line" > "$fe_fixture/fly.env"
got="$(FLY_ENV_FILE="$fe_fixture/fly.env" FLY_CONTROL_URL=http://control \
FLY_METRICS_URL=http://sim \
WD_RUN_DIR="$fe_fixture/run" WD_STATE_DIR="$fe_fixture/state" \
TEXTFILE_DIR="$fe_fixture/textfile" \
bash -c "source '$fe_fixture/wd.sh'; flysim_health_url" 2>&1 || true)"
if [ "$got" = "$want" ]; then
pass "check 1 flysim health: $label -> $got"
else
fail "check 1 flysim health: $label: got '$got', want '$want'"
fi
}
health_url_case "direct" "FLY_CONTROL_VIA=direct" "http://control/healthz"
health_url_case "no FLY_CONTROL_VIA line" "FLY_FEED_VIA=bus" "http://control/healthz"
health_url_case "bus" "FLY_CONTROL_VIA=bus" "http://sim/healthz"
health_url_case "Bus" 'FLY_CONTROL_VIA="Bus"' "http://sim/healthz"
rm -rf "$fe_fixture"
fi
# ---------------------------------------------------------------------------
# 3b2b. EDGE-02: the feed on the bus in production. fly.env's FLY_FEED_VIA is the one switch:
# flysim.service Wants= the edge, the edge's ExecCondition= skips it in direct mode, `fly-feed`
# rewrites the line and restarts flysim, the watchdog judges the edge only while flysim itself
# serves it through the bus. Driven for real against stubs.
# ---------------------------------------------------------------------------
echo "--- EDGE-02: flyedge is skipped in direct mode, started by every flysim start in bus mode ---"
grep -qE '^Wants=.*\bflyedge\.service\b' "$INFRA_DIR/units/flysim.service" \
&& pass "flysim.service Wants=flyedge.service (every flysim start brings the edge up in bus mode)" \
|| fail "flysim.service must Want flyedge.service: a stop and start of flysim (fly-loop-reset) would leave the edge down"
grep -qE '^ExecCondition=.*FLY_FEED_VIA.*\[Bb\]\[Uu\]\[Ss\]' "$EDGE_UNIT" \
&& pass "flyedge.service runs only when FLY_FEED_VIA is bus (ExecCondition=, any case)" \
|| fail "flyedge.service needs an ExecCondition= on FLY_FEED_VIA (case-insensitive bus)"
if grep -qE '^\[Install\]' "$EDGE_UNIT"; then
fail "flyedge.service has an [Install] section; flysim's Wants= is what starts it"
else
pass "flyedge.service has no [Install] section"
fi
grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=[0-9.]+:9102$' "$EDGE_UNIT" \
&& pass "flyedge.service serves its metrics on :9102 (the dashboard's second target; the watchdog uses loopback)" \
|| fail "flyedge.service FLY_EDGE_METRICS_ADDR must be an address on :9102"
if grep -qE '^Wants=.*flyedge' "$INFRA_DIR/units/flysim-session.service"; then
fail "flysim-session.service Wants flyedge.service, whose Requires=flysim.service would start the unit it Conflicts with"
else
pass "flysim-session.service (the standalone rehearsal unit) does not pull the edge in"
fi
grep -qE 'for name in .*\bfly-feed\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh installs fly-feed" \
|| fail "05-deploy.sh must converge bin/fly-feed to /opt/fly/bin"
grep -qF 'this release has no fly-edge' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"${release_path}/fly-edge"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without fly-edge while the feed is on the bus (before the symlink moves)" \
|| fail "05-deploy.sh must refuse a release without fly-edge when FLY_FEED_VIA is bus (env file or container)"
grep -qE '^fly ALL=\(root\) NOPASSWD: /usr/bin/systemctl restart flyedge\.service$' "$INFRA_DIR/config/fly-sudoers" \
&& grep -qE '^fly ALL=\(root\) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait$' "$INFRA_DIR/config/fly-sudoers" \
&& pass "sudoers lets the watchdog restart flyedge and run exactly 'fly-feed direct --no-wait'" \
|| fail "config/fly-sudoers must grant the watchdog 'systemctl restart flyedge.service' and 'fly-feed direct --no-wait'"
echo "--- fly-feed: bus, direct, status, rollback ---"
ff_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-feed.XXXXXX")"
mkdir -p "$ff_dir/bin" "$ff_dir/release" "$ff_dir/proc/4242" "$ff_dir/run"
cat > "$ff_dir/bin/systemctl" <<'FFSTUB'
#!/usr/bin/env bash
echo "$*" >> "$FF_DIR/systemctl.log"
# FF_SLOW: answer is-active late, as a real systemctl does, so a reader can leave in between
[ -n "${FF_SLOW:-}" ] && [ "$1" = is-active ] && sleep 0.3
case "$1" in
restart) n=$(( $(cat "$FF_DIR/invocation" 2>/dev/null || echo 1) + 1 )); echo "$n" > "$FF_DIR/invocation"
# the new flysim's environment is whatever fly.env says now
v="$(awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' "$FF_ENV")"
printf 'FLY_FEED_VIA=%s\0' "$v" > "$FF_DIR/proc/4242/environ" ;;
show) case "$*" in
*MainPID*) echo 4242 ;;
*InvocationID*) echo "inv$(cat "$FF_DIR/invocation" 2>/dev/null || echo 1)" ;;
esac ;;
is-active)
case "${*: -1}" in
flystage.service) [ "${FF_PAGE:-1}" = 1 ]; exit $? ;;
flyedge.service) [ "${FF_EDGE_ACTIVE:-0}" = 1 ]; exit $? ;;
esac ;;
esac
exit 0
FFSTUB
cat > "$ff_dir/bin/curl" <<'FFSTUB'
#!/usr/bin/env bash
url="${*: -1}"
quiet=0; for a in "$@"; do [ "$a" = /dev/null ] && quiet=1; done
case "$url" in
http://control/healthz) [ "${FF_CONTROL_OK:-1}" = 1 ] || exit 22; exit 0 ;;
http://edge/healthz) [ "${FF_EDGE_OK:-1}" = 1 ] || exit 22; exit 0 ;;
http://sim/metrics|http://edge/metrics)
n=$(( $(cat "$FF_DIR/frames" 2>/dev/null || echo 1000) + 30 )); echo "$n" > "$FF_DIR/frames"
[ "${FF_FLAT:-0}" = 1 ] && n=1000
echo "fly_feed_clients ${FF_CLIENTS:-1}"; echo "fly_frames_sent_total $n"
echo "fly_edge_snapshot_age_seconds 0.03"; echo "fly_edge_bus_lost_total 0" ;;
*) exit 22 ;;
esac
FFSTUB
printf '#!/usr/bin/env bash\necho 0\n' > "$ff_dir/bin/id"
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/bin/logger"
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"
chmod +x "$ff_dir"/bin/* "$ff_dir/release/fly-edge"
ff_env="$ff_dir/fly.env"
fly_feed() {
env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \
FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \
FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \
FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=3 FLY_FEED_SAMPLE_SECONDS=0 \
"$@" bash "$INFRA_DIR/bin/fly-feed" "${FF_ARGS[@]}"
}
ff_reset() { # ff_reset VIA_IN_FILE VIA_RUNNING
printf 'FLY_GAME=pokemon-red\nFLY_FEED_VIA=%s\nFLY_MACRO_MODE=raw\n' "$1" > "$ff_env"
chmod 0640 "$ff_env"
printf 'FLY_FEED_VIA=%s\0' "$2" > "$ff_dir/proc/4242/environ"
: > "$ff_dir/systemctl.log"; rm -f "$ff_dir/feed.log" "$ff_dir/frames" "$ff_dir/invocation"
}
ff_restarts() { grep -c '^restart --no-block flysim.service$' "$ff_dir/systemctl.log" || true; }
ff_reset direct direct
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
if printf '%s\n' "$ff_out" | grep -qx 'configured: direct' && printf '%s\n' "$ff_out" | grep -qx 'running: direct'; then
pass "fly-feed status: direct, running direct"
else
fail "fly-feed status wrong: $ff_out"
fi
# `fly-feed status | head -1` under `pct exec`, which runs commands with SIGPIPE ignored: every
# write after head exits fails with EPIPE, and bash prints "write error: Broken pipe" unless
# fly-feed stops printing quietly (seen live on 2026-10-02). Reproduce both conditions: SIGPIPE
# ignored (inherited by the script) and a reader that leaves after the first line.
ff_reset direct direct
FF_ARGS=(status)
ff_pipe_err="$(mktemp)"
( trap '' PIPE; export FF_SLOW=1; fly_feed 2>"$ff_pipe_err" ) | head -1 >/dev/null || true
if [ ! -s "$ff_pipe_err" ]; then
pass "fly-feed status | head -1 with SIGPIPE ignored: nothing written to stderr"
else
fail "fly-feed status | head -1 wrote to stderr: $(cat "$ff_pipe_err")"
fi
rm -f "$ff_pipe_err"
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed && [ "$(grep -c '^FLY_FEED_VIA=' "$ff_env")" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env" \
&& grep -qx 'FLY_GAME=pokemon-red' "$ff_env" && grep -qx 'FLY_MACRO_MODE=raw' "$ff_env" \
&& [ "$(stat -c %a "$ff_env")" = 640 ] && [ "$(ff_restarts)" = 1 ] && grep -q 'bus: healthy' "$ff_dir/feed.log"; then
pass "fly-feed bus: one FLY_FEED_VIA line, the rest and the mode kept, flysim restarted once, healthy on the edge's counters"
else
fail "fly-feed bus: wrong ($(tr '\n' ' ' < "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null))"
fi
FF_ARGS=(bus)
: > "$ff_dir/systemctl.log"
if fly_feed && [ "$(ff_restarts)" = 0 ]; then
pass "fly-feed bus when already bus and running bus: nothing to do, no restart"
else
fail "fly-feed bus must not restart flysim when fly.env and the running process already say bus"
fi
# A deploy wrote bus but the running flysim started direct: `bus` applies it (and a bus fly.env is not its own way back).
ff_reset bus direct
FF_ARGS=(bus)
if fly_feed && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env"; then
pass "fly-feed bus applies a fly.env that says bus to a flysim that started direct"
else
fail "fly-feed bus must restart flysim when fly.env says bus and it is running direct"
fi
ff_reset bus bus
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
if printf '%s\n' "$ff_out" | grep -q '^edge healthz: ok'; then
pass "fly-feed status in bus mode reads the edge"
else
fail "fly-feed status in bus mode must report the edge's healthz"
fi
ff_reset Bus direct
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
printf '%s\n' "$ff_out" | grep -qx 'configured: bus' \
&& pass "fly-feed reads FLY_FEED_VIA=Bus as bus (flysim lowercases it)" \
|| fail "fly-feed must read FLY_FEED_VIA case-insensitively"
# A bus that never becomes healthy (the edge answers 503) rolls back to direct and says so.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_EDGE_OK=0; then
fail "fly-feed bus must exit non-zero when the edge never becomes healthy"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 2 ] && grep -q 'automatic rollback' "$ff_dir/feed.log"; then
pass "fly-feed bus rolls back to direct, restarting flysim again, when the edge is not healthy"
else
fail "fly-feed bus rollback wrong ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts))"
fi
# A page that never reaches the feed (no clients) is not healthy either; --no-rollback leaves the switch in place.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_CLIENTS=0; then
fail "fly-feed bus must not call a feed with no page on it healthy while flystage is active"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env"; then
pass "fly-feed bus: a page that never connects is a failed switch, rolled back"
else
fail "fly-feed bus with no client must roll back"
fi
ff_reset direct direct
FF_ARGS=(bus --no-rollback)
if fly_feed FF_EDGE_OK=0; then
fail "--no-rollback: must still fail"
elif grep -qx 'FLY_FEED_VIA=bus' "$ff_env" && [ "$(ff_restarts)" = 1 ]; then
pass "fly-feed bus --no-rollback leaves the switch as it is when unhealthy"
else
fail "--no-rollback must leave FLY_FEED_VIA=bus and restart once"
fi
# Frames that never advance are not a feed.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_FLAT=1; then fail "flat frames counter must not be healthy"; else pass "fly-feed bus: a frames counter that does not move is not healthy"; fi
# No page unit: the wait ends at the edge's healthz.
ff_reset direct direct
FF_ARGS=(bus)
fly_feed FF_PAGE=0 FF_CLIENTS=0 \
&& pass "fly-feed bus on a box with no active page unit waits for the edge only" \
|| fail "fly-feed bus with flystage inactive must succeed on the edge's healthz alone"
# A release without fly-edge refuses before touching anything.
ff_reset direct direct
rm -f "$ff_dir/release/fly-edge"
FF_ARGS=(bus)
if fly_feed; then
fail "fly-feed bus must refuse a release without fly-edge"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ]; then
pass "fly-feed bus refuses a release without fly-edge, changing and restarting nothing"
else
fail "refusal must leave fly.env and flysim alone"
fi
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge"
# direct: the way back, which works with no fly-edge at all and stops a lingering edge.
ff_reset bus bus
rm -f "$ff_dir/release/fly-edge"
FF_ARGS=(direct)
if fly_feed FF_EDGE_ACTIVE=1 && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 1 ] \
&& grep -qx 'stop flyedge.service' "$ff_dir/systemctl.log" && grep -q 'direct: healthy' "$ff_dir/feed.log"; then
pass "fly-feed direct: back to flysim on :7400 with no fly-edge in the release, a lingering edge stopped"
else
fail "fly-feed direct wrong ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/systemctl.log" | tr '\n' ';'))"
fi
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge"
ff_reset bus bus
FF_ARGS=(direct --no-restart)
fly_feed && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ] \
&& pass "fly-feed direct --no-restart writes the line and restarts nothing" \
|| fail "--no-restart must only write fly.env"
ff_reset bus bus
FF_ARGS=(direct --no-wait)
fly_feed FF_CONTROL_OK=0 && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" \
&& pass "fly-feed direct --no-wait (the watchdog's fallback) restarts flysim and returns without a health wait" \
|| fail "--no-wait must restart flysim and return 0 whatever the health"
ff_reset 'buss' direct
FF_ARGS=(bus)
if fly_feed; then fail "fly-feed must refuse an invalid FLY_FEED_VIA"; else pass "fly-feed refuses an invalid FLY_FEED_VIA in fly.env, touching nothing"; fi
# An interrupted switch (INT/TERM/HUP) rolls back: the stub restart hangs the health wait; kill it mid-way.
ff_reset direct direct
FF_ARGS=(bus)
env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \
FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \
FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \
FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=30 FLY_FEED_SAMPLE_SECONDS=0 FF_EDGE_OK=0 \
bash "$INFRA_DIR/bin/fly-feed" bus >/dev/null 2>&1 &
ff_pid=$!
sleep 2
kill -TERM "$ff_pid" 2>/dev/null || true
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$ff_pid" 2>/dev/null || break; sleep 0.5; done
(kill -0 "$ff_pid" 2>/dev/null && kill -KILL "$ff_pid" 2>/dev/null) || true
wait "$ff_pid" 2>/dev/null || true
if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && grep -q 'interrupted or failed' "$ff_dir/feed.log" 2>/dev/null; then
pass "fly-feed bus interrupted mid-switch puts FLY_FEED_VIA back"
else
fail "an interrupted fly-feed bus must roll back ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))"
fi
# N2 (EDGE-02 notes): an interrupted `fly-feed direct` is never rolled back to bus: direct is the
# safe terminal state, and flysim is restarted so the running process matches the line.
ff_reset bus bus
env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \
FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \
FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \
FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=30 FLY_FEED_SAMPLE_SECONDS=0 FF_CONTROL_OK=0 \
bash "$INFRA_DIR/bin/fly-feed" direct >/dev/null 2>&1 &
ff_pid=$!
sleep 2
kill -TERM "$ff_pid" 2>/dev/null || true
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$ff_pid" 2>/dev/null || break; sleep 0.5; done
(kill -0 "$ff_pid" 2>/dev/null && kill -KILL "$ff_pid" 2>/dev/null) || true
wait "$ff_pid" 2>/dev/null || true
if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && ! grep -q 'FLY_FEED_VIA=bus' "$ff_env" \
&& grep -q 'kept: direct is the safe state' "$ff_dir/feed.log" 2>/dev/null && [ "$(ff_restarts)" -ge 2 ]; then
pass "fly-feed direct interrupted mid-switch stays on direct (never back to bus), flysim restarted to match"
else
fail "an interrupted fly-feed direct must end on direct ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))"
fi
rm -rf "$ff_dir"
echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---"
wf_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-wdedge.XXXXXX")"
mkdir -p "$wf_dir/bin" "$wf_dir/proc/4242" "$wf_dir/run" "$wf_dir/state" "$wf_dir/textfile"
cat > "$wf_dir/bin/systemctl" <<'WFSTUB'
#!/usr/bin/env bash
case "$1" in
show) echo 4242 ;;
is-active) [ "${WF_EDGE_ACTIVE:-1}" = 1 ]; exit $? ;;
restart) echo "restart $2" >> "$WF_DIR/actions.log" ;;
esac
exit 0
WFSTUB
cat > "$wf_dir/bin/sudo" <<'WFSTUB'
#!/usr/bin/env bash
if [ "$1" = /usr/bin/systemctl ]; then shift; exec systemctl "$@"; fi
echo "sudo $*" >> "$WF_DIR/actions.log"
exit 0
WFSTUB
cat > "$wf_dir/bin/curl" <<'WFSTUB'
#!/usr/bin/env bash
url="${*: -1}"
case "$url" in
http://control/healthz) [ "${WF_CONTROL_OK:-1}" = 1 ] || exit 22 ;;
http://edge/healthz) [ "${WF_EDGE_OK:-1}" = 1 ] || exit 22 ;;
http://edge/metrics) echo "fly_frames_sent_total ${WF_EDGE_FRAMES:-100}"; echo "fly_feed_clients 1" ;;
http://sim/metrics) echo "fly_frames_sent_total ${WF_SIM_FRAMES:-0}"; echo "fly_feed_clients 0" ;;
*) exit 22 ;;
esac
WFSTUB
printf '#!/usr/bin/env bash\ncat >/dev/null\n' > "$wf_dir/bin/systemd-cat"
chmod +x "$wf_dir"/bin/*
sed '$d' "$INFRA_DIR/bin/fly-watchdog" > "$wf_dir/wd.sh"
wd_edge() { # wd_edge VIA_RUNNING 'ENV...' -- COMMANDS
local via="$1"; shift
printf 'FLY_FEED_VIA=%s\0' "$via" > "$wf_dir/proc/4242/environ"
env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" \
FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge \
WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" \
"$@" bash -c "source '$wf_dir/wd.sh'; $WD_CMDS" >/dev/null 2>&1 || true
}
wd_acts() { cat "$wf_dir/actions.log" 2>/dev/null | tr '\n' ';'; }
wd_reset() { : > "$wf_dir/actions.log"; rm -f "$wf_dir/run"/*; }
echo 'FLY_FEED_VIA=bus' > "$wf_dir/fly.env"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge direct
[ -z "$(wd_acts)" ] && pass "check 2a does nothing in direct mode" || fail "check 2a acted in direct mode: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0 WF_CONTROL_OK=0
[ -z "$(wd_acts)" ] && pass "check 2a leaves a down flysim to check 1" || fail "check 2a acted while flysim was down: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=1
[ -z "$(wd_acts)" ] && pass "check 2a: a healthy edge is left alone" || fail "check 2a acted on a healthy edge: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge'
wd_edge bus WF_EDGE_OK=0
[ -z "$(wd_acts)" ] && pass "check 2a lets the first failed pass go (a flysim that only just answered)" || fail "check 2a acted on the first failure: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"restart flyedge.service;") pass "check 2a: the second failed pass restarts flyedge" ;;
*) fail "check 2a second failure should restart flyedge only: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"restart flyedge.service;restart flyedge.service;restart flystage.service;restart flycast.service;") pass "check 2a: the third restarts the page and the encoder as well" ;;
*) fail "check 2a third failure: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
*"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: the fourth failed pass puts the feed back on flysim (fly-feed direct --no-wait)" ;;
*) fail "check 2a fourth failure must run fly-feed direct --no-wait: $(wd_acts)" ;;
esac
# N3 (EDGE-02 notes): failures spread over more than 15 minutes (passes are skipped while flysim is
# down) still fall back to direct from the 4th, and a long run of edge failures never reboots.
wd_reset; WD_CMDS='f="$(fails_file flyedge)"; for i in 1 2 3 4 5 6; do echo $(( $(now) - 7200 + i )) >> "$f"; done; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: failures older than 15 minutes still fall back to direct, with no restart chain and no reboot" ;;
*) fail "check 2a with a stretched failure run must run fly-feed direct only: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
if ! grep -q reboot "$wf_dir/actions.log" 2>/dev/null && [ ! -e "$wf_dir/state/last-reboot" ]; then
pass "check 2a: eight failed passes (fly-feed direct unable to fix it) never reboot the container"
else
fail "an edge fault must never reboot: $(wd_acts)"
fi
wd_reset; WD_CMDS='check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0
case "$(wd_acts)" in
"restart flyedge.service;") pass "check 2a: an inactive edge in bus mode is a failure like an unhealthy one" ;;
*) fail "check 2a inactive edge: $(wd_acts)" ;;
esac
# fly.env says bus but the running flysim started direct (a deploy, not yet restarted): it serves the feed itself.
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge direct WF_EDGE_OK=0 WF_EDGE_ACTIVE=0
[ -z "$(wd_acts)" ] && pass "check 2a follows the running flysim, not fly.env: a pending switch is not an outage" || fail "check 2a acted on a pending switch: $(wd_acts)"
WD_CMDS='feed_metrics_url'
got="$(printf 'FLY_FEED_VIA=direct\0' > "$wf_dir/proc/4242/environ"; env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" bash -c "source '$wf_dir/wd.sh'; feed_metrics_url" 2>/dev/null || true)"
[ "$got" = http://sim ] && pass "check 2 reads flysim's counters while the running flysim serves the feed itself" || fail "check 2 URL for a pending switch: $got"
# Check 2 in bus mode: an unhealthy edge is check 2a's, not a reason to restart the page; a healthy
# edge with a flat frames counter restarts the page and, after three, the edge and the encoder.
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage'
wd_edge bus WF_EDGE_OK=0
[ -z "$(wd_acts)" ] && pass "check 2 in bus mode leaves a silent edge to check 2a (the page is not restarted)" || fail "check 2 restarted things while the edge was down: $(wd_acts)"
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage'
wd_edge bus WF_EDGE_OK=1 WF_EDGE_FRAMES=100
case "$(wd_acts)" in
"restart flystage.service;restart flystage.service;restart flystage.service;restart flyedge.service;restart flycast.service;")
pass "check 2 in bus mode: frames flat restarts the page, then the edge and the encoder in the chain" ;;
*) fail "check 2 bus chain: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage'
wd_edge direct WF_SIM_FRAMES=100
case "$(wd_acts)" in
*"restart flyedge"*) fail "check 2 in direct mode must not touch the edge: $(wd_acts)" ;;
*) pass "check 2 in direct mode never restarts the edge" ;;
esac
rm -rf "$wf_dir"
# ---------------------------------------------------------------------------
# 3c. lib/common.sh cpuset_partition — the three-way cpuset split used by
# 05-deploy.sh section 3b (flysim / page-capture / flycast). Run as its own
@ -2101,8 +1486,8 @@ set -euo pipefail
PLANEOF
chmod +x "$plan_bin"
check_plan() {
local label="$1" cpuset="$2" rayon="$3" encoder="$4" aux="${5:-0}" plan sim other u cpus bad=""
plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" "$aux" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; }
local label="$1" cpuset="$2" rayon="$3" encoder="$4" plan sim other u cpus bad=""
plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; }
sim="$(awk '$1 == "flysim.slice" {print $2}' <<< "$plan")"
other="$(awk '$1 == "FLY_OTHER_CPUS=" {print $2}' <<< "$plan")"
[ "$sim" = "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$plan")" ] || bad="$bad SIM-list-differs-from-slice"
@ -2111,7 +1496,7 @@ check_plan() {
done
# every other unit, and the confinement list, is disjoint from the sim's cpus
while read -r u cpus; do
case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=|FLY_AUX_CPUS=) continue ;; esac
case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=) continue ;; esac
if [ -n "$(comm -12 <(tr ',' '\n' <<< "$sim" | sort) <(tr ',' '\n' <<< "$cpus" | sort))" ]; then
bad="$bad $u-overlaps-sim"
fi
@ -2129,29 +1514,6 @@ check_plan() {
}
check_plan "release shape (sixteen cpus, four sim, four encoder)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4
check_plan "ten cpus, ENCODER_CORES=3" "1,3,5,7,9,11,13,15,17,19" 4 3
check_plan "release shape with one aux cpu (EDGE-02 N1)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1
check_plan "release shape with two aux cpus" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2
# The aux cpu is the last page cpu, is in flysim.slice, is in FLY_SIM_CPUS (so fly-cpu-confine keeps every
# other process off it), is named in FLY_AUX_CPUS and is in no page or encoder unit.
aux_plan="$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1 2>&1)"
if [ "$(awk '$1 == "flysim.slice" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \
&& [ "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \
&& [ "$(awk '$1 == "FLY_AUX_CPUS=" {print $2}' <<< "$aux_plan")" = "35" ] \
&& [ "$(awk '$1 == "xvfb.service" {print $2}' <<< "$aux_plan")" = "9,11,13,15,29,31,33" ] \
&& ! grep -q "FLY_AUX_CPUS=" <<< "$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2>&1)"; then
pass "cpuset_dropin_plan: the aux cpu (35) is flysim.slice's, in FLY_SIM_CPUS, off every page unit; none without SESSION_AUX_CPUS"
else
fail "cpuset_dropin_plan: aux cpu wiring wrong: $aux_plan"
fi
if "$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,17,19" 4 3 3 >/dev/null 2>&1; then
fail "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu must be refused"
else
pass "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu is refused"
fi
grep -q 'FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}' "$INFRA_DIR/05-deploy.sh" \
&& grep -q 'SESSION_AUX_EFFECTIVE")"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes FLY_SESSION_AUX_CPUS and passes the aux count to the plan" \
|| fail "05-deploy.sh must write FLY_SESSION_AUX_CPUS and pass SESSION_AUX_EFFECTIVE to cpuset_dropin_plan"
check_plan "eight cpus, default encoder" "1,3,5,7,9,11,13,15" 4 ""
check_plan "dev shape (RAYON_THREADS=2)" "0,2,4,6,8,10,12,14" 2 ""
# the generated drop-ins: a slice gets [Slice], a service [Service], both AllowedCPUs=

View file

@ -1,56 +0,0 @@
# 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,41 +1,30 @@
# infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service.
#
# The feed WebSocket served from flysim's feed bus (docs/design/flybus.md,
# "Feed over the bus"; services/flysim/crates/fly-edge). Whether it runs is
# decided by one line, FLY_FEED_VIA in /etc/fly/fly.env (05-deploy.sh writes it
# from the env file's FLY_FEED_VIA, default `direct`):
# "Feed over the bus"; services/flysim/crates/fly-edge). DISABLED BY DEFAULT:
# it is in no target's Wants=/Requires= and 07-enable.sh does not enable it.
# With FLY_FEED_VIA=direct (the default, written into /etc/fly/fly.env by
# 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:
#
# direct flysim binds 127.0.0.1:7400 itself. ExecCondition= below fails, so
# this unit starts as "skipped" (inactive, no failure, no restart).
# bus flysim publishes on its feed bus and leaves :7400 to this unit.
# 1. FLY_FEED_VIA=bus in the env file, then 05-deploy.sh (rewrites fly.env);
# 2. systemctl enable --now flyedge.service; systemctl restart flysim.service
# (flysim stops binding :7400, the edge binds it once the first snapshot
# 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.
#
# 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.
#
# 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
# Back: FLY_FEED_VIA=direct, deploy, systemctl disable --now flyedge.service,
# restart 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 the
# edge follows it. Requires= makes an explicit stop or restart of flysim stop
# or 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
# nothing here has to be restarted by hand. The edge holds no state; the 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.
# owns the router and its store under /run/fly/bus, so it starts first and
# the edge follows it. Requires= makes an explicit stop or restart of flysim
# (the unstick rule's `systemctl restart flysim.service` included) stop or
# 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 nothing here has to be restarted by hand. The edge holds no state; the
# store is flysim's and a new router removes the previous one's directory.
[Unit]
Description=flyedge: the feed WebSocket served from flysim's feed bus
After=flysim.service
@ -53,17 +42,15 @@ User=fly
EnvironmentFile=/etc/fly/fly.env
Environment=FLY_FEED_BIND=127.0.0.1:7400
Environment=FLY_BUS_DIR=/run/fly/bus
# Its own read-only /metrics and /healthz: watchdog check 2 reads them in bus mode (over
# loopback), and so can the metrics dashboard, as a second target beside flysim's :9101, which
# 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'
# Its own read-only /metrics and /healthz, for watchdog check 2 in bus mode.
# Loopback only: nothing off the container needs the edge's counters.
Environment=FLY_EDGE_METRICS_ADDR=127.0.0.1:9102
ExecStart=/opt/fly/current/fly-edge
Restart=always
RestartSec=2
# A few snapshots in flight and a WebSocket per client; the store itself is
# flysim's (tmpfs, bounded by feedbus::limits at 32 MiB).
MemoryMax=256M
[Install]
WantedBy=fly.target

View file

@ -14,15 +14,6 @@
[Unit]
Description=flysim: the fly brain, emulator, and control/feed APIs
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
StartLimitBurst=5

View file

@ -416,23 +416,6 @@ dependencies = [
"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]]
name = "fly-edge"
version = "0.1.1"
@ -459,8 +442,6 @@ dependencies = [
"anyhow",
"axum",
"clap",
"fly-control-edge",
"fly-edge",
"fly-session",
"flybrain-core",
"flybrain-gb",
@ -477,24 +458,6 @@ dependencies = [
"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]]
name = "fly-session"
version = "0.1.1"
@ -505,7 +468,6 @@ dependencies = [
"flybrain-gb",
"flybus",
"flysim-store",
"libc",
"serde_json",
"tempfile",
"tokio",
@ -535,7 +497,6 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"tempfile",
]
[[package]]

View file

@ -1,7 +1,6 @@
[workspace]
resolver = "3"
members = [
"crates/fly-control-edge",
"crates/fly-edge",
"crates/fly-legacy-session",
"crates/fly-session",
@ -11,7 +10,6 @@ members = [
"crates/flybus",
"crates/flysim",
"crates/flysim-store",
"crates/fly-scorecard",
]
[workspace.package]

View file

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

@ -1,462 +0,0 @@
//! `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

@ -1,81 +0,0 @@
//! `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

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

@ -1,320 +0,0 @@
#![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

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

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

@ -1,90 +0,0 @@
//! `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();
}

View file

@ -18,9 +18,8 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use std::time::Duration;
use anyhow::{Context, Result, anyhow};
use axum::extract::State;
@ -33,19 +32,6 @@ use flysim::feedbus;
use flysim::metrics::{Metrics, metric};
use tokio::sync::{oneshot, watch};
/// A subscription that has delivered nothing for this long is not serving: the loop publishes a
/// header at least every `1 / idle_snapshot_hz` even when paused, so silence this long means the
/// bus is wedged, not that the fly is idle. `/healthz` turns 503 so the watchdog restarts the edge
/// (it restarts nothing while flysim itself is unhealthy: that is flysim's check).
pub const STALE_AFTER: Duration = Duration::from_secs(15);
static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
/// Milliseconds since the process first asked, plus one so that 0 can mean "never".
fn now_ms() -> u64 {
EPOCH.elapsed().as_millis() as u64 + 1
}
/// What the edge needs to know. Built from flysim's own configuration, so both processes read
/// one environment file and cannot disagree about the port, the bus directory or the cadence.
#[derive(Debug, Clone)]
@ -89,41 +75,9 @@ pub struct EdgeMetrics {
pub decode_failures: AtomicU64,
/// Sessions that reached the bus but could not bind the feed port.
pub bind_failures: AtomicU64,
/// [`now_ms`] when the last snapshot was taken off the bus; 0 before the first.
last_snapshot_ms: AtomicU64,
}
impl EdgeMetrics {
/// Note that a snapshot has just been taken off the bus.
fn snapshot_arrived(&self) {
self.snapshots.fetch_add(1, Ordering::Relaxed);
self.last_snapshot_ms.store(now_ms(), Ordering::Relaxed);
}
/// Seconds since the last snapshot came off the bus, or `None` before the first.
pub fn snapshot_age(&self) -> Option<Duration> {
match self.last_snapshot_ms.load(Ordering::Relaxed) {
0 => None,
at => Some(Duration::from_millis(now_ms().saturating_sub(at))),
}
}
/// Whether the edge is serving: subscribed, and hearing from the bus within [`STALE_AFTER`].
pub fn health(&self) -> Result<(), String> {
self.health_within(STALE_AFTER)
}
fn health_within(&self, stale_after: Duration) -> Result<(), String> {
if self.connected.load(Ordering::Relaxed) != 1 {
return Err("waiting for the feed bus".to_owned());
}
match self.snapshot_age() {
Some(age) if age <= stale_after => Ok(()),
Some(age) => Err(format!("no snapshot for {} s", age.as_secs())),
None => Err("no snapshot yet".to_owned()),
}
}
pub fn render(&self) -> String {
let mut out = String::with_capacity(1_024);
let feed = &self.feed;
@ -162,13 +116,6 @@ impl EdgeMetrics {
"1 while the edge is subscribed to the feed bus and serving.",
self.connected.load(Ordering::Relaxed),
);
metric(
&mut out,
"fly_edge_snapshot_age_seconds",
"gauge",
"Seconds since the last snapshot came off the feed bus (-1 before the first).",
self.snapshot_age().map_or(-1.0, |age| age.as_secs_f64()),
);
metric(
&mut out,
"fly_edge_bus_lost_total",
@ -271,9 +218,10 @@ async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoRespons
}
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
match metrics.health() {
Ok(()) => (StatusCode::OK, "ok".to_owned()),
Err(why) => (StatusCode::SERVICE_UNAVAILABLE, why),
if metrics.connected.load(Ordering::Relaxed) == 1 {
(StatusCode::OK, "ok")
} else {
(StatusCode::SERVICE_UNAVAILABLE, "waiting for the feed bus")
}
}
@ -343,7 +291,7 @@ async fn serve(
listener: tokio::net::TcpListener,
) {
let (snapshots, receiver) = watch::channel(Arc::new(first));
metrics.snapshot_arrived();
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
tracing::info!(feed = %config.feed_bind, bus = %config.bus_dir.display(), "serving the feed from the bus");
metrics.connected.store(1, Ordering::Relaxed);
@ -369,7 +317,7 @@ async fn serve(
Ok(snapshot) => {
drop(message);
snapshots.send_replace(Arc::new(snapshot));
metrics.snapshot_arrived();
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
}
Err(error) => {
metrics.decode_failures.fetch_add(1, Ordering::Relaxed);
@ -394,32 +342,3 @@ async fn serve(
tracing::warn!("the feed listener took more than 5 s to stop");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn health_needs_the_bus_and_recent_snapshots() {
let metrics = EdgeMetrics::default();
assert_eq!(metrics.snapshot_age(), None);
assert!(metrics.health().unwrap_err().contains("waiting"));
metrics.connected.store(1, Ordering::Relaxed);
assert!(metrics.health().unwrap_err().contains("no snapshot yet"));
metrics.snapshot_arrived();
assert_eq!(metrics.health(), Ok(()));
std::thread::sleep(Duration::from_millis(40));
assert!(metrics.snapshot_age().unwrap() >= Duration::from_millis(40));
assert!(
metrics
.health_within(Duration::from_millis(10))
.unwrap_err()
.contains("no snapshot for")
);
metrics.snapshot_arrived();
assert_eq!(metrics.health_within(Duration::from_millis(30)), Ok(()));
metrics.connected.store(0, Ordering::Relaxed);
assert!(metrics.health().is_err());
assert!(metrics.render().contains("fly_edge_snapshot_age_seconds"));
}
}

View file

@ -175,68 +175,6 @@ async fn a_header_too_large_for_an_envelope_travels_as_an_artifact_and_arrives_i
assert!(direct == edge);
}
/// Each artifact a snapshot rides on is its own bytes, whatever came before it (BUS-02 review
/// N3): smaller attachments after larger ones, and a header that travels as an artifact, then
/// inline, then as a smaller artifact, reach the edge's clients exactly as the direct feed
/// writes them, with nothing of an earlier snapshot in them.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn smaller_artifacts_after_larger_ones_arrive_exactly() {
let base = snapshot_of(&fixture_messages("macros")[10]).unwrap();
let with_events = |n: u64, fill: char| {
let mut snapshot = base.clone();
for id in 0..n {
snapshot.header.events.push(flysim::snapshot::FeedEvent {
id: 10_000 + id,
wall_ms: 1_757_000_000_000 + id,
brain_ms: 5.0,
kind: flysim::snapshot::FeedEventKind::System,
label: fill.to_string().repeat(200),
value: None,
reward_kind: None,
by: None,
});
}
snapshot
};
// (header events, attachment length, fill): large, then smaller, then large-but-smaller.
let plan = [(400, 92_160, 0xA1u8), (0, 1_000, 0xB2), (0, 7, 0xC3), (360, 4_096, 0xD4), (0, 3, 0xE5)];
let mut snapshots = Vec::new();
for (seq, (events, len, fill)) in plan.into_iter().enumerate() {
let mut snapshot = with_events(events, char::from(b'a' + seq as u8));
snapshot.header.seq = base.header.seq + seq as u64;
snapshot.frame = vec![fill; len].into();
snapshot.audio = vec![fill ^ 0xFF; len / 2].into();
snapshot.spikes = vec![fill.rotate_left(1); len / 3].into();
snapshots.push(snapshot);
}
let paths = start(snapshots[0].clone(), true).await;
let wants = ["frame", "audio", "spikes"];
let mut direct = connect(paths.direct, &wants).await;
let mut edge = connect(paths.edge, &wants).await;
for (index, snapshot) in snapshots.iter().enumerate() {
if index > 0 {
paths.snapshots.send_replace(std::sync::Arc::new(snapshot.clone()));
}
let d = next_binary(&mut direct, Duration::from_secs(20)).await;
let e = next_binary(&mut edge, Duration::from_secs(20)).await;
assert_eq!(seq_of(&e), snapshot.header.seq, "#{index}");
assert!(d == e, "#{index}: the edge's message differs from the direct feed's");
let (_, attachments) = split(&e);
let expected: Vec<&[u8]> = snapshot
.header
.attachments
.iter()
.map(|kind| match kind {
flysim::snapshot::AttachmentKind::Frame => snapshot.frame.as_slice(),
flysim::snapshot::AttachmentKind::Audio => snapshot.audio.as_slice(),
flysim::snapshot::AttachmentKind::Spikes => snapshot.spikes.as_slice(),
})
.collect();
assert!(!expected.is_empty());
assert_eq!(attachments, expected, "#{index}: attachments");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_edge_drops_its_clients_and_unbinds_when_the_bus_goes_away_then_comes_back() {
let snapshot = snapshot_of(&fixture_messages("shop")[5]).unwrap();

View file

@ -231,29 +231,15 @@ async fn hoarding_subscriber() -> Outcome {
// Every subscription the seat may open, each keeping every delivery at the in-flight cap:
// the worst case the store has to hold (`feedbus::limits`, flybus.md "Feed sizing").
let seats = feedbus::limits().max_subscriptions_per_client;
// The publisher declares the topic on its own task after `start` returns: under load the
// first subscribe can get there first (NO_TOPIC), so it waits for the topic (BUS-02 review
// N7).
let deadline = Instant::now() + Duration::from_secs(30);
let mut hoards = Vec::new();
for _ in 0..seats {
let mut subscription = loop {
match client
let mut subscription = client
.subscribe(
feedbus::TOPIC,
SubscriptionConfig::latest().in_flight(2).replay(true),
)
.await
{
Ok(subscription) => break subscription,
Err(error)
if error.code == flybus::ErrorCode::NoTopic && Instant::now() < deadline =>
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
Err(error) => panic!("subscribe: {error:?}"),
}
};
.unwrap();
hoards.push(tokio::spawn(async move {
let mut kept = Vec::new();
while let Some(message) = subscription.next().await {

View file

@ -21,11 +21,6 @@ path = "src/bin/flysim-session.rs"
name = "fly-shadow"
path = "src/bin/fly-shadow.rs"
[features]
# The LIF tick on the GPU (GPU-02), for `flysim-session` and `fly-shadow`: the same switch as
# flysim's, so `FLY_CARGO_FEATURES=cuda infra/build/build-flysim.sh` builds every binary with it.
cuda = ["fly-session/cuda", "flysim/cuda"]
[dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" }
@ -47,12 +42,8 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies]
# CTRL-01: the service contracts with the control API on the bus (`tests/service_parity.rs`).
fly-control-edge = { path = "../fly-control-edge" }
tempfile = "3"
axum = "0.8"
futures-util = "0.3"
tokio-tungstenite = "0.29"
tower = { version = "0.5", features = ["util"] }
# EDGE-02: the session runtime serves the feed over the bus (tests/feed_bus.rs).
fly-edge = { path = "../fly-edge" }

View file

@ -18,7 +18,7 @@
//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` |
//! | `--spool DIR` | `<out>/spool` |
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores |
//! | `--mode local\|bus/in-process\|bus/thread\|bus/process` | `$FLY_SHADOW_MODE`, else `local` (in-process over the local lane); `in-process`, `thread`, `process` and `bus` are accepted (BUS-01) |
//! | `--mode in-process\|thread\|process` | `in-process` |
//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads |
//! | `--required-brain-seconds S` | 10800 |
//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) |
@ -46,9 +46,7 @@
//! and writes nothing outside DIR; N bounds the mirrored saves (3072).
//!
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
//! [--max-age-seconds N] [--require-arm ARM]`: the cutover rule of
//! `fly_legacy_session::shadow::verdict`, and with `--require-arm` (BUS-01: `bus/process`, ...) also
//! that the shadow ran that topology. `--current`
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current`
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
@ -162,8 +160,6 @@ fn main() {
.unwrap_or_else(|| "flysim-session".to_owned());
let compatibility = args.value("--compatibility");
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
// BUS-01: the topology the cutover goes into, which the shadow must have run.
let require_arm = args.value("--require-arm");
args.done();
let compatibility = compatibility.unwrap_or_else(|| {
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e));
@ -183,12 +179,7 @@ fn main() {
dir: &dir_text,
binaries: &binaries,
};
let allowed = verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age)
.and_then(|()| match &require_arm {
Some(arm) => verdict::ran_arm(&value, arm),
None => Ok(()),
});
match allowed {
match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) {
Ok(()) => println!("cutover allowed: {}", value["reason"]),
Err(reason) => {
println!("cutover refused: {reason}");
@ -221,18 +212,12 @@ fn run(mut args: Args) {
.map(PathBuf::from)
.or_else(|| env_path("FLY_SHADOW_WORK"))
.unwrap_or_else(|| out_dir.join("work"));
// BUS-01: `--mode` (else `FLY_SHADOW_MODE`, which the remote relay forwards to the box) names
// the topology: `local` (= `in-process`, the default), `bus/in-process`, `bus/thread`,
// `bus/process` (= `bus`, = `process`), `thread`.
let arm = args
.value("--mode")
.or_else(|| std::env::var("FLY_SHADOW_MODE").ok().filter(|v| !v.is_empty()))
.map(|value| {
fly_legacy_session::composition::SessionArm::parse(&value)
.unwrap_or_else(|e| die(format!("--mode / FLY_SHADOW_MODE: {e}")))
})
.unwrap_or(fly_legacy_session::composition::SessionArm::LOCAL);
let mode: ExecutionMode = arm.mode;
let mode = match args.value("--mode").as_deref() {
None | Some("in-process") => ExecutionMode::InProcess,
Some("thread") => ExecutionMode::Thread,
Some("process") => ExecutionMode::Process,
Some(other) => die(format!("--mode {other:?}")),
};
let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| {
std::env::var("FLY_SHADOW_THREADS")
.ok()
@ -307,7 +292,6 @@ fn run(mut args: Args) {
macro_mode: config.macros.mode,
speed: config.loop_.speed,
mode,
transport: arm.transport,
agent_threads,
required_brain_seconds: required,
all_files,
@ -325,8 +309,7 @@ fn run(mut args: Args) {
run_id_file,
};
eprintln!(
"fly-shadow: {} ({} mode), {} threads, following {} (stores {} and {}, read only)",
arm.label(),
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)",
mode.label(),
agent_threads,
shadow_config.trace_dir.display(),

View file

@ -7,11 +7,10 @@
//!
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
//! sidecar, and serves the same feed, control API and metrics. These variables are its own:
//! sidecar, and serves the same feed, control API and metrics. Three variables are its own:
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
//! `FLY_SESSION_TRANSPORT` (`local`, the default, or `bus`; `--transport`), `FLY_SESSION_MODE`
//! (`in-process`, `thread` or `process`; `process` by default on the bus), `FLY_SESSION_PIN`,
//! `FLY_SESSION_AUX_CPUS` and `FLY_SESSION_PROFILE` (`production`, or `toy` for tests).
//! `FLY_SESSION_MODE` (`in-process`, `thread` or `process`) and `FLY_SESSION_PROFILE`
//! (`production`, or `toy` for tests).
//!
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and
@ -49,12 +48,6 @@ struct Args {
/// service stopped; `flysim --reset-to-milestone`, the same store).
#[arg(long, value_name = "RANK")]
reset_to_milestone: Option<u32>,
/// `local` (in-process over the local lane) or `bus` (every participant a socket client of
/// the session's router, one process each unless `FLY_SESSION_MODE` says otherwise).
/// Overrides `FLY_SESSION_TRANSPORT`.
#[arg(long, value_name = "local|bus")]
transport: Option<String>,
}
fn main() -> Result<()> {
@ -62,8 +55,7 @@ fn main() -> Result<()> {
init_tracing();
let config = Config::load(args.config.as_deref())?;
let options =
fly_legacy_session::service::ServiceOptions::from_env_with(args.transport.as_deref())?;
let options = fly_legacy_session::service::ServiceOptions::from_env()?;
tracing::info!(config = ?config, options = ?options, "resolved configuration");
if args.check_config {
println!("{}", toml::to_string_pretty(&config)?);

View file

@ -14,8 +14,8 @@ use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy;
use fly_session::launcher::{
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, ProcessCpus,
SUPERVISOR_CLIENT, ThreadBudget, Via,
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
ThreadBudget, Via,
};
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
use fly_session::legacy_env::BackendConfig;
@ -54,152 +54,12 @@ const COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world";
const ENV_WORKER: &str = "world";
/// The environment's worker id, which [`LegacyConfig::placements`] names it by.
pub const WORLD_WORKER: &str = ENV_WORKER;
const AGENT_CLIENT: &str = "legacy-fly";
/// How the session's participants reach each other (BUS-01).
///
/// - `Local`: in-process participants are called over the local lane (PERF-01): no bus message
/// and no store file per call. Only [`ExecutionMode::InProcess`] has a lane.
/// - `Bus`: every participant is a client of the session's router over a Unix-domain socket,
/// launcher-bound to its identity, with its artifacts in the router's store: the topology that
/// takes more flies and more worlds by configuration. In-process, thread and process modes all
/// run it; thread and process modes have no other transport.
///
/// Neither changes a result, a trace or a checkpoint: the transport carries the same domain calls
/// to the same endpoints (`legacy-gameboy-v1` section 12, amendment 2026-10-01 BUS-01).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Transport {
#[default]
Local,
Bus,
}
impl Transport {
pub fn label(&self) -> &'static str {
match self {
Transport::Local => "local",
Transport::Bus => "bus",
}
}
/// `local` or `bus`.
pub fn parse(value: &str) -> Result<Transport, String> {
match value {
"local" => Ok(Transport::Local),
"bus" => Ok(Transport::Bus),
other => Err(format!("transport {other:?}: local or bus")),
}
}
/// The launcher transport for a mode: the lane only in process and only when asked for (and
/// not turned off by `FLY_SESSION_LOCAL_LANE=0`, which keeps an in-memory bus); Unix sockets
/// for the bus, and always for a thread or a process.
pub fn via(&self, mode: ExecutionMode) -> Via {
match (self, mode) {
(Transport::Local, ExecutionMode::InProcess) if local_lane_enabled() => Via::Local,
(Transport::Local, ExecutionMode::InProcess) => Via::Memory,
_ => Via::Unix,
}
}
}
/// One way to run the composition: where the participants run and how they are reached.
/// `local` (in-process over the lane, the release default until the bus cutover), `bus/in-process`,
/// `bus/thread` and `bus/process`. Parity runs and measurements name them this way
/// (`FLY_PARITY_ARMS`, `FLY_PERF_ARMS`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SessionArm {
pub mode: ExecutionMode,
pub transport: Transport,
}
impl SessionArm {
pub const LOCAL: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Local,
};
pub const BUS_IN_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Bus,
};
pub const BUS_THREAD: SessionArm = SessionArm {
mode: ExecutionMode::Thread,
transport: Transport::Bus,
};
pub const BUS_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::Process,
transport: Transport::Bus,
};
pub fn label(&self) -> String {
match self.transport {
Transport::Local => "local".to_owned(),
Transport::Bus => format!("bus/{}", self.mode.label()),
}
}
/// `local`, `bus` (= `bus/process`), `bus/in-process`, `bus/thread`, `bus/process`; also the
/// bare mode names `in-process` (= local), `thread` and `process` (= the bus).
pub fn parse(value: &str) -> Result<SessionArm, String> {
Ok(match value.trim() {
"local" | "in-process" => SessionArm::LOCAL,
"bus/in-process" => SessionArm::BUS_IN_PROCESS,
"bus/thread" | "thread" => SessionArm::BUS_THREAD,
"bus" | "bus/process" | "process" => SessionArm::BUS_PROCESS,
other => {
return Err(format!(
"{other:?}: local, bus/in-process, bus/thread or bus/process"
));
}
})
}
/// The arms a parity run compares with the legacy loop: `FLY_PARITY_ARMS` (a list of
/// [`SessionArm::parse`] names), else `local`, `bus/thread` and `bus/process`. Process mode
/// needs the workspace's `fly-session` binary; a build without it skips that arm and says so.
pub fn parity_arms() -> Vec<SessionArm> {
let arms = match std::env::var("FLY_PARITY_ARMS") {
Ok(list) if !list.trim().is_empty() => SessionArm::parse_list(&list)
.unwrap_or_else(|e| panic!("FLY_PARITY_ARMS: {e}")),
_ => vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS],
};
let program = fly_session::launcher::default_worker_program();
arms.into_iter()
.filter(|arm| {
let runnable = arm.mode != ExecutionMode::Process || program.is_file();
if !runnable {
eprintln!(
"{} skipped: no worker program at {}",
arm.label(),
program.display()
);
}
runnable
})
.collect()
}
/// A comma-separated list of [`SessionArm::parse`] names.
pub fn parse_list(value: &str) -> Result<Vec<SessionArm>, String> {
value
.split(',')
.filter(|part| !part.trim().is_empty())
.map(SessionArm::parse)
.collect()
}
}
/// How one legacy session is composed.
#[derive(Clone, Debug)]
pub struct LegacyConfig {
pub mode: ExecutionMode,
/// The transport in-process participants use; thread and process modes always use the bus.
pub transport: Transport,
/// Process mode: where each participant process's threads run, by worker id (the agent's
/// id, [`WORLD_WORKER`]). Empty: they float (BUS-01).
pub placements: BTreeMap<Id, ProcessCpus>,
pub rom_path: PathBuf,
pub dataset_dir: PathBuf,
pub profile: LegacyProfileKind,
@ -477,11 +337,11 @@ impl LegacySession {
let mut launcher = Launcher::start(
router,
config.mode,
// `Transport::Local`: in-process participants are called over the local lane: the same
// worker shell, no bus message and no store file per artifact (PERF-01, `workers-v1`
// amendment). `Transport::Bus`: every participant is a socket client of the router,
// whatever its mode (BUS-01); a thread or a separate process always is.
config.transport.via(config.mode),
// In-process participants reach the router in memory: no socket between two tasks
// of one process (a separate process always uses the socket). They are called over
// the local lane: the same worker shell, no bus message and no store file per
// artifact (PERF-01, `workers-v1` amendment).
if local_lane_enabled() { Via::Local } else { Via::Memory },
&store_root,
&sockets,
budget,
@ -489,9 +349,6 @@ impl LegacySession {
.await
.map_err(|e| format!("launcher: {}", e.message))?;
for (worker, cpus) in &config.placements {
launcher.place_process(worker, cpus.clone());
}
let mut backend = BackendConfig::legacy(&rom_digest);
backend.slots = vec![id(crate::task::SLOT)];
launcher

View file

@ -35,10 +35,8 @@ use serde_json::Value;
use tokio::sync::{mpsc, oneshot, watch};
use fly_session::fly_session_types::gameboy;
use fly_session::launcher::{ExecutionMode, ProcessCpus};
use fly_session::legacy_agent::{
FEED_STATUS_ATTACHMENT, LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT,
};
use fly_session::launcher::ExecutionMode;
use fly_session::legacy_agent::{LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT};
use fly_session::legacy_checkpoint::{RankChange, SaveKind, SaveReport, SaveTicket};
use fly_session::types::*;
use flybrain_gb::adapter::GameAdapter;
@ -58,14 +56,9 @@ use flysim::snapshot::{
PROTOCOL, RewardKind, Snapshot, f32_bytes, finite,
};
use crate::composition::{
Boot, LegacyConfig, LegacySession, StoreConfig, Transport, boot_unsaved,
};
use crate::composition::{Boot, LegacyConfig, LegacySession, StoreConfig, boot_unsaved};
use crate::task::GAME;
/// The service's one agent.
const AGENT_ID: &str = "fly";
/// The runtime name the sugar journal's boot header records.
pub const RUNTIME: &str = "fly-session";
@ -74,87 +67,30 @@ pub const SESSION_DIR_ENV: &str = "FLY_SESSION_DIR";
pub const DEFAULT_SESSION_DIR: &str = "/run/fly/session";
/// `in-process` (the default), `thread` or `process` (`fly-session`'s launcher modes).
pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE";
/// `local` (the default: in-process over the local lane) or `bus` (every participant a socket
/// client of the session's router; the mode defaults to `process`). BUS-01.
pub const SESSION_TRANSPORT_ENV: &str = "FLY_SESSION_TRANSPORT";
/// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only).
pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE";
/// `0` keeps every thread floating over the cpuset; anything else, or unset, places them
/// ([`place_threads`]).
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
/// A CPU list for the threads that are not the sim, instead of the sweep's host CPU. It must lie
/// in the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs, where 05-deploy.sh adds
/// it with `SESSION_AUX_CPUS`) and is exclusive to those threads. Process mode (BUS-01): the
/// service process (router, coordinator, listeners, checkpoint writer) and the environment
/// process. In-process and thread modes (EDGE-02): the `flysim-bus` runtime, i.e. the feed
/// publisher, the router and the control services; the sweep workers, the dispatcher and every
/// other thread are placed on the rest.
pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS";
/// How the service composes its session, beyond flysim's own [`Config`].
#[derive(Clone, Debug)]
pub struct ServiceOptions {
pub mode: ExecutionMode,
pub transport: Transport,
pub profile: LegacyProfileKind,
pub session_dir: PathBuf,
/// Process mode: each participant process's CPUs, by worker id ([`place_threads`]).
pub placements: std::collections::BTreeMap<Id, ProcessCpus>,
}
/// The mode and transport from their two settings: `FLY_SESSION_TRANSPORT` (or `--transport`)
/// and `FLY_SESSION_MODE`. Unset, the transport follows the mode (thread and process modes have
/// only the bus) and the mode follows the transport (`bus` runs one process per participant).
/// `local` with a thread or a process is refused: those have no local lane.
pub fn mode_and_transport(
mode: Option<&str>,
transport: Option<&str>,
) -> Result<(ExecutionMode, Transport)> {
let mode = match mode.filter(|v| !v.is_empty()) {
None => None,
Some("in-process") => Some(ExecutionMode::InProcess),
Some("thread") => Some(ExecutionMode::Thread),
Some("process") => Some(ExecutionMode::Process),
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"),
};
let transport = match transport.filter(|v| !v.is_empty()) {
None => None,
Some(value) => {
Some(Transport::parse(value).map_err(|e| anyhow!("{SESSION_TRANSPORT_ENV}: {e}"))?)
}
};
Ok(match (mode, transport) {
(None, None) | (None, Some(Transport::Local)) => {
(ExecutionMode::InProcess, Transport::Local)
}
(None, Some(Transport::Bus)) => (ExecutionMode::Process, Transport::Bus),
(Some(ExecutionMode::InProcess), transport) => {
(ExecutionMode::InProcess, transport.unwrap_or(Transport::Local))
}
(Some(mode), None | Some(Transport::Bus)) => (mode, Transport::Bus),
(Some(mode), Some(Transport::Local)) => bail!(
"{SESSION_MODE_ENV}={} has no local lane: its participants reach the router over \
sockets ({SESSION_TRANSPORT_ENV}=bus, or unset)",
mode.label()
),
})
}
impl ServiceOptions {
/// From `FLY_SESSION_MODE`, `FLY_SESSION_TRANSPORT`, `FLY_SESSION_PROFILE` and
/// `FLY_SESSION_DIR`.
/// From `FLY_SESSION_MODE`, `FLY_SESSION_PROFILE` and `FLY_SESSION_DIR`.
pub fn from_env() -> Result<ServiceOptions> {
Self::from_env_with(None)
}
/// [`ServiceOptions::from_env`], with `--transport` in place of `FLY_SESSION_TRANSPORT`.
pub fn from_env_with(transport: Option<&str>) -> Result<ServiceOptions> {
let env_transport = std::env::var(SESSION_TRANSPORT_ENV).ok();
let (mode, transport) = mode_and_transport(
std::env::var(SESSION_MODE_ENV).ok().as_deref(),
transport.or(env_transport.as_deref()),
)?;
let mode = match std::env::var(SESSION_MODE_ENV).ok().as_deref() {
None | Some("") | Some("in-process") => ExecutionMode::InProcess,
Some("thread") => ExecutionMode::Thread,
Some("process") => ExecutionMode::Process,
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"),
};
let profile = match std::env::var(SESSION_PROFILE_ENV).ok().as_deref() {
None | Some("") | Some("production") => LegacyProfileKind::Production,
Some("toy") => LegacyProfileKind::Toy,
@ -165,10 +101,8 @@ impl ServiceOptions {
.unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR));
Ok(ServiceOptions {
mode,
transport,
profile,
session_dir,
placements: Default::default(),
})
}
}
@ -200,13 +134,11 @@ pub fn legacy_config(config: &Config, options: &ServiceOptions) -> Result<Legacy
}
Ok(LegacyConfig {
mode: options.mode,
transport: options.transport,
placements: options.placements.clone(),
rom_path: config.paths.rom.clone(),
dataset_dir: config.paths.dataset.clone(),
profile: options.profile,
macro_mode: config.macros.mode,
agent_id: id(AGENT_ID),
agent_id: id("fly"),
agent_threads: config.loop_.threads.max(1),
record: false,
})
@ -247,7 +179,7 @@ pub fn service_config(mut config: Config) -> Config {
}
/// Run the service until a signal or a fatal error: [`flysim::serve`] around a [`SessionHost`].
pub fn run(config: Config, mut options: ServiceOptions) -> Result<()> {
pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
let config = service_config(config);
// Refuse a configuration the session cannot run before any listener is bound.
legacy_config(&config, &options)?;
@ -259,19 +191,7 @@ pub fn run(config: Config, mut options: ServiceOptions) -> Result<()> {
tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored");
}
}
place_threads(&config, &mut options);
tracing::info!(
transport = options.transport.label(),
mode = options.mode.label(),
"session participants: {}",
match (options.transport, options.mode) {
(Transport::Local, _) => "in process, over the local lane",
(Transport::Bus, ExecutionMode::InProcess) => "in process, socket clients of the router",
(Transport::Bus, ExecutionMode::Thread) => "on threads, socket clients of the router",
(Transport::Bus, ExecutionMode::Process) =>
"one process each, socket clients of the router",
}
);
place_threads(&config, &options);
flysim::serve(config, move |shared, snapshots, commands, notifier| {
run_host(shared, snapshots, commands, notifier, &options)
})
@ -282,100 +202,20 @@ pub fn run(config: Config, mut options: ServiceOptions) -> Result<()> {
/// writer), before any of them is spawned. The legacy loop's four busy threads keep their CPUs by
/// themselves; the session's host threads sleep and wake around every transition, and without
/// this the sweep workers' wake-ups often land two on one CPU (`flybrain_core::pool::
/// place_workers`). Placement changes no result, trace or checkpoint.
///
/// In-process and thread modes place this process's own threads. Process mode (BUS-01) makes the
/// same split of this process's cpuset and hands it out: the agent process gets the sweep CPUs
/// and the host CPU (`--sweep-cpus`, `--host-cpus`), and this process -- the router, the
/// coordinator, the listeners -- and the environment process run on the host CPU too, or on
/// `FLY_SESSION_AUX_CPUS` when it is set. The transaction is serial (nothing overlaps Prepare,
/// PERF-01), so they share that CPU with the agent's dispatcher without contending.
fn place_threads(config: &Config, options: &mut ServiceOptions) {
/// place_workers`). In-process and thread modes only: a worker process would inherit the host's
/// mask without the plan. Placement changes no result, trace or checkpoint.
fn place_threads(config: &Config, options: &ServiceOptions) {
if std::env::var(SESSION_PIN_ENV).ok().as_deref() == Some("0") {
tracing::info!("{SESSION_PIN_ENV}=0: the threads float over the cpuset");
return;
}
if !matches!(
options.mode,
ExecutionMode::InProcess | ExecutionMode::Thread
) {
return;
}
let workers = config.loop_.threads;
if options.mode == ExecutionMode::Process {
let plan = flybrain_core::pool::allowed_cpus()
.and_then(|allowed| flybrain_core::pool::split_cpus(&allowed, workers));
let Some(plan) = plan else {
tracing::info!(
workers,
"threads not placed (fewer cpus than sweep threads): every process floats"
);
return;
};
let aux = match std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) {
None => plan.host.clone(),
Some(value) => match flybrain_core::pool::parse_cpu_list(&value) {
Some(cpus) => cpus,
None => {
tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored");
plan.host.clone()
}
},
};
let aux = if flybrain_core::pool::confine_current(&aux) {
aux
} else {
tracing::warn!(?aux, "could not confine the service to these cpus; using the host cpus");
if !flybrain_core::pool::confine_current(&plan.host) {
tracing::warn!("could not confine the service at all: every process floats");
return;
}
plan.host.clone()
};
// The agent's own host threads (its dispatcher is sweep worker 0) keep the plan's host
// cpus, less any the service and the world were moved onto.
let agent_host: Vec<usize> = plan.host.iter().copied().filter(|c| !aux.contains(c)).collect();
options.placements.insert(
id(AGENT_ID),
ProcessCpus {
host: if agent_host.is_empty() { plan.host.clone() } else { agent_host },
sweep: plan.workers.clone(),
},
);
options.placements.insert(
id(crate::composition::WORLD_WORKER),
ProcessCpus {
host: aux.clone(),
sweep: Vec::new(),
},
);
tracing::info!(
sweep_workers = ?plan.workers,
agent_host = ?plan.host,
service_and_world = ?aux,
"process mode: the agent's sweep workers pinned one per cpu; the service, the router \
and the world on the rest"
);
return;
}
// In-process and thread modes: FLY_SESSION_AUX_CPUS names cpus of the unit's cpuset that are
// not the sim's. The sweep and the dispatcher are placed on the rest, and the bus runtime
// (feed publisher, router, control services) on these (EDGE-02 review N1).
if let Some(value) = std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) {
match flybrain_core::pool::parse_cpu_list(&value) {
None => tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored"),
Some(aux) => match flybrain_core::pool::place_workers_aux(workers, &aux) {
Some((placement, aux)) => {
tracing::info!(
sweep_workers = ?placement.workers,
host = ?placement.host,
bus_aux = ?aux,
"sweep workers pinned one per cpu; the bus runtime on the aux cpus, every \
other thread on the host cpus"
);
return;
}
None => tracing::warn!(
"{SESSION_AUX_CPUS_ENV}={value:?} is not inside the cpuset, or leaves fewer \
cpus than sweep threads; ignored (the bus runtime shares the host cpus)"
),
},
}
}
match flybrain_core::pool::place_workers(workers) {
Some(placement) => tracing::info!(
sweep_workers = ?placement.workers,
@ -562,12 +402,6 @@ pub struct SessionHost {
spikes: Vec<u8>,
/// The agent's feed status as last read, for a publish whose read failed.
last_feed: AgentFeed,
/// Over the bus (BUS-01): the feed status the last Commit attached, as of the committed
/// boundary; the next publish uses it instead of calling `Legacy.FeedStatus`. Cleared by a
/// rollback, which changes the agent after its Commit.
committed_feed: Option<Value>,
/// Whether the agent attaches its feed status to every Commit (the bus transport).
feed_on_commit: bool,
semantic_rewards: bool,
next_profile: Instant,
@ -688,8 +522,6 @@ impl SessionHost {
dc_blocker: DcBlocker::default(),
spikes: Vec::new(),
last_feed: AgentFeed::default(),
committed_feed: None,
feed_on_commit: options.transport == Transport::Bus,
semantic_rewards,
next_profile: now + PROFILE_PERIOD,
shared,
@ -700,15 +532,9 @@ impl SessionHost {
// The service reads every transition's commit (the spike bitset) and paces itself by
// flysim's `Pacer`, as the legacy loop does.
host.session.coordinator.disable_pacing();
if host.feed_on_commit {
host.session
.coordinator
.request_commit_attachments(&[SPIKES_ATTACHMENT, FEED_STATUS_ATTACHMENT]);
} else {
host.session
.coordinator
.request_commit_attachments(&[SPIKES_ATTACHMENT]);
}
host.session.coordinator.digest_views(false);
let origin = match &boot {
@ -833,7 +659,6 @@ impl SessionHost {
let mut next_watchdog = Instant::now();
loop {
let iteration = Instant::now();
self.shared.beat();
if let Some(period) = watchdog_period {
let now = Instant::now();
@ -914,9 +739,6 @@ impl SessionHost {
"the simulation is behind real time; no frames are being skipped"
);
}
// The frame's compute time, before the pacing sleep (`fly_frame_work_*`), as the
// legacy loop records it.
self.shared.metrics.frame_work.record(iteration.elapsed());
let sleep = pacer.next_sleep(Instant::now());
if !sleep.is_zero() {
tokio::time::sleep(sleep).await;
@ -965,9 +787,6 @@ impl SessionHost {
self.remaining_ms = remaining;
}
for (agent, name, bytes) in &details.commit_attachments {
if *agent == self.agent_id && name == FEED_STATUS_ATTACHMENT {
self.committed_feed = serde_json::from_slice(bytes).ok();
}
if *agent == self.agent_id && name == SPIKES_ATTACHMENT {
if self.spikes.len() < bytes.len() {
self.spikes.resize(bytes.len(), 0);
@ -1041,8 +860,6 @@ impl SessionHost {
.await
.map_err(|e| anyhow!("rollback ({} at {}): {}", e.detail, e.phase, e.error.message))?;
if rolled_back {
// The rollback changed the agent after its Commit: the next publish asks again.
self.committed_feed = None;
let feed = self.session.task.take_feed();
let (game_over, events) = feed.rollback.unwrap_or_default();
self.recovered(game_over, &events).await;
@ -1460,11 +1277,7 @@ impl SessionHost {
/// `Sim::publish`: one snapshot of the committed boundary. `with_attachments` is false while
/// not running, which is the protocol's header-only idle cadence.
async fn publish(&mut self, with_attachments: bool) {
let feed = match self.committed_feed.take() {
Some(value) => AgentFeed::parse(&value),
None => self.read_feed().await,
};
match feed {
match self.read_feed().await {
Ok(feed) => self.last_feed = feed,
Err(error) => tracing::warn!(%error, "the agent's feed status: publishing the last one"),
}
@ -1570,53 +1383,6 @@ impl SessionHost {
mod tests {
use super::*;
/// BUS-01: the transport and the mode, from their two settings.
#[test]
fn the_transport_and_the_mode_follow_each_other() {
use crate::composition::SessionArm;
let pick = |mode, transport| mode_and_transport(mode, transport).ok();
let local = (ExecutionMode::InProcess, Transport::Local);
assert_eq!(pick(None, None), Some(local));
assert_eq!(pick(Some(""), Some("")), Some(local));
assert_eq!(pick(None, Some("local")), Some(local));
assert_eq!(pick(Some("in-process"), None), Some(local));
assert_eq!(pick(None, Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
assert_eq!(
pick(Some("in-process"), Some("bus")),
Some((ExecutionMode::InProcess, Transport::Bus))
);
// A thread or a process has only the bus, whether or not the transport says so.
assert_eq!(pick(Some("thread"), None), Some((ExecutionMode::Thread, Transport::Bus)));
assert_eq!(pick(Some("process"), Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
assert_eq!(pick(Some("process"), Some("local")), None);
assert_eq!(pick(Some("thread"), Some("local")), None);
assert_eq!(pick(Some("fork"), None), None);
assert_eq!(pick(None, Some("udp")), None);
// The arms the parity runs and the shadow name parse to the same pairs.
for (name, arm) in [
("local", SessionArm::LOCAL),
("in-process", SessionArm::LOCAL),
("bus", SessionArm::BUS_PROCESS),
("process", SessionArm::BUS_PROCESS),
("bus/process", SessionArm::BUS_PROCESS),
("bus/thread", SessionArm::BUS_THREAD),
("thread", SessionArm::BUS_THREAD),
("bus/in-process", SessionArm::BUS_IN_PROCESS),
] {
assert_eq!(SessionArm::parse(name), Ok(arm), "{name}");
}
assert_eq!(SessionArm::BUS_PROCESS.label(), "bus/process");
assert_eq!(SessionArm::LOCAL.label(), "local");
assert!(SessionArm::parse("bus/fork").is_err());
assert_eq!(
SessionArm::parse_list("local, bus/thread,,bus").unwrap(),
vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS]
);
// The launcher transport each arm runs on.
assert_eq!(Transport::Bus.via(ExecutionMode::InProcess), fly_session::Via::Unix);
assert_eq!(Transport::Local.via(ExecutionMode::Process), fly_session::Via::Unix);
}
/// The environment's native audio through the f32 DC blocker is the legacy loop's u8 audio
/// through its own, bit for bit, across chunk boundaries.
#[test]

View file

@ -51,7 +51,7 @@ use fly_session::types::{id, parse_id};
use flysim::snapshot::MacroMode;
use crate::admission::LegacyAdmission;
use crate::composition::{LegacyConfig, LegacySession, Transport};
use crate::composition::{LegacyConfig, LegacySession};
use crate::trace::{self, Agreement, Difference};
use checkpoint::ShadowCapture;
use follow::Follower;
@ -87,9 +87,6 @@ pub struct ShadowConfig {
pub macro_mode: MacroMode,
pub speed: f64,
pub mode: ExecutionMode,
/// How the shadow session's participants reach each other (BUS-01): the local lane, or the
/// router's sockets.
pub transport: Transport,
pub agent_threads: usize,
pub required_brain_seconds: f64,
/// Follow every trace file present at start, oldest first (a rehearsal), rather than only the
@ -460,9 +457,6 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
}
let session_config = LegacyConfig {
mode: config.mode,
transport: config.transport,
// The shadow places nothing: its box gives it cores of its own.
placements: Default::default(),
rom_path: config.rom_path.clone(),
dataset_dir: config.dataset_dir.clone(),
profile: config.profile,
@ -523,7 +517,6 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
release: config.release.clone(),
compatibility: compatibility.clone(),
execution_mode: config.mode.label().to_owned(),
transport: config.transport.label().to_owned(),
agent_threads: config.agent_threads,
required_brain_seconds: config.required_brain_seconds,
agreement: Agreement::default(),

View file

@ -57,9 +57,7 @@ pub const TRACE_CHUNK: u64 = 4 << 20;
/// The live configuration the relay forwards to the box, so the remote shadow runs the live
/// service's composition (game, macro mode, accepted adapters, pins): exactly these names, and
/// nothing that is a path or a secret. The box's own env file supplies the paths.
pub const FORWARDED_ENV: [&str; 15] = [
// BUS-01: the topology the box's shadow runs (`fly-shadow-run start --bus`).
"FLY_SHADOW_MODE",
pub const FORWARDED_ENV: [&str; 14] = [
"FLY_GAME",
"FLYSIM_LOOP_GAME",
"FLY_MACRO_MODE",

View file

@ -229,8 +229,6 @@ pub struct Verdict {
pub release: String,
pub compatibility: String,
pub execution_mode: String,
/// `local` or `bus` (BUS-01): with `execution_mode`, the topology the shadow ran.
pub transport: String,
pub agent_threads: usize,
pub required_brain_seconds: f64,
pub agreement: Agreement,
@ -326,7 +324,6 @@ impl Verdict {
"compatibility": self.compatibility,
"compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()),
"executionMode": self.execution_mode,
"transport": self.transport,
"agentThreads": self.agent_threads,
},
"required": {"brainSeconds": self.required_brain_seconds},
@ -427,36 +424,6 @@ pub struct Release<'a> {
pub binaries: &'a std::collections::BTreeMap<String, String>,
}
/// The topology a verdict's shadow ran, named as [`crate::composition::SessionArm::label`] names
/// it: `local`, `bus/in-process`, `bus/thread` or `bus/process`. A verdict from before BUS-01 has
/// no `transport`: its in-process shadow ran the local lane, a thread or a process the bus.
pub fn shadowed_arm(verdict: &Value) -> String {
let candidate = &verdict["candidate"];
let mode = candidate["executionMode"].as_str().unwrap_or("in-process");
let transport = match candidate["transport"].as_str() {
Some(transport) => transport,
None if mode == "in-process" => "local",
None => "bus",
};
if transport == "local" {
"local".to_owned()
} else {
format!("{transport}/{mode}")
}
}
/// `fly-shadow check --require-arm`: the cutover is into a topology, so the shadow must have run
/// that one (BUS-01). `required` is a [`crate::composition::SessionArm`] name.
pub fn ran_arm(verdict: &Value, required: &str) -> Result<(), String> {
let required = crate::composition::SessionArm::parse(required)?.label();
let ran = shadowed_arm(verdict);
if ran == required {
Ok(())
} else {
Err(format!("the shadow ran {ran}, not {required}"))
}
}
/// How far ahead of the clock a verdict's `updatedAt` may be before it is refused.
const MAX_CLOCK_SKEW_S: i64 = 60;
@ -604,7 +571,6 @@ mod tests {
release: "/opt/fly/releases/test".to_owned(),
compatibility: "c".to_owned(),
execution_mode: "in-process".to_owned(),
transport: "local".to_owned(),
agent_threads: 2,
required_brain_seconds: 10_800.0,
agreement: Agreement::default(),
@ -641,7 +607,6 @@ mod tests {
release: String::new(),
compatibility: String::new(),
execution_mode: String::new(),
transport: String::new(),
agent_threads: 1,
required_brain_seconds: 10_800.0,
agreement: Agreement::default(),
@ -668,27 +633,6 @@ mod tests {
}
}
#[test]
fn the_arm_a_verdict_ran_is_checked_by_name() {
// BUS-01: a cutover onto the bus needs a shadow that ran the bus.
let mut v = verdict(Status::Pass, 10_800_000.0);
assert_eq!(shadowed_arm(&v), "local");
assert!(ran_arm(&v, "local").is_ok());
assert!(ran_arm(&v, "bus/process").is_err());
v["candidate"]["executionMode"] = json!("process");
v["candidate"]["transport"] = json!("bus");
assert_eq!(shadowed_arm(&v), "bus/process");
assert!(ran_arm(&v, "bus").is_ok());
assert!(ran_arm(&v, "process").is_ok());
assert!(ran_arm(&v, "bus/thread").is_err());
assert!(ran_arm(&v, "nonsense").is_err());
// A verdict from before BUS-01: no transport.
v["candidate"].as_object_mut().expect("an object").remove("transport");
assert_eq!(shadowed_arm(&v), "bus/process");
v["candidate"]["executionMode"] = json!("in-process");
assert_eq!(shadowed_arm(&v), "local");
}
#[test]
fn a_stop_ends_the_window() {
// B2: brain time compared before a coverage gap never counts toward a pass.

View file

@ -368,19 +368,6 @@ impl PokeredTask {
)
}
/// Read the committed boundary's memory image through the cartridge, as the macro engine
/// reads it, for a harness that measures play (the scorecard). `None` before the first
/// observation. Changes nothing.
pub fn with_reader<R>(
&self,
f: impl FnOnce(&mut dyn flybrain_gb::MemoryReader) -> R,
) -> Option<R> {
let inner = self.lock();
let (_, image) = inner.current.as_ref()?;
let mut reader = ImageReader::new(image, &inner.cartridge);
Some(f(&mut reader))
}
/// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`.
pub fn brain_ms(&self) -> f64 {
self.lock().ms

View file

@ -1,480 +0,0 @@
//! EDGE-02: the session runtime serves the feed over the bus.
//!
//! `flysim-session` runs behind `flysim::serve`, so `FLY_FEED_VIA=bus` should work on it exactly
//! as on `flysim`. This runs the real `flysim-session` binary (the toy connectome, the real
//! cartridge, a store seeded by a legacy fresh start) twice from copies of the same store:
//!
//! - `direct`: the binary binds the feed port and a WebSocket client records it;
//! - `bus`: the binary binds nothing on the feed port, `fly-edge` (in process) does, and the same
//! client records that. The binary is then stopped and started again under the same edge, which
//! must unbind, reconnect and serve the new instance.
//!
//! The two recordings are compared snapshot by snapshot on the sim frame: the header minus the
//! fields that are wall clock by definition, and the three attachments byte for byte. Gated on
//! `FLY_ROM` (source `bin/rom-env.sh`): without it the test returns early.
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Child, Command as Process, Stdio};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use fly_edge::{EdgeConfig, EdgeMetrics};
use flysim::config::{Config, FeedVia};
use flysim::eventlog::EventRing;
use flysim::simloop::{Command, Shared, Sim, booting_snapshot};
use flysim::snapshot::MacroMode;
use futures_util::{SinkExt as _, StreamExt as _};
use serde_json::Value;
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::Message as WsMessage;
fn rom_path() -> Option<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
fn free_port() -> SocketAddr {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
}
/// The service configuration: slow enough that a recorder on a loaded box sees every frame, every
/// frame published, no timed checkpoints.
fn config(rom: &Path, dataset: &Path, dir: &Path, via: FeedVia, bus_dir: &Path) -> Config {
let mut config = Config::default();
config.paths.rom = rom.to_path_buf();
config.paths.dataset = dataset.to_path_buf();
config.paths.save_dir = dir.join("durable");
config.paths.hot_dir = dir.join("hot");
config.loop_.game = "pokemon-red".to_owned();
config.loop_.speed = 0.25;
config.loop_.threads = 1;
config.loop_.snapshot_hz = 240.0;
config.loop_.hot_seconds = 1e9;
config.loop_.checkpoint_seconds = 1e9;
config.macros.mode = MacroMode::Raw;
config.chat.enabled = false;
config.feed.via = via;
config.feed.bus_dir = bus_dir.to_path_buf();
config.feed.bind = free_port();
config.control.bind = free_port();
config.control.metrics_bind = Some(free_port());
config
}
/// A store seeded by a legacy fresh start, shut down cleanly (as `service_parity` does).
fn seed_by_legacy_fresh_start(rom: &Path, dataset: &Path, dir: &Path) {
let mut config = config(rom, dataset, dir, FeedVia::Direct, dir);
config.loop_.speed = 1.0;
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(64);
let (snapshots_tx, mut snapshots) =
watch::channel(Arc::new(booting_snapshot(0, 0, MacroMode::Raw)));
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?;
sim.run(&flysim::sdnotify::Notifier::from_env())
});
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
loop {
snapshots.changed().await.unwrap();
if snapshots.borrow().header.frame >= 120 {
break;
}
}
let (reply, ack) = tokio::sync::oneshot::channel();
commands.send(Command::Shutdown { reply }).await.unwrap();
let _ = ack.await;
});
thread.join().unwrap().unwrap();
}
fn seed(from: &Path, to: &Path) {
for sub in ["durable", "hot"] {
let dst = to.join(sub);
std::fs::create_dir_all(&dst).unwrap();
if let Ok(entries) = std::fs::read_dir(from.join(sub)) {
for entry in entries.flatten() {
if entry.file_type().unwrap().is_file() {
std::fs::copy(entry.path(), dst.join(entry.file_name())).unwrap();
}
}
}
}
}
/// A running `flysim-session`, stopped (SIGTERM, then kill) when dropped.
struct Service {
child: Child,
config: Config,
}
impl Service {
fn start(config: Config, work: &Path, name: &str) -> Service {
Service::start_env(config, work, name, &[])
}
/// [`Service::start`] with extra environment, which wins over the test's defaults.
fn start_env(config: Config, work: &Path, name: &str, envs: &[(&str, &str)]) -> Service {
let path = work.join(format!("{name}.toml"));
std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap();
let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap();
let child = Process::new(env!("CARGO_BIN_EXE_flysim-session"))
.arg("--config")
.arg(&path)
.env("FLY_SESSION_PROFILE", "toy")
.env("FLY_SESSION_DIR", work.join(format!("{name}-session")))
// The test process's own cpus are not the sim's.
.env("FLY_SESSION_PIN", "0")
.env_remove("FLY_FEED_VIA")
.env_remove("FLY_BUS_DIR")
.env_remove("FLY_FEED_BIND")
.env_remove("FLY_CONTROL_BIND")
.env_remove("FLY_METRICS_ADDR")
.envs(envs.iter().copied())
.stdout(Stdio::null())
.stderr(log)
.spawn()
.expect("flysim-session starts");
Service { child, config }
}
/// SIGTERM and wait for the clean stop (the unit's own way to stop it).
fn stop(&mut self) {
let pid = self.child.id().to_string();
let _ = Process::new("kill").args(["-TERM", &pid]).status();
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
if self.child.try_wait().unwrap().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
/// Whether `flysim-session` itself holds the feed port (a connect succeeds and the peer is
/// not the edge): used only for the direct run, where it must.
fn log(&self, work: &Path, name: &str) -> PathBuf {
work.join(format!("{name}.log"))
}
fn feed_bind(&self) -> SocketAddr {
self.config.feed.bind
}
}
impl Drop for Service {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// What one running snapshot comes to on the wire.
#[derive(Debug, Clone, PartialEq)]
struct Seen {
header: Value,
attachments: Vec<Vec<u8>>,
}
fn comparable(header: &Value) -> Value {
let mut value = header.clone();
let map = value.as_object_mut().expect("a header is an object");
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(sugar) = map.get_mut("sugar").and_then(Value::as_object_mut) {
sugar.remove("cooldownMs");
}
for list in ["events", "chat"] {
if let Some(items) = map.get_mut(list).and_then(Value::as_array_mut) {
for item in items {
if let Some(item) = item.as_object_mut() {
item.remove("wallMs");
}
}
}
}
value
}
fn parse(message: &[u8]) -> Seen {
let read = |at: usize| u32::from_le_bytes(message[at..at + 4].try_into().unwrap()) as usize;
let header_len = read(0);
let header: Value = serde_json::from_slice(&message[4..4 + header_len]).unwrap();
let mut at = 4 + header_len;
let mut attachments = Vec::new();
while at < message.len() {
let len = read(at);
attachments.push(message[at + 4..at + 4 + len].to_vec());
at += 4 + len;
}
Seen {
header,
attachments,
}
}
type Ws =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
/// Connect (retrying while nothing listens yet) and say `hello`.
async fn connect(addr: SocketAddr, within: Duration, log: &Path) -> Ws {
let url = format!("ws://{addr}/feed");
let deadline = Instant::now() + within;
loop {
match tokio_tungstenite::connect_async(&url).await {
Ok((mut ws, _)) => {
let hello = serde_json::json!({ "protocol": 1, "client": "feed-bus-test", "wants": ["frame", "audio", "spikes"] });
ws.send(WsMessage::Text(hello.to_string().into()))
.await
.unwrap();
return ws;
}
Err(error) => {
assert!(
Instant::now() < deadline,
"{url}: {error}\n--- {} ---\n{}",
log.display(),
std::fs::read_to_string(log).unwrap_or_default()
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
}
/// Running snapshots (three attachments) by sim frame, until `frames` of them or `within`.
async fn record(ws: &mut Ws, frames: usize, within: Duration) -> BTreeMap<u64, Seen> {
let deadline = tokio::time::Instant::now() + within;
let mut seen = BTreeMap::new();
while seen.len() < frames {
let Ok(Some(Ok(message))) = tokio::time::timeout_at(deadline, ws.next()).await else {
break;
};
if let WsMessage::Binary(bytes) = message {
let snapshot = parse(&bytes);
if snapshot.attachments.len() == 3 {
let frame = snapshot.header["frame"].as_u64().unwrap();
seen.insert(frame, snapshot);
}
}
}
seen
}
fn fresh_dir(root: &Path, seeded: &Path, name: &str) -> PathBuf {
let dir = root.join(name);
seed(seeded, &dir);
dir
}
#[test]
fn the_session_runtime_serves_the_same_feed_over_the_bus() {
let Some(rom) = rom_path() else { return };
let dataset = fly_session::legacy_parity::toy::dir();
let root = tempfile::tempdir().unwrap();
let seeded = root.path().join("seeded");
std::fs::create_dir_all(&seeded).unwrap();
seed_by_legacy_fresh_start(&rom, &dataset, &seeded);
let runtime = tokio::runtime::Runtime::new().unwrap();
const FRAMES: usize = 90;
let within = Duration::from_secs(90);
// Direct: the service binds the feed port itself.
let direct = {
let dir = fresh_dir(root.path(), &seeded, "direct");
let bus = root.path().join("direct-bus");
let mut service = Service::start(
config(&rom, &dataset, &dir, FeedVia::Direct, &bus),
root.path(),
"direct",
);
let recorded = runtime.block_on(async {
let mut ws = connect(
service.feed_bind(),
Duration::from_secs(60),
&service.log(root.path(), "direct"),
)
.await;
record(&mut ws, FRAMES, within).await
});
service.stop();
assert!(!bus.join("edge.sock").exists(), "direct mode opened a bus");
recorded
};
assert!(
direct.len() >= FRAMES,
"direct recorded {} running snapshots",
direct.len()
);
// Bus: the service leaves the feed port to the edge.
let bus_dir = root.path().join("bus");
let bus = {
let dir = fresh_dir(root.path(), &seeded, "bus");
let service_config = config(&rom, &dataset, &dir, FeedVia::Bus, &bus_dir);
let edge_addr = service_config.feed.bind;
let edge_metrics = Arc::new(EdgeMetrics::default());
let edge = EdgeConfig {
retry: Duration::from_millis(100),
..EdgeConfig::from_flysim(&service_config, None)
};
let _edge = runtime.spawn(fly_edge::run(edge, Arc::clone(&edge_metrics)));
let mut service = Service::start(service_config.clone(), root.path(), "bus");
let recorded = runtime.block_on(async {
// Nothing is bound until the edge has its first snapshot, and it is the edge that binds.
let mut ws = connect(
edge_addr,
Duration::from_secs(60),
&root.path().join("bus.log"),
)
.await;
let recorded = record(&mut ws, FRAMES, within).await;
assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1);
recorded
});
service.stop();
// The edge notices, drops its clients and unbinds the port.
let lost = Instant::now();
while edge_metrics.connected.load(Ordering::Relaxed) != 0 {
assert!(
lost.elapsed() < Duration::from_secs(10),
"the edge never saw the bus go"
);
std::thread::sleep(Duration::from_millis(50));
}
assert!(edge_metrics.bus_lost.load(Ordering::Relaxed) >= 1);
// A new instance under the same edge: it reconnects by itself and serves the new router.
let mut again = Service::start(service_config, root.path(), "bus-again");
runtime.block_on(async {
let mut ws = connect(
edge_addr,
Duration::from_secs(60),
&root.path().join("bus-again.log"),
)
.await;
let after = record(&mut ws, 10, within).await;
assert!(
after.len() >= 10,
"after the restart: {} running snapshots",
after.len()
);
});
assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1);
again.stop();
recorded
};
assert!(
bus.len() >= FRAMES,
"bus recorded {} running snapshots",
bus.len()
);
// The same frames, the same bytes.
let mut compared = 0;
for (frame, a) in &direct {
let Some(b) = bus.get(frame) else { continue };
assert_eq!(
comparable(&a.header),
comparable(&b.header),
"frame {frame}: header"
);
assert_eq!(a.attachments.len(), b.attachments.len(), "frame {frame}");
for (index, (x, y)) in a.attachments.iter().zip(&b.attachments).enumerate() {
assert!(x == y, "frame {frame}: attachment {index} differs");
}
compared += 1;
}
eprintln!(
"session feed: direct {} and bus {} running snapshots, {compared} frames in common and identical",
direct.len(),
bus.len()
);
assert!(compared >= FRAMES / 2, "only {compared} frames in common");
}
/// The cpus a `/proc/.../status` says a thread may run on.
fn allowed_cpus(status: &Path) -> Vec<usize> {
let text = std::fs::read_to_string(status).unwrap_or_default();
let line = text
.lines()
.find_map(|l| l.strip_prefix("Cpus_allowed_list:"))
.unwrap_or("")
.trim()
.to_owned();
flybrain_core::pool::parse_cpu_list(&line).unwrap_or_default()
}
/// EDGE-02 review N1: with `FLY_SESSION_AUX_CPUS` the feed publisher's runtime (`flysim-bus`, its
/// blocking pool included) runs on the aux cpu alone, and no other thread of the service may.
/// Needs a toy store and three cpus (two sweep workers and one aux); no ROM.
#[test]
fn the_bus_threads_run_on_the_aux_cpu_and_nothing_else_does() {
let allowed = allowed_cpus(Path::new("/proc/self/status"));
if allowed.len() < 3 {
eprintln!("skipping: needs three cpus, have {allowed:?}");
return;
}
let Some(rom) = rom_path() else { return };
let aux = *allowed.last().unwrap();
let dataset = fly_session::legacy_parity::toy::dir();
let root = tempfile::tempdir().unwrap();
let seeded = root.path().join("seeded");
std::fs::create_dir_all(&seeded).unwrap();
seed_by_legacy_fresh_start(&rom, &dataset, &seeded);
let dir = fresh_dir(root.path(), &seeded, "aux");
let mut config = config(&rom, &dataset, &dir, FeedVia::Bus, &root.path().join("aux-bus"));
config.loop_.threads = 2;
let aux_text = aux.to_string();
let service = Service::start_env(
config,
root.path(),
"aux",
&[("FLY_SESSION_PIN", "1"), ("FLY_SESSION_AUX_CPUS", &aux_text)],
);
let task_dir = PathBuf::from(format!("/proc/{}/task", service.child.id()));
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let mut bus = 0;
let mut others = Vec::new();
for task in std::fs::read_dir(&task_dir).into_iter().flatten().flatten() {
let comm = std::fs::read_to_string(task.path().join("comm"))
.unwrap_or_default()
.trim()
.to_owned();
let cpus = allowed_cpus(&task.path().join("status"));
if comm == "flysim-bus" {
bus += 1;
assert_eq!(cpus, vec![aux], "a flysim-bus thread is on {cpus:?}, not on {aux}");
} else {
others.push((comm, cpus));
}
}
if bus >= 2 && others.len() >= 3 {
for (comm, cpus) in &others {
assert!(!cpus.contains(&aux), "thread {comm} may run on the aux cpu {aux}: {cpus:?}");
}
return;
}
assert!(
Instant::now() < deadline,
"never saw the bus threads: {bus} bus, {} others",
others.len()
);
std::thread::sleep(Duration::from_millis(200));
}
}

View file

@ -25,8 +25,6 @@ async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)>
};
let config = LegacyConfig {
mode: ExecutionMode::InProcess,
transport: Default::default(),
placements: Default::default(),
rom_path,
dataset_dir: legacy_parity::toy::dir(),
profile: LegacyProfileKind::Toy,

View file

@ -11,8 +11,7 @@
//! - **feed**: every running snapshot, header field by field and attachments byte for byte,
//! except the fields that are wall clock by definition (`wallMs`, `uptimeSeconds`,
//! `realtimeFactor`, `sugar.cooldownMs`, an event's or chat line's `wallMs`) and `seq`, which
//! counts the idle headers a pause publishes at 2 Hz of wall clock (the script holds the
//! resume until the recorder has seen the first one, so each runtime must publish one);
//! counts the idle headers a pause publishes at 2 Hz of wall clock;
//! - **control**: status code and body of every request (`/stimulate` 202 and 429 with the same
//! `retryAfterMs`, `/reward` 403, `/chat` 202/422, `/checkpoint` the same generation,
//! `/pause`, `/resume`, `/events`, `/healthz`), `/status` minus its wall-clock fields, and the
@ -20,10 +19,6 @@
//! - **store**: the event log file, the journal lines (minus `wallMs`, the boot header's runtime
//! and wall clock), and the final durable checkpoint decoded (minus `wallMs`).
//!
//! The in-process session runs a second time with its control API on the bus (CTRL-01): the
//! same script through `fly-control-edge`'s router and the control services on an embedded
//! router, compared against the legacy run the same way.
//!
//! Gated on `FLY_ROM` (source `bin/rom-env.sh`). `toy_raw_*` uses the committed toy connectome and
//! a store seeded by a legacy fresh start; `fafb_*` (also `FLY_SERVE01_FAFB`) the real connectome
//! from the ENV-01 service trace's `rollback` checkpoint, which rolls back on its first boundary.
@ -34,8 +29,8 @@ use std::time::{Duration, Instant};
use axum::body::Body;
use axum::http::{Method, Request};
use fly_legacy_session::composition::SessionArm;
use fly_legacy_session::service::{ServiceOptions, run_host};
use fly_session::launcher::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use flysim::AppState;
use flysim::config::Config;
@ -74,21 +69,14 @@ fn sha(bytes: &[u8]) -> String {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Runtime {
Legacy,
Session(SessionArm),
/// The session runtime with its control API on the bus (`FLY_CONTROL_VIA=bus`, CTRL-01): the
/// script goes through `fly-control-edge`'s router, over the edge's Unix socket, to the
/// control services on the embedded router.
SessionOverBus(SessionArm),
Session(ExecutionMode),
}
impl Runtime {
fn label(&self) -> String {
match self {
Runtime::Legacy => "legacy".to_owned(),
Runtime::Session(arm) => format!("session ({})", arm.label()),
Runtime::SessionOverBus(arm) => {
format!("session ({}) over the control bus", arm.label())
}
Runtime::Session(mode) => format!("session ({})", mode.label()),
}
}
}
@ -257,13 +245,11 @@ fn record(
let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?;
sim.run(&notifier)
}
Runtime::Session(arm) | Runtime::SessionOverBus(arm) => {
Runtime::Session(mode) => {
let options = ServiceOptions {
mode: arm.mode,
transport: arm.transport,
mode,
profile,
session_dir,
placements: Default::default(),
};
run_host(loop_shared, snapshots_tx, command_rx, &notifier, &options)
}
@ -275,23 +261,7 @@ fn record(
.enable_all()
.build()
.unwrap();
let bus_dir = config.paths.save_dir.parent().unwrap().join("bus");
let (router, _control_bus) = match runtime {
Runtime::SessionOverBus(_) => driver.block_on(async {
let scope = flysim::controlbus::Scope::live();
let uses = flysim::bus::Uses { feed: false, control: true };
let bus = flysim::bus::start(&bus_dir, uses, &scope).await.unwrap();
let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope)
.await
.unwrap();
let mut edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None);
edge_config.bus_dir = bus_dir.clone();
let metrics = Arc::new(fly_control_edge::EdgeMetrics::default());
let backend = fly_control_edge::connect(&edge_config, &metrics).await.unwrap();
(flysim::api::router_with(backend), Some((bus, host)))
}),
_ => (flysim::api::router(state.clone()), None),
};
let router = flysim::api::router(state.clone());
let metrics_router = flysim::api::metrics_router(state.clone());
let recording = driver.block_on(async {
let mut snapshots = snapshots;
@ -345,29 +315,6 @@ fn record(
));
// Sent now, in order, each drained before the next frame.
for action in actions.iter().filter(|a| a.at == index) {
if action.path == "/resume" {
// The pause is only observable as idle headers if the loop stays
// paused until it has published one (a header-only publish is due
// within the 2 Hz idle period). Resuming 2 ms after the pause let a
// loaded box skip it in one runtime and not the other, so wait, bounded,
// for the condition instead of racing it.
let before = idle.len();
let waited = Instant::now();
while idle.len() == before {
match tokio::time::timeout(Duration::from_secs(30), snapshots.changed()).await {
Ok(Ok(())) => {}
other => panic!(
"{}: no idle header within 30 s of the pause ({other:?})",
runtime.label()
),
}
let snap = Arc::clone(&snapshots.borrow_and_update());
if snap.header.status == FeedStatus::Paused {
idle.push(comparable(&snap));
}
}
eprintln!(" {}: idle header after {:.1?} paused", runtime.label(), waited.elapsed());
}
let router = router.clone();
let label = format!("{} {}", action_label(action), index);
let action = action.clone();
@ -376,18 +323,6 @@ fn record(
tokio::time::sleep(Duration::from_millis(2)).await;
pending.push((label, handle));
}
// Requests sent at one frame must all be drained together (two sugars before
// one commit): if the loop published another snapshot while they were being
// sent, a loaded box split them across frames and the run cannot be compared.
let group = actions.iter().filter(|a| a.at == index).count();
let pauses = actions.iter().any(|a| a.at == index && a.path.starts_with("/pause"));
if group > 1 && !pauses && snapshots.has_changed().unwrap_or(false) {
eprintln!(
" {}: the loop moved on while {group} requests were sent at frame {index}; the run will be repeated",
runtime.label()
);
complete = false;
}
}
FeedStatus::Paused => idle.push(comparable(&snapshot)),
FeedStatus::Booting | FeedStatus::Error => {}
@ -528,26 +463,6 @@ fn truncate(value: &Value) -> String {
}
}
/// A `/stimulate` refused because a pulse is still running (429) answers the pulse's remaining
/// brain time at the frame the loop drained the request on. The script sends each request on its
/// frame's snapshot, while the loop sleeps; on a loaded box a request can still reach the loop
/// after its next drain and be drained one frame later (BUS-02 review N7: seen once, the session
/// over bus/process under load 16-22). A refusal changes no state (no event, no journal line, no
/// admission), so the only trace of that is a `retryAfterMs` exactly one emulated frame
/// (16.74 brain ms, so 16 or 17 once rounded up) apart; anything else is still a difference.
fn one_frame_late_refusal(label: &str, status: u16, a: &Value, b: &Value) -> bool {
let retry = |v: &Value| {
let map = v.as_object()?;
if map.len() != 1 {
return None;
}
map.get("retryAfterMs")?.as_u64()
};
label.starts_with("POST /stimulate")
&& status == 429
&& matches!((retry(a), retry(b)), (Some(x), Some(y)) if (16..=17).contains(&x.abs_diff(y)))
}
fn compare(legacy: &Recording, session: &Recording, label: &str) {
assert_eq!(
legacy.running.len(),
@ -576,20 +491,9 @@ fn compare(legacy: &Recording, session: &Recording, label: &str) {
);
}
}
assert!(!legacy.idle.is_empty(), "{label}: the legacy pause published no idle header");
assert!(!session.idle.is_empty(), "{label}: the session pause published no idle header");
assert_eq!(legacy.idle.is_empty(), session.idle.is_empty(), "{label}: idle headers");
if let (Some(a), Some(b)) = (legacy.idle.first(), session.idle.first()) {
// An idle header carries the events not yet published, and which publish that is (the
// pause's own or a later one, whichever the recorder saw first) is wall clock; the events
// themselves are compared in the running snapshots and the event log.
let strip = |v: &Value| {
let mut v = v.clone();
if let Some(map) = v.as_object_mut() {
map.remove("events");
}
v
};
same(&format!("{label}: the first idle header"), &strip(a), &strip(b));
same(&format!("{label}: the first idle header"), a, b);
}
assert_eq!(legacy.responses.len(), session.responses.len());
for ((la, sa, ba), (lb, sb, bb)) in legacy.responses.iter().zip(&session.responses) {
@ -606,14 +510,6 @@ fn compare(legacy: &Recording, session: &Recording, label: &str) {
}
v
};
if one_frame_late_refusal(la, *sa, ba, bb) {
eprintln!(
" {label}: {la}: retryAfterMs {} vs {}, one frame apart: the loaded box delivered \
the refused request a frame later in one run (a refusal changes nothing else)",
ba["retryAfterMs"], bb["retryAfterMs"]
);
continue;
}
same(&format!("{label}: {la} body"), &strip(ba), &strip(bb));
}
let status = |v: &Value| {
@ -684,8 +580,15 @@ fn seed(from: &Path, to: &Path) {
}
}
fn modes() -> Vec<SessionArm> {
SessionArm::parity_arms()
fn modes() -> Vec<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!("process mode skipped: no worker program at {}", program.display());
}
modes
}
#[allow(clippy::too_many_arguments)]
@ -724,22 +627,10 @@ fn run_pair(
let started = Instant::now();
let legacy = run(Runtime::Legacy, "legacy");
eprintln!("{label}: legacy {} running snapshots in {:.1?}", legacy.running.len(), started.elapsed());
let runtimes = modes()
.into_iter()
.map(Runtime::Session)
.chain([Runtime::SessionOverBus(SessionArm::LOCAL)]);
for runtime in runtimes {
for exec in modes() {
let started = Instant::now();
let exec = match runtime {
Runtime::Session(exec) | Runtime::SessionOverBus(exec) => exec,
Runtime::Legacy => unreachable!(),
};
let name = match runtime {
Runtime::SessionOverBus(_) => format!("session-bus-{}", exec.label()),
_ => format!("session-{}", exec.label()),
};
let session = run(runtime, &name);
let label = format!("{label}, {}", runtime.label());
let session = run(Runtime::Session(exec), &format!("session-{}", exec.label()));
let label = format!("{label}, {}", exec.label());
compare(&legacy, &session, &label);
let rewards = legacy
.events

View file

@ -31,12 +31,11 @@ use std::sync::Arc;
use serde_json::Value;
use fly_legacy_session::admission::LegacyAdmission;
use fly_legacy_session::composition::{
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
use fly_legacy_session::task::ledgers_of;
use fly_legacy_session::trace::{self, Agreement};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use fly_session::types::id;
@ -82,8 +81,18 @@ fn env_usize(name: &str, default: usize) -> usize {
.unwrap_or(default)
}
fn modes() -> Vec<SessionArm> {
SessionArm::parity_arms()
fn modes() -> Vec<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!(
"process mode skipped: no worker program at {}",
program.display()
);
}
modes
}
/// What each frame admits at its top, in admission order, and whether the rotation driver hands
@ -221,7 +230,7 @@ fn run_legacy(
/// The same run on the session framework.
#[allow(clippy::too_many_arguments)]
async fn run_session(
mode: SessionArm,
mode: ExecutionMode,
rom_path: &Path,
dataset_dir: &Path,
profile: LegacyProfileKind,
@ -232,9 +241,7 @@ async fn run_session(
) -> Run {
let root = tempfile::tempdir().expect("tmp");
let config = LegacyConfig {
mode: mode.mode,
transport: mode.transport,
placements: Default::default(),
mode,
rom_path: rom_path.to_owned(),
dataset_dir: dataset_dir.to_owned(),
profile,
@ -592,10 +599,8 @@ async fn fafb_boot_run_save_restore() {
flysim::store::Store::new(&store.durable_dir, store.keep_generations)
.commit(generation, &original, None)
.expect("the seeded store");
let config = |mode: SessionArm| LegacyConfig {
mode: mode.mode,
transport: mode.transport,
placements: Default::default(),
let config = |mode| LegacyConfig {
mode,
rom_path: rom_path.clone(),
dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production,

View file

@ -203,7 +203,6 @@ fn config(
macro_mode: MacroMode::Raw,
speed: 0.0,
mode: ExecutionMode::InProcess,
transport: Default::default(),
agent_threads: 1,
required_brain_seconds: 30.0,
all_files: true,

View file

@ -182,7 +182,6 @@ fn box_shadow(rom: &Path, root: &Path) -> ShadowConfig {
// The live service's loop.speed (real time), which its saves record.
speed: 1.0,
mode: ExecutionMode::InProcess,
transport: Default::default(),
agent_threads: 1,
required_brain_seconds: 20.0,
all_files: false,

View file

@ -12,9 +12,8 @@
use std::sync::Arc;
use std::time::Instant;
use fly_legacy_session::composition::{
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use fly_session::types::id;
@ -176,16 +175,13 @@ async fn session_against_legacy_per_frame() {
);
// ---- The session, unpaced then paced, in each mode.
for arm in [SessionArm::LOCAL, SessionArm::BUS_PROCESS] {
let mode = arm.mode;
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] {
for paced in [false, true] {
let root = tempfile::tempdir().unwrap();
let mut session = LegacySession::start(
root.path(),
LegacyConfig {
mode,
transport: arm.transport,
placements: Default::default(),
rom_path: rom_path.clone(),
dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production,

View file

@ -12,9 +12,8 @@
use std::sync::Arc;
use std::time::Instant;
use fly_legacy_session::composition::{
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use fly_session::types::id;
@ -152,24 +151,23 @@ async fn run(workers: usize) {
let bytes = std::fs::read(&checkpoint_path).unwrap();
let checkpoint = flysim::store::decode(&bytes).unwrap();
// PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-process
// over the local lane, the default in-process path), `memory` (in-process over the bus in
// memory, `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path), and the BUS-01 socket arms
// `bus/in-process`, `bus/thread`, `bus/process` (`process`). Default: local, memory, process.
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,memory,process".to_owned());
// over the local lane, the default in-process path), `bus` (in-process over the bus,
// `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three.
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned());
// `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's
// `flysim-session`): the spike bitset of every commit and the audio chunk of every boundary.
let service = std::env::var_os("FLY_PERF_SERVICE").is_some();
for arm in arms.split(',') {
let parsed = match arm {
"memory" => SessionArm::LOCAL,
other => SessionArm::parse(other).unwrap_or_else(|e| panic!("FLY_PERF_ARMS: {e}")),
let mode = match arm {
"local" | "bus" => ExecutionMode::InProcess,
"process" => ExecutionMode::Process,
other => panic!("unknown arm {other}"),
};
let mode = parsed.mode;
// SAFETY: set before the session's runtime reads it; nothing else reads the variable.
unsafe {
std::env::set_var(
fly_legacy_session::composition::LOCAL_LANE_ENV,
if arm == "memory" { "0" } else { "1" },
if arm == "bus" { "0" } else { "1" },
);
}
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
@ -178,8 +176,6 @@ async fn run(workers: usize) {
root.path(),
LegacyConfig {
mode,
transport: parsed.transport,
placements: Default::default(),
rom_path: rom_path.clone(),
dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production,

View file

@ -1,32 +0,0 @@
[package]
name = "fly-scorecard"
version.workspace = true
edition = "2024"
rust-version.workspace = true
license.workspace = true
publish = false
description = "The behavioural scorecard (B2): a repeatable multi-seed good-play regression harness over a fixed checkpoint set, on either runtime, with a release-against-release compare."
[lib]
name = "fly_scorecard"
path = "src/lib.rs"
[[bin]]
name = "fly-scorecard"
path = "src/main.rs"
[dependencies]
# The unchanged engine under test: flysim's frame and macro layer (the legacy runtime), the
# session composition (the session runtime), flybrain-gb's adapter and state readers.
flysim = { path = "../flysim" }
fly-legacy-session = { path = "../fly-legacy-session" }
fly-session = { path = "../fly-session" }
flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" }
anyhow = "1.0"
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
tempfile = "3"
libc = "0.2"

View file

@ -1,893 +0,0 @@
//! Release A against release B: a verdict per metric from the runs, not from one run.
//!
//! The runs of the two suites are paired by `(checkpoint, seed)`. Each pair gives one difference
//! per metric, signed so that positive means B is worse. A metric fails when B is worse than A by
//! more than its tolerance **and** a sign-flip permutation test over the pairs says the shortfall
//! is not noise (one-sided, `alpha`, Holm-adjusted over the judged metrics so the whole compare
//! has a family-wise false-fail rate of at most `alpha` under "nothing changed", where the
//! unadjusted per-metric test had about 15% over 13 metrics). Otherwise it passes, and when B is
//! better by the same two tests it says so. A metric with no direction (`info`) is only reported.
//!
//! The pooled test cannot see a trap confined to one place (three seeds of one checkpoint among
//! thirty-six pairs), so a second, non-statistical rule runs per checkpoint: see [`trap_rule`].
//!
//! The test is exact up to 20 pairs and a fixed-seed Monte-Carlo beyond, so the same two suites
//! always give the same verdicts.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::suite::SuiteReport;
use crate::tally::RunReport;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
/// More is better.
Up,
/// Less is better.
Down,
/// Reported, never judged.
Info,
}
/// One metric: how to read it off a run, which way is good, and how big a change must be before
/// it can count.
pub struct Metric {
pub name: &'static str,
pub unit: &'static str,
pub direction: Direction,
/// A change smaller than this (in `unit`) is never a regression or an improvement.
pub abs_tol: f64,
/// ... nor one smaller than this share of A's mean.
pub rel_tol: f64,
pub read: fn(&RunReport) -> f64,
}
fn per_hour(count: f64, run: &RunReport) -> f64 {
if run.minutes <= 0.0 { 0.0 } else { count * 60.0 / run.minutes }
}
fn pct(part: f64, whole: f64) -> f64 {
if whole <= 0.0 { 0.0 } else { 100.0 * part / whole }
}
/// The scorecard's metrics, in report order.
pub const METRICS: &[Metric] = &[
Metric {
name: "rungs_per_hour",
unit: "rungs/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.15,
read: |r| per_hour(f64::from(r.rungs.gained), r),
},
Metric {
name: "places_per_hour",
unit: "places/h",
direction: Direction::Up,
abs_tol: 5.0,
rel_tol: 0.15,
read: |r| per_hour(f64::from(r.places_end.saturating_sub(r.places_start)), r),
},
Metric {
name: "empty_pad_pct",
unit: "% of frames",
direction: Direction::Down,
abs_tol: 1.0,
rel_tol: 0.25,
read: |r| 100.0 * r.pad.empty_fraction,
},
Metric {
name: "watchdog_suspected_pct",
unit: "% of probes",
direction: Direction::Down,
abs_tol: 5.0,
rel_tol: 0.25,
read: |r| pct(r.watchdog.suspected as f64, r.watchdog.probes as f64),
},
Metric {
name: "ladder_events_per_hour",
unit: "traps/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.watchdog.ladder_events as f64, r),
},
// The trap hunt's windows are reported, not judged: a fly that fights for most of a run
// presses NEXT through battle text more than ten times in two minutes, which that instrument
// reads as a repeated sequence, so on these checkpoints nine windows in ten are flagged and
// the number has no room to move. The watchdog's rules above are the judged ones.
Metric {
name: "hunt_flagged_pct",
unit: "% of windows",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| pct(r.hunt.flagged as f64, r.hunt.windows as f64),
},
Metric {
name: "ratchet_rollbacks_per_hour",
unit: "rollbacks/h",
direction: Direction::Down,
abs_tol: 1.0,
rel_tol: 0.25,
read: |r| per_hour(f64::from(r.ratchet.rollbacks), r),
},
Metric {
name: "blocked_macro_pct",
unit: "% of finishes",
direction: Direction::Down,
abs_tol: 2.0,
rel_tol: 0.25,
read: |r| {
let finishes = r.macros.done + r.macros.failed();
pct(r.macros.failed() as f64, finishes as f64)
},
},
Metric {
name: "buy_ball_per_hour",
unit: "buys/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.buy_ball_done as f64, r),
},
Metric {
name: "throws_per_hour",
unit: "throws/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.throw_ball_done as f64, r),
},
// Reported, never judged on its own: a blocked THROW BALL storm is the trap rule's and the
// watchdog's business, and `throws_per_hour` above counts only throws that happened.
Metric {
name: "throw_ball_blocked_per_hour",
unit: "blocked/h",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| per_hour(r.macros.by_macro.get("THROW BALL").map_or(0, |c| c.blocked) as f64, r),
},
Metric {
name: "catches_per_hour",
unit: "catches/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.catches as f64, r),
},
Metric {
name: "battles_won_per_hour",
unit: "wins/h",
direction: Direction::Up,
abs_tol: 1.0,
rel_tol: 0.2,
read: |r| per_hour(r.battles.won as f64, r),
},
Metric {
name: "battles_lost_per_hour",
unit: "losses/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.battles.lost as f64, r),
},
Metric {
name: "whiteouts_per_hour",
unit: "whiteouts/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.whiteouts as f64, r),
},
// Reported, never judged: healing more can follow losing more.
Metric {
name: "heals_per_hour",
unit: "heals/h",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| per_hour(r.heals.heal_done as f64, r),
},
Metric {
name: "macro_starts_per_minute",
unit: "starts/min",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| if r.minutes <= 0.0 { 0.0 } else { r.macros.starts as f64 / r.minutes },
},
];
pub fn mean(values: &[f64]) -> f64 {
if values.is_empty() { 0.0 } else { values.iter().sum::<f64>() / values.len() as f64 }
}
pub fn stdev(values: &[f64]) -> f64 {
if values.len() < 2 {
return 0.0;
}
let m = mean(values);
(values.iter().map(|v| (v - m).powi(2)).sum::<f64>() / (values.len() - 1) as f64).sqrt()
}
/// One-sided sign-flip p-value for "the mean of `diffs` is greater than zero by more than chance":
/// the share of sign assignments whose mean is at least the observed one. Exact for up to 20
/// differences, 20,000 fixed-seed draws beyond.
pub fn sign_flip_p(diffs: &[f64]) -> f64 {
let n = diffs.len();
if n == 0 {
return 1.0;
}
let observed: f64 = diffs.iter().sum();
let eps = 1e-9 * (1.0 + observed.abs());
if n <= 20 {
let total = 1u64 << n;
let mut at_least = 0u64;
for mask in 0..total {
let sum: f64 = diffs
.iter()
.enumerate()
.map(|(i, d)| if mask >> i & 1 == 1 { -d } else { *d })
.sum();
if sum >= observed - eps {
at_least += 1;
}
}
return at_least as f64 / total as f64;
}
let draws = 20_000u64;
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut at_least = 1u64; // the observed assignment is one of them
for _ in 0..draws {
let mut sum = 0.0;
let mut bits = 0u64;
for (i, d) in diffs.iter().enumerate() {
if i % 64 == 0 {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
bits = state;
}
sum += if bits >> (i % 64) & 1 == 1 { -d } else { *d };
}
if sum >= observed - eps {
at_least += 1;
}
}
at_least as f64 / (draws + 1) as f64
}
/// Holm's step-down adjustment: the adjusted p of each value (same order), so that rejecting
/// where `adjusted < alpha` controls the family-wise error rate at `alpha` under any dependence
/// between the tests.
pub fn holm_adjust(ps: &[f64]) -> Vec<f64> {
let m = ps.len();
let mut order: Vec<usize> = (0..m).collect();
order.sort_by(|&i, &j| ps[i].total_cmp(&ps[j]));
let mut adjusted = vec![1.0; m];
let mut running = 0.0f64;
for (rank, &i) in order.iter().enumerate() {
running = running.max(((m - rank) as f64 * ps[i]).min(1.0));
adjusted[i] = running;
}
adjusted
}
/// Blocked finishes of one macro in one run that make a storm no watchdog window is needed to
/// read: the row-71 bag bug blocked THROW BALL 131 times in ten brain minutes.
pub const STORM_BLOCKED: u64 = 50;
/// Trapped runs of B on a checkpoint (and this many more than A) that fail the checkpoint.
pub const TRAP_RUNS: usize = 2;
/// Why a run counts as trapped, if it does: a recovery-ladder event (two suspected watchdog
/// probes in a row, any rule including stalled and zero-progress), at least half the probes
/// suspected, or a blocked-macro storm.
pub fn trapped(run: &RunReport) -> Option<String> {
if let Some((name, n)) = storm(run) {
return Some(format!("{n} blocked {name}"));
}
let w = &run.watchdog;
if w.ladder_events > 0 {
return Some(format!("{} ladder event(s), {}/{} probes suspected", w.ladder_events, w.suspected, w.probes));
}
if w.probes >= 2 && w.suspected * 2 >= w.probes {
return Some(format!("{}/{} probes suspected", w.suspected, w.probes));
}
None
}
/// The macro with the most blocked finishes in the run when that is a storm.
pub fn storm(run: &RunReport) -> Option<(String, u64)> {
run.macros
.by_macro
.iter()
.map(|(name, c)| (name.clone(), c.blocked))
.filter(|(_, n)| *n >= STORM_BLOCKED)
.max_by_key(|(_, n)| *n)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckpointTrap {
pub checkpoint: String,
pub runs_a: usize,
pub runs_b: usize,
pub trapped_a: usize,
pub trapped_b: usize,
pub storms_a: usize,
pub storms_b: usize,
/// What B's trapped runs looked like (seed: reason).
pub detail: Vec<String>,
}
/// The per-checkpoint trap rule, independent of the cross-seed test: a checkpoint FAILS when B is
/// trapped on at least `TRAP_RUNS` of its runs and on at least `TRAP_RUNS` more than A, or when B
/// has a blocked-macro storm on any run and A has none on that checkpoint. A fault confined to one
/// place cannot fail the pooled test (three seeds give a sign-flip p of at least 1/8, and the
/// shift is diluted over every checkpoint), but it is exactly the regression class this exists
/// for. Returns the failing checkpoints.
pub fn trap_rule(a: &SuiteReport, b: &SuiteReport) -> Vec<CheckpointTrap> {
let mut ids: Vec<&str> = b.runs.iter().map(|r| r.checkpoint.as_str()).collect();
ids.sort_unstable();
ids.dedup();
let mut failing = Vec::new();
for id in ids {
let ra: Vec<&RunReport> = a.runs.iter().filter(|r| r.checkpoint == id).collect();
let rb: Vec<&RunReport> = b.runs.iter().filter(|r| r.checkpoint == id).collect();
if ra.is_empty() {
continue;
}
let trapped_a = ra.iter().filter(|r| trapped(r).is_some()).count();
let trapped_b = rb.iter().filter(|r| trapped(r).is_some()).count();
let storms_a = ra.iter().filter(|r| storm(r).is_some()).count();
let storms_b = rb.iter().filter(|r| storm(r).is_some()).count();
let fails = (trapped_b >= TRAP_RUNS && trapped_b >= trapped_a + TRAP_RUNS) || (storms_b > 0 && storms_a == 0);
if fails {
failing.push(CheckpointTrap {
checkpoint: id.to_owned(),
runs_a: ra.len(),
runs_b: rb.len(),
trapped_a,
trapped_b,
storms_a,
storms_b,
detail: rb.iter().filter_map(|r| trapped(r).map(|why| format!("seed {}: {why}", r.seed))).collect(),
});
}
}
failing
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
Pass,
Better,
Fail,
Info,
/// No run of A pairs with a run of B.
None,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricVerdict {
pub metric: String,
pub unit: String,
pub direction: Direction,
pub pairs: usize,
pub mean_a: f64,
pub mean_b: f64,
pub delta: f64,
/// The one-sided p of "B is worse" and of "B is better".
pub p_worse: f64,
pub p_better: f64,
/// The same, Holm-adjusted over the judged metrics (what the verdict uses).
#[serde(default)]
pub p_worse_adj: f64,
#[serde(default)]
pub p_better_adj: f64,
/// The smallest change that counts, in the metric's unit.
pub tolerance: f64,
pub verdict: Verdict,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Comparison {
pub schema: String,
pub a: String,
pub b: String,
pub alpha: f64,
pub pairs: usize,
pub unpaired_a: usize,
pub unpaired_b: usize,
pub notes: Vec<String>,
pub metrics: Vec<MetricVerdict>,
/// Checkpoints the per-checkpoint trap rule failed.
#[serde(default)]
pub trapped_checkpoints: Vec<CheckpointTrap>,
/// Every metric that failed, in order, then `trap@<checkpoint>` for each failed checkpoint.
pub failed: Vec<String>,
pub pass: bool,
}
fn key(run: &RunReport) -> (String, u32) {
(run.checkpoint.clone(), run.seed)
}
/// Compares two suites. `alpha` is the one-sided significance level.
pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison {
let by_key = |suite: &SuiteReport| -> BTreeMap<(String, u32), RunReport> {
suite.runs.iter().map(|run| (key(run), run.clone())).collect()
};
let runs_a = by_key(a);
let runs_b = by_key(b);
let pairs: Vec<(&RunReport, &RunReport)> =
runs_a.iter().filter_map(|(k, ra)| runs_b.get(k).map(|rb| (ra, rb))).collect();
let mut notes = Vec::new();
if a.config.minutes != b.config.minutes {
notes.push(format!(
"the suites ran different lengths ({} and {} brain minutes): rates are comparable, counts are not",
a.config.minutes, b.config.minutes
));
}
if a.runtime != b.runtime {
notes.push(format!("the suites ran on different runtimes ({} and {})", a.runtime, b.runtime));
}
if a.config.probe_s != b.config.probe_s || a.config.window_s != b.config.window_s {
notes.push("the watchdog probes differ between the suites".to_owned());
}
if pairs.len() < 8 {
notes.push(format!(
"only {} paired runs: the permutation test cannot reach alpha {alpha} with fewer than {} pairs",
pairs.len(),
(1.0 / alpha).log2().ceil() as usize
));
}
// First the raw p-values of every metric, then Holm over the judged ones.
struct Raw {
mean_a: f64,
mean_b: f64,
delta: f64,
tolerance: f64,
shortfall: f64,
p_worse: f64,
p_better: f64,
}
let raws: Vec<Raw> = METRICS
.iter()
.map(|metric| {
let va: Vec<f64> = pairs.iter().map(|(ra, _)| (metric.read)(ra)).collect();
let vb: Vec<f64> = pairs.iter().map(|(_, rb)| (metric.read)(rb)).collect();
let (mean_a, mean_b) = (mean(&va), mean(&vb));
let delta = mean_b - mean_a;
// Signed so that positive is worse.
let sign = match metric.direction {
Direction::Up => -1.0,
Direction::Down | Direction::Info => 1.0,
};
let worse: Vec<f64> = va.iter().zip(&vb).map(|(x, y)| sign * (y - x)).collect();
let better: Vec<f64> = worse.iter().map(|d| -d).collect();
Raw {
mean_a,
mean_b,
delta,
tolerance: metric.abs_tol.max(metric.rel_tol * mean_a.abs()),
shortfall: sign * delta,
p_worse: sign_flip_p(&worse),
p_better: sign_flip_p(&better),
}
})
.collect();
let judged: Vec<usize> = (0..METRICS.len()).filter(|&i| METRICS[i].direction != Direction::Info).collect();
let adj_worse = holm_adjust(&judged.iter().map(|&i| raws[i].p_worse).collect::<Vec<_>>());
let adj_better = holm_adjust(&judged.iter().map(|&i| raws[i].p_better).collect::<Vec<_>>());
let mut metrics = Vec::new();
for (i, metric) in METRICS.iter().enumerate() {
let raw = &raws[i];
let slot = judged.iter().position(|&j| j == i);
let (p_worse_adj, p_better_adj) = slot.map_or((raw.p_worse, raw.p_better), |k| (adj_worse[k], adj_better[k]));
let verdict = if pairs.is_empty() {
Verdict::None
} else if metric.direction == Direction::Info {
Verdict::Info
} else if raw.shortfall > raw.tolerance && p_worse_adj < alpha {
Verdict::Fail
} else if -raw.shortfall > raw.tolerance && p_better_adj < alpha {
Verdict::Better
} else {
Verdict::Pass
};
metrics.push(MetricVerdict {
metric: metric.name.to_owned(),
unit: metric.unit.to_owned(),
direction: metric.direction,
pairs: pairs.len(),
mean_a: raw.mean_a,
mean_b: raw.mean_b,
delta: raw.delta,
p_worse: raw.p_worse,
p_better: raw.p_better,
p_worse_adj,
p_better_adj,
tolerance: raw.tolerance,
verdict,
});
}
let trapped_checkpoints = trap_rule(a, b);
let mut failed: Vec<String> = metrics
.iter()
.filter(|m| m.verdict == Verdict::Fail)
.map(|m| m.metric.clone())
.collect();
failed.extend(trapped_checkpoints.iter().map(|t| format!("trap@{}", t.checkpoint)));
Comparison {
schema: "fly-scorecard-compare-v1".to_owned(),
a: a.label.clone(),
b: b.label.clone(),
alpha,
pairs: pairs.len(),
unpaired_a: runs_a.len() - pairs.len(),
unpaired_b: runs_b.len() - pairs.len(),
notes,
pass: failed.is_empty() && !pairs.is_empty(),
failed,
metrics,
trapped_checkpoints,
}
}
impl Comparison {
/// The comparison as a markdown table.
pub fn markdown(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"# Scorecard: {} vs {}: {}\n\n",
self.a,
self.b,
if self.pass { "PASS" } else { "FAIL" }
));
out.push_str(&format!(
"{} paired runs (alpha {} one-sided, sign-flip test, Holm over the judged metrics); {} only in {}, {} only in {}.\n\n",
self.pairs, self.alpha, self.unpaired_a, self.a, self.unpaired_b, self.b
));
for note in &self.notes {
out.push_str(&format!("- note: {note}\n"));
}
if !self.notes.is_empty() {
out.push('\n');
}
out.push_str(&format!(
"| metric | {} | {} | delta | tolerance | p worse (Holm) | p better (Holm) | verdict |\n",
self.a, self.b
));
out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |\n");
for m in &self.metrics {
let arrow = match m.direction {
Direction::Up => "up",
Direction::Down => "down",
Direction::Info => "info",
};
out.push_str(&format!(
"| {} ({}, {}) | {:.2} | {:.2} | {:+.2} | {:.2} | {:.3} | {:.3} | {} |\n",
m.metric,
arrow,
m.unit,
m.mean_a,
m.mean_b,
m.delta,
m.tolerance,
m.p_worse_adj,
m.p_better_adj,
match m.verdict {
Verdict::Pass => "pass",
Verdict::Better => "better",
Verdict::Fail => "**FAIL**",
Verdict::Info => "info",
Verdict::None => "n/a",
}
));
}
if !self.trapped_checkpoints.is_empty() {
out.push_str("\n**Per-checkpoint trap rule: FAIL**\n\n");
for t in &self.trapped_checkpoints {
out.push_str(&format!(
"- `{}`: {} trapped / {} storm run(s) of {} in {}, against {} / {} of {} in {} ({})\n",
t.checkpoint,
t.trapped_b,
t.storms_b,
t.runs_b,
self.b,
t.trapped_a,
t.storms_a,
t.runs_a,
self.a,
t.detail.join("; ")
));
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::suite::{SuiteConfig, SuiteReport};
#[test]
fn the_exact_test_has_the_textbook_p() {
// Seven positive differences: only the all-positive assignment is as extreme.
assert!((sign_flip_p(&[1.0; 7]) - 1.0 / 128.0).abs() < 1e-12);
// All-negative: every assignment is at least as extreme as the observed.
assert!((sign_flip_p(&[-1.0; 7]) - 1.0).abs() < 1e-12);
// Nothing observed is no evidence.
assert_eq!(sign_flip_p(&[]), 1.0);
assert!((sign_flip_p(&[0.0; 5]) - 1.0).abs() < 1e-12);
// Mixed: three of four positive, the largest positive.
let p = sign_flip_p(&[3.0, 1.0, 1.0, -1.0]);
assert!(p > 0.0 && p < 0.5, "{p}");
}
#[test]
fn beyond_twenty_pairs_the_draws_are_fixed() {
let diffs: Vec<f64> = (0..30).map(|i| 1.0 + f64::from(i % 3)).collect();
let p = sign_flip_p(&diffs);
assert_eq!(p, sign_flip_p(&diffs));
assert!(p < 0.001, "{p}");
let noise: Vec<f64> = (0..30).map(|i| if i % 2 == 0 { 1.0 } else { -1.0 }).collect();
assert!(sign_flip_p(&noise) > 0.3);
}
fn run(checkpoint: &str, seed: u32, mutate: impl FnOnce(&mut RunReport)) -> RunReport {
let mut r = RunReport {
checkpoint: checkpoint.to_owned(),
seed,
runtime: "session".into(),
mode: "macros".into(),
minutes: 12.0,
..RunReport::default()
};
r.macros.done = 100;
mutate(&mut r);
r
}
fn suite(label: &str, runs: Vec<RunReport>) -> SuiteReport {
SuiteReport {
schema: crate::suite::SCHEMA.to_owned(),
label: label.to_owned(),
build: Default::default(),
runtime: "session".into(),
mode: "macros".into(),
config: SuiteConfig { minutes: 12.0, seeds: vec![1, 2, 3], ..SuiteConfig::default() },
runs,
failed_runs: Vec::new(),
}
}
fn many(label: &str, f: impl Fn(&str, u32, &mut RunReport)) -> SuiteReport {
let mut runs = Vec::new();
for c in ["r08", "r09", "r10", "r11", "r12", "r13"] {
for s in 1..=3 {
runs.push(run(c, s, |r| f(c, s, r)));
}
}
suite(label, runs)
}
#[test]
fn identical_suites_pass_with_nothing_better_or_worse() {
let a = many("a", |_, s, r| r.rungs.gained = s % 2);
let b = many("b", |_, s, r| r.rungs.gained = s % 2);
let c = compare(&a, &b, 0.05);
assert!(c.pass, "{:?}", c.failed);
assert!(c.metrics.iter().all(|m| matches!(m.verdict, Verdict::Pass | Verdict::Info)));
assert_eq!(c.pairs, 18);
}
#[test]
fn a_consistent_drop_in_rungs_fails_and_a_single_bad_run_does_not() {
let a = many("a", |_, _, r| r.rungs.gained = 1);
let b = many("b", |_, _, r| r.rungs.gained = 0);
let c = compare(&a, &b, 0.05);
assert!(!c.pass);
assert_eq!(c.failed, vec!["rungs_per_hour".to_owned()]);
assert!(c.markdown().contains("**FAIL**"));
// One run of eighteen collapses: not significant, not a regression.
let b = many("b", |ck, s, r| r.rungs.gained = if ck == "r10" && s == 2 { 0 } else { 1 });
assert!(compare(&a, &b, 0.05).pass);
}
#[test]
fn a_rise_in_traps_fails_and_a_drop_is_better() {
let calm = many("a", |_, _, _| {});
let trapped = many("b", |_, _, r| {
r.watchdog.ladder_events = 1;
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
});
let up = compare(&calm, &trapped, 0.05);
assert!(up.failed.contains(&"ladder_events_per_hour".to_owned()), "{:?}", up.failed);
assert!(up.failed.contains(&"watchdog_suspected_pct".to_owned()));
let down = compare(&trapped, &calm, 0.05);
assert!(down.pass);
let better: Vec<&str> = down
.metrics
.iter()
.filter(|m| m.verdict == Verdict::Better)
.map(|m| m.metric.as_str())
.collect();
assert!(better.contains(&"ladder_events_per_hour"), "{better:?}");
}
#[test]
fn a_change_inside_the_tolerance_is_noise_however_consistent() {
// 0.25 pp more empty pad on every run: significant, but under the 1 pp floor.
let a = many("a", |_, _, r| r.pad.empty_fraction = 0.10);
let b = many("b", |_, _, r| r.pad.empty_fraction = 0.1025);
let c = compare(&a, &b, 0.05);
let pad = c.metrics.iter().find(|m| m.metric == "empty_pad_pct").unwrap();
assert_eq!(pad.verdict, Verdict::Pass, "{pad:?}");
}
#[test]
fn runs_pair_by_checkpoint_and_seed_and_unpaired_runs_are_reported() {
let a = many("a", |_, _, _| {});
let mut b = many("b", |_, _, _| {});
b.runs.retain(|r| r.checkpoint != "r13");
let c = compare(&a, &b, 0.05);
assert_eq!((c.pairs, c.unpaired_a, c.unpaired_b), (15, 3, 0));
let none = compare(&a, &suite("empty", Vec::new()), 0.05);
assert!(!none.pass);
assert!(none.metrics.iter().all(|m| m.verdict == Verdict::None));
}
fn row71(r: &mut RunReport) {
// The v0.7.3 row-71 bag bug: THROW BALL started and blocked 131 times, suspected on every probe.
let c = r.macros.by_macro.entry("THROW BALL".into()).or_default();
c.start = 132;
c.blocked = 131;
r.macros.blocked = 131;
r.watchdog.probes = 4;
r.watchdog.suspected = 4;
r.watchdog.ladder_events = 1;
}
#[test]
fn a_trap_on_one_checkpoint_fails_though_the_pooled_test_cannot_see_it() {
let a = many("a", |_, _, _| {});
let b = many("b", |ck, _, r| {
if ck == "r10" {
row71(r)
}
});
let c = compare(&a, &b, 0.05);
assert!(!c.pass);
assert!(c.failed.contains(&"trap@r10".to_owned()), "{:?}", c.failed);
assert_eq!(c.trapped_checkpoints.len(), 1);
assert_eq!(c.trapped_checkpoints[0].trapped_b, 3);
assert!(c.markdown().contains("`r10`"));
// ... while the same suite against itself passes.
assert!(compare(&b, &b, 0.05).pass);
assert!(compare(&a, &a, 0.05).pass);
}
#[test]
fn the_trap_rule_wants_two_seeds_or_a_storm_and_a_clean_a() {
let a = many("a", |_, _, _| {});
// One trapped seed with no storm: not enough.
let one = many("b", |ck, s, r| {
if ck == "r10" && s == 1 {
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
r.watchdog.ladder_events = 1;
}
});
assert!(trap_rule(&a, &one).is_empty());
// Two trapped seeds fail it.
let two = many("b", |ck, s, r| {
if ck == "r10" && s <= 2 {
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
r.watchdog.ladder_events = 1;
}
});
assert_eq!(trap_rule(&a, &two)[0].checkpoint, "r10");
// One seed with a storm fails it.
let storm_one = many("b", |ck, s, r| {
if ck == "r11" && s == 3 {
r.macros.by_macro.entry("GO OUT".into()).or_default().blocked = 50;
}
});
assert_eq!(trap_rule(&a, &storm_one)[0].checkpoint, "r11");
// The same storm in A as well is not new.
assert!(trap_rule(&storm_one, &storm_one).is_empty());
// A was trapped on two seeds already: B trapped on the same two is not a new trap.
assert!(trap_rule(&two, &two).is_empty());
}
#[test]
fn a_blocked_throw_is_not_a_throw() {
let r = run("x", 1, |r| {
r.funnel.throw_ball_start = 132;
r.funnel.throw_ball_done = 1;
row71(r);
});
let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r);
assert!((get("throws_per_hour") - 5.0).abs() < 1e-9);
assert!((get("throw_ball_blocked_per_hour") - 131.0 * 5.0).abs() < 1e-9);
}
#[test]
fn holm_adjusts_step_down_and_never_below_the_raw_p() {
let adj = holm_adjust(&[0.01, 0.04, 0.03, 0.20]);
let want = [0.04, 0.09, 0.09, 0.20];
for (x, y) in adj.iter().zip(want) {
assert!((x - y).abs() < 1e-12, "{adj:?}");
}
assert!(holm_adjust(&[]).is_empty());
assert_eq!(holm_adjust(&[0.6, 0.9]), vec![1.0, 1.0]);
}
/// The false-fail rate of the whole compare under "nothing changed but the trajectory":
/// resample each checkpoint's seeds with replacement (A is the committed v0.7.5 card, B a
/// bootstrap of it) and count failing compares. Slow; run with `--ignored --nocapture`.
#[test]
#[ignore = "a simulation: about a minute in release"]
fn null_false_fail_rate() {
let text = include_str!("../../../../../tools/scorecard/baseline-v0.7.5.json");
let a: SuiteReport = serde_json::from_str(text).expect("baseline");
let mut ids: Vec<String> = a.runs.iter().map(|r| r.checkpoint.clone()).collect();
ids.dedup();
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |n: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % n as u64) as usize
};
let (reps, mut fails, mut metric_fails, mut trap_fails) = (200, 0, 0, 0);
let mut by_checkpoint = BTreeMap::new();
for _ in 0..reps {
let mut b = a.clone();
b.label = "boot".into();
b.runs.clear();
for id in &ids {
let pool: Vec<&RunReport> = a.runs.iter().filter(|r| &r.checkpoint == id).collect();
for (seed, _) in pool.iter().enumerate() {
let mut r = pool[next(pool.len())].clone();
r.seed = pool[seed].seed;
b.runs.push(r);
}
}
let c = compare(&a, &b, 0.05);
if !c.pass {
fails += 1;
}
metric_fails += usize::from(c.failed.iter().any(|f| !f.starts_with("trap@")));
trap_fails += usize::from(!c.trapped_checkpoints.is_empty());
for t in &c.trapped_checkpoints {
*by_checkpoint.entry(t.checkpoint.clone()).or_insert(0usize) += 1;
}
}
println!("null compares: {fails}/{reps} fail ({metric_fails} by a metric, {trap_fails} by the trap rule)");
println!("trap rule by checkpoint: {by_checkpoint:?}");
}
#[test]
fn rates_are_per_brain_hour() {
let r = run("x", 1, |r| {
r.rungs.gained = 1;
r.whiteouts = 2;
});
let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r);
assert!((get("rungs_per_hour") - 5.0).abs() < 1e-9);
assert!((get("whiteouts_per_hour") - 10.0).abs() < 1e-9);
let empty = RunReport::default();
assert_eq!((METRICS[0].read)(&empty), 0.0);
}
}

View file

@ -1,16 +0,0 @@
//! The behavioural scorecard (B2): a repeatable multi-seed regression harness for good play.
//!
//! A fixed set of checkpoints, K seeds each, T brain minutes each, on the real connectome with the
//! macro layer, on the session runtime (default) or the legacy loop. Every run reduces to one
//! [`tally::RunReport`]; a suite is the set of runs ([`suite::SuiteReport`]); two suites compare
//! with a verdict per metric ([`compare::compare`]), by a test over the paired runs rather than
//! by one run.
//!
//! The harness measures and presses nothing. See `docs/scorecard.md`.
pub mod compare;
pub mod obs;
pub mod runner;
pub mod suite;
pub mod tally;
pub mod watchdog;

View file

@ -1,403 +0,0 @@
//! `fly-scorecard`: run the behavioural scorecard, compare two releases, summarise a run.
//!
//! ```sh
//! export FLY_ROM=... # the cartridge, never copied anywhere
//! fly-scorecard list # the set, resolved, with each rung
//! fly-scorecard suite --label v0.7.5 --out card.json # the set x seeds x minutes
//! fly-scorecard compare old.json new.json # exit 1 when a metric regressed
//! fly-scorecard summary card.json # a one-screen markdown
//! fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON on stdout
//! ```
//!
//! The checkpoint set is `tools/scorecard/checkpoints.json`: each entry names the environment
//! variable that holds the checkpoint's path (the ROM tests' own, `rom-env.sh`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, Subcommand};
use flysim::snapshot::MacroMode;
use fly_scorecard::compare::compare;
use fly_scorecard::runner::{Runtime, RunSpec, build_info, run_legacy, run_session};
use fly_scorecard::tally::RunReport;
use fly_scorecard::suite::{
CheckpointSet, ChildArgs, Job, SCHEMA, SuiteConfig, SuiteReport, note, run_jobs,
};
#[derive(Debug, Parser)]
#[command(name = "fly-scorecard", about = "The behavioural scorecard: multi-seed good-play regression.")]
struct Args {
#[command(subcommand)]
command: Cmd,
}
#[derive(Debug, Subcommand)]
enum Cmd {
/// Resolve the checkpoint set and print each checkpoint's rung.
List {
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
/// Extra checkpoints, `id=path`.
#[arg(long = "extra", value_name = "ID=PATH")]
extra: Vec<String>,
},
/// One run: a checkpoint, a seed. Prints the run's JSON on stdout.
RunOne {
#[arg(long)]
id: Option<String>,
#[arg(long)]
checkpoint: PathBuf,
#[arg(long, default_value_t = 1)]
seed: u32,
#[arg(long, default_value_t = 10.0)]
minutes: f64,
#[arg(long, default_value = "session")]
runtime: String,
#[arg(long, default_value = "macros")]
mode: String,
#[arg(long, default_value_t = 1)]
threads: usize,
#[arg(long, default_value_t = 120.0)]
probe_s: f64,
#[arg(long, default_value_t = 600.0)]
window_s: f64,
#[arg(long)]
dataset: Option<PathBuf>,
/// Write the JSON here instead of stdout (the emulator library prints on stdout).
#[arg(long)]
out: Option<PathBuf>,
},
/// The set times the seeds, `--jobs` at a time, as one JSON.
Suite {
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
#[arg(long = "extra", value_name = "ID=PATH")]
extra: Vec<String>,
/// Only these checkpoint ids (comma separated).
#[arg(long, value_delimiter = ',')]
only: Vec<String>,
/// Seeds 1..=K.
#[arg(long, default_value_t = 3)]
seeds: u32,
#[arg(long, default_value_t = 10.0)]
minutes: f64,
#[arg(long, default_value = "session")]
runtime: String,
#[arg(long, default_value = "macros")]
mode: String,
/// Sweep threads per run. One: a run's pool spins at its barriers, so on a box shared with
/// other jobs one-thread runs lose far less than four-thread ones, and the result does
/// not depend on the count.
#[arg(long, default_value_t = 1)]
threads: usize,
/// Runs at a time.
#[arg(long, default_value_t = 8)]
jobs: usize,
#[arg(long, default_value_t = 120.0)]
probe_s: f64,
#[arg(long, default_value_t = 600.0)]
window_s: f64,
/// Names the release or commit under test.
#[arg(long)]
label: String,
#[arg(long)]
out: PathBuf,
/// Also write the one-screen summary here.
#[arg(long)]
md: Option<PathBuf>,
#[arg(long)]
dataset: Option<PathBuf>,
/// Fail instead of running a smaller set when a checkpoint of the set is missing.
#[arg(long)]
strict: bool,
/// Keep the runs an earlier invocation finished (`<out>.runs.jsonl`) and run the rest.
#[arg(long)]
resume: bool,
},
/// Release A against release B. Exit 1 when a metric regressed.
Compare {
a: PathBuf,
b: PathBuf,
#[arg(long, default_value_t = 0.05)]
alpha: f64,
#[arg(long)]
json: Option<PathBuf>,
#[arg(long)]
md: Option<PathBuf>,
},
/// A one-screen markdown of one suite.
Summary {
file: PathBuf,
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
},
}
fn env_dataset(given: Option<PathBuf>) -> PathBuf {
given
.or_else(|| std::env::var_os("FLY_MACRO_BRAIN").map(PathBuf::from))
.or_else(|| std::env::var_os("FLY_DATASET").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("data/fafb-v783"))
}
fn rom() -> Result<PathBuf> {
std::env::var_os("FLY_ROM").map(PathBuf::from).ok_or_else(|| anyhow!("FLY_ROM is not set"))
}
fn mode_of(text: &str) -> Result<MacroMode> {
match text {
"raw" => Ok(MacroMode::Raw),
"macros" => Ok(MacroMode::Macros),
other => bail!("mode {other:?} is not raw or macros"),
}
}
fn parse_extra(extra: &[String]) -> Result<Vec<(String, PathBuf)>> {
extra
.iter()
.map(|item| {
let (id, path) = item.split_once('=').ok_or_else(|| anyhow!("--extra wants ID=PATH, got {item:?}"))?;
Ok((id.to_owned(), PathBuf::from(path)))
})
.collect()
}
/// The rung a checkpoint stands on, from its reward ledger.
fn rung_of(path: &Path) -> Result<(u32, &'static str, usize)> {
use flybrain_gb::adapter::GameAdapter;
let checkpoint = flysim::store::load(path)?;
let mut adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
adapter.import_state(&checkpoint.runtime.reward).map_err(|e| anyhow!("{e}"))?;
let progress = adapter.progress();
Ok((progress.rank, progress.rank_label, progress.unique_locations))
}
struct Resolved {
id: String,
path: PathBuf,
rung: Option<u32>,
}
fn resolve(set_path: &Path, extra: &[String], only: &[String], strict: bool) -> Result<Vec<Resolved>> {
let set = CheckpointSet::load(set_path)?;
let (found, missing) = set.resolve(&|name| std::env::var(name).ok());
if !missing.is_empty() {
eprintln!("scorecard: {} checkpoints of the set are missing: {}", missing.len(), missing.join(", "));
if strict {
bail!("--strict: the set is not complete");
}
}
let mut out: Vec<Resolved> = found
.into_iter()
.map(|(entry, path)| Resolved { id: entry.id, path, rung: Some(entry.rung) })
.collect();
for (id, path) in parse_extra(extra)? {
if !path.is_file() {
bail!("--extra {id}: {} is not a file", path.display());
}
out.push(Resolved { id, path, rung: None });
}
if !only.is_empty() {
out.retain(|r| only.contains(&r.id));
}
if out.is_empty() {
bail!("no checkpoint to run");
}
Ok(out)
}
fn main() {
if let Err(error) = real_main() {
eprintln!("fly-scorecard: {error:#}");
std::process::exit(2);
}
}
fn real_main() -> Result<()> {
let args = Args::parse();
match args.command {
Cmd::List { set, extra } => {
for r in resolve(&set, &extra, &[], false)? {
match rung_of(&r.path) {
Ok((rank, label, places)) => println!(
"{:<28} set rung {:>2} checkpoint rung {rank:>2} {label} ({places} places)",
r.id,
r.rung.map_or("-".to_owned(), |n| n.to_string())
),
Err(error) => println!("{:<28} unreadable: {error:#}", r.id),
}
}
Ok(())
}
Cmd::RunOne { id, checkpoint, seed, minutes, runtime, mode, threads, probe_s, window_s, dataset, out } => {
let runtime = Runtime::parse(&runtime)?;
let id = id.unwrap_or_else(|| {
checkpoint.file_stem().map_or_else(|| "checkpoint".to_owned(), |s| s.to_string_lossy().into_owned())
});
let spec = RunSpec {
id,
checkpoint,
rom: rom()?,
dataset: env_dataset(dataset),
seed,
minutes,
threads,
mode: mode_of(&mode)?,
tally: RunSpec::tally_config(probe_s, window_s),
};
let report = match runtime {
Runtime::Legacy => run_legacy(&spec)?,
Runtime::Session => tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?
.block_on(run_session(&spec))?,
};
let text = serde_json::to_string(&report)? + "\n";
match out {
Some(path) => std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?,
None => print!("{text}"),
}
Ok(())
}
Cmd::Suite {
set, extra, only, seeds, minutes, runtime, mode, threads, jobs, probe_s, window_s, label, out, md,
dataset, strict, resume,
} => {
Runtime::parse(&runtime)?;
mode_of(&mode)?;
rom()?;
let resolved = resolve(&set, &extra, &only, strict)?;
let exe = std::env::current_exe().context("finding this executable")?;
let seed_list: Vec<u32> = (1..=seeds).collect();
// Every finished run is appended to `<out>.runs.jsonl` at once, so a suite that dies
// (a box that reboots, a job that is killed) keeps what it finished.
let runs_log = out.with_extension("runs.jsonl");
let mut prior: Vec<RunReport> = Vec::new();
if resume {
if let Ok(text) = std::fs::read_to_string(&runs_log) {
prior = text
.lines()
.filter_map(|line| serde_json::from_str::<RunReport>(line).ok())
.filter(|run| run.runtime == runtime && run.mode == mode && run.minutes >= minutes - 0.01)
.collect();
}
} else {
let _ = std::fs::remove_file(&runs_log);
}
let mut queue = Vec::new();
for r in &resolved {
for seed in &seed_list {
if prior.iter().any(|run| run.checkpoint == r.id && run.seed == *seed) {
continue;
}
queue.push(Job { id: r.id.clone(), path: r.path.clone(), seed: *seed });
}
}
if !prior.is_empty() {
eprintln!("scorecard: resuming with {} finished runs, {} to go", prior.len(), queue.len());
}
let child = ChildArgs {
runtime: runtime.clone(),
mode: mode.clone(),
minutes,
threads,
probe_s,
window_s,
dataset: dataset.clone().or_else(|| Some(env_dataset(None))),
};
let progress = out.with_extension("progress.log");
let _ = std::fs::remove_file(&progress);
eprintln!(
"scorecard {label}: {} runs ({} checkpoints x {} seeds) of {minutes} brain min, {jobs} at a time, {threads} threads each",
queue.len(),
resolved.len(),
seed_list.len()
);
let began = std::time::Instant::now();
let outcomes = run_jobs(&exe, queue, &child, jobs, &|outcome| {
let line = match outcome {
Ok(run) => format!(
"{:>6.0}s done {} seed {}: rung {}->{} in {:.1} min, {:.0}s wall",
began.elapsed().as_secs_f64(), run.checkpoint, run.seed, run.rungs.start, run.rungs.end,
run.minutes, run.wall_seconds
),
Err(failed) => format!(
"{:>6.0}s FAILED {} seed {}: {}",
began.elapsed().as_secs_f64(), failed.checkpoint, failed.seed, failed.error
),
};
eprintln!("{line}");
note(&progress, &line);
if let Ok(run) = outcome
&& let Ok(text) = serde_json::to_string(run)
{
note(&runs_log, &text);
}
});
let mut runs = prior;
let mut failed_runs = Vec::new();
for outcome in outcomes {
match outcome {
Ok(run) => runs.push(run),
Err(failed) => failed_runs.push(failed),
}
}
let order: BTreeMap<&str, usize> =
resolved.iter().enumerate().map(|(i, r)| (r.id.as_str(), i)).collect();
runs.sort_by_key(|run| (order.get(run.checkpoint.as_str()).copied().unwrap_or(usize::MAX), run.seed));
let suite = SuiteReport {
schema: SCHEMA.to_owned(),
label,
build: build_info(""),
runtime,
mode,
config: SuiteConfig { minutes, seeds: seed_list, threads, jobs, probe_s, window_s },
runs,
failed_runs,
};
let mut suite = suite;
suite.build.release = suite.label.clone();
std::fs::write(&out, serde_json::to_string_pretty(&suite)? + "\n")
.with_context(|| format!("writing {}", out.display()))?;
let rungs: BTreeMap<String, u32> =
resolved.iter().filter_map(|r| r.rung.map(|n| (r.id.clone(), n))).collect();
let markdown = suite.markdown(&rungs);
if let Some(md) = md {
std::fs::write(&md, &markdown).with_context(|| format!("writing {}", md.display()))?;
}
println!("{markdown}");
eprintln!("scorecard: {:.0} s wall", began.elapsed().as_secs_f64());
if suite.runs.is_empty() {
bail!("every run failed");
}
Ok(())
}
Cmd::Compare { a, b, alpha, json, md } => {
let (sa, sb) = (SuiteReport::load(&a)?, SuiteReport::load(&b)?);
let comparison = compare(&sa, &sb, alpha);
let markdown = comparison.markdown();
if let Some(json) = json {
std::fs::write(&json, serde_json::to_string_pretty(&comparison)? + "\n")?;
}
if let Some(md) = md {
std::fs::write(&md, &markdown)?;
}
println!("{markdown}");
if !comparison.pass {
std::process::exit(1);
}
Ok(())
}
Cmd::Summary { file, set } => {
let suite = SuiteReport::load(&file)?;
let rungs: BTreeMap<String, u32> = CheckpointSet::load(&set)
.map(|s| s.checkpoints.into_iter().map(|e| (e.id, e.rung)).collect())
.unwrap_or_default();
println!("{}", suite.markdown(&rungs));
Ok(())
}
}
}

View file

@ -1,146 +0,0 @@
//! What the scorecard sees of one frame, whichever runtime ran it.
//!
//! The legacy loop hands a harness a live emulator and the frame's events; the session runtime
//! hands it a task object holding the boundary's memory image. Both are reduced to the same
//! [`Frame`] here, so every metric is computed once ([`crate::tally`]) and a comparison between
//! the two runtimes cannot differ in what was measured.
use flybrain_gb::MemoryReader;
use flybrain_gb::pokemon_red::state;
use flybrain_gb::pokemon_red::symbols::ram;
/// One macro event: a start (`outcome` is `None`) or a finish.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MacroEv {
pub name: &'static str,
pub outcome: Option<&'static str>,
}
/// A rollback the ratchet ran at this boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rolled {
/// The trigger was a game over, else a stall.
pub game_over: bool,
}
/// Facts read off game memory on one frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Facts {
/// `wIsInBattle`: 0 none, 1 wild, 2 trainer, `$ff` the frame a battle is lost.
pub battle: u8,
/// Party members with a species (a half-written slot is not counted).
pub party: u8,
/// Of them, those with HP left.
pub alive: u8,
/// Poke Balls of every kind in the bag.
pub balls: u32,
pub money: u32,
/// Species owned (Pokedex bits).
pub owned: u32,
/// The map the player stands on, `0xff` when the adapter cannot place the player.
pub map: u32,
}
impl Facts {
/// Every member of a non-empty party has fainted: the state a whiteout starts from.
pub fn all_fainted(&self) -> bool {
self.party > 0 && self.alive == 0
}
pub fn in_battle(&self) -> bool {
self.battle != 0
}
}
/// Reads [`Facts`] from any memory (a live emulator or a boundary image).
pub fn facts_of(memory: &mut dyn MemoryReader) -> Facts {
let battle = memory.read8(ram::wIsInBattle);
let party = state::party(memory);
let real: Vec<_> = party.mons.iter().filter(|mon| mon.species != 0).collect();
let alive = real.iter().filter(|mon| mon.hp > 0).count();
let balls: u32 = state::bag(memory)
.iter()
.filter(|item| (0x01..=0x04).contains(&item.id))
.map(|item| u32::from(item.count))
.sum();
let money = state::money(memory);
let owned: u32 = (0..19u16).map(|i| memory.read8(ram::wPokedexOwned + i).count_ones()).sum();
let map = state::player(memory).map_or(0xff, |player| u32::from(player.map));
Facts {
battle,
party: real.len() as u8,
alive: alive as u8,
balls,
money,
owned,
map,
}
}
/// One frame, as the scorecard takes it.
#[derive(Clone, Debug)]
pub struct Frame {
/// The brain clock of the frame, ms.
pub ms: f64,
/// The macro layer's events this frame: executed, abandoned and a rollback's, in order.
pub events: Vec<MacroEv>,
/// Rewards paid this frame: the adapter's kind and value.
pub rewards: Vec<(&'static str, f64)>,
pub rank: u32,
/// Distinct places the adapter has observed (the exploration count).
pub places: u32,
/// `(map, x, y)` the adapter placed the player on, when it could.
pub location: Option<(u32, u32, u32)>,
/// The macro layer is on (macros mode).
pub macros_on: bool,
/// No macro runs and the scene dealt no button.
pub pad_empty: bool,
pub scene: &'static str,
pub rollback: Option<Rolled>,
pub facts: Facts,
}
/// The idle frames a seed starts with.
///
/// A checkpoint restores a deterministic brain, so two runs from it with different "seeds" would
/// be the same run. A seed therefore chooses how many frames the readout is ignored before the
/// measurement starts: the brain still ticks, the noise generator still advances, the game sees
/// no button, and from the first measured frame the brain is on a different point of its own
/// trajectory. Seed 0 is no idle at all (the run the trap hunt does from the same checkpoint).
/// Nothing presses for the fly and nothing changes what it chooses once the measurement starts.
pub fn idle_frames(seed: u32) -> u32 {
if seed == 0 {
return 0;
}
// splitmix64 of the seed, so consecutive seeds are unrelated; 1 to 30 seconds of idle.
let mut z = u64::from(seed).wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^= z >> 31;
60 + (z % 1741) as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn seed_zero_is_no_idle_and_seeds_differ() {
assert_eq!(idle_frames(0), 0);
let idles: Vec<u32> = (1..=8).map(idle_frames).collect();
assert!(idles.iter().all(|n| (60..=1800).contains(n)));
let mut sorted = idles.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), idles.len(), "{idles:?}");
assert_eq!(idle_frames(3), idle_frames(3));
}
#[test]
fn a_party_that_has_all_fainted() {
let down = Facts { party: 2, alive: 0, ..Facts::default() };
assert!(down.all_fainted());
assert!(!Facts { party: 2, alive: 1, ..Facts::default() }.all_fainted());
assert!(!Facts::default().all_fainted(), "no party is not a whiteout");
}
}

View file

@ -1,397 +0,0 @@
//! One run on a real brain: a checkpoint restored, the seed's idle frames, then the measured
//! brain minutes, on either runtime.
//!
//! Both runtimes drive the unchanged engine. The legacy runner is the stream's own frame
//! (`flysim::frame::LegacyFrame`, as the trap hunt runs it); the session runner is the session
//! composition the release cut over to (`fly_legacy_session::composition::LegacySession`, the
//! agent, the world and the task under one coordinator, in-process, unpaced). Each hands the same
//! [`Frame`] to the same [`Tally`].
//!
//! Neither runner presses anything or changes what the brain chooses. The seed's idle frames
//! ignore the brain's readout for a while before the measurement starts ([`idle_frames`]); from
//! the first measured frame the readout is the brain's own.
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use anyhow::{Context, Result, anyhow};
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir};
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::lif::SweepPlan;
use flybrain_gb::adapter::GameAdapter;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::Ratchet;
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
use flysim::config::Config;
use flysim::frame::{FrameObserver, LegacyFrame, Parts, RollbackTrigger};
use flysim::macros::{MacroEvent, MacroLayer, macro_layer};
use flysim::snapshot::MacroMode;
use crate::obs::{Frame, MacroEv, Rolled, facts_of, idle_frames};
use crate::tally::{RunReport, Tally, TallyConfig};
use crate::watchdog::Rules;
/// Which runtime ran it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Runtime {
Session,
Legacy,
}
impl Runtime {
pub fn parse(text: &str) -> Result<Self> {
match text {
"session" => Ok(Self::Session),
"legacy" => Ok(Self::Legacy),
other => Err(anyhow!("runtime {other:?} is not session or legacy")),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Session => "session",
Self::Legacy => "legacy",
}
}
}
/// Everything one run needs.
#[derive(Clone, Debug)]
pub struct RunSpec {
pub id: String,
pub checkpoint: PathBuf,
pub rom: PathBuf,
pub dataset: PathBuf,
pub seed: u32,
pub minutes: f64,
pub threads: usize,
pub mode: MacroMode,
pub tally: TallyConfig,
}
impl RunSpec {
/// A tally configuration with the probe cadence and window the caller chose.
pub fn tally_config(probe_s: f64, window_s: f64) -> TallyConfig {
TallyConfig {
rules: Rules { window_ms: window_s * 1000.0, ..Rules::default() },
probe_s,
..TallyConfig::default()
}
}
fn identity(&self, runtime: Runtime, idle: u32, wall: f64) -> RunReport {
RunReport {
checkpoint: self.id.clone(),
seed: self.seed,
runtime: runtime.as_str().to_owned(),
mode: self.mode.as_str().to_owned(),
idle_frames: idle,
wall_seconds: wall,
..RunReport::default()
}
}
}
fn conv(event: &MacroEvent) -> MacroEv {
MacroEv { name: event.name, outcome: event.outcome.map(|outcome| outcome.as_str()) }
}
/// The measurement's start: it begins on the first frame after the idle frames, with the rung and
/// the exploration count the run stood on just before it.
struct Measure {
spec: RunSpec,
idle_left: u32,
prev: (u32, u32),
tally: Option<Tally>,
}
impl Measure {
fn new(spec: &RunSpec, rank: u32, places: u32) -> Self {
Self { spec: spec.clone(), idle_left: idle_frames(spec.seed), prev: (rank, places), tally: None }
}
/// Takes one frame; true when the measured minutes are up.
fn take(&mut self, frame: Frame) -> bool {
let (rank, places) = (frame.rank, frame.places);
if self.idle_left > 0 {
self.idle_left -= 1;
self.prev = (rank, places);
return false;
}
let tally = self.tally.get_or_insert_with(|| {
Tally::new(self.spec.tally.clone(), frame.ms, self.prev.0, self.prev.1)
});
tally.push(&frame);
tally.minutes() >= self.spec.minutes
}
fn finish(self, runtime: Runtime, wall: f64) -> Result<RunReport> {
let idle = idle_frames(self.spec.seed);
let tally = self.tally.ok_or_else(|| anyhow!("no frame was measured"))?;
Ok(tally.finish(self.spec.identity(runtime, idle, wall)))
}
}
// -- the legacy runtime -----------------------------------------------------------------------
/// The seed's idle frames, and the pad's state read just before the executor decides.
struct Idle {
left: u32,
pad_empty: bool,
}
impl FrameObserver for Idle {
fn readout(&mut self, _ms: f64, _bound: Option<&[String]>, active: &mut Vec<String>) {
if self.left > 0 {
self.left -= 1;
active.clear();
}
}
fn before_execute(&mut self, _frame: &LegacyFrame, parts: &mut Parts<'_>, _active: &[String]) {
self.pad_empty = parts
.macros
.as_deref()
.is_some_and(|layer| layer.running().is_none() && layer.feed_palette().is_empty());
}
}
fn load_dataset(spec: &RunSpec) -> Result<Arc<BrainDataset>> {
let data = load_brain_dataset_from_dir(&spec.dataset)
.map_err(|e| anyhow!("loading the connectome at {}: {e}", spec.dataset.display()))?;
Ok(Arc::new(data))
}
/// The stream's own frame, restored from the checkpoint as the stream restores it.
pub fn run_legacy(spec: &RunSpec) -> Result<RunReport> {
let began_wall = Instant::now();
let rom = std::fs::read(&spec.rom).with_context(|| format!("reading {}", spec.rom.display()))?;
let checkpoint = flysim::store::load(&spec.checkpoint)
.with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?;
let data = load_dataset(spec)?;
let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.map_err(|e| anyhow!("the cartridge: {e}"))?;
let mut adapter = PokemonRedReward::new();
let channels =
if spec.mode.dealt() { flybrain_gb::macro_channels("pokemon-red") } else { Vec::new() };
let preset = gameboy_decoder_config_with_macros(&channels);
let hold_ms = preset
.macros
.as_ref()
.or(preset.exclusive.as_ref())
.map(|group| group.hold_ms)
.ok_or_else(|| anyhow!("the preset has no group"))?;
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
let mut agent = NeuralAgent::new(Arc::clone(&data), AgentConfig::with_decoder(preset))
.map_err(|e| anyhow!("{e}"))?;
if spec.threads > 1 {
agent.set_sweep_plan(SweepPlan::with_threads(spec.threads).map_err(|e| anyhow!("{e}"))?);
}
let mut frame = LegacyFrame::new();
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
&checkpoint,
)
.context("the checkpoint should restore")?;
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_string();
config.macros.mode = spec.mode;
// As the service seeds it after a restore: the restored brain's own generator.
let mut macros: Option<MacroLayer> =
macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let ledger = AdapterLedger(&adapter);
let _ = layer.observe(&mut emulator, &ledger, agent.network.ms);
}
let start = adapter.progress();
let mut measure = Measure::new(spec, start.rank, start.unique_locations as u32);
let mut observer = Idle { left: measure.idle_left, pad_empty: false };
loop {
let mut parts = Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: macros.as_mut(),
};
let transition = frame.transition(&mut parts, &mut observer).context("a frame")?;
let boundary = frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.context("the boundary")?;
let mut events: Vec<MacroEv> = transition.executed.events.iter().map(conv).collect();
events.extend(transition.evaluated.abandoned.iter().map(conv));
let rolled = boundary.rollback.as_ref().map(|rollback| {
events.extend(rollback.events.iter().map(conv));
Rolled { game_over: rollback.trigger == RollbackTrigger::GameOver }
});
let progress = &transition.evaluated.progress;
let obs = Frame {
ms: transition.ms,
events,
rewards: transition.evaluated.rewards.iter().map(|r| (r.kind, r.value)).collect(),
rank: progress.rank,
places: progress.unique_locations as u32,
location: parts.adapter.location(),
macros_on: parts.macros.is_some(),
pad_empty: observer.pad_empty,
scene: parts.macros.as_deref().map_or("raw", MacroLayer::scene_name),
rollback: rolled,
facts: facts_of(parts.emulator),
};
if measure.take(obs) {
break;
}
}
measure.finish(Runtime::Legacy, began_wall.elapsed().as_secs_f64())
}
// -- the session runtime ----------------------------------------------------------------------
/// The seed's idle frames on the session's executor: the same readout replacement the legacy
/// frame's observer makes.
struct IdleDriver {
left: u32,
}
impl fly_legacy_session::driver::DecisionDriver for IdleDriver {
fn readout(&mut self, _ms: f64, _bound: &[String], active: &mut Vec<String>) {
if self.left > 0 {
self.left -= 1;
active.clear();
}
}
}
/// The session composition the release runs, in-process and unpaced, from the checkpoint.
pub async fn run_session(spec: &RunSpec) -> Result<RunReport> {
use fly_legacy_session::composition::Transport; // overlay:bus01
use fly_legacy_session::composition::{LegacyConfig, LegacySession};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::types::id;
let began_wall = Instant::now();
let checkpoint = flysim::store::load(&spec.checkpoint)
.with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?;
let root = tempfile::tempdir().context("a scratch directory")?;
let mut session = LegacySession::start(
root.path(),
LegacyConfig {
mode: ExecutionMode::InProcess,
transport: Transport::default(), // overlay:bus01
placements: Default::default(), // overlay:bus01
rom_path: spec.rom.clone(),
dataset_dir: spec.dataset.clone(),
profile: LegacyProfileKind::Production,
macro_mode: spec.mode,
agent_id: id("fly"),
agent_threads: spec.threads.max(1),
record: false,
},
)
.await
.map_err(|e| anyhow!("{e}"))?;
session.bootstrap().await.map_err(|e| anyhow!("{e}"))?;
session
.import_checkpoint(&checkpoint, &id("e2"))
.await
.map_err(|e| anyhow!("importing the checkpoint: {e}"))?;
// A measurement runs as fast as the brain allows.
session.coordinator.disable_pacing();
let task = session.task.clone();
let (rank, places) = task.inspect(|adapter, _, _| {
let progress = adapter.progress();
(progress.rank, progress.unique_locations as u32)
});
let mut measure = Measure::new(spec, rank, places);
task.set_driver(Box::new(IdleDriver { left: measure.idle_left }));
let outcome = async {
loop {
session.step().await.map_err(|e| anyhow!("{e}"))?;
let feed = task.take_feed();
let ms = task.brain_ms();
let mut events: Vec<MacroEv> = feed.executed.iter().map(conv).collect();
events.extend(feed.abandoned.iter().map(conv));
let rolled = feed.rollback.as_ref().map(|(game_over, rollback_events)| {
events.extend(rollback_events.iter().map(conv));
Rolled { game_over: *game_over }
});
let (rank, places, location, macros_on, pad_empty, scene) =
task.inspect(|adapter, _, macros| {
let progress = adapter.progress();
(
progress.rank,
progress.unique_locations as u32,
adapter.location(),
macros.is_some(),
macros.is_some_and(|l| l.running().is_none() && l.feed_palette().is_empty()),
macros.map_or("raw", MacroLayer::scene_name),
)
});
let facts = task
.with_reader(|memory| facts_of(memory))
.ok_or_else(|| anyhow!("the task has no boundary image"))?;
let obs = Frame {
ms,
events,
rewards: feed.rewards.iter().map(|r| (r.kind, r.value)).collect(),
rank,
places,
location,
macros_on,
pad_empty,
scene,
rollback: rolled,
facts,
};
if measure.take(obs) {
break;
}
}
anyhow::Ok(())
}
.await;
session.stop().await;
outcome?;
measure.finish(Runtime::Session, began_wall.elapsed().as_secs_f64())
}
/// The adapter and the compatibility digest of this build, for the report.
pub fn build_info(release: &str) -> crate::suite::BuildInfo {
use fly_legacy_session::composition::Transport; // overlay:bus01
use fly_legacy_session::composition::{LegacyConfig, compatibility_of};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::types::id;
let adapter = GameAdapter::id(&PokemonRedReward::new()).to_owned();
let compat = compatibility_of(&LegacyConfig {
mode: ExecutionMode::InProcess,
transport: Transport::default(), // overlay:bus01
placements: Default::default(), // overlay:bus01
rom_path: PathBuf::new(),
dataset_dir: PathBuf::new(),
profile: LegacyProfileKind::Production,
macro_mode: MacroMode::Macros,
agent_id: id("fly"),
agent_threads: 1,
record: false,
});
let digest = flybrain_core::dataset::sha256_hex(compat.as_bytes());
crate::suite::BuildInfo {
release: release.to_owned(),
adapter,
compatibility_sha: digest.chars().take(12).collect(),
}
}

View file

@ -1,471 +0,0 @@
//! A suite: the checkpoint set times the seeds, run as child processes, aggregated.
//!
//! One run is one process (`fly-scorecard run-one`), so two runs never share a thread pool, a
//! tokio runtime or a brain. The suite starts `jobs` children at a time and collects the JSON each
//! prints. A child that fails is recorded as a failed run and never silently dropped: a suite with
//! failed runs says so in its summary and `compare` pairs only what finished.
use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::compare::{METRICS, mean, stdev};
use crate::tally::RunReport;
pub const SCHEMA: &str = "fly-scorecard-v1";
pub const SET_SCHEMA: &str = "fly-scorecard-set-v1";
/// One checkpoint of the fixed set. Public files name the environment variable that holds the
/// path (the ROM tests' own, `rom-env.sh`), never a path.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SetEntry {
pub id: String,
/// The rung the checkpoint is at, for the report's order and the by-rung table.
pub rung: u32,
pub env: String,
#[serde(default)]
pub note: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckpointSet {
pub schema: String,
pub checkpoints: Vec<SetEntry>,
}
impl CheckpointSet {
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let set: CheckpointSet = serde_json::from_str(&text).context("the checkpoint set")?;
if set.schema != SET_SCHEMA {
bail!("{}: schema {:?}, expected {SET_SCHEMA}", path.display(), set.schema);
}
let mut seen = std::collections::BTreeSet::new();
for entry in &set.checkpoints {
if !seen.insert(entry.id.clone()) {
bail!("{}: checkpoint id {:?} twice", path.display(), entry.id);
}
}
Ok(set)
}
/// The entries whose checkpoint file exists in this environment, with their paths, and the
/// ids that do not (reported, never skipped silently).
pub fn resolve(&self, env: &dyn Fn(&str) -> Option<String>) -> (Vec<(SetEntry, PathBuf)>, Vec<String>) {
let mut found = Vec::new();
let mut missing = Vec::new();
for entry in &self.checkpoints {
match env(&entry.env).map(PathBuf::from).filter(|path| path.is_file()) {
Some(path) => found.push((entry.clone(), path)),
None => missing.push(format!("{} (${})", entry.id, entry.env)),
}
}
(found, missing)
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SuiteConfig {
/// Brain minutes measured per run.
pub minutes: f64,
pub seeds: Vec<u32>,
pub threads: usize,
pub jobs: usize,
pub probe_s: f64,
pub window_s: f64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BuildInfo {
/// The release or commit under test, as the caller names it.
pub release: String,
pub adapter: String,
/// The compatibility string's SHA-256 prefix (the string itself names no private value, but
/// the digest is enough to tell two builds' checkpoints apart).
pub compatibility_sha: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FailedRun {
pub checkpoint: String,
pub seed: u32,
pub error: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SuiteReport {
pub schema: String,
pub label: String,
pub build: BuildInfo,
pub runtime: String,
pub mode: String,
pub config: SuiteConfig,
pub runs: Vec<RunReport>,
pub failed_runs: Vec<FailedRun>,
}
impl SuiteReport {
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let suite: SuiteReport = serde_json::from_str(&text).with_context(|| format!("{} is not a scorecard", path.display()))?;
if suite.schema != SCHEMA {
bail!("{}: schema {:?}, expected {SCHEMA}", path.display(), suite.schema);
}
Ok(suite)
}
pub fn brain_hours(&self) -> f64 {
self.runs.iter().map(|run| run.minutes).sum::<f64>() / 60.0
}
/// The headline: totals over every run, as rates per brain hour where that is the unit.
pub fn headline(&self) -> Headline {
let hours = self.brain_hours();
let sum = |f: &dyn Fn(&RunReport) -> f64| self.runs.iter().map(f).sum::<f64>();
let per_hour = |x: f64| if hours > 0.0 { x / hours } else { 0.0 };
let probes = sum(&|r| r.watchdog.probes as f64);
let windows = sum(&|r| r.hunt.windows as f64);
let frames = sum(&|r| r.frames as f64);
let finishes = sum(&|r| (r.macros.done + r.macros.failed()) as f64);
Headline {
runs: self.runs.len(),
brain_hours: hours,
rungs_per_hour: per_hour(sum(&|r| f64::from(r.rungs.gained))),
runs_with_a_climb: self.runs.iter().filter(|r| r.rungs.gained > 0).count(),
empty_pad_pct: if frames > 0.0 { 100.0 * sum(&|r| r.pad.empty_frames as f64) / frames } else { 0.0 },
suspected_probe_pct: if probes > 0.0 { 100.0 * sum(&|r| r.watchdog.suspected as f64) / probes } else { 0.0 },
ladder_events: self.runs.iter().map(|r| r.watchdog.ladder_events).sum(),
runs_with_a_ladder_event: self.runs.iter().filter(|r| r.watchdog.ladder_events > 0).count(),
hunt_flagged_pct: if windows > 0.0 { 100.0 * sum(&|r| r.hunt.flagged as f64) / windows } else { 0.0 },
blocked_macro_pct: if finishes > 0.0 { 100.0 * sum(&|r| r.macros.failed() as f64) / finishes } else { 0.0 },
buy_ball_done: self.runs.iter().map(|r| r.funnel.buy_ball_done).sum(),
throws: self.runs.iter().map(|r| r.funnel.throw_ball_done).sum(),
catches: self.runs.iter().map(|r| r.funnel.catches).sum(),
heals: self.runs.iter().map(|r| r.heals.heal_done).sum(),
whiteouts: self.runs.iter().map(|r| r.whiteouts).sum(),
battles_won: self.runs.iter().map(|r| r.battles.won).sum(),
battles_lost: self.runs.iter().map(|r| r.battles.lost).sum(),
ratchet_rollbacks: self.runs.iter().map(|r| u64::from(r.ratchet.rollbacks)).sum(),
}
}
/// A one-screen summary: the headline, then a row per checkpoint with its seeds' spread.
pub fn markdown(&self, rungs: &BTreeMap<String, u32>) -> String {
let h = self.headline();
let mut out = String::new();
out.push_str(&format!(
"# Scorecard {}: {} runtime, {}\n\n",
self.label, self.runtime, self.mode
));
out.push_str(&format!(
"{} runs, {:.2} brain hours ({} brain min each, seeds {:?}), adapter `{}`, compatibility `{}`.\n\n",
h.runs,
h.brain_hours,
self.config.minutes,
self.config.seeds,
self.build.adapter,
self.build.compatibility_sha
));
if !self.failed_runs.is_empty() {
out.push_str(&format!("**{} runs failed:**\n", self.failed_runs.len()));
for failed in &self.failed_runs {
out.push_str(&format!("- {} seed {}: {}\n", failed.checkpoint, failed.seed, failed.error));
}
out.push('\n');
}
out.push_str("| headline | value |\n| --- | ---: |\n");
let rows: Vec<(&str, String)> = vec![
("rungs per brain hour", format!("{:.2} ({} of {} runs climbed)", h.rungs_per_hour, h.runs_with_a_climb, h.runs)),
("empty-pad time", format!("{:.2}% of frames", h.empty_pad_pct)),
("watchdog probes suspected", format!("{:.1}%", h.suspected_probe_pct)),
("ladder-worthy traps", format!("{} (in {} runs)", h.ladder_events, h.runs_with_a_ladder_event)),
("trap-hunt windows flagged", format!("{:.1}%", h.hunt_flagged_pct)),
("blocked macro finishes", format!("{:.1}%", h.blocked_macro_pct)),
("buy ball / throw / catch", format!("{} / {} / {}", h.buy_ball_done, h.throws, h.catches)),
("heals / whiteouts", format!("{} / {}", h.heals, h.whiteouts)),
("battles won / lost", format!("{} / {}", h.battles_won, h.battles_lost)),
("ratchet rollbacks", format!("{}", h.ratchet_rollbacks)),
];
for (name, value) in rows {
out.push_str(&format!("| {name} | {value} |\n"));
}
out.push_str("\n| checkpoint | rung | seeds | rungs/h | empty pad % | suspected % | traps | buy/throw/catch | won/lost | whiteouts |\n");
out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | --- | ---: |\n");
let mut by: BTreeMap<&str, Vec<&RunReport>> = BTreeMap::new();
for run in &self.runs {
by.entry(run.checkpoint.as_str()).or_default().push(run);
}
let mut order: Vec<(&str, &Vec<&RunReport>)> = by.iter().map(|(k, v)| (*k, v)).collect();
order.sort_by_key(|(id, runs)| (rungs.get(*id).copied().unwrap_or(runs[0].rungs.start), *id));
for (id, runs) in order {
let rate = |name: &str| -> Vec<f64> {
let metric = METRICS.iter().find(|m| m.name == name).expect("a metric");
runs.iter().map(|r| (metric.read)(r)).collect()
};
let rungs_h = rate("rungs_per_hour");
let pad = rate("empty_pad_pct");
let susp = rate("watchdog_suspected_pct");
let sum = |f: &dyn Fn(&RunReport) -> u64| runs.iter().map(|r| f(r)).sum::<u64>();
out.push_str(&format!(
"| {id} | {} | {} | {:.1} ± {:.1} | {:.1} | {:.0} | {} | {}/{}/{} | {}/{} | {} |\n",
rungs.get(id).copied().unwrap_or(runs[0].rungs.start),
runs.len(),
mean(&rungs_h),
stdev(&rungs_h),
mean(&pad),
mean(&susp),
sum(&|r| r.watchdog.ladder_events as u64),
sum(&|r| r.funnel.buy_ball_done),
sum(&|r| r.funnel.throw_ball_done),
sum(&|r| r.funnel.catches),
sum(&|r| r.battles.won),
sum(&|r| r.battles.lost),
sum(&|r| r.whiteouts),
));
}
out
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Headline {
pub runs: usize,
pub brain_hours: f64,
pub rungs_per_hour: f64,
pub runs_with_a_climb: usize,
pub empty_pad_pct: f64,
pub suspected_probe_pct: f64,
pub ladder_events: usize,
pub runs_with_a_ladder_event: usize,
pub hunt_flagged_pct: f64,
pub blocked_macro_pct: f64,
pub buy_ball_done: u64,
pub throws: u64,
pub catches: u64,
pub heals: u64,
pub whiteouts: u64,
pub battles_won: u64,
pub battles_lost: u64,
pub ratchet_rollbacks: u64,
}
/// One run to do: a checkpoint of the set, a seed.
#[derive(Clone, Debug)]
pub struct Job {
pub id: String,
pub path: PathBuf,
pub seed: u32,
}
/// What every child shares.
#[derive(Clone, Debug)]
pub struct ChildArgs {
pub runtime: String,
pub mode: String,
pub minutes: f64,
pub threads: usize,
pub probe_s: f64,
pub window_s: f64,
pub dataset: Option<PathBuf>,
}
/// Runs the jobs `jobs` at a time as children of this executable, calling `done` as each one
/// finishes (so a caller can write partial results). Returns the finished runs and the failures,
/// in job order.
pub fn run_jobs(
exe: &Path,
jobs: Vec<Job>,
args: &ChildArgs,
parallel: usize,
done: &(dyn Fn(&Result<RunReport, FailedRun>) + Sync),
) -> Vec<Result<RunReport, FailedRun>> {
let queue = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::<std::collections::VecDeque<_>>()));
let results = Arc::new(Mutex::new(Vec::new()));
std::thread::scope(|scope| {
for _ in 0..parallel.max(1) {
let queue = Arc::clone(&queue);
let results = Arc::clone(&results);
scope.spawn(move || {
loop {
let next = queue.lock().expect("queue").pop_front();
let Some((index, job)) = next else { break };
let outcome = run_child(exe, &job, args);
done(&outcome);
results.lock().expect("results").push((index, outcome));
}
});
}
});
let mut results = Arc::try_unwrap(results).expect("all workers joined").into_inner().expect("results");
results.sort_by_key(|(index, _)| *index);
results.into_iter().map(|(_, outcome)| outcome).collect()
}
/// The child gets SIGKILL when this process dies (PR_SET_PDEATHSIG), so a killed or timed-out
/// suite leaves no `run-one` behind. The parent-pid check closes the race where the parent
/// died between the fork and the prctl.
#[cfg(target_os = "linux")]
fn die_with_parent(command: &mut Command) {
use std::os::unix::process::CommandExt;
// SAFETY: only async-signal-safe calls (prctl, getppid, _exit) run between fork and exec.
unsafe {
let parent = libc::getpid();
command.pre_exec(move || {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() != parent {
libc::_exit(1);
}
Ok(())
});
}
}
#[cfg(not(target_os = "linux"))]
fn die_with_parent(_command: &mut Command) {}
fn run_child(exe: &Path, job: &Job, args: &ChildArgs) -> Result<RunReport, FailedRun> {
let fail = |error: String| FailedRun { checkpoint: job.id.clone(), seed: job.seed, error };
let mut command = Command::new(exe);
command
.arg("run-one")
.arg("--id")
.arg(&job.id)
.arg("--checkpoint")
.arg(&job.path)
.arg("--seed")
.arg(job.seed.to_string())
.arg("--runtime")
.arg(&args.runtime)
.arg("--mode")
.arg(&args.mode)
.arg("--minutes")
.arg(args.minutes.to_string())
.arg("--threads")
.arg(args.threads.to_string())
.arg("--probe-s")
.arg(args.probe_s.to_string())
.arg("--window-s")
.arg(args.window_s.to_string());
if let Some(dataset) = &args.dataset {
command.arg("--dataset").arg(dataset);
}
// The report travels in a file: the emulator library prints the cartridge's header on stdout.
let report = tempfile::NamedTempFile::new().map_err(|e| fail(format!("a scratch file: {e}")))?;
command.arg("--out").arg(report.path());
die_with_parent(&mut command);
let status = command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::inherit())
.status()
.map_err(|e| fail(format!("starting the child: {e}")))?;
if !status.success() {
return Err(fail(format!("the child exited with {status}")));
}
let text = std::fs::read(report.path()).map_err(|e| fail(format!("the child's report: {e}")))?;
serde_json::from_slice::<RunReport>(&text).map_err(|e| fail(format!("the child's report: {e}")))
}
/// Appends a line to a log, ignoring a failure to: progress is a courtesy.
pub fn note(path: &Path, line: &str) {
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(file, "{line}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_set_is_resolved_from_the_environment_and_names_what_is_missing() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.checkpoint");
std::fs::write(&file, b"x").unwrap();
let set = CheckpointSet {
schema: SET_SCHEMA.to_owned(),
checkpoints: vec![
SetEntry { id: "a".into(), rung: 8, env: "FLY_A".into(), note: String::new() },
SetEntry { id: "b".into(), rung: 9, env: "FLY_B".into(), note: String::new() },
SetEntry { id: "c".into(), rung: 9, env: "FLY_C".into(), note: String::new() },
],
};
let env = |name: &str| match name {
"FLY_A" => Some(file.display().to_string()),
"FLY_C" => Some("/nonexistent/c.checkpoint".to_owned()),
_ => None,
};
let (found, missing) = set.resolve(&env);
assert_eq!(found.len(), 1);
assert_eq!(found[0].0.id, "a");
assert_eq!(missing, vec!["b ($FLY_B)".to_owned(), "c ($FLY_C)".to_owned()]);
}
#[test]
fn the_shipped_set_parses_and_has_unique_ids() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/checkpoints.json");
let set = CheckpointSet::load(&path).expect("the shipped set");
assert!(set.checkpoints.len() >= 8);
assert!(set.checkpoints.iter().all(|e| e.env.starts_with("FLY_") && e.env.ends_with("_CHECKPOINT")));
assert!(set.checkpoints.iter().all(|e| (8..=15).contains(&e.rung)));
}
#[test]
fn the_committed_baseline_is_a_valid_card_and_passes_against_itself() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/baseline-v0.7.5.json");
let card = SuiteReport::load(&path).expect("the reference card");
assert_eq!(card.label, "v0.7.5");
assert_eq!(card.build.adapter, "pokered-unique8-v8");
assert_eq!(card.runs.len(), 36);
assert!(card.failed_runs.is_empty());
assert!(card.runs.iter().all(|run| run.frames > 30_000 && run.minutes >= 10.0));
let comparison = crate::compare::compare(&card, &card, 0.05);
assert!(comparison.pass, "{:?}", comparison.failed);
assert_eq!(comparison.pairs, 36);
// Nothing in a public card names a path or a host.
let text = std::fs::read_to_string(&path).unwrap();
assert!(!text.contains("/home/") && !text.contains("192.168"));
}
#[test]
fn a_suite_round_trips_and_summarises() {
let mut run = RunReport {
checkpoint: "r08".into(),
seed: 1,
runtime: "session".into(),
mode: "macros".into(),
minutes: 12.0,
frames: 1000,
..RunReport::default()
};
run.rungs.gained = 1;
run.watchdog.probes = 4;
run.macros.done = 9;
run.macros.blocked = 1;
let suite = SuiteReport {
schema: SCHEMA.to_owned(),
label: "t".into(),
build: BuildInfo::default(),
runtime: "session".into(),
mode: "macros".into(),
config: SuiteConfig { minutes: 12.0, seeds: vec![1], ..SuiteConfig::default() },
runs: vec![run],
failed_runs: vec![FailedRun { checkpoint: "r09".into(), seed: 1, error: "boom".into() }],
};
let text = serde_json::to_string(&suite).unwrap();
let back: SuiteReport = serde_json::from_str(&text).unwrap();
assert_eq!(back, suite);
let h = back.headline();
assert!((h.rungs_per_hour - 5.0).abs() < 1e-9);
assert!((h.blocked_macro_pct - 10.0).abs() < 1e-9);
let md = back.markdown(&BTreeMap::new());
assert!(md.contains("r08") && md.contains("1 runs failed") && md.contains("boom"));
}
}

View file

@ -1,940 +0,0 @@
//! One run's frames in, one [`RunReport`] out.
//!
//! Everything the scorecard measures about play is computed here from [`Frame`]s, with no
//! emulator, brain or runtime in sight, so every definition is unit-tested on synthetic frames.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::obs::{Facts, Frame};
use crate::watchdog::{Ev, Probe, Rules, Watchdog};
/// One Game Boy frame of game time, ms (`70,224` cycles at `4,194,304` Hz).
pub const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
const MINUTE_MS: f64 = 60_000.0;
/// The trap hunt's window rules (`examples/trap_hunt.rs` in flysim), kept as it has them: two
/// brain minutes, stepped by fifteen seconds, fewer than four tiles or one macro sequence
/// repeated more than ten times (any period up to eight).
pub const HUNT_WINDOW_MS: f64 = 2.0 * MINUTE_MS;
pub const HUNT_STEP_MS: f64 = 15_000.0;
pub const HUNT_MIN_TILES: usize = 4;
pub const HUNT_MAX_REPEATS: usize = 10;
pub const HUNT_MAX_PERIOD: usize = 8;
/// How a run is measured.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TallyConfig {
pub rules: Rules,
/// Brain seconds between watchdog probes.
pub probe_s: f64,
/// Brain seconds before the first probe (a window needs some life in it).
pub first_probe_s: f64,
}
impl Default for TallyConfig {
fn default() -> Self {
Self { rules: Rules::default(), probe_s: 120.0, first_probe_s: 240.0 }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RungReport {
pub start: u32,
pub end: u32,
pub gained: u32,
/// `[rung, brain minute]` for every climb.
pub climbs: Vec<(u32, f64)>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PadReport {
/// Frames with the macro layer on, nothing running and no button dealt.
pub empty_frames: u64,
pub empty_seconds: f64,
pub empty_fraction: f64,
pub longest_empty_seconds: f64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct WatchdogReport {
pub probes: usize,
pub suspected: usize,
/// Probes that were suspected with the one before also suspected (the loop recovery's
/// "confirmed": two fresh suspected reports in a row).
pub confirmed: usize,
/// Runs of two or more suspected probes: each is one trap the recovery ladder would act on.
pub ladder_events: usize,
pub reasons: BTreeMap<String, usize>,
pub flagged: Vec<Probe>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HuntWindow {
pub at_min: f64,
pub tiles: usize,
pub macros: usize,
pub cycle: Option<(String, usize)>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HuntReport {
pub windows: usize,
pub flagged: usize,
/// The first twenty flagged windows.
pub first_flagged: Vec<HuntWindow>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RatchetReport {
pub rollbacks: u32,
pub game_over: u32,
pub stall: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MacroCounts {
pub start: u64,
pub done: u64,
pub blocked: u64,
pub timeout: u64,
pub refused: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct MacroReport {
pub starts: u64,
pub done: u64,
pub blocked: u64,
pub timeout: u64,
pub refused: u64,
pub by_macro: BTreeMap<String, MacroCounts>,
}
impl MacroReport {
/// Finishes that were not `done`, which is what "blocked macro counts" asks for.
pub fn failed(&self) -> u64 {
self.blocked + self.timeout + self.refused
}
}
/// GO SHOP, BUY BALL, THROW BALL, catch, and the bag around them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FunnelReport {
pub go_shop_start: u64,
pub go_shop_done: u64,
pub buy_ball_start: u64,
pub buy_ball_done: u64,
pub throw_ball_start: u64,
pub throw_ball_done: u64,
/// `catch` rewards: a wild Pokemon kept.
pub catches: u64,
/// New species owned (Pokedex bits that went up).
pub species_gained: u64,
pub balls_gained: u64,
pub balls_spent: u64,
/// How far down GO SHOP done, BUY BALL done, THROW BALL start, catch the run got, in order of
/// first occurrence (0 to 4).
pub depth: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HealReport {
pub go_heal_start: u64,
pub go_heal_done: u64,
pub heal_start: u64,
/// The nurse's `HEAL` finished: a party healed.
pub heal_done: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BattleReport {
pub started: u64,
pub ended: u64,
pub wild: u64,
pub trainer: u64,
/// Ended with a battle or trainer payout.
pub won: u64,
/// Ended with the whole party fainted.
pub lost: u64,
/// A wild Pokemon kept.
pub caught: u64,
/// Ended otherwise (run away, a ball thrown away from the kept Pokemon, ...).
pub other: u64,
pub longest_frames: u64,
pub still_running: bool,
pub macros_in_longest: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RewardTotals {
pub n: u64,
pub total: f64,
}
/// One run: a checkpoint, a seed, a runtime, some brain minutes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RunReport {
pub checkpoint: String,
pub seed: u32,
pub runtime: String,
pub mode: String,
/// Brain minutes measured (after the seed's idle frames).
pub minutes: f64,
pub frames: u64,
pub idle_frames: u32,
pub wall_seconds: f64,
pub rungs: RungReport,
pub places_start: u32,
pub places_end: u32,
pub pad: PadReport,
pub watchdog: WatchdogReport,
pub hunt: HuntReport,
pub ratchet: RatchetReport,
pub macros: MacroReport,
pub funnel: FunnelReport,
pub heals: HealReport,
pub whiteouts: u64,
pub battles: BattleReport,
pub rewards: BTreeMap<String, RewardTotals>,
pub scenes: BTreeMap<String, u64>,
pub ended_map: u32,
}
/// The battle in progress.
#[derive(Clone, Debug, Default)]
struct Battle {
frames: u64,
macros: u64,
won: bool,
caught: bool,
fainted: bool,
}
pub struct Tally {
config: TallyConfig,
began_ms: f64,
last_ms: f64,
frames: u64,
start_rank: u32,
rank: u32,
start_places: u32,
places: u32,
climbs: Vec<(u32, f64)>,
macros_on: bool,
empty_frames: u64,
empty_run: u64,
longest_empty: u64,
events: Vec<Ev>,
watchdog: Watchdog,
next_probe_ms: f64,
probes: Vec<Probe>,
steps: Vec<(f64, u32, u32, u32)>,
starts: Vec<(f64, &'static str)>,
ratchet: RatchetReport,
macro_report: MacroReport,
funnel: FunnelReport,
funnel_order: [Option<f64>; 4],
heals: HealReport,
whiteouts: u64,
was_fainted: bool,
battles: BattleReport,
battle: Option<Battle>,
rewards: BTreeMap<String, RewardTotals>,
scenes: BTreeMap<String, u64>,
last_facts: Option<Facts>,
ended_map: u32,
}
/// The feed's kind for an adapter reward kind (`flysim::snapshot::RewardKind::from_adapter`), or
/// an empty string where the feed has no counter. The watchdog reads the feed's names.
pub fn feed_kind(adapter_kind: &str) -> &'static str {
flysim::snapshot::RewardKind::from_adapter(adapter_kind).map_or("", |kind| kind.as_str())
}
impl Tally {
/// The first frame's brain clock, rung and exploration count are the run's start. Nothing
/// before it is measured.
pub fn new(config: TallyConfig, began_ms: f64, rank: u32, places: u32) -> Self {
let watchdog = Watchdog::new(config.rules.clone(), places);
let next_probe_ms = began_ms + config.first_probe_s * 1000.0;
Self {
config,
began_ms,
last_ms: began_ms,
frames: 0,
start_rank: rank,
rank,
start_places: places,
places,
climbs: Vec::new(),
macros_on: false,
empty_frames: 0,
empty_run: 0,
longest_empty: 0,
events: Vec::new(),
watchdog,
next_probe_ms,
probes: Vec::new(),
steps: Vec::new(),
starts: Vec::new(),
ratchet: RatchetReport::default(),
macro_report: MacroReport::default(),
funnel: FunnelReport::default(),
funnel_order: [None; 4],
heals: HealReport::default(),
whiteouts: 0,
was_fainted: false,
battles: BattleReport::default(),
battle: None,
rewards: BTreeMap::new(),
scenes: BTreeMap::new(),
last_facts: None,
ended_map: 0xff,
}
}
/// Brain minutes measured so far.
pub fn minutes(&self) -> f64 {
(self.last_ms - self.began_ms) / MINUTE_MS
}
pub fn push(&mut self, frame: &Frame) {
let ms = frame.ms;
self.frames += 1;
self.last_ms = ms;
self.macros_on |= frame.macros_on;
if frame.rank != self.rank {
if frame.rank > self.rank {
self.climbs.push((frame.rank, (ms - self.began_ms) / MINUTE_MS));
self.events.push(Ev::Milestone { ms });
}
self.rank = frame.rank;
}
self.places = frame.places;
if let Some((map, x, y)) = frame.location {
self.steps.push((ms, map, x, y));
}
*self.scenes.entry(frame.scene.to_owned()).or_insert(0) += 1;
// The pad.
if frame.macros_on && frame.pad_empty {
self.empty_frames += 1;
self.empty_run += 1;
self.longest_empty = self.longest_empty.max(self.empty_run);
} else {
self.empty_run = 0;
}
// Macros.
for event in &frame.events {
let counts = self.macro_report.by_macro.entry(event.name.to_owned()).or_default();
match event.outcome {
None => {
counts.start += 1;
self.macro_report.starts += 1;
self.starts.push((ms, event.name));
if let Some(battle) = self.battle.as_mut() {
battle.macros += 1;
}
}
Some("done") => {
counts.done += 1;
self.macro_report.done += 1;
}
Some("blocked") => {
counts.blocked += 1;
self.macro_report.blocked += 1;
}
Some("timeout") => {
counts.timeout += 1;
self.macro_report.timeout += 1;
}
Some("refused") => {
counts.refused += 1;
self.macro_report.refused += 1;
}
Some(_) => {}
}
self.events.push(Ev::Macro { ms, name: event.name, outcome: event.outcome });
self.funnel_and_heals(ms, event.name, event.outcome);
}
// Rewards.
let mut won_now = false;
let mut caught_now = false;
for (kind, value) in &frame.rewards {
let totals = self.rewards.entry((*kind).to_owned()).or_default();
totals.n += 1;
totals.total += value;
self.events.push(Ev::Reward { ms, kind: feed_kind(kind) });
match *kind {
"battle" | "trainer" => won_now = true,
"catch" => {
caught_now = true;
self.funnel.catches += 1;
self.note_stage(3, ms);
}
_ => {}
}
}
// The ratchet.
if let Some(rolled) = frame.rollback {
self.ratchet.rollbacks += 1;
if rolled.game_over {
self.ratchet.game_over += 1;
} else {
self.ratchet.stall += 1;
}
}
// Memory: bag, party, battles.
let facts = frame.facts;
if let Some(last) = self.last_facts {
if facts.balls > last.balls {
self.funnel.balls_gained += u64::from(facts.balls - last.balls);
}
if facts.balls < last.balls {
self.funnel.balls_spent += u64::from(last.balls - facts.balls);
}
if facts.owned > last.owned {
self.funnel.species_gained += u64::from(facts.owned - last.owned);
}
}
self.last_facts = Some(facts);
self.ended_map = facts.map;
let fainted = facts.all_fainted();
if fainted && !self.was_fainted {
self.whiteouts += 1;
}
self.was_fainted = fainted;
match (facts.in_battle(), self.battle.as_mut()) {
(true, None) => {
self.battles.started += 1;
if facts.battle == 2 {
self.battles.trainer += 1;
} else {
self.battles.wild += 1;
}
self.battle = Some(Battle {
frames: 1,
won: won_now,
caught: caught_now,
fainted,
..Battle::default()
});
}
(true, Some(battle)) => {
battle.frames += 1;
battle.won |= won_now;
battle.caught |= caught_now;
battle.fainted |= fainted;
}
(false, Some(battle)) => {
battle.won |= won_now;
battle.caught |= caught_now;
battle.fainted |= fainted;
let battle = self.battle.take().expect("a battle");
self.end_battle(battle);
}
(false, None) => {}
}
// Probes.
while ms >= self.next_probe_ms {
let at_min = (self.next_probe_ms - self.began_ms) / MINUTE_MS;
let probe = self.watchdog.probe(&self.events, self.places, at_min);
self.probes.push(probe);
self.next_probe_ms += self.config.probe_s * 1000.0;
}
}
fn end_battle(&mut self, battle: Battle) {
self.battles.ended += 1;
if battle.frames > self.battles.longest_frames {
self.battles.longest_frames = battle.frames;
self.battles.macros_in_longest = battle.macros;
}
if battle.won {
self.battles.won += 1;
} else if battle.fainted {
self.battles.lost += 1;
} else if battle.caught {
self.battles.caught += 1;
} else {
self.battles.other += 1;
}
if battle.caught {
// A catch that is also a win payout counts once as a win and is still a catch.
if battle.won {
self.battles.caught += 1;
}
}
}
fn funnel_and_heals(&mut self, ms: f64, name: &str, outcome: Option<&str>) {
let f = &mut self.funnel;
let h = &mut self.heals;
let mut stage = None;
match (name, outcome) {
("GO SHOP", None) => f.go_shop_start += 1,
("GO SHOP", Some("done")) => {
f.go_shop_done += 1;
stage = Some(0);
}
("BUY BALL", None) => f.buy_ball_start += 1,
("BUY BALL", Some("done")) => {
f.buy_ball_done += 1;
stage = Some(1);
}
("THROW BALL", None) => {
f.throw_ball_start += 1;
stage = Some(2);
}
("THROW BALL", Some("done")) => f.throw_ball_done += 1,
("GO HEAL", None) => h.go_heal_start += 1,
("GO HEAL", Some("done")) => h.go_heal_done += 1,
("HEAL", None) => h.heal_start += 1,
("HEAL", Some("done")) => h.heal_done += 1,
_ => {}
}
if let Some(stage) = stage {
self.note_stage(stage, ms);
}
}
fn note_stage(&mut self, stage: usize, ms: f64) {
self.funnel_order[stage].get_or_insert(ms);
}
/// The run's report. `checkpoint`, `seed`, `runtime` and the rest of the identity are the
/// caller's.
pub fn finish(mut self, identity: RunReport) -> RunReport {
// The funnel's depth: stages in order of first occurrence, each after the last one.
let mut depth = 0;
let mut after = f64::NEG_INFINITY;
for first in self.funnel_order {
match first {
Some(ms) if ms >= after => {
depth += 1;
after = ms;
}
_ => break,
}
}
self.funnel.depth = depth;
if let Some(battle) = self.battle.take() {
self.battles.still_running = true;
self.battles.longest_frames = self.battles.longest_frames.max(battle.frames);
}
let minutes = self.minutes();
let seconds = |frames: u64| frames as f64 * FRAME_MS / 1000.0;
// The watchdog.
let mut watchdog = WatchdogReport { probes: self.probes.len(), ..Default::default() };
let mut run = 0usize;
for probe in &self.probes {
if probe.suspected {
watchdog.suspected += 1;
run += 1;
if run >= 2 {
watchdog.confirmed += 1;
}
if run == 2 {
watchdog.ladder_events += 1;
}
if let Some(reason) = &probe.reason {
*watchdog.reasons.entry(reason.clone()).or_insert(0) += 1;
}
if watchdog.flagged.len() < 20 {
watchdog.flagged.push(probe.clone());
}
} else {
run = 0;
}
}
let hunt = hunt(&self.steps, &self.starts, self.began_ms, self.last_ms);
let macro_report = std::mem::take(&mut self.macro_report);
RunReport {
minutes,
frames: self.frames,
rungs: RungReport {
start: self.start_rank,
end: self.rank,
gained: self.rank.saturating_sub(self.start_rank),
climbs: self.climbs,
},
places_start: self.start_places,
places_end: self.places,
pad: PadReport {
empty_frames: self.empty_frames,
empty_seconds: seconds(self.empty_frames),
empty_fraction: if self.frames == 0 || !self.macros_on {
0.0
} else {
self.empty_frames as f64 / self.frames as f64
},
longest_empty_seconds: seconds(self.longest_empty),
},
watchdog,
hunt,
ratchet: self.ratchet,
macros: macro_report,
funnel: self.funnel,
heals: self.heals,
whiteouts: self.whiteouts,
battles: self.battles,
rewards: self.rewards,
scenes: self.scenes,
ended_map: self.ended_map,
..identity
}
}
}
/// The longest run of one repeated block in `names`, as `(block, repeats)`
/// (`examples/trap_hunt.rs`: every period up to eight, every offset).
pub fn longest_cycle(names: &[&'static str]) -> Option<(String, usize)> {
let mut best: Option<(String, usize)> = None;
for period in 1..=HUNT_MAX_PERIOD.min(names.len()) {
let mut start = 0;
while start + period <= names.len() {
let block = &names[start..start + period];
let mut repeats = 1;
while start + period * (repeats + 1) <= names.len()
&& &names[start + period * repeats..start + period * (repeats + 1)] == block
{
repeats += 1;
}
if best.as_ref().is_none_or(|(_, known)| repeats > *known) {
best = Some((block.join(", "), repeats));
}
start += period * repeats;
}
}
best
}
/// Every window of the run that is a trap by the trap hunt's rules: it did things (a window with
/// no macro in it is the fly choosing nothing, which is the doctrine working) and either stood on
/// fewer than four distinct tiles or repeated one macro sequence more than ten times.
pub fn hunt(
steps: &[(f64, u32, u32, u32)],
starts: &[(f64, &'static str)],
began_ms: f64,
ended_ms: f64,
) -> HuntReport {
let mut report = HuntReport::default();
let mut at = began_ms;
while at + HUNT_WINDOW_MS <= ended_ms {
let until = at + HUNT_WINDOW_MS;
report.windows += 1;
let tiles: BTreeSet<(u32, u32, u32)> = steps
.iter()
.filter(|(ms, ..)| *ms >= at && *ms < until)
.map(|(_, map, x, y)| (*map, *x, *y))
.collect();
let names: Vec<&'static str> = starts
.iter()
.filter(|(ms, _)| *ms >= at && *ms < until)
.map(|(_, name)| *name)
.collect();
let cycle = longest_cycle(&names).filter(|(_, repeats)| *repeats > HUNT_MAX_REPEATS);
let stuck = tiles.len() < HUNT_MIN_TILES && !names.is_empty();
if stuck || cycle.is_some() {
report.flagged += 1;
if report.first_flagged.len() < 20 {
report.first_flagged.push(HuntWindow {
at_min: (at - began_ms) / MINUTE_MS,
tiles: tiles.len(),
macros: names.len(),
cycle,
});
}
}
at += HUNT_STEP_MS;
}
report
}
#[cfg(test)]
mod tests {
use super::*;
use crate::obs::{MacroEv, Rolled};
fn frame(ms: f64) -> Frame {
Frame {
ms,
events: Vec::new(),
rewards: Vec::new(),
rank: 8,
places: 100,
location: Some((1, (ms / 1000.0) as u32 % 50, 3)),
macros_on: true,
pad_empty: false,
scene: "overworld",
rollback: None,
facts: Facts { party: 2, alive: 2, balls: 3, money: 500, owned: 10, map: 1, battle: 0 },
}
}
fn ev(name: &'static str, outcome: Option<&'static str>) -> MacroEv {
MacroEv { name, outcome }
}
fn run(frames: &[Frame]) -> RunReport {
let mut tally = Tally::new(TallyConfig::default(), 0.0, 8, 100);
for frame in frames {
tally.push(frame);
}
tally.finish(RunReport { checkpoint: "t".into(), ..RunReport::default() })
}
#[test]
fn rungs_climb_and_are_timed() {
let mut a = frame(1000.0);
a.rank = 9;
let mut b = frame(61_000.0);
b.rank = 10;
let report = run(&[a, b]);
assert_eq!((report.rungs.start, report.rungs.end, report.rungs.gained), (8, 10, 2));
assert_eq!(report.rungs.climbs, vec![(9, 1000.0 / 60_000.0), (10, 61_000.0 / 60_000.0)]);
}
#[test]
fn the_empty_pad_is_counted_in_seconds_and_in_its_longest_stretch() {
let mut frames = Vec::new();
for i in 0..10u64 {
let mut f = frame(i as f64 * FRAME_MS);
f.pad_empty = (2..7).contains(&i) || i == 9;
frames.push(f);
}
let report = run(&frames);
assert_eq!(report.pad.empty_frames, 6);
assert!((report.pad.empty_fraction - 0.6).abs() < 1e-9);
assert!((report.pad.longest_empty_seconds - 5.0 * FRAME_MS / 1000.0).abs() < 1e-9);
}
#[test]
fn raw_mode_has_no_pad_to_be_empty() {
let mut f = frame(0.0);
f.macros_on = false;
f.pad_empty = true;
assert_eq!(run(&[f]).pad.empty_fraction, 0.0);
}
#[test]
fn the_shop_to_catch_funnel_counts_each_stage_and_its_depth() {
let mut frames = Vec::new();
let script: [(&'static str, Option<&'static str>); 6] = [
("GO SHOP", None),
("GO SHOP", Some("done")),
("BUY BALL", None),
("BUY BALL", Some("done")),
("THROW BALL", None),
("THROW BALL", Some("done")),
];
for (i, (name, outcome)) in script.iter().enumerate() {
let mut f = frame(i as f64 * 1000.0);
f.events = vec![ev(name, *outcome)];
frames.push(f);
}
let mut f = frame(7000.0);
f.rewards = vec![("catch", 5.0), ("species", 1.0)];
frames.push(f);
let report = run(&frames);
let funnel = &report.funnel;
assert_eq!(
(funnel.go_shop_done, funnel.buy_ball_done, funnel.throw_ball_start, funnel.catches),
(1, 1, 1, 1)
);
assert_eq!(funnel.depth, 4);
assert_eq!(report.macros.starts, 3);
assert_eq!(report.macros.done, 3);
assert_eq!(report.rewards["catch"].n, 1);
}
#[test]
fn a_funnel_that_skips_the_shop_stops_at_depth_zero() {
let mut f = frame(0.0);
f.events = vec![ev("BUY BALL", Some("done"))];
// Stage 0 never occurred: depth counts the unbroken prefix only.
assert_eq!(run(&[f]).funnel.depth, 0);
}
#[test]
fn blocked_refused_and_timed_out_macros_are_counted_by_macro() {
let mut f = frame(0.0);
f.events = vec![
ev("GO ROUTE", Some("refused")),
ev("GO ROUTE", Some("refused")),
ev("GO OUT", Some("blocked")),
ev("GO NPC", Some("timeout")),
ev("NEXT", Some("done")),
];
let report = run(&[f]);
assert_eq!(report.macros.failed(), 4);
assert_eq!(report.macros.by_macro["GO ROUTE"].refused, 2);
assert_eq!(report.macros.done, 1);
}
#[test]
fn heals_are_the_nurses_heal_and_the_walk_to_her() {
let mut f = frame(0.0);
f.events = vec![
ev("GO HEAL", None),
ev("GO HEAL", Some("done")),
ev("HEAL", None),
ev("HEAL", Some("done")),
];
let heals = run(&[f]).heals;
assert_eq!((heals.go_heal_done, heals.heal_done), (1, 1));
}
fn battle_frames(kind: u8, n: usize, from_ms: f64) -> Vec<Frame> {
(0..n)
.map(|i| {
let mut f = frame(from_ms + i as f64 * FRAME_MS);
f.facts.battle = kind;
f
})
.collect()
}
#[test]
fn a_battle_is_won_lost_or_caught_by_what_ended_it() {
let mut frames = Vec::new();
// A won trainer battle.
frames.extend(battle_frames(2, 5, 0.0));
let mut win = frame(100.0);
win.rewards = vec![("trainer", 1.0)];
frames.push(win);
// A wild battle lost: the party faints inside it, then a whiteout.
frames.extend(battle_frames(1, 3, 200.0));
let mut down = battle_frames(1, 3, 300.0);
for f in &mut down {
f.facts.alive = 0;
}
frames.extend(down);
let mut after = frame(400.0);
after.facts.alive = 0;
frames.push(after);
frames.push(frame(500.0));
// A wild battle caught.
frames.extend(battle_frames(1, 4, 600.0));
let mut catch = battle_frames(1, 1, 700.0);
catch[0].rewards = vec![("catch", 3.0)];
frames.extend(catch);
frames.push(frame(800.0));
// One run away from.
frames.extend(battle_frames(1, 2, 900.0));
frames.push(frame(1000.0));
// One still running at the end.
frames.extend(battle_frames(1, 2, 1100.0));
let report = run(&frames);
let b = &report.battles;
assert_eq!((b.started, b.ended), (5, 4));
assert_eq!((b.trainer, b.wild), (1, 4));
assert_eq!((b.won, b.lost, b.caught, b.other), (1, 1, 1, 1));
assert!(b.still_running);
assert_eq!(report.whiteouts, 1);
assert_eq!(report.funnel.catches, 1);
}
#[test]
fn bag_and_dex_changes_become_ball_and_species_counts() {
let mut a = frame(0.0);
a.facts.balls = 5;
let mut b = frame(1000.0);
b.facts.balls = 3;
let mut c = frame(2000.0);
c.facts.balls = 8;
c.facts.owned = 12;
let report = run(&[a, b, c]);
assert_eq!((report.funnel.balls_spent, report.funnel.balls_gained), (2, 5));
assert_eq!(report.funnel.species_gained, 2);
}
#[test]
fn ratchet_rollbacks_are_split_by_trigger() {
let mut a = frame(0.0);
a.rollback = Some(Rolled { game_over: true });
let mut b = frame(1.0);
b.rollback = Some(Rolled { game_over: false });
let report = run(&[a, b]);
assert_eq!((report.ratchet.rollbacks, report.ratchet.game_over, report.ratchet.stall), (2, 1, 1));
}
/// The Viridian cycle on three tiles for twelve minutes: the watchdog confirms it and so does
/// the trap hunt.
#[test]
fn a_ring_is_caught_by_both_instruments() {
let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"];
let mut frames = Vec::new();
let mut i = 0usize;
let mut ms = 0.0;
while ms < 12.0 * MINUTE_MS {
let mut f = frame(ms);
f.location = Some((1, (i % 3) as u32, 3));
if ((ms / FRAME_MS) as u64).is_multiple_of(180) {
f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))];
i += 1;
}
frames.push(f);
ms += FRAME_MS;
}
let report = run(&frames);
assert!(report.watchdog.suspected >= 2, "{:?}", report.watchdog);
assert!(report.watchdog.ladder_events >= 1);
assert!(report.watchdog.confirmed >= 1);
assert!(report.watchdog.reasons.get("sequence").copied().unwrap_or(0) > 0);
assert!(report.hunt.flagged > 0 && report.hunt.windows > 0, "{:?}", report.hunt);
// The run explored nothing: the count never moved.
assert_eq!(report.places_end, report.places_start);
}
/// The same cadence of macros on a fly that keeps finding new tiles is not a trap.
#[test]
fn a_walk_that_finds_places_is_not_flagged() {
let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"];
let mut frames = Vec::new();
let mut i = 0usize;
let mut ms = 0.0;
while ms < 12.0 * MINUTE_MS {
let mut f = frame(ms);
f.location = Some((1, (ms / 1000.0) as u32, 3));
f.places = 100 + (ms / 10_000.0) as u32;
if ((ms / FRAME_MS) as u64).is_multiple_of(180) {
f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))];
i += 1;
}
frames.push(f);
ms += FRAME_MS;
}
let report = run(&frames);
assert_eq!(report.watchdog.suspected, 0, "{:?}", report.watchdog);
assert_eq!(report.hunt.flagged, 0);
assert!(report.watchdog.probes >= 4);
}
#[test]
fn the_hunt_ignores_a_window_with_no_macro_in_it() {
let steps: Vec<(f64, u32, u32, u32)> = (0..9000).map(|i| (i as f64 * 20.0, 1, 1, 1)).collect();
let report = hunt(&steps, &[], 0.0, 180_000.0);
assert!(report.windows > 0);
assert_eq!(report.flagged, 0);
// The same ground with a macro in each window is a stand-still.
let starts: Vec<(f64, &'static str)> = (0..18).map(|i| (i as f64 * 10_000.0, "NEXT")).collect();
assert!(hunt(&steps, &starts, 0.0, 180_000.0).flagged > 0);
}
#[test]
fn the_longest_cycle_finds_the_shortest_block_and_its_repeats() {
let names = ["A", "B", "A", "B", "A", "B", "C"];
assert_eq!(longest_cycle(&names), Some(("A, B".to_string(), 3)));
assert_eq!(longest_cycle(&[]), None);
}
}

View file

@ -1,401 +0,0 @@
//! `fly-watchdog` check 10 (loop suspected), as a function of a run's events.
//!
//! The live check reads the event log's tail, the exploration count from `/status.json` and its
//! own state files; this reads the same three things from a run. The rules, their order and every
//! default are the shell's (`infra/bin/fly-watchdog`, `loop_analyze` and `check_loop`), so a run
//! that would have raised the flag on the stream raises it here. Two differences, both about time:
//!
//! - the probe cadence is a parameter (the stream's is every five wall minutes; a run is short,
//! so the scorecard probes more often), and a window is the last `window_ms` of brain time or
//! the whole run when it is shorter;
//! - the exploration count the first probe compares with is the run's starting count, which the
//! live check does not have for its first probe after a boot.
//!
//! Like the shell, this reads and reports. It never acts.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// The thresholds of `fly-watchdog`'s `WD_LOOP_*` variables.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rules {
pub window_ms: f64,
pub max_period: usize,
pub max_distinct: usize,
pub min_repeats: usize,
pub dominance_pct: usize,
pub min_events: usize,
pub stall_pct: usize,
pub busy_min: usize,
pub fight_min: usize,
}
impl Default for Rules {
fn default() -> Self {
Self {
window_ms: 600_000.0,
max_period: 8,
max_distinct: 4,
min_repeats: 20,
dominance_pct: 95,
min_events: 20,
stall_pct: 90,
busy_min: 100,
fight_min: 24,
}
}
}
/// One line of the event log the check reads: a macro event, a reward or a rung.
#[derive(Clone, Debug, PartialEq)]
pub enum Ev {
/// `<NAME> start` is `outcome: None`; a finish carries its word (done, blocked, timeout,
/// refused).
Macro { ms: f64, name: &'static str, outcome: Option<&'static str> },
/// A reward, with the feed's kind (`wildwin`, `trainer`, `badge`, `pokedex`, `area`, ...), or
/// an empty string for an adapter kind the feed has no counter for.
Reward { ms: f64, kind: &'static str },
Milestone { ms: f64 },
}
/// `loop_analyze`'s result for one window.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Analysis {
pub starts: usize,
pub decisions: usize,
pub distinct: usize,
pub top_name: String,
pub top_count: usize,
pub period: usize,
pub repeats: usize,
pub refused: usize,
pub blocked: usize,
pub timeout: usize,
pub done: usize,
pub rewards: usize,
pub fights: usize,
pub wins: usize,
pub progress: usize,
pub window_from: f64,
pub window_to: f64,
}
fn is_lasting(kind: &str) -> bool {
matches!(kind, "milestone" | "pokedex" | "area" | "trainer" | "badge")
}
/// `loop_analyze`: the window ends at the newest macro event.
pub fn analyze(events: &[Ev], rules: &Rules) -> Analysis {
let last_macro = events.iter().rev().find_map(|event| match event {
Ev::Macro { ms, .. } => Some(*ms),
_ => None,
});
let Some(to) = last_macro else { return Analysis::default() };
let from = to - rules.window_ms;
let mut a = Analysis { window_from: from, window_to: to, ..Analysis::default() };
for event in events {
let (ms, kind) = match event {
Ev::Reward { ms, kind } => (*ms, *kind),
Ev::Milestone { ms } => (*ms, "milestone"),
Ev::Macro { .. } => continue,
};
if ms < from {
continue;
}
if is_lasting(kind) {
a.progress += 1;
}
if kind == "milestone" {
continue;
}
a.rewards += 1;
if matches!(kind, "wildwin" | "trainer" | "badge") {
a.wins += 1;
}
}
let mut seq: Vec<&'static str> = Vec::new();
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
for event in events {
let Ev::Macro { ms, name, outcome } = event else { continue };
if *ms < from {
continue;
}
match outcome {
Some("blocked") => {
a.blocked += 1;
continue;
}
Some("timeout") => {
a.timeout += 1;
continue;
}
Some("done") => {
a.done += 1;
continue;
}
Some("refused") => a.refused += 1,
None => a.starts += 1,
Some(_) => continue,
}
seq.push(name);
if matches!(*name, "MOVE 1" | "MOVE 2" | "MOVE 3" | "MOVE 4") {
a.fights += 1;
}
let n = counts.entry(name).or_insert(0);
*n += 1;
if *n > a.top_count {
a.top_count = *n;
a.top_name = (*name).to_owned();
}
}
a.decisions = seq.len();
a.distinct = counts.len();
let k = seq.len();
let mut p = 1;
while p <= rules.max_period && p * 2 <= k {
let mut r = 1;
while (r + 1) * p <= k {
let same = (0..p).all(|j| seq[k - 1 - j] == seq[k - 1 - r * p - j]);
if !same {
break;
}
r += 1;
}
if r >= 2 {
a.period = p;
a.repeats = r;
break;
}
p += 1;
}
a
}
/// One probe's verdict.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Probe {
/// Brain minutes into the run.
pub at_min: f64,
pub suspected: bool,
pub reason: Option<String>,
pub decisions: usize,
pub distinct: usize,
pub period: usize,
pub repeats: usize,
pub done: usize,
pub failed: usize,
pub rewards: usize,
pub fights: usize,
pub wins: usize,
pub places_delta: i64,
}
/// `check_loop`'s memory between probes.
#[derive(Clone, Debug)]
pub struct Watchdog {
pub rules: Rules,
prev_places: i64,
prev_idle: bool,
prev_busy: bool,
prev_unwon: bool,
}
impl Watchdog {
/// `places` is the exploration count the run starts with.
pub fn new(rules: Rules, places: u32) -> Self {
Self {
rules,
prev_places: i64::from(places),
prev_idle: false,
prev_busy: false,
prev_unwon: false,
}
}
/// One probe over every event so far.
pub fn probe(&mut self, events: &[Ev], places: u32, at_min: f64) -> Probe {
let rules = &self.rules;
let a = analyze(events, rules);
let delta = i64::from(places) - self.prev_places;
self.prev_places = i64::from(places);
// `grown` is 1 unless the count is known not to have grown.
let grown = delta > 0;
let idle = a.decisions > 0 && a.done == 0 && !grown;
let busy = a.decisions >= rules.busy_min && a.rewards == 0 && !grown;
let unwon = a.fights >= rules.fight_min && a.wins == 0 && !grown;
let failed = a.refused + a.blocked + a.timeout;
let mut reason = None;
if a.decisions > 0 && !grown {
reason = if a.decisions >= rules.min_events
&& failed * 100 >= a.decisions * rules.stall_pct
{
Some("stalled")
} else if idle && self.prev_idle {
Some("zero-progress")
} else if a.distinct <= rules.max_distinct && a.repeats >= rules.min_repeats {
Some("sequence")
} else if a.decisions >= rules.min_events
&& a.top_count * 100 >= a.decisions * rules.dominance_pct
{
Some("dominant")
} else if busy && self.prev_busy {
Some("unrewarded")
} else if unwon && self.prev_unwon {
Some("unwon-battles")
} else {
None
};
}
self.prev_idle = idle;
self.prev_busy = busy;
self.prev_unwon = unwon;
Probe {
at_min,
suspected: reason.is_some(),
reason: reason.map(str::to_owned),
decisions: a.decisions,
distinct: a.distinct,
period: a.period,
repeats: a.repeats,
done: a.done,
failed,
rewards: a.rewards,
fights: a.fights,
wins: a.wins,
places_delta: delta,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn start(ms: f64, name: &'static str) -> [Ev; 2] {
[
Ev::Macro { ms, name, outcome: None },
Ev::Macro { ms: ms + 1.0, name, outcome: Some("done") },
]
}
fn cycle(names: &[&'static str], times: usize) -> Vec<Ev> {
let mut events = Vec::new();
let mut ms = 0.0;
for _ in 0..times {
for name in names {
events.extend(start(ms, name));
ms += 3000.0;
}
}
events
}
#[test]
fn the_viridian_cycle_is_a_sequence_when_nothing_is_explored() {
// GO NPC, GO OUT, NEXT, GO FRONTIER, every three brain seconds, 25 times.
let events = cycle(&["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"], 25);
let a = analyze(&events, &Rules::default());
assert_eq!((a.period, a.repeats, a.distinct), (4, 25, 4));
let mut watchdog = Watchdog::new(Rules::default(), 100);
let probe = watchdog.probe(&events, 100, 5.0);
assert!(probe.suspected);
assert_eq!(probe.reason.as_deref(), Some("sequence"));
// The same sequence on a fly that is still finding places is a long walk, not a loop.
let mut watchdog = Watchdog::new(Rules::default(), 100);
assert!(!watchdog.probe(&events, 101, 5.0).suspected);
}
#[test]
fn a_pad_of_one_refusing_button_is_a_stall() {
let mut events = Vec::new();
for i in 0..30 {
events.push(Ev::Macro {
ms: 1000.0 * i as f64,
name: "GO ROUTE",
outcome: Some("refused"),
});
}
let mut watchdog = Watchdog::new(Rules::default(), 7);
let probe = watchdog.probe(&events, 7, 1.0);
assert_eq!(probe.reason.as_deref(), Some("stalled"));
assert_eq!(probe.failed, 30);
}
#[test]
fn unrewarded_needs_two_probes() {
// Ten distinct names (a period past the cap), all done, no reward, 120 decisions, no new
// ground: row 58's shape. The first probe remembers it and only the second flags.
let names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
let mut events = Vec::new();
let mut ms = 0.0;
for _ in 0..12 {
for name in names {
events.extend(start(ms, name));
ms += 1000.0;
}
}
let mut watchdog = Watchdog::new(Rules::default(), 5);
let first = watchdog.probe(&events, 5, 3.0);
assert!(!first.suspected, "{first:?}");
let second = watchdog.probe(&events, 5, 5.0);
assert_eq!(second.reason.as_deref(), Some("unrewarded"), "{second:?}");
// One new place clears it.
let third = watchdog.probe(&events, 6, 7.0);
assert!(!third.suspected);
}
#[test]
fn rewards_and_rungs_inside_the_window_are_counted() {
let mut events = cycle(&["GO FRONTIER", "NEXT"], 3);
events.push(Ev::Reward { ms: 100.0, kind: "wildwin" });
events.push(Ev::Reward { ms: 200.0, kind: "" });
events.push(Ev::Milestone { ms: 300.0 });
let a = analyze(&events, &Rules::default());
assert_eq!((a.rewards, a.wins, a.progress), (2, 1, 1));
// A reward before the window's start is not in it.
let rules = Rules { window_ms: 1000.0, ..Rules::default() };
let late = analyze(&events, &rules);
assert_eq!(late.rewards, 0);
}
#[test]
fn a_window_with_no_macro_is_not_a_loop() {
let mut watchdog = Watchdog::new(Rules::default(), 5);
let probe = watchdog.probe(&[Ev::Reward { ms: 5.0, kind: "wildwin" }], 5, 5.0);
assert!(!probe.suspected);
assert_eq!(probe.decisions, 0);
}
#[test]
fn the_shortest_period_wins() {
let events = cycle(&["X", "Y"], 40);
let a = analyze(&events, &Rules::default());
assert_eq!((a.period, a.repeats), (2, 40));
}
#[test]
fn fights_without_a_win_flag_on_the_second_probe_only() {
let mut events = Vec::new();
let moves = ["MOVE 1", "MOVE 2"];
let mut ms = 0.0;
// Alternate MOVE n with a varying filler so no short cycle or dominant name forms.
let fillers = ["NEXT", "TALK", "YES", "NO", "BACK", "MENU", "CLOSE"];
for i in 0..30usize {
events.extend(start(ms, moves[i % 2]));
ms += 1000.0;
events.extend(start(ms, fillers[(i * 3 + i / 4) % fillers.len()]));
ms += 1000.0;
}
let rules = Rules { min_repeats: 1000, ..Rules::default() };
let mut watchdog = Watchdog::new(rules, 9);
let first = watchdog.probe(&events, 9, 4.0);
assert!(!first.suspected, "{first:?}");
let second = watchdog.probe(&events, 9, 6.0);
assert_eq!(second.reason.as_deref(), Some("unwon-battles"), "{second:?}");
// A win in the window clears it.
events.push(Ev::Reward { ms: 100.0, kind: "wildwin" });
let third = watchdog.probe(&events, 9, 8.0);
assert!(!third.suspected);
}
}

View file

@ -1,79 +0,0 @@
//! The scorecard on the real cartridge and connectome: a short run per runtime from a real
//! checkpoint. ROM-gated: `FLY_ROM`, `FLY_DOOR_CHECKPOINT` (rom-env.sh) and `data/fafb-v783`;
//! without them each test prints why and returns (source rom-env.sh, or it covers nothing).
//!
//! What it holds:
//! - a run measures something (frames, a pad, macros) and its minutes are the minutes asked for;
//! - the same seed twice is the same run, and two seeds are not (the idle frames);
//! - the session runtime and the legacy loop, from the same checkpoint and seed, give the same
//! report: what the scorecard measures does not depend on which runtime ran it.
use std::path::PathBuf;
use fly_scorecard::runner::{RunSpec, run_legacy, run_session};
use fly_scorecard::tally::RunReport;
use flysim::snapshot::MacroMode;
fn spec(seed: u32) -> Option<RunSpec> {
let rom = std::env::var_os("FLY_ROM").map(PathBuf::from);
let checkpoint = std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from);
let dataset = fly_session::legacy_parity::fafb_dir();
let (Some(rom), Some(checkpoint), Some(dataset)) = (rom, checkpoint, dataset) else {
eprintln!("skipping: FLY_ROM, FLY_DOOR_CHECKPOINT or data/fafb-v783 missing");
return None;
};
Some(RunSpec {
id: "door".to_owned(),
checkpoint,
rom,
dataset,
seed,
minutes: 0.4,
threads: 2,
mode: MacroMode::Macros,
tally: RunSpec::tally_config(5.0, 20.0),
})
}
/// A report with what legitimately differs between runs of the same thing blanked.
fn essence(mut report: RunReport) -> RunReport {
report.wall_seconds = 0.0;
report.runtime = String::new();
report
}
#[test]
fn the_legacy_loop_is_measured_reproducibly_and_seeds_differ() {
let (Some(a), Some(b), Some(c)) = (spec(0), spec(3), spec(4)) else { return };
let first = run_legacy(&a).expect("a legacy run");
assert!(first.frames > 1000, "{} frames", first.frames);
assert!((first.minutes - 0.4).abs() < 0.01, "{} minutes", first.minutes);
assert_eq!(first.idle_frames, 0);
assert!(first.macros.starts > 0, "the macro layer dealt nothing");
assert!(first.scenes.values().sum::<u64>() == first.frames);
assert_eq!(essence(first.clone()), essence(run_legacy(&a).expect("a second run")));
let (x, y) = (run_legacy(&b).expect("seed 3"), run_legacy(&c).expect("seed 4"));
assert_ne!(x.idle_frames, y.idle_frames);
assert!(x.idle_frames > 0);
// Different starting points of the brain's own trajectory: the runs need not agree.
eprintln!(
"seed 0/3/4 macro starts {}/{}/{}, pad {:.3}/{:.3}/{:.3}",
first.macros.starts,
x.macros.starts,
y.macros.starts,
first.pad.empty_fraction,
x.pad.empty_fraction,
y.pad.empty_fraction
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_session_runtime_and_the_legacy_loop_measure_the_same_run() {
let Some(spec) = spec(2) else { return };
let legacy = run_legacy(&spec).expect("the legacy run");
let session = run_session(&spec).await.expect("the session run");
assert_eq!(session.runtime, "session");
assert_eq!(legacy.runtime, "legacy");
assert!(session.frames > 1000);
assert_eq!(essence(legacy), essence(session));
}

View file

@ -18,11 +18,6 @@ path = "src/lib.rs"
name = "fly-session"
path = "src/bin/fly-session.rs"
[features]
# The LIF tick on the GPU (GPU-02), a passthrough to `flybrain-core/cuda`. Compiling it in does not
# turn it on: the agent worker attaches the backend only when `FLY_LIF_CUDA=1` reaches it.
cuda = ["flybrain-core/cuda"]
[dependencies]
# The domain contract (scalars, payloads, canonical digests, the trace format) and the bus.
# Everything else this crate needs is std or Tokio.
@ -41,8 +36,6 @@ flate2 = { workspace = true }
flysim-store = { path = "../flysim-store" }
serde_json = { workspace = true }
# PR_SET_PDEATHSIG for worker processes (a child never outlives its parent, systemd or not).
libc = "0.2"
# `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread
# worker each build their own runtime sized to the launcher's thread allocation.
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "io-util"] }

View file

@ -95,26 +95,6 @@ fly-session legacy-environment ... --worker ID --port p1 --rom PATH --rom-digest
fly-session measure --steps 300 --agents 1,2,4
```
BUS-01 (the live composition on the router) added four things here:
- **Placement per process.** `Launcher::place_process(worker_id, ProcessCpus { host, sweep })`
hands a separate process its CPUs as `--host-cpus` and `--sweep-cpus`; the worker applies them
(`flybrain_core::pool::apply_placement`) before it starts a thread, so an agent process pins its
own sweep and every agent can have its own CPUs.
- **The launcher's own clients in memory.** In thread and process modes the supervisor's and the
coordinator's connections are in memory (they live with the router); the participants' are the
sockets.
- **One async worker per participant, and long handlers give it up.** A thread or process
participant runs on a multi-thread runtime with one worker, so a bus request crosses no thread
inside it; a handler that can run for seconds (`*.Initialize`, `State.*`, `Agent.Rollback`) runs
under `tokio::task::block_in_place`, so the shell keeps reading -- and answers `Worker.Status`
and an exact duplicate's `IN_PROGRESS` -- while the legacy agent warms up. The local lane is
unchanged.
- **Writers allocated ahead** (`worker::WriterPool`): after each bus reply the shell allocates a
staging writer for each of the last few reply-artifact shapes it sealed, so the next step's seal
is one round trip instead of two. Reply artifacts the worker holds itself (its own seals) are
cached by clone, not by a second `retain`.
## What it implements
- **The transaction, in order.** Prepare all agents concurrently; run each task-local executor

View file

@ -42,8 +42,6 @@ fly-session <command> [options]
Worker options (agent and environment):
--socket PATH the launcher's endpoint for this participant
--host-cpus LIST the CPUs every thread of this process runs on (optional)
--sweep-cpus LIST an agent's sweep workers, one CPU each (optional, with --host-cpus)
--store-root PATH the router's artifact store root
--client-id ID the configured bus client identity
--service NAME the one service name this worker registers
@ -214,7 +212,6 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
}
let session_id = options.id(flags::SESSION)?;
let incarnation_id = options.id(flags::INCARNATION)?;
place(options)?;
let what = match role {
"agent" => Started::Agent(AgentLaunch {
session_id,
@ -294,28 +291,8 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
service: service.clone(),
}),
};
if crate::profile::enabled() {
// A worker process keeps its own span table (`FLY_SESSION_PROFILE`): printed once a
// minute on stderr, the service's journal, beside the coordinator's profile line.
let who = client_id.clone();
std::thread::spawn(move || {
loop {
std::thread::sleep(std::time::Duration::from_secs(60));
let line: Vec<String> = crate::profile::report_with_max()
.into_iter()
.map(|(name, count, mean, max)| {
format!(
"{name}={count}x{:.3}/{:.1}",
mean.as_secs_f64() * 1e3,
max.as_secs_f64() * 1e3
)
})
.collect();
eprintln!("worker profile {who} (count x mean/max ms): {}", line.join(" "));
}
});
}
let runtime = crate::launcher::participant_runtime(threads)
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build()
.map_err(|e| format!("runtime: {e}"))?;
@ -328,42 +305,6 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
})
}
/// `--host-cpus` and `--sweep-cpus` (BUS-01): the placement the launcher made for this process,
/// applied before any thread starts, so every thread inherits the host set and every sweep pool
/// pins its workers. Without `--host-cpus` the process floats over what it inherited.
fn place(options: &Options) -> Result<(), String> {
let list = |flag: &str| -> Result<Option<Vec<usize>>, String> {
options
.optional(flag)
.map(|value| {
flybrain_core::pool::parse_cpu_list(value)
.ok_or_else(|| format!("--{flag}: {value:?} is not a cpu list"))
})
.transpose()
};
let (host, sweep) = (list(flags::HOST_CPUS)?, list(flags::SWEEP_CPUS)?);
let Some(host) = host else {
if sweep.is_some() {
return Err(format!("--{} needs --{}", flags::SWEEP_CPUS, flags::HOST_CPUS));
}
return Ok(());
};
let placement = flybrain_core::pool::Placement {
workers: sweep.unwrap_or_default(),
host,
};
// Best effort, as in the service: a refused placement leaves the process floating.
if flybrain_core::pool::apply_placement(&placement) {
eprintln!(
"placed: sweep workers {:?}, every other thread on {:?}",
placement.workers, placement.host
);
} else {
eprintln!("placement {placement:?} refused; the threads float");
}
Ok(())
}
fn parse_channels(value: &str) -> Result<Vec<String>, String> {
value
.split(',')

View file

@ -281,20 +281,6 @@ impl ResultCache {
}
}
/// Drops a lifecycle reply that never reached its caller (its artifacts could not be
/// sealed), as if it had never been recorded: a retry runs again, as it would have when
/// the handler itself failed to store them.
pub fn forget_lifecycle(&mut self, request: &DomainRequestId) {
if self.lifecycle.remove(request.as_str()).is_some() {
self.lifecycle_order.retain(|existing| existing != request.as_str());
}
}
/// Drops a read-only reply that never reached its caller.
pub fn forget_readonly(&mut self, request: &DomainRequestId) {
self.readonly.retain(|(existing, _)| existing != request.as_str());
}
/// Releases an operation that did not mutate anything, so the key stays free.
pub fn abandon(&mut self, key: &OperationKey) {
self.active.remove(key);

View file

@ -411,16 +411,8 @@ pub enum ReapOutcome {
struct Endpoints {
router: Router,
via: Via,
/// How this process's own clients -- the supervisor and the coordinator, which live with the
/// router -- reach it: in memory when the participants are a thread or a process away (their
/// sockets are the ones that cross a boundary; BUS-01), else the participants' transport.
own: Via,
store_root: PathBuf,
sockets: PathBuf,
/// The GPU fallback record the worker processes share (`flybrain_core::lif::health`): a
/// replacement worker that is a new process must not re-attach a GPU that failed in an
/// earlier one. Emptied when this launcher starts.
gpu_marker: PathBuf,
next_socket: AtomicU64,
listeners: Mutex<Vec<UnixListenerHandle>>,
}
@ -431,18 +423,9 @@ impl Endpoints {
self.sockets.join(format!("{client_id}-{n}.sock"))
}
/// A connection this process owns: the supervisor's and the coordinator's.
/// A connection this process owns, over the configured transport.
async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> {
self.connect_via(self.own, client_id).await
}
/// A connection for an in-process participant, over the participants' transport.
async fn connect_participant(&self, client_id: &str) -> Result<Client, flybus::BusError> {
self.connect_via(self.via, client_id).await
}
async fn connect_via(&self, via: Via, client_id: &str) -> Result<Client, flybus::BusError> {
let transport = match via {
let transport = match self.via {
Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id),
Via::Unix => {
let path = self.socket_path(client_id);
@ -497,30 +480,6 @@ pub struct Launcher {
serial: u64,
/// Whether an in-process participant's reference carries its local lane (PERF-01).
local_lane: bool,
/// Where each separate-process participant's threads run, by worker id (BUS-01).
placements: BTreeMap<Id, ProcessCpus>,
}
/// Where a separate-process participant's threads run (BUS-01): `host` for every thread of the
/// process, and for an agent `sweep`, one CPU per spawned sweep worker (`flybrain_core::pool::
/// Placement`). Given to the worker as `--host-cpus` and `--sweep-cpus`; the worker applies it
/// before it starts a thread. Placement chooses a CPU, never a result.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessCpus {
pub host: Vec<usize>,
pub sweep: Vec<usize>,
}
/// The runtime a thread or process participant serves on (BUS-01): one async worker, so a bus
/// request crosses no thread inside the participant -- each crossing was a wake-up on the
/// participant's shared CPU, about a millisecond a transition in all -- and multi-thread rather
/// than current-thread, so a handler that runs for seconds (a warm-up, a restore, a capture) can
/// hand that worker over (`tokio::task::block_in_place`) and the shell keeps answering status and
/// duplicates meanwhile. The thread allocation (`threads`) is the agent's sweep, not this runtime's.
pub fn participant_runtime(_threads: usize) -> tokio::runtime::Builder {
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.worker_threads(1);
builder
}
/// The bus client id the supervisor connects under.
@ -552,40 +511,7 @@ pub fn default_worker_program() -> PathBuf {
PathBuf::from(name)
}
/// Makes `command`'s child die with its parent (BUS-01 review N2): the kernel sends it SIGKILL when
/// the parent *thread* that spawned it exits, so a worker never outlives its coordinator even outside
/// systemd's cgroup kill (a hung worker used to survive a killed parent, once for 47 hours).
///
/// Linux delivers the signal when the spawning thread ends, not the whole process, so spawn from a
/// thread that lives as long as the process: a runtime worker or the main thread, never a
/// short-lived blocking-pool thread. Setting the signal races a parent that already died; the child
/// checks its parent id after setting it and exits if it was already re-parented.
pub fn die_with_parent(command: &mut std::process::Command) {
use std::os::unix::process::CommandExt;
let parent = std::process::id() as libc::pid_t;
// SAFETY: the closure runs between fork and exec and calls only async-signal-safe functions
// (prctl, getppid, _exit); it allocates nothing and takes no locks.
unsafe {
command.pre_exec(move || {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() != parent {
libc::_exit(1);
}
Ok(())
});
}
}
impl Launcher {
/// GPU failures that moved the LIF tick to the CPU under this launcher: its worker
/// processes' (the marker) and, for workers in this process, this process's.
pub fn gpu_fallbacks(&self) -> u64 {
flybrain_core::lif::health::marker_fallbacks(&self.endpoints.gpu_marker)
.max(flybrain_core::lif::health::fallbacks())
}
/// Connects the supervisor and prepares the launcher. Nothing is started yet.
pub async fn start(
router: Router,
@ -599,18 +525,11 @@ impl Launcher {
std::fs::create_dir_all(&sockets).map_err(|e| {
flybus::BusError::new(flybus::ErrorCode::StoreFailure, format!("sockets: {e}"))
})?;
let gpu_marker = sockets.join("lif-gpu-fallbacks");
flybrain_core::lif::health::reset_marker(&gpu_marker);
let endpoints = Endpoints {
router,
via: mode.transport(via),
own: match mode {
ExecutionMode::InProcess => via,
ExecutionMode::Thread | ExecutionMode::Process => Via::Memory,
},
store_root: store_root.into(),
sockets,
gpu_marker,
next_socket: AtomicU64::new(0),
listeners: Mutex::new(Vec::new()),
};
@ -625,16 +544,9 @@ impl Launcher {
workers: BTreeMap::new(),
serial: 0,
local_lane: mode == ExecutionMode::InProcess && via == Via::Local,
placements: BTreeMap::new(),
})
}
/// Places the separate process of `worker_id` (launched from now on) on `cpus`. Process mode
/// only; the other modes share this process's placement.
pub fn place_process(&mut self, worker_id: &Id, cpus: ProcessCpus) {
self.placements.insert(worker_id.clone(), cpus);
}
/// Offers every in-process participant launched from now on over the local lane
/// ([`crate::worker::LocalLane`]): its [`LaunchedWorker::worker_ref`] carries the lane, so a
/// coordinator in this process calls its endpoint methods without the bus. A thread or a
@ -895,7 +807,7 @@ impl Launcher {
) -> Result<(WorkerHandle, StatusCell), DomainError> {
let client = self
.endpoints
.connect_participant(&identity.client_id)
.connect(&identity.client_id)
.await
.map_err(|e| launch_error(&identity.worker_id, &e))?;
let service = register_with_retry(&client, &identity.service, self.health.boot)
@ -950,7 +862,10 @@ impl Launcher {
let join = std::thread::Builder::new()
.name(format!("fly-session-{}", identity.worker_id))
.spawn(move || {
let runtime = participant_runtime(threads).enable_all().build();
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build();
let runtime = match runtime {
Ok(runtime) => runtime,
Err(e) => {
@ -1038,21 +953,7 @@ impl Launcher {
for (flag, value) in what.arguments() {
command.arg(flag).arg(value);
}
if let Some(cpus) = self.placements.get(&identity.worker_id) {
if !cpus.host.is_empty() {
command
.arg(format!("--{}", flags::HOST_CPUS))
.arg(flybrain_core::pool::format_cpu_list(&cpus.host));
}
if !cpus.sweep.is_empty() {
command
.arg(format!("--{}", flags::SWEEP_CPUS))
.arg(flybrain_core::pool::format_cpu_list(&cpus.sweep));
}
}
command.env(flybrain_core::lif::health::MARKER_ENV, &self.endpoints.gpu_marker);
command.stdin(std::process::Stdio::null());
die_with_parent(&mut command);
let child = command.spawn().map_err(|e| {
DomainError::new(
ErrorCode::BackendFailure,
@ -1510,10 +1411,6 @@ pub(crate) mod flags {
pub const WORKER_THREADS: &str = "worker-threads";
pub const MODES: &str = "modes";
/// BUS-01: the CPUs of the worker's threads, and an agent's sweep workers.
pub const HOST_CPUS: &str = "host-cpus";
pub const SWEEP_CPUS: &str = "sweep-cpus";
/// What every launched worker is given.
pub const COMMON: &[&str] = &[
SOCKET,
@ -1523,8 +1420,6 @@ pub(crate) mod flags {
THREADS,
SESSION,
INCARNATION,
HOST_CPUS,
SWEEP_CPUS,
];
/// What only an agent is given.
pub const AGENT_ONLY: &[&str] = &[
@ -1713,9 +1608,6 @@ pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usiz
dataset_dir: spec.dataset_dir.clone(),
profile: spec.profile,
macro_channels: spec.macro_channels.clone(),
// The deployment's switch, read where the worker runs: a thread, or a child process
// that inherited the launcher's environment.
lif_backend: flybrain_core::lif::LifBackend::from_env(),
}
}

View file

@ -42,8 +42,7 @@ use flybrain_core::envelope::{
agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope,
};
use flybrain_core::json::JsonValue;
use flybrain_core::lif::health as lif_health;
use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version};
use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version};
use serde_json::{Value, json};
use crate::clock::TickAccumulator;
@ -96,14 +95,6 @@ pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
/// answered in any phase once initialized, and is not in any trace.
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
/// BUS-01: the same feed status, as of the boundary the Commit commits, attached to a Commit reply
/// that reaches the agent over the bus (`application/json`, the [`METHOD_FEED_STATUS`] result's
/// bytes). The service host reads it instead of calling [`METHOD_FEED_STATUS`] after the step, which
/// over the bus is a round trip of its own; the bytes are the ones that call would return, since
/// nothing changes the agent between its Commit and the host's publish. Over the local lane, where
/// the call costs nothing, the reply does not carry it.
pub const FEED_STATUS_ATTACHMENT: &str = "legacy.feed-status";
pub const FEED_STATUS_CONTENT_TYPE: &str = "application/json";
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
/// The one stimulus kind the profile supports.
@ -461,10 +452,6 @@ pub struct LegacyAgentConfig {
pub profile: LegacyProfileKind,
/// The composition's `executor.macroChannels`, in composition order; empty in raw mode.
pub macro_channels: Vec<String>,
/// Where the LIF tick runs (GPU-02): `FLY_LIF_CUDA` / `FLY_LIF_CUDA_DEVICE` as the launcher
/// read them, or why they could not be read. Never identity: the GPU tick is bit-exact, so
/// the compatibility digest and every checkpoint are the CPU's.
pub lif_backend: Result<LifBackend, String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -516,9 +503,9 @@ pub struct LegacyAgentWorker {
/// The brain time before the in-flight transition's ticks: the spike window's start.
transition_start_ms: f64,
/// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike
/// lists during Prepare (PERF-01; on the GPU too since GPU-02). It is the bitset
/// `spike_bitset` would scan out of `last_spike_ms` for the same window, without the
/// 139,255-neuron scan. `None` only before a Prepare: Commit then scans.
/// lists during Prepare (PERF-01). It is the bitset `spike_bitset` would scan out of
/// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the
/// kernel keeps no per-tick list (the GPU backend): Commit scans as before.
tick_spikes: Option<Vec<u8>>,
staged: Option<StagedAgent>,
activated: BTreeSet<Id>,
@ -874,63 +861,6 @@ impl LegacyAgentWorker {
/// Builds a network and readout over `dataset`, before any state is installed, and checks
/// every identity the profile pins: kernel and plasticity versions, frame size, rate roles.
/// The backend this agent runs on, attached. A GPU that already failed in this process is
/// not tried again, and one that cannot be attached now (a lost device, a failed CUDA init
/// after a restart) is a fallback to the CPU with a warning, never a failed worker
/// (operator decision, 2026-10-02): the stream keeps going from the same checkpoint, which
/// is backend-neutral. A build without the `cuda` feature that is asked for the GPU is a
/// misconfiguration and still fails `Agent.Initialize`.
///
/// Each attach builds a new backend (about 57 MiB of device memory) while the agent it
/// replaces may still be alive; harmless on a 24 GB card, to be budgeted when GPU-03 batches
/// flies onto an 8 GB one.
fn attach_backend(
&self,
agent: &mut NeuralAgent,
wanted: LifBackend,
) -> Result<LifBackend, DomainError> {
let LifBackend::Cuda { .. } = wanted else {
agent.network.set_backend(LifBackend::Cpu).map_err(|e| {
DomainError::before(ErrorCode::BackendFailure, format!("LIF backend cpu: {e}"))
})?;
return Ok(LifBackend::Cpu);
};
if LifBackend::cuda_compiled() {
if lif_health::gpu_unusable() {
eprintln!(
"legacy agent {}: LIF backend cpu (the GPU failed earlier in this process: {})",
self.config.agent_id,
lif_health::last_reason().unwrap_or_default()
);
return Ok(LifBackend::Cpu);
}
return match agent.network.set_backend(wanted) {
Ok(()) => Ok(wanted),
Err(e) => {
lif_health::record_fallback(&format!(
"agent {}: attaching {} failed: {e}",
self.config.agent_id,
wanted.label()
));
Ok(LifBackend::Cpu)
}
};
}
agent.network.set_backend(wanted).map_err(|e| {
DomainError::before(
ErrorCode::BackendFailure,
format!("LIF backend {}: {e}", wanted.label()),
)
})?;
Ok(wanted)
}
/// A GPU failure in this worker: the GPU is out for the process, and the metric says so.
fn gpu_failed(config: &LegacyAgentConfig, reason: &str) {
lif_health::record_fallback(&format!("agent {}: {reason}", config.agent_id));
lif_health::write_textfile(LifBackend::Cpu, config.lif_backend.clone().unwrap_or_default());
}
fn build_agent(
&self,
dataset: Arc<BrainDataset>,
@ -995,21 +925,8 @@ impl LegacyAgentWorker {
if self.config.worker_threads > 1 {
let plan = SweepPlan::with_threads(self.config.worker_threads)
.map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?;
// Without the core's `FLY_LIF_CUDA` test hook: the backend is this worker's choice.
agent.network.configure_sweep(plan);
agent.set_sweep_plan(plan);
}
let wanted = self.config.lif_backend.clone().map_err(|e| {
DomainError::before(ErrorCode::BackendFailure, format!("LIF backend: {e}"))
})?;
let backend = self.attach_backend(&mut agent, wanted)?;
if backend != LifBackend::Cpu {
eprintln!(
"legacy agent {}: LIF backend {} attached, device-owned state",
self.config.agent_id,
backend.label()
);
}
lif_health::write_textfile(backend, wanted);
let fingerprint = self.profile.dataset_fingerprint.clone();
let graph = AgentGraph {
dataset_digest: dataset_digest(&fingerprint),
@ -1244,27 +1161,22 @@ impl LegacyAgentWorker {
let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.ticks");
// The frame's ticks in one call (GPU-02): on the CPU the one-tick loop `step(ticks)`
// runs, on the GPU one batch with the state left on the device. Either way each tick's
// spike list is OR-ed into the transition's bitset, which is the window `spike_bitset`
// would scan out of `last_spike_ms`.
// One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped
// are its spike list, so the transition's bitset is their union.
let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)];
if let Err(e) = agent.network.step_frame(ticks, &mut bits) {
// The device state was the only current copy, so this worker cannot go on: it fails
// and the replacement restores the last checkpoint on the CPU (the GPU is out for
// the process).
Self::gpu_failed(&self.config, &format!("{e}; the agent fails, a replacement restores the last checkpoint on the CPU"));
return Err(applied(
ErrorCode::BackendFailure,
format!("the brain ticks failed: {e}"),
));
let mut listed = true;
for _ in 0..ticks {
let count = agent.network.step(1) as usize;
match agent.network.tick_spikes(count) {
Some(list) if listed => {
for &neuron in list {
bits[neuron as usize >> 3] |= 1 << (neuron & 7);
}
if let Some(fault) = agent.network.take_backend_fault() {
// The host state was current: the frame finished on the CPU in this call, and this
// worker continues there.
Self::gpu_failed(&self.config, &fault);
}
self.tick_spikes = Some(bits);
_ => listed = false,
}
}
self.tick_spikes = listed.then_some(bits);
drop(ticks_span);
crate::profile::record(
"agent.ticks.phase_clock",
@ -1446,32 +1358,16 @@ impl LegacyAgentWorker {
telemetry: self.telemetry(),
};
let _seal_span = crate::profile::span("agent.seal_spikes");
// Over the bus the feed status rides along, sealed beside the spikes (one round trip for
// both): the service host's publish then needs no call of its own.
let feed = match (ctx.is_local(), self.agent.as_ref()) {
(false, Some(agent)) => Some(
serde_json::to_vec(&feed_status_of(agent)).expect("a JSON value serializes"),
),
_ => None,
};
let (artifact, feed) = tokio::join!(ctx.seal(SPIKES_CONTENT_TYPE, spikes), async {
match feed {
Some(bytes) => ctx.seal(FEED_STATUS_CONTENT_TYPE, bytes).await.map(Some),
None => Ok(None),
}
});
let artifact = artifact.map_err(|e| applied(e.code, e.message))?;
let feed = feed.map_err(|e| applied(e.code, e.message))?;
let artifact = ctx
.seal(SPIKES_CONTENT_TYPE, spikes)
.await
.map_err(|e| applied(e.code, e.message))?;
self.status.set_state(WorkerState::Ready);
self.status
.set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1)));
let mut attachments = vec![(SPIKES_ATTACHMENT.to_owned(), artifact)];
if let Some(feed) = feed {
attachments.push((FEED_STATUS_ATTACHMENT.to_owned(), feed));
}
Ok(HandlerReply::with_artifacts(
object(result.to_json()),
attachments,
vec![(SPIKES_ATTACHMENT.to_owned(), artifact)],
))
}
@ -1631,19 +1527,6 @@ impl LegacyAgentWorker {
));
}
let params: CaptureParams = ctx.params()?;
// With a device-owned GPU backend this is where `membrane` and `refractory` come back
// over PCIe: at checkpoints only (GPU-02). A no-op on the CPU.
{
let _span = crate::profile::span("agent.capture.sync_host");
let agent = self.agent.as_mut().expect("initialized");
if let Err(e) = agent.network.sync_host() {
Self::gpu_failed(&self.config, &format!("device state read-back: {e}"));
return Err(applied(
ErrorCode::BackendFailure,
format!("the device state cannot be read back: {e}"),
));
}
}
// The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's
// `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
// connectome -- run after the lock is released (`HandlerReply::deferred`), so the next

View file

@ -991,11 +991,6 @@ impl LegacyRig {
self.launch(agent_id).await
}
/// GPU failures so far that moved a worker's LIF tick to the CPU ([`Launcher::gpu_fallbacks`]).
pub fn gpu_fallbacks(&self) -> u64 {
self.launcher.gpu_fallbacks()
}
pub async fn stop(mut self) {
self.launcher.reap_all(&id("done")).await;
}
@ -1582,53 +1577,12 @@ pub async fn run_on_worker_from_then_capture(
Ok((records, captured.expect("a capture was asked for")))
}
/// [`run_on_worker`] with the coordinator's recovery for a failed frame (GPU-02): the agent is
/// Failed, so the last checkpoint (the script's `checkpoints`) is restored into a replacement
/// worker, and the script goes on from the step after it. Returns the records and, for each
/// recovery, the index of the step whose checkpoint was restored. The restore resets the
/// readout's transients by design, so the matching CPU reference is the script with a
/// `ScriptStep::Restore` after that step ([`script_with_restore_after`]).
pub async fn run_on_worker_recovering(
rig: &mut LegacyRig,
agent_id: &Id,
script: &LegacyScript,
) -> Result<(Vec<ParityRecord>, Vec<usize>), String> {
let mut recovered = Vec::new();
let (records, _) = run_script_with(rig, agent_id, script, None, false, Some(&mut recovered)).await?;
Ok((records, recovered))
}
/// `script` with a restore into a fresh agent right after step `at` (an index into `steps`), and
/// its checkpoints moved onto the steps' new positions: the CPU reference for a run that
/// recovered from the checkpoint at `at`.
pub fn script_with_restore_after(script: &LegacyScript, at: usize) -> LegacyScript {
let mut alt = script.clone();
alt.steps.insert(at + 1, ScriptStep::Restore);
alt.checkpoints = script
.checkpoints
.iter()
.map(|&i| if i > at { i + 1 } else { i })
.collect();
alt
}
async fn run_script(
rig: &mut LegacyRig,
agent_id: &Id,
script: &LegacyScript,
start: Option<(&flybrain_core::agent::AgentState, u64)>,
capture_at_end: bool,
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
run_script_with(rig, agent_id, script, start, capture_at_end, None).await
}
async fn run_script_with(
rig: &mut LegacyRig,
agent_id: &Id,
script: &LegacyScript,
start: Option<(&flybrain_core::agent::AgentState, u64)>,
capture_at_end: bool,
mut recovered: Option<&mut Vec<usize>>,
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
let mut driver = rig.driver(agent_id, script);
let first = match start {
@ -1640,12 +1594,7 @@ async fn run_script_with(
}
};
let mut records = vec![first];
// The last checkpoint, for a recovery: (step, records so far, the capture, and the driver
// state a restore returns to).
let mut last_checkpoint: Option<(usize, usize, Captured, u64, TypedValue, RationalNs)> = None;
let mut index = 0usize;
while index < script.steps.len() {
let step = &script.steps[index];
for (index, step) in script.steps.iter().enumerate() {
let mut record = match step {
ScriptStep::Frame {
sugar,
@ -1653,31 +1602,9 @@ async fn run_script_with(
rewards,
next_context,
} => {
match driver
driver
.frame(index + 1, sugar, *frame, rewards, next_context)
.await
{
Ok(record) => record,
Err(e) if recovered.is_some() && last_checkpoint.is_some() => {
let (at, kept, captured, boundary, context, remainder) =
last_checkpoint.take().expect("checked");
eprintln!(
"recovery: step {} failed ({e}); restoring the checkpoint after step {at} into a replacement",
index + 1
);
driver.boundary = boundary;
driver.context = context.clone();
driver.remainder = remainder;
let target = rig.replace(agent_id).await?;
driver.restore_into(target, &captured).await?;
records.truncate(kept);
recovered.as_mut().expect("checked").push(at);
last_checkpoint = Some((at, kept, captured, boundary, context, remainder));
index = at + 1;
continue;
}
Err(e) => return Err(e),
}
.await?
}
ScriptStep::Rollback { frame, context } => {
driver.rollback(index + 1, *frame, context).await?
@ -1705,20 +1632,8 @@ async fn run_script_with(
if script.checkpoints.contains(&index) {
let captured = driver.capture().await?;
record.state = Some(payload_state_digest(&captured.bytes)?);
records.push(record);
last_checkpoint = Some((
index,
records.len(),
captured,
driver.boundary,
driver.context.clone(),
driver.remainder,
));
index += 1;
continue;
}
records.push(record);
index += 1;
}
let captured = if capture_at_end {
Some(driver.capture().await?.bytes)

View file

@ -50,7 +50,7 @@ pub fn audio_attachment(stream_id: &str) -> String {
format!("audio.{stream_id}")
}
pub(crate) fn store_error(what: &str, message: &str) -> DomainError {
fn store_error(what: &str, message: &str) -> DomainError {
DomainError::new(
ErrorCode::BackendFailure,
format!("{what}: {message}"),

View file

@ -186,15 +186,29 @@ impl SentCall {
let result = pending.result().await.map_err(|e| bus_error(method, &e))?;
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
// Each wanted attachment's handle keeps the result delivery's ownership alive for as long
// as it lives (bus-v1 section 8.3), and a delivery's handle can be forwarded -- to the
// Commit calls and to publication -- like a hold (section 8.2). So the handles are kept
// as delivered: an explicit hold per attachment was a router round trip each, on the
// step's critical path, and an `artifact.release` each later (BUS-02).
// An independent explicit hold on each wanted attachment, so the handle outlives this
// delivery and can be forwarded to several Commit calls and to publication. The holds
// are independent router round trips, so they are taken concurrently.
let wanted: Vec<(String, flybus::Artifact)> = self
.want_artifacts
.iter()
.filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a)))
.collect();
let retains: Vec<_> = wanted
.into_iter()
.map(|(name, artifact)| {
tokio::spawn(async move {
match artifact.retain().await {
Ok(hold) => (name, hold),
Err(_) => (name, artifact),
}
})
})
.collect();
let mut artifacts = BTreeMap::new();
for name in &self.want_artifacts {
if let Ok(artifact) = result.artifact(name) {
artifacts.insert(name.clone(), artifact);
for retain in retains {
if let Ok((name, artifact)) = retain.await {
artifacts.insert(name, artifact);
}
}
drop(result);

View file

@ -160,111 +160,6 @@ pub struct HandlerCtx<'a> {
pub request: &'a SessionRpcRequest,
pub client: &'a flybus::Client,
pub incoming: &'a Incoming,
/// Staging writers allocated ahead for the reply artifacts this worker seals every step.
pub(crate) writers: &'a WriterPool,
/// The reply artifacts [`HandlerCtx::seal`] wrote and left for the reply to seal (BUS-02).
pub(crate) unsealed: &'a Mutex<Vec<flybus::Unsealed>>,
}
/// Staging writers allocated ahead of need (BUS-01), and handed back by the router after each
/// reply (BUS-02). A bus worker seals the same shapes of reply artifact every step -- the
/// environment a 92,160-byte frame, a 65,536-byte memory image and an audio chunk of one of two
/// lengths, the agent a 17,407-byte spike bitset and its feed status, a JSON document of varying
/// length -- and allocating one is a router round trip. The pool remembers the last few
/// `(content type, capacity)` shapes [`HandlerCtx::seal`] asked for; a capacity is the length
/// rounded up to 4 KiB, so the two audio lengths and every feed status share one writer. A seal
/// takes a ready writer of its content type with room for its bytes, writes them, and leaves
/// the artifact for the reply to seal (bus-v1 section 12 amendment 2026-10-02): the reply
/// recycles each writer's allocation, the pool takes the recycled writers back, and only a shape
/// with no writer is allocated, off the critical path, after the reply. A writer is an artifact
/// like any other: unsealed, it is released when dropped, and the bytes sealed are exactly the
/// bytes written, so nothing a caller sees depends on the pool.
#[derive(Default)]
pub struct WriterPool {
state: Mutex<PoolState>,
}
#[derive(Default)]
struct PoolState {
/// The most recent distinct shapes, newest last.
recent: Vec<(String, u64)>,
ready: Vec<flybus::ArtifactWriter>,
allocating: Vec<(String, u64)>,
}
/// Shapes the pool keeps writers for: an environment's three reply artifacts and an agent's
/// two, with room to spare.
const POOL_SHAPES: usize = 6;
/// The allocation a reply artifact of `len` bytes is written into.
fn pool_capacity(len: u64) -> u64 {
len.max(1).div_ceil(4096) * 4096
}
impl WriterPool {
fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> {
let mut st = self.state.lock().expect("never poisoned");
let shape = (content_type.to_owned(), pool_capacity(len));
if let Some(at) = st.recent.iter().position(|s| *s == shape) {
st.recent.remove(at);
} else if st.recent.len() >= POOL_SHAPES {
let gone = st.recent.remove(0);
st.ready
.retain(|w| (w.content_type(), w.byte_length()) != (gone.0.as_str(), gone.1));
}
st.recent.push(shape);
let at = st
.ready
.iter()
.enumerate()
.filter(|(_, w)| w.content_type() == content_type && w.byte_length() >= len)
.min_by_key(|(_, w)| w.byte_length())
.map(|(at, _)| at)?;
Some(st.ready.swap_remove(at))
}
/// Takes back the writers a sealing reply recycled, for the shapes still in use.
fn give(&self, writers: Vec<flybus::ArtifactWriter>) {
let mut st = self.state.lock().expect("never poisoned");
for w in writers {
let shape = (w.content_type().to_owned(), w.byte_length());
let spare = st.ready.iter().any(|r| (r.content_type(), r.byte_length()) == (shape.0.as_str(), shape.1));
if st.recent.contains(&shape) && !spare {
st.ready.push(w);
}
}
}
/// Allocates, in the background, a writer for every remembered shape that has none.
fn refill(self: &Arc<Self>, client: &flybus::Client) {
let wanted: Vec<(String, u64)> = {
let mut st = self.state.lock().expect("never poisoned");
let wanted: Vec<_> = st
.recent
.iter()
.filter(|s| {
!st.ready.iter().any(|w| (w.content_type(), w.byte_length()) == (s.0.as_str(), s.1))
&& !st.allocating.contains(s)
})
.cloned()
.collect();
st.allocating.extend(wanted.iter().cloned());
wanted
};
for shape in wanted {
let (pool, client) = (self.clone(), client.clone());
tokio::spawn(async move {
let writer = client.artifacts().allocate(shape.1, &shape.0).await;
let mut st = pool.state.lock().expect("never poisoned");
st.allocating.retain(|s| *s != shape);
if let Ok(writer) = writer
&& st.recent.contains(&shape)
{
st.ready.push(writer);
}
});
}
}
}
/// How a domain request reached the shell, and so where its attachments are.
@ -323,36 +218,13 @@ impl HandlerCtx<'_> {
}
/// One immutable reply artifact holding `bytes`. Over the local lane it is an in-memory
/// artifact that owns `bytes` (no copy, no store file, no router round trip). Over the bus
/// the bytes go into a staging writer (one allocated ahead, [`WriterPool`]) and the reply
/// that carries the artifact seals it as the router admits the reply (bus-v1 section 12
/// amendment 2026-10-02, BUS-02): the handle is valid from then on, and the handler must
/// put it in its reply.
/// artifact that owns `bytes` (no copy, no store file, no router round trip); over the bus
/// it is allocated, written and sealed in the router's store as before.
pub async fn seal(&self, content_type: &str, bytes: Vec<u8>) -> DomainResult<flybus::Artifact> {
if self.is_local() {
return Ok(flybus::Artifact::in_memory(content_type, bytes));
}
let len = bytes.len() as u64;
let mut writer = match self.writers.take(content_type, len) {
Some(writer) => writer,
None => {
let _span = crate::profile::span("shell.seal.allocated");
self.client
.artifacts()
.allocate(pool_capacity(len), content_type)
.await
.map_err(|e| crate::media::store_error("allocate", &e.message))?
}
};
let _span = crate::profile::span("shell.seal.pooled");
use std::io::Write as _;
writer
.write_all(&bytes)
.map_err(|e| crate::media::store_error("write", &e.to_string()))?;
let unsealed = writer.into_unsealed();
let artifact = unsealed.artifact().clone();
self.unsealed.lock().expect("never poisoned").push(unsealed);
Ok(artifact)
crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await
}
}
@ -519,42 +391,16 @@ enum Answer {
Local(tokio::sync::oneshot::Sender<LocalReply>),
}
/// What answering a call came to.
enum Sent {
/// Answered, or the caller is gone (nothing more can reach it), with the writers a sealing
/// reply recycled.
Done(Vec<flybus::ArtifactWriter>),
/// The router refused the reply that was to seal the handler's artifacts (a store failure:
/// quota, IO, a writer gone). Nothing reached the caller and the call is still open: the
/// answer comes back to send the failure on (BUS-02 review N1).
SealRefused(Answer, flybus::BusError),
}
impl Answer {
/// Answers the call. Over the bus, the artifacts left unsealed by [`HandlerCtx::seal`] are
/// sealed by the reply itself and their writers come back recycled, for the pool (BUS-02).
async fn send(
self,
outcome: SessionRpcOutcome,
artifacts: &[(String, flybus::Artifact)],
unsealed: Vec<flybus::Unsealed>,
) -> Sent {
async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) {
match self {
Answer::Bus(responder) => {
let list: Vec<(&str, &flybus::Artifact)> =
artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
if unsealed.is_empty() {
let _ = responder.reply(outcome.to_outcome(), &list).await;
return Sent::Done(Vec::new());
}
match responder.reply_sealing(outcome.to_outcome(), &list, unsealed, true).await {
Ok(sealed) => Sent::Done(sealed.writers),
Err(error) => Sent::SealRefused(Answer::Bus(responder), error),
}
}
Answer::Local(tx) => {
let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() });
Sent::Done(Vec::new())
}
}
}
@ -576,8 +422,6 @@ struct Shell<E> {
closed: std::sync::atomic::AtomicBool,
/// The admitted mutations' tasks, awaited when the shell stops.
running: Mutex<Vec<tokio::task::JoinHandle<()>>>,
/// Reply writers allocated ahead (BUS-01).
writers: Arc<WriterPool>,
}
/// The local lane's hold on a shell.
@ -648,7 +492,6 @@ pub fn serve<E: WorkerEndpoint>(
admission: tokio::sync::Mutex::new(()),
closed: std::sync::atomic::AtomicBool::new(false),
running: Mutex::new(Vec::new()),
writers: Arc::default(),
});
let local = LocalLane(Arc::new(ShellRef(shell.clone())));
let task = tokio::spawn(run(shell, service, common));
@ -820,7 +663,7 @@ impl<E: WorkerEndpoint> Shell<E> {
DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")),
request.scope.clone(),
);
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
return;
};
@ -831,7 +674,7 @@ impl<E: WorkerEndpoint> Shell<E> {
Ok(body) => body,
Err(e) => {
let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone());
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
return;
}
};
@ -845,7 +688,7 @@ impl<E: WorkerEndpoint> Shell<E> {
},
(OpClass::StepMutation, None) => {
let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None);
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
return;
}
_ => OperationKey {
@ -866,12 +709,12 @@ impl<E: WorkerEndpoint> Shell<E> {
};
match admission {
Admission::Replay(reply) => {
answer.send(reply.outcome.clone(), &reply.artifacts, Vec::new()).await;
answer.send(reply.outcome.clone(), &reply.artifacts).await;
return;
}
Admission::Refuse(e) => {
let outcome = refuse(e, request.scope.clone());
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
return;
}
Admission::Execute => {}
@ -976,7 +819,6 @@ async fn execute<E: WorkerEndpoint>(
let Admitted { class, key, serial, body, method, request, incoming } = admitted;
let (worker_id, incarnation_id, status, cache) =
(&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache);
let unsealed = Mutex::new(Vec::new());
let outcome = {
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
// never held across a bus round trip taken by anything else.
@ -987,25 +829,8 @@ async fn execute<E: WorkerEndpoint>(
request: &request,
client: &shell.client,
incoming: &incoming,
writers: &shell.writers,
unsealed: &unsealed,
};
if matches!(incoming, Incoming::Bus(_)) && long_method(&method) && blocking_allowed() {
// A long bus request's handler runs with this worker thread handed over to blocking
// work (BUS-01): the legacy agent's warm-up is seconds of synchronous computation, and
// a Tokio worker blocked that long strands the tasks queued on it -- the shell's own
// bus loop and its connection's reader among them -- so a duplicate arriving
// mid-execution could not be answered IN_PROGRESS and `ipc-v1` section 6's resolution
// of a slow Initialize ran out ("never resolved"). `block_in_place` moves those tasks
// to another thread first. A step's handlers (milliseconds) run in place: the hand-over
// is a thread wake-up of its own. The local lane's caller awaits the handler on its own
// task and is unchanged.
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(e.handle(ctx))
})
} else {
e.handle(ctx).await
}
};
// A deferred reply finishes here, with the endpoint's lock released.
let outcome = match outcome {
@ -1026,12 +851,7 @@ async fn execute<E: WorkerEndpoint>(
.map(|(name, artifact)| {
let (name, artifact) = (name.clone(), artifact.clone());
async move {
// An in-memory artifact is its own hold, and so is a sealed one this
// worker holds explicitly (its own seal): a clone keeps it as long as the
// cache needs it, without another router round trip (BUS-01). Only a
// delivery's handle -- a forwarded request attachment -- needs a hold of
// its own, so the delivery can be consumed.
if artifact.is_in_memory() || artifact.is_hold() {
if artifact.is_in_memory() {
return (name, artifact);
}
let task = tokio::spawn(async move {
@ -1048,92 +868,17 @@ async fn execute<E: WorkerEndpoint>(
for retain in retains {
holds.push(retain.await);
}
let cache_span = crate::profile::span("shell.record.cache");
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
let unsealed = std::mem::take(&mut *unsealed.lock().expect("never poisoned"));
// The cache records the reply before it is sent, so a duplicate never re-executes;
// but until the reply that seals this handler's artifacts is admitted they are
// still writers, and a replay attaching one would seal it into the duplicate's
// reply (or be refused) and refuse the original (BUS-02 review N2). So a sealing
// reply is sent with the cache held: a duplicate waits for it in admission and
// replays sealed handles, or the failure below. A reply that seals nothing (the
// lane's, or a handler's without artifacts of its own) holds nothing.
let mut held = Some(cache.lock().await);
{
let c = held.as_mut().expect("just taken");
let mut c = cache.lock().await;
match class {
OpClass::StepMutation => {
c.record(key.clone(), serial.clone(), body.clone(), cached)
}
OpClass::Lifecycle => c.record_lifecycle(serial.clone(), body.clone(), cached),
OpClass::ReadOnly => c.record_readonly(serial.clone(), cached),
OpClass::StepMutation => c.record(key, serial, body, cached),
OpClass::Lifecycle => c.record_lifecycle(serial, body, cached),
OpClass::ReadOnly => c.record_readonly(serial, cached),
}
}
status.set_completed(request.request_id.clone());
if unsealed.is_empty() {
held = None;
}
drop(cache_span);
#[cfg(test)]
sealing_tests::gate(worker_id).await;
let reply_span = crate::profile::span("shell.reply");
let sent = answer.send(outcome, &reply.artifacts, unsealed).await;
drop(reply_span);
let recycled = match sent {
Sent::Done(recycled) => {
drop(held);
recycled
}
Sent::SealRefused(answer, error) => {
// The handler's artifacts could not be stored. Before BUS-02 the handler's
// own seal failed and returned this error; it is answered, cached and
// reported exactly as that was (BUS-02 review N1), instead of reaching the
// caller as a bus-level failed call.
eprintln!(
"worker {worker_id}: {method}: the reply's artifacts were not sealed ({}: {}); \
answering BACKEND_FAILURE",
error.code.as_str(),
error.message
);
let e = crate::media::store_error("seal", &error.message);
let mut c = held.take().expect("a sealing reply holds the cache");
match class {
OpClass::StepMutation => c.record(
key,
serial,
body,
CachedReply::new(failure_outcome(
&request.request_id,
worker_id,
incarnation_id,
request.scope.clone(),
e.clone(),
)),
),
OpClass::Lifecycle => c.forget_lifecycle(&serial),
OpClass::ReadOnly => c.forget_readonly(&serial),
}
drop(c);
status.set_state(WorkerState::Failed);
status.set_active(None);
let outcome = failure(
&request.request_id,
worker_id,
incarnation_id,
request.scope.clone(),
e,
);
let _ = answer.send(outcome, &[], Vec::new()).await;
Vec::new()
}
};
// The next step's writers: the ones the reply recycled, and any shape without one
// allocated while the caller goes on (bus requests only: the lane seals nothing into
// the store).
if matches!(incoming, Incoming::Bus(_)) {
shell.writers.give(recycled);
shell.writers.refill(&shell.client);
}
answer.send(outcome, &reply.artifacts).await;
}
Err(e) => {
if e.mutation == MutationCertainty::None {
@ -1164,25 +909,11 @@ answering BACKEND_FAILURE",
request.scope.clone(),
e,
);
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
}
}
}
/// The methods whose handlers can run for seconds: the warm-ups, the restores and the captures.
/// A step's methods (Prepare, Advance, Commit: milliseconds) are not among them; neither are the
/// read-only extensions.
fn long_method(method: &str) -> bool {
method.ends_with(".Initialize") || method.starts_with("State.") || method == "Agent.Rollback"
}
/// Whether this thread is a worker of a multi-thread Tokio runtime, where
/// [`tokio::task::block_in_place`] is allowed.
fn blocking_allowed() -> bool {
tokio::runtime::Handle::try_current()
.is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
}
/// The retention class of every method name the contracts define.
fn classify_default(method: &str) -> Option<OpClass> {
match method {
@ -1338,7 +1069,3 @@ async fn acknowledge(
let result = AcknowledgeResult { acknowledged };
Ok(object(result.to_json()))
}
#[cfg(test)]
#[path = "worker_sealing_tests.rs"]
mod sealing_tests;

View file

@ -1,204 +0,0 @@
//! A bus worker's reply artifacts are sealed by the reply that carries them (BUS-02). These
//! tests hold a worker between recording a reply and sending it, which no client can arrange
//! from outside, so they live beside the shell.
//!
//! - Review N2: a duplicate replayed in that window must never attach the still-unsealed
//! writer. It waits for the sealing reply and replays the sealed artifact.
//! - Review N1: a store failure while the reply seals reaches the caller as the typed domain
//! failure the handler's own seal gave before BUS-02 (`BACKEND_FAILURE`, mutation applied),
//! not as a bus-level failed call, and a retry replays nothing it could not deliver.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde_json::Map;
use tokio::sync::Semaphore;
use super::*;
use crate::rpc::{self, WorkerRef};
/// Workers held before their reply until the test lets them go, by worker id.
static GATES: Mutex<Vec<(String, Arc<Semaphore>)>> = Mutex::new(Vec::new());
/// Waits, in a worker under test, until the test opens its gate. Other workers pass.
pub(super) async fn gate(worker: &Id) {
let gate = GATES
.lock()
.unwrap()
.iter()
.find(|(w, _)| w == worker.as_str())
.map(|(_, g)| g.clone());
if let Some(gate) = gate {
let _ = gate.acquire().await.expect("never closed");
}
}
fn hold(worker: &str) -> Arc<Semaphore> {
let gate = Arc::new(Semaphore::new(0));
GATES.lock().unwrap().push((worker.to_owned(), gate.clone()));
gate
}
/// A worker whose `State.Capture` seals `len` bytes of a value that changes every execution.
struct Sealer {
worker: Id,
status: StatusCell,
len: usize,
executions: Arc<std::sync::atomic::AtomicU64>,
}
impl WorkerEndpoint for Sealer {
fn worker_id(&self) -> Id {
self.worker.clone()
}
fn incarnation_id(&self) -> Id {
id("inc-1")
}
fn session_id(&self) -> Id {
id("sealing")
}
fn role(&self) -> Role {
Role::Environment
}
fn capabilities(&self) -> Vec<Id> {
Vec::new()
}
fn status_cell(&self) -> StatusCell {
self.status.clone()
}
fn worker_threads(&self) -> u64 {
1
}
fn methods(&self) -> Vec<&'static str> {
vec!["State.Capture"]
}
fn handle<'a>(&'a mut self, ctx: HandlerCtx<'a>) -> BoxFuture<'a, DomainResult<HandlerReply>> {
Box::pin(async move {
let n = self.executions.fetch_add(1, std::sync::atomic::Ordering::SeqCst) as u8;
let blob = ctx.seal("application/octet-stream", vec![0x40 + n; self.len]).await?;
Ok(HandlerReply::with_artifacts(Map::new(), vec![("blob".into(), blob)]))
})
}
}
struct Rig {
_dir: tempfile::TempDir,
_router: flybus::Router,
caller: flybus::Client,
target: WorkerRef,
executions: Arc<std::sync::atomic::AtomicU64>,
handle: WorkerHandle,
}
async fn rig(worker: &str, len: usize, max_store_bytes: Option<u64>) -> Rig {
let dir = tempfile::tempdir().unwrap();
let mut config = flybus::RouterConfig::new(dir.path().join("store"));
config.policy = flybus::Policy::open();
if let Some(max) = max_store_bytes {
config.limits.max_store_bytes = max;
config.limits.max_artifact_bytes = max;
config.limits.max_retained_bytes = max;
}
let router = flybus::Router::new(config).unwrap();
let connect = |who: &str| {
let transport = router.connect_in_memory_as(who);
flybus::Client::connect(transport, flybus::ClientConfig::new(who, router.store_root()))
};
let worker_client = connect(worker).await.unwrap();
let caller = connect("caller").await.unwrap();
let service = worker_client
.register(&format!("w.{worker}"), flybus::ServiceConfig::default())
.await
.unwrap();
let target = WorkerRef::new(service.name(), service.incarnation(), &id(worker));
let executions = Arc::new(std::sync::atomic::AtomicU64::new(0));
let endpoint = Sealer {
worker: id(worker),
status: StatusCell::new(),
len,
executions: executions.clone(),
};
let handle = serve(worker_client, service, endpoint);
Rig { _dir: dir, _router: router, caller, target, executions, handle }
}
async fn capture(rig: &Rig, serial: u64) -> rpc::SentCall {
rpc::send(
&rig.caller,
&rig.target,
"State.Capture",
None,
Map::new(),
&[],
DomainRequestId::from_serial(serial),
&["blob".to_owned()],
)
.await
.unwrap()
}
async fn within<T>(what: &str, f: impl std::future::Future<Output = T>) -> T {
tokio::time::timeout(Duration::from_secs(20), f)
.await
.unwrap_or_else(|_| panic!("{what} timed out"))
}
/// N2: the original's reply is recorded and held unsent; a duplicate arrives, finds the record,
/// and must not attach the writer the held reply is about to seal. Both calls get the same
/// sealed bytes, from one execution.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_replay_waits_for_the_reply_that_seals_its_artifacts() {
const LEN: usize = 300_000;
let rig = rig("n2-worker", LEN, None).await;
let gate = hold("n2-worker");
let original = capture(&rig, 1).await;
// The handler ran and the reply is recorded: the worker is at the gate.
within("the original executes", async {
while rig.executions.load(std::sync::atomic::Ordering::SeqCst) == 0 {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await;
tokio::time::sleep(Duration::from_millis(50)).await;
let duplicate = capture(&rig, 1).await;
let duplicate = tokio::spawn(duplicate.finish());
// Long enough for the duplicate to reach admission and, without the fix, to replay the
// unsealed handle and race the held reply.
tokio::time::sleep(Duration::from_millis(300)).await;
gate.add_permits(1);
let original = within("original", original.finish()).await.expect("the original succeeds");
let duplicate = within("duplicate", duplicate)
.await
.unwrap()
.expect("the duplicate replays the same reply");
assert_eq!(rig.executions.load(std::sync::atomic::Ordering::SeqCst), 1);
let a = original.artifacts["blob"].read_all().await.unwrap();
let b = duplicate.artifacts["blob"].read_all().await.unwrap();
assert_eq!(a, vec![0x40; LEN]);
assert_eq!(a, b);
rig.handle.stop().await;
}
/// N1: the store refuses the sealing copy (quota). The caller gets the typed failure, with the
/// mutation applied, as when the handler's own `artifact.seal` was refused before BUS-02; a
/// retry runs again rather than replaying a reply that never reached anyone.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_refused_seal_is_a_typed_domain_failure() {
const LEN: usize = 8192;
// The writer's allocation fits; its sealed copy does not.
let rig = rig("n1-worker", LEN, Some(LEN as u64 + 100)).await;
let reply = within("capture", capture(&rig, 1).await.finish()).await;
let error = match reply {
Ok(reply) => reply.result().expect_err("the seal was refused"),
Err(e) => panic!("a bus-level failure instead of the domain failure: {e:?}"),
};
assert_eq!(error.code, ErrorCode::BackendFailure, "{error:?}");
assert_eq!(error.mutation, MutationCertainty::Applied);
assert!(error.message.starts_with("seal: "), "{}", error.message);
assert_eq!(rig.handle.state(), WorkerState::Failed);
// Nothing of the refused reply is cached: the retry executes again.
let retry = within("retry", capture(&rig, 1).await.finish()).await.unwrap();
assert!(retry.result().is_err());
assert_eq!(rig.executions.load(std::sync::atomic::Ordering::SeqCst), 2);
rig.handle.stop().await;
}

View file

@ -1,256 +0,0 @@
//! GPU-02 notes round (N2, operator decision 2026-10-02): a GPU failure on the live brain falls
//! back to the CPU and the session keeps going from the last checkpoint, with no loop re-attaching
//! a dead device.
//!
//! The fault-injection hook (`flybrain_core::lif::cuda::inject`, or `FLY_LIF_CUDA_FAULT` for a
//! worker process) raises a CUDA error where a real one would surface. Against the CPU reference
//! on the real connectome:
//!
//! - **Permanent, mid-run** (the device held the only current state): the agent fails, a
//! replacement worker restores the last checkpoint on the CPU and the records are those of the CPU
//! reference with a restore at that checkpoint -- in-process, and as a process, where the
//! replacement is a new process that must not re-attach the GPU (no second failure).
//! - **Init failure** (a lost device at a restart): `Agent.Initialize` succeeds on the CPU, with
//! a warning and a counted fallback, and a restore into a replacement stays on the CPU.
//! - **Transient** (the host state was current: the first batch): the frame finishes on the CPU in
//! the call, bit-exact, and no recovery is needed; the fallback is counted and the GPU is not
//! re-attached by a later restore.
//!
//! Needs `--features cuda` and `data/fafb-v783`. The cases that run a real device also need
//! `FLY_GPU02_CUDA=1` and a visible card; the init-failure case needs neither.
#![cfg(feature = "cuda")]
use std::sync::Arc;
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity::{
self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RewardEvent,
RigAgent, ScriptStep, fafb_dir, frame_pool,
};
use fly_session::types::id;
use fly_session_types::gameboy::{Location, ReadoutContext};
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::lif::cuda::inject;
use flybrain_core::lif::health;
fn pokered_channels() -> Vec<String> {
let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors");
file["cases"][1]["macroChannels"]
.as_array()
.expect("the Pokemon Red macro group")
.iter()
.map(|c| c.as_str().expect("a channel").to_owned())
.collect()
}
/// Frames with sugar and reward pulses, a checkpoint every 25 steps, an optional restore.
fn script(frames: usize, restore_at: Option<usize>) -> LegacyScript {
let channels = pokered_channels();
let bound = |k: usize| -> Vec<String> {
let take: &[usize] = match k % 120 {
0..20 => &[],
20..50 => &[0, 1, 9],
_ => &[1, 4, 5, 6],
};
take.iter().map(|i| channels[*i].clone()).collect()
};
let mut steps = Vec::new();
for k in 1..=frames {
steps.push(ScriptStep::Frame {
sugar: if k % 97 == 12 { vec![400.0] } else { vec![] },
frame: k % 6,
rewards: if k % 11 == 0 {
vec![RewardEvent {
value: 0.5,
stimulation_ms: 120.0,
}]
} else {
vec![]
},
next_context: ReadoutContext {
boot: k < 10,
bound: bound(k),
location: (k > 5).then_some(Location {
area: 12,
x: 3 + (k / 40) as u32,
y: 7,
}),
},
});
if restore_at == Some(k) {
steps.push(ScriptStep::Restore);
}
}
let last = steps.len() - 1;
let checkpoints = (0..steps.len())
.filter(|i| i % 25 == 24)
.chain([last])
.collect();
LegacyScript {
name: "gpu02-fallback".to_owned(),
macro_channels: channels,
frames: Arc::new(frame_pool(6, 783)),
initial_frame: 0,
initial_context: ReadoutContext {
boot: true,
bound: vec![],
location: None,
},
steps,
checkpoints,
}
}
fn agent(dir: &std::path::Path, script: &LegacyScript) -> RigAgent {
RigAgent {
agent_id: id("fly-a"),
port_id: id("p1"),
dataset_dir: dir.to_path_buf(),
profile: LegacyProfileKind::Production,
macro_channels: script.macro_channels.clone(),
worker_threads: 1,
}
}
fn reset() {
inject::clear();
health::reset_for_tests();
}
struct Outcome {
records: Vec<ParityRecord>,
recovered: Vec<usize>,
fallbacks: u64,
}
async fn run(dir: &std::path::Path, script: &LegacyScript, mode: ExecutionMode) -> Outcome {
let root = tempfile::tempdir().expect("tmp");
let mut rig = LegacyRig::start(root.path(), mode, &[agent(dir, script)])
.await
.expect("the rig");
let (records, recovered) =
legacy_parity::run_on_worker_recovering(&mut rig, &id("fly-a"), script)
.await
.unwrap_or_else(|e| panic!("{}: {e}", mode.label()));
let fallbacks = rig.gpu_fallbacks();
rig.stop().await;
Outcome {
records,
recovered,
fallbacks,
}
}
fn reference(dir: &std::path::Path, script: &LegacyScript) -> Vec<ParityRecord> {
let dataset = Arc::new(load_brain_dataset_from_dir(dir).expect("the dataset loads"));
DirectSource { dataset }
.records(script)
.expect("the CPU reference runs")
}
/// The records of the CPU reference with a restore after step `at`, minus that restore's own
/// record (the recovery has none), against what the recovered run recorded.
fn assert_recovered_equals_reference(
dir: &std::path::Path,
script: &LegacyScript,
at: usize,
got: &[ParityRecord],
case: &str,
) {
let alt = legacy_parity::script_with_restore_after(script, at);
let mut want = reference(dir, &alt);
want.remove(at + 2); // records[0] is the first record, step i is records[i + 1]
assert_eq!(want.len(), got.len(), "{case}: record count");
for (i, (w, g)) in want.iter().zip(got).enumerate() {
let (mut w, mut g) = (w.clone(), g.clone());
w.index = 0;
g.index = 0;
assert_eq!(w, g, "{case}: record {i} differs from the CPU reference");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_gpu_failure_falls_back_to_the_cpu_and_the_session_continues() {
let Some(dir) = fafb_dir() else {
eprintln!("skipping: data/fafb-v783 is not present in this checkout");
return;
};
let device = std::env::var_os("FLY_GPU02_CUDA").is_some();
let frames = 120;
// SAFETY: the only test in this binary; no worker (thread or child) exists yet.
unsafe { std::env::set_var("FLY_LIF_CUDA", "1") };
let plain = script(frames, None);
// Init failure: a restart whose CUDA init fails. No device needed.
reset();
inject::fail_attach(true);
let with_restore = script(frames, Some(60));
let got = run(&dir, &with_restore, ExecutionMode::InProcess).await;
assert!(got.recovered.is_empty(), "nothing failed mid-run");
assert_eq!(got.fallbacks, 1, "one failed attach; the restore did not try the GPU again");
legacy_parity::compare(&reference(&dir, &with_restore), &got.records)
.unwrap_or_else(|e| panic!("init failure: {e}"));
assert!(health::gpu_unusable());
eprintln!("init failure: continued on the CPU, {} records identical", got.records.len());
if !device {
eprintln!("skipping the device cases: FLY_GPU02_CUDA is not set");
reset();
return;
}
// Control: the GPU, no fault, no fallback.
reset();
let started = inject::batches();
let got = run(&dir, &plain, ExecutionMode::InProcess).await;
// A game frame is one batch; the warm-up before the first frame is many. The faults below
// go off `frames - 50` batches from the run's end: mid-run, never in the warm-up.
let run_batches = inject::batches() - started;
assert!(run_batches > frames as u64);
assert_eq!(got.fallbacks, 0, "the GPU attached");
legacy_parity::compare(&reference(&dir, &plain), &got.records)
.unwrap_or_else(|e| panic!("control: {e}"));
// Transient: the first batch (the warm-up) fails with the host state current. The frame
// finishes on the CPU in the call: no recovery, bit-exact, and the GPU stays out.
reset();
inject::fail_batch_after(0);
let got = run(&dir, &with_restore, ExecutionMode::InProcess).await;
assert!(got.recovered.is_empty(), "the call finished on the CPU");
assert_eq!(got.fallbacks, 1, "counted once; the restore did not re-attach the GPU");
legacy_parity::compare(&reference(&dir, &with_restore), &got.records)
.unwrap_or_else(|e| panic!("transient: {e}"));
eprintln!("transient: finished on the CPU in place, {} records identical", got.records.len());
// Permanent, mid-run, in-process: the device held the only current state.
reset();
inject::fail_batch_after(run_batches - 50);
let got = run(&dir, &plain, ExecutionMode::InProcess).await;
assert_eq!(got.recovered.len(), 1, "one recovery, no loop");
assert_eq!(got.fallbacks, 1);
assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent in-process");
eprintln!(
"permanent in-process: recovered from the checkpoint after step {}, {} records identical",
got.recovered[0],
got.records.len()
);
// Permanent, mid-run, as a process: the replacement is a new process, which must read the
// failure from the launcher's marker. With the fault armed in every process at the same
// batch, a replacement that re-attached the GPU would fail again about 50 frames after the
// restore (its warm-up is the same length, then 50 frames to the same batch).
reset();
unsafe { std::env::set_var("FLY_LIF_CUDA_FAULT", format!("batch={}", run_batches - 50)) };
let got = run(&dir, &plain, ExecutionMode::Process).await;
unsafe { std::env::remove_var("FLY_LIF_CUDA_FAULT") };
assert_eq!(got.recovered.len(), 1, "the replacement process stayed on the CPU");
assert_eq!(got.fallbacks, 1);
assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent process");
eprintln!(
"permanent process: recovered from the checkpoint after step {}, {} records identical",
got.recovered[0],
got.records.len()
);
reset();
}

View file

@ -1,176 +0,0 @@
//! GPU-02: the legacy agent worker on the CUDA LIF backend, against the CPU reference, on the real
//! connectome.
//!
//! The worker steps a frame per `step_frame` call with the state left on the device, and syncs it
//! back only for `State.Capture`. This runs a FAFB scenario with every kind of step the session
//! takes -- frames with sugar, reward pulses and reinforcement, a rollback, a restore into a
//! fresh worker (and so a fresh backend fed by an imported checkpoint), full-state checkpoints --
//! through the worker on the GPU, in-process and as a process, at one and two sweep threads, and
//! requires every record (decision, telemetry, the transition's spike bitset digest, the full
//! state digest at each checkpoint) to equal `NeuralAgent` driven directly on the CPU.
//!
//! An explicit job: `--features cuda`, `FLY_GPU02_CUDA=1`, a visible device and `data/fafb-v783`.
//! `FLY_GPU02_FRAMES` sets the length (default 300 frames, about 5,000 ticks). The worker picks the
//! GPU up from `FLY_LIF_CUDA=1`, set here before any worker starts. A host that cannot attach the
//! backend now falls back to the CPU (GPU-02 notes, `cuda_fallback.rs`), so this test asserts that
//! no fallback was recorded: a pass on the CPU would mean nothing.
#![cfg(feature = "cuda")]
use std::sync::Arc;
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity::{
self, DirectSource, LegacyRig, LegacyScript, ReferenceSource, RewardEvent, RigAgent,
ScriptStep, fafb_dir, frame_pool,
};
use fly_session::types::id;
use fly_session_types::gameboy::{Location, ReadoutContext};
use flybrain_core::dataset::load_brain_dataset_from_dir;
fn pokered_channels() -> Vec<String> {
let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors");
file["cases"][1]["macroChannels"]
.as_array()
.expect("the Pokemon Red macro group")
.iter()
.map(|c| c.as_str().expect("a channel").to_owned())
.collect()
}
fn script(frames: usize) -> LegacyScript {
let channels = pokered_channels();
let bound = |k: usize| -> Vec<String> {
let take: &[usize] = match k % 120 {
0..20 => &[],
20..50 => &[0, 1, 9],
_ => &[1, 4, 5, 6],
};
take.iter().map(|i| channels[*i].clone()).collect()
};
let rollback_at = frames * 2 / 5;
let restore_at = frames * 7 / 10;
let mut steps = Vec::new();
for k in 1..=frames {
steps.push(ScriptStep::Frame {
sugar: if k % 97 == 12 { vec![400.0] } else { vec![] },
frame: k % 6,
rewards: if k % 11 == 0 {
vec![RewardEvent {
value: 0.5,
stimulation_ms: 120.0,
}]
} else {
vec![]
},
next_context: ReadoutContext {
boot: k < 10,
bound: bound(k),
location: (k > 5).then_some(Location {
area: 12,
x: 3 + (k / 40) as u32,
y: 7,
}),
},
});
if k == rollback_at {
steps.push(ScriptStep::Rollback {
frame: 2,
context: ReadoutContext {
boot: false,
bound: bound(k),
location: None,
},
});
}
if k == restore_at {
steps.push(ScriptStep::Restore);
}
}
let last = steps.len() - 1;
let checkpoints = (0..steps.len())
.filter(|i| i % 50 == 49)
.chain([last])
.collect();
LegacyScript {
name: "gpu02-fafb".to_owned(),
macro_channels: channels,
frames: Arc::new(frame_pool(6, 783)),
initial_frame: 0,
initial_context: ReadoutContext {
boot: true,
bound: vec![],
location: None,
},
steps,
checkpoints,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_gpu_worker_matches_the_cpu_reference_on_fafb() {
if std::env::var_os("FLY_GPU02_CUDA").is_none() {
eprintln!("skipping: FLY_GPU02_CUDA is not set");
return;
}
let Some(dir) = fafb_dir() else {
eprintln!("skipping: data/fafb-v783 is not present in this checkout");
return;
};
let frames = std::env::var("FLY_GPU02_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(300);
let script = script(frames);
let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads"));
let started = std::time::Instant::now();
let want = DirectSource { dataset }
.records(&script)
.expect("the CPU reference runs");
eprintln!(
"cpu reference: {} records in {:?}, digest {}",
want.len(),
started.elapsed(),
legacy_parity::golden_json(&script, &want)["digest"]
);
// SAFETY: the only test in this binary, and no worker (thread or child) exists yet; every
// worker started from here on reads the switch through `LifBackend::from_env`.
unsafe { std::env::set_var("FLY_LIF_CUDA", "1") };
for (mode, threads) in [
(ExecutionMode::InProcess, 1),
(ExecutionMode::InProcess, 2),
(ExecutionMode::Process, 2),
] {
let started = std::time::Instant::now();
let root = tempfile::tempdir().expect("tmp");
let agent = RigAgent {
agent_id: id("fly-a"),
port_id: id("p1"),
dataset_dir: dir.clone(),
profile: LegacyProfileKind::Production,
macro_channels: script.macro_channels.clone(),
worker_threads: threads,
};
let mut rig = LegacyRig::start(root.path(), mode, &[agent])
.await
.expect("the rig");
let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script)
.await
.unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label()));
assert_eq!(
rig.gpu_fallbacks(),
0,
"{} x{threads}: the GPU did not attach, so this ran on the CPU",
mode.label()
);
rig.stop().await;
legacy_parity::compare(&want, &got)
.unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label()));
eprintln!(
"gpu worker {} x{threads}: {} records identical to the CPU in {:?}",
mode.label(),
got.len(),
started.elapsed()
);
}
}

View file

@ -1,75 +0,0 @@
//! BUS-01 review N2: a worker process never outlives its parent, outside systemd too.
//!
//! The test re-executes its own binary as the "parent" (selected by an environment variable),
//! which spawns one worker through the launcher's `die_with_parent` and one plain control child,
//! then waits. The outer test `kill -9`s the parent and checks the worker is gone within a bound
//! while the control child, which has no death signal, survives (so the check can fail).
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
const ROLE: &str = "FLY_TEST_ORPHAN_PARENT";
const BOUND: Duration = Duration::from_secs(5);
/// True while `pid` is a live process (a zombie awaiting its reaper counts as gone).
fn alive(pid: u32) -> bool {
match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
Ok(stat) => {
let state = stat.rsplit(')').next().unwrap_or("").trim().chars().next();
state != Some('Z') && state != Some('X')
}
Err(_) => false,
}
}
fn wait_gone(pid: u32) -> bool {
let start = Instant::now();
while start.elapsed() < BOUND {
if !alive(pid) {
return true;
}
std::thread::sleep(Duration::from_millis(50));
}
false
}
#[test]
fn a_killed_parent_takes_its_workers_with_it() {
if std::env::var_os(ROLE).is_some() {
// The parent: spawn a protected worker and an unprotected control, report, then wait.
let mut worker = Command::new("sleep");
worker.arg("300");
fly_session::launcher::die_with_parent(&mut worker);
let mut worker = worker.spawn().unwrap();
let mut control = Command::new("sleep").arg("300").spawn().unwrap();
println!("{} {}", worker.id(), control.id());
let _ = worker.wait();
let _ = control.wait();
return;
}
let mut parent = Command::new(std::env::current_exe().unwrap())
.args(["--exact", "a_killed_parent_takes_its_workers_with_it", "--nocapture", "--test-threads=1"])
.env(ROLE, "1")
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut lines = BufReader::new(parent.stdout.take().unwrap()).lines();
let (worker, control) = loop {
let line = lines.next().expect("the parent reports its children").unwrap();
let ids: Vec<u32> = line.split_whitespace().filter_map(|t| t.parse().ok()).collect();
if ids.len() == 2 {
break (ids[0], ids[1]);
}
};
assert!(alive(worker) && alive(control));
// SIGKILL: no cleanup runs in the parent, so only the kernel can take the worker down.
unsafe { libc::kill(parent.id() as i32, libc::SIGKILL) };
parent.wait().unwrap();
let worker_gone = wait_gone(worker);
let control_survived = alive(control);
unsafe { libc::kill(control as i32, libc::SIGKILL) };
unsafe { libc::kill(worker as i32, libc::SIGKILL) };
assert!(worker_gone, "the worker outlived its killed parent");
assert!(control_survived, "the control child should have survived (the check cannot fail otherwise)");
}

View file

@ -29,7 +29,6 @@ libc = "0.2"
[dev-dependencies]
base64.workspace = true
tempfile = "3"
[[example]]
name = "bench"

View file

@ -21,23 +21,13 @@
//! ```
//!
//! Optional arguments: a dataset directory, then the tick count, then the CPU thread count for the
//! reference run (default 4), then the mode: `tick` (the default, above) or `frame`.
//!
//! `frame` is the session runtime's shape since GPU-02: both sides step a game frame (16 or 17
//! ticks) per [`LifNetwork::step_frame`] call, the GPU with device-owned state, so `membrane` and
//! `refractory` stay on the card. After every frame the frame's spike bitset and everything the
//! host keeps (the spike stamps, the RNG, the clock, the rates, the plasticity) are compared;
//! `membrane` and `refractory` only at the checkpoints the session would take: every 60 frames
//! through `export_state` while the host copy is stale (the download path), and every 300 frames
//! after `sync_host` (the capture path), plus a checkpoint round trip (the GPU network imports the
//! CPU's exported state halfway). The device-owned run's PCIe traffic per frame is printed.
//! `FLY_LIF_CUDA_DEVICE` picks the card in both modes (default 0).
//! reference run (default 4).
use std::sync::Arc;
use std::time::Instant;
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::lif::{LifBackend, LifConfig, LifNetwork, LifState, SweepPlan};
use flybrain_core::lif::{LifConfig, LifNetwork, SweepPlan};
use flybrain_core::plasticity::PlasticityConfig;
#[cfg(feature = "cuda")]
@ -111,95 +101,6 @@ fn scalar(what: &str, tick: u64, cpu: f64, gpu: f64) -> Option<Divergence> {
})
}
/// Every field of two exported states, in a fixed order; the first difference.
fn compare_states(
tick: u64,
role_names: &[String],
left: &LifState,
right: &LifState,
) -> Option<Divergence> {
compare_f32("membrane", tick, &left.membrane, &right.membrane)
.or_else(|| {
left.refractory
.iter()
.zip(right.refractory.iter())
.position(|(a, b)| a != b)
.map(|index| Divergence {
tick,
what: format!(
"refractory[{index}]: cpu {} vs gpu {}",
left.refractory[index], right.refractory[index]
),
})
})
.or_else(|| {
compare_f64(
"lastSpikeMs",
tick,
&left.last_spike_ms,
&right.last_spike_ms,
)
})
.or_else(|| scalar("ms", tick, left.ms, right.ms))
.or_else(|| {
scalar(
"populationRate",
tick,
left.population_rate,
right.population_rate,
)
})
.or_else(|| {
scalar(
"rewardRemaining",
tick,
left.reward_remaining,
right.reward_remaining,
)
})
.or_else(|| {
(left.rng != right.rng).then(|| Divergence {
tick,
what: format!("rng: cpu {} vs gpu {}", left.rng, right.rng),
})
})
.or_else(|| {
role_names.iter().find_map(|name| {
scalar(
&format!("rate {name}"),
tick,
left.rates.get_or_zero(name),
right.rates.get_or_zero(name),
)
})
})
.or_else(|| {
compare_f32(
"plasticity.gains",
tick,
&left.plasticity.gains,
&right.plasticity.gains,
)
})
.or_else(|| {
compare_f32(
"plasticity.traces",
tick,
&left.plasticity.traces,
&right.plasticity.traces,
)
})
.or_else(|| {
compare_f64(
"plasticity.touched",
tick,
&left.plasticity.touched,
&right.plasticity.touched,
)
})
}
#[cfg(not(feature = "cuda"))]
fn main() {
eprintln!("cuda_exact: build with --features cuda");
@ -220,14 +121,6 @@ fn main() {
.next()
.and_then(|value| value.parse().ok())
.unwrap_or(4);
let mode = args.next().unwrap_or_else(|| "tick".to_string());
let device = match LifBackend::from_values(
Some("1"),
std::env::var("FLY_LIF_CUDA_DEVICE").ok().as_deref(),
) {
Ok(LifBackend::Cuda { device }) => device,
other => panic!("FLY_LIF_CUDA_DEVICE: {other:?}"),
};
let data = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset must load"));
println!(
@ -236,11 +129,6 @@ fn main() {
data.meta.neurons,
data.targets.len()
);
match mode.as_str() {
"tick" => {}
"frame" => return frame_mode(&data, ticks, threads, device),
other => panic!("mode {other}: expected tick or frame"),
}
let build = || {
LifNetwork::new(
@ -254,7 +142,7 @@ fn main() {
let mut gpu = build();
cpu.set_sweep_plan(SweepPlan::with_threads(threads).expect("a pool"));
let backend = CudaLif::new(&gpu, device).expect("the CUDA backend must start");
let backend = CudaLif::new(&gpu, 0).expect("the CUDA backend must start");
println!(
"cuda backend up: {:.1} MiB of device memory, max {} ticks per call",
backend.device_bytes as f64 / (1024.0 * 1024.0),
@ -325,7 +213,85 @@ fn main() {
let left = cpu.export_state();
let right = gpu.export_state();
divergence = compare_states(tick, &cpu.role_names, &left, &right);
divergence = compare_f32("membrane", tick, &left.membrane, &right.membrane)
.or_else(|| {
left.refractory
.iter()
.zip(right.refractory.iter())
.position(|(a, b)| a != b)
.map(|index| Divergence {
tick,
what: format!(
"refractory[{index}]: cpu {} vs gpu {}",
left.refractory[index], right.refractory[index]
),
})
})
.or_else(|| {
compare_f64(
"lastSpikeMs",
tick,
&left.last_spike_ms,
&right.last_spike_ms,
)
})
.or_else(|| scalar("ms", tick, left.ms, right.ms))
.or_else(|| {
scalar(
"populationRate",
tick,
left.population_rate,
right.population_rate,
)
})
.or_else(|| {
scalar(
"rewardRemaining",
tick,
left.reward_remaining,
right.reward_remaining,
)
})
.or_else(|| {
(left.rng != right.rng).then(|| Divergence {
tick,
what: format!("rng: cpu {} vs gpu {}", left.rng, right.rng),
})
})
.or_else(|| {
cpu.role_names.iter().find_map(|name| {
scalar(
&format!("rate {name}"),
tick,
left.rates.get_or_zero(name),
right.rates.get_or_zero(name),
)
})
})
.or_else(|| {
compare_f32(
"plasticity.gains",
tick,
&left.plasticity.gains,
&right.plasticity.gains,
)
})
.or_else(|| {
compare_f32(
"plasticity.traces",
tick,
&left.plasticity.traces,
&right.plasticity.traces,
)
})
.or_else(|| {
compare_f64(
"plasticity.touched",
tick,
&left.plasticity.touched,
&right.plasticity.touched,
)
});
if divergence.is_some() {
break;
}
@ -361,147 +327,3 @@ fn main() {
}
}
}
/// The session's shape: a frame per call, device-owned state, full state only at checkpoints.
#[cfg(feature = "cuda")]
fn frame_mode(data: &Arc<flybrain_core::dataset::BrainDataset>, ticks: u64, threads: usize, device: usize) {
const EXPORT_EVERY: u64 = 60;
const SYNC_EVERY: u64 = 300;
let build = || {
LifNetwork::new(
Arc::clone(data),
LifConfig::default(),
PlasticityConfig::default(),
)
.expect("a network")
};
let mut cpu = build();
let mut gpu = build();
cpu.configure_sweep(SweepPlan::with_threads(threads).expect("a pool"));
gpu.set_backend(LifBackend::Cuda { device })
.expect("the CUDA backend must start");
println!("frame mode: gpu backend {}, device-owned state", gpu.backend().label());
let frames = frame_pool(24, 9_781);
let neurons = data.meta.neurons;
let count = ticks.div_ceil(FRAME_TICKS);
let started = Instant::now();
let mut divergence: Option<Divergence> = None;
let mut total_spikes = 0u64;
let mut gpu_ns = 0u128;
let mut cpu_ns = 0u128;
let mut tick = 0u64;
let mut exports = 0u64;
let mut syncs = 0u64;
for frame in 0..count {
let image = &frames[frame as usize % frames.len()];
cpu.set_visual_frame(image, FRAME_WIDTH, FRAME_HEIGHT);
gpu.set_visual_frame(image, FRAME_WIDTH, FRAME_HEIGHT);
if frame % (STIMULATE_EVERY / FRAME_TICKS) == 0 {
cpu.stimulate(12.0);
gpu.stimulate(12.0);
}
if frame > 0 && frame % (REWARD_EVERY / FRAME_TICKS) == 0 {
let ms = cpu.ms;
cpu.plasticity.reinforce(0.75, ms);
gpu.plasticity.reinforce(0.75, ms);
}
if frame == count / 2 {
// A checkpoint carried from the CPU into the GPU network mid-run.
let state = cpu.export_state();
gpu.import_state(&state).expect("the CPU's state imports");
}
// The session's tick count alternates 16 and 17 (548625/32768 ms per frame).
let step = if frame % 2 == 0 { FRAME_TICKS } else { FRAME_TICKS - 1 };
let mut want = vec![0u8; neurons.div_ceil(8)];
let mut got = vec![0u8; neurons.div_ceil(8)];
let at = Instant::now();
let cpu_spikes = cpu.step_frame(step, &mut want).expect("the CPU");
cpu_ns += at.elapsed().as_nanos();
let at = Instant::now();
let gpu_spikes = gpu.step_frame(step, &mut got).expect("the GPU frame");
gpu_ns += at.elapsed().as_nanos();
if let Some(fault) = gpu.take_backend_fault() {
panic!("the GPU backend detached itself: {fault}");
}
total_spikes += cpu_spikes;
tick += step;
if cpu_spikes != gpu_spikes || want != got {
let at = want.iter().zip(&got).position(|(a, b)| a != b);
divergence = Some(Divergence {
tick,
what: format!(
"frame {frame}: spikes cpu {cpu_spikes} vs gpu {gpu_spikes}, first bitset byte \
differing {at:?}"
),
});
break;
}
// What the host keeps, every frame, without touching the device's arrays.
let left = cpu.export_state();
let host = {
let mut copy = left.clone();
copy.last_spike_ms = gpu.last_spike_ms.clone();
copy.ms = gpu.ms;
copy.population_rate = gpu.population_rate;
copy.reward_remaining = gpu.reward_remaining();
copy.rng = gpu.rng_state();
copy.rates = gpu.rates.clone();
copy.plasticity = gpu.plasticity.export_state();
copy.visual_drive = gpu.visual_drive().to_vec();
copy
};
divergence = compare_states(tick, &cpu.role_names, &left, &host);
if divergence.is_some() {
break;
}
if frame % EXPORT_EVERY == EXPORT_EVERY - 1 {
assert!(!gpu.host_state_current(), "device-owned: the host lags between syncs");
divergence = compare_states(tick, &cpu.role_names, &left, &gpu.export_state());
exports += 1;
}
if divergence.is_none() && frame % SYNC_EVERY == SYNC_EVERY - 1 {
gpu.sync_host().expect("the capture sync");
assert!(gpu.host_state_current());
divergence = compare_f32("membrane (synced)", tick, &cpu.membrane, &gpu.membrane)
.or_else(|| {
(cpu.refractory != gpu.refractory).then(|| Divergence {
tick,
what: "refractory (synced) differs".to_string(),
})
});
syncs += 1;
}
if divergence.is_some() {
break;
}
}
let elapsed = started.elapsed().as_secs_f64();
let backend = gpu.cuda().expect("still attached");
let (up, down) = (backend.uploaded_bytes, backend.downloaded_bytes);
match divergence {
None => {
println!(
"PASS: {count} frames ({tick} ticks) bit-exact, {total_spikes} spikes, {elapsed:.1} s \
wall (frame per call, device-owned state; host state every frame, {exports} \
exports through the device download, {syncs} host syncs, one CPU->GPU import)"
);
println!(
" step_frame: cpu ({threads} threads) {:.3} ms/frame, gpu {:.3} ms/frame; PCIe \
{:.1} KB/frame up, {:.1} KB/frame down (syncs and the import included)",
cpu_ns as f64 / 1e6 / count as f64,
gpu_ns as f64 / 1e6 / count as f64,
up as f64 / 1024.0 / count as f64,
down as f64 / 1024.0 / count as f64,
);
}
Some(divergence) => {
println!(
"FAIL: first divergence at tick {} after {:.1} s",
divergence.tick, elapsed
);
println!(" {}", divergence.what);
std::process::exit(1);
}
}
}

View file

@ -220,10 +220,8 @@ impl NeuralAgent {
bail!("Agent is already warmed up");
}
self.network.plasticity.enabled = false;
// `try_step`, so a GPU backend that fails here is an error, not a panic; the CPU cannot.
let stepped = self.network.try_step(self.warmup_ms);
self.network.step(self.warmup_ms);
self.network.plasticity.enabled = true;
stepped?;
let rates = self.network.rates.clone();
self.decoder.calibrate(&rates);
if let Some(frame) = first_frame {

View file

@ -21,9 +21,6 @@ use crate::version::version_for;
#[cfg(feature = "cuda")]
pub mod cuda;
/// Whether the GPU may still be used in this process, and the fallback record.
pub mod health;
/// Version of the default configuration; kept verbatim so existing checkpoints stay loadable.
pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2";
@ -60,64 +57,6 @@ pub struct Stimulation {
pub drive: f64,
}
/// Which hardware runs the per-millisecond tick.
///
/// A deployment choice, like the sweep's thread count, and never part of the compatibility
/// string: the GPU tick is bit-exact with the CPU one (`lif/cuda.rs`), so a checkpoint moves
/// between the two in either direction. The CUDA variant needs the `cuda` feature; asking for it
/// in a build without the feature is an error from [`LifNetwork::set_backend`], never a silent CPU
/// run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LifBackend {
#[default]
Cpu,
/// The CUDA backend on device ordinal `device`, with device-owned state.
Cuda { device: usize },
}
impl LifBackend {
/// `FLY_LIF_CUDA=1` asks for the GPU, on device `FLY_LIF_CUDA_DEVICE` (an ordinal, default 0).
/// Any other value of `FLY_LIF_CUDA`, or none, is the CPU, as it always was.
pub fn from_env() -> std::result::Result<LifBackend, String> {
Self::from_values(
std::env::var("FLY_LIF_CUDA").ok().as_deref(),
std::env::var("FLY_LIF_CUDA_DEVICE").ok().as_deref(),
)
}
/// [`LifBackend::from_env`] over explicit values. A device that is not an ordinal is refused
/// rather than read as 0.
pub fn from_values(
cuda: Option<&str>,
device: Option<&str>,
) -> std::result::Result<LifBackend, String> {
if cuda.map(str::trim) != Some("1") {
return Ok(LifBackend::Cpu);
}
let device = match device.map(str::trim) {
None | Some("") => 0,
Some(text) => text.parse::<usize>().map_err(|_| {
format!("FLY_LIF_CUDA_DEVICE={text}: expected a device ordinal (0, 1, ...)")
})?,
};
Ok(LifBackend::Cuda { device })
}
/// `cpu` or `cuda:<device>`, for logs.
pub fn label(&self) -> String {
match self {
LifBackend::Cpu => "cpu".to_string(),
LifBackend::Cuda { device } => format!("cuda:{device}"),
}
}
/// Whether this build carries the CUDA backend at all.
pub const fn cuda_compiled() -> bool {
cfg!(feature = "cuda")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LifConfig {
/// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`.
@ -336,12 +275,7 @@ pub struct LifNetwork {
/// Version string of this configuration; pin it in checkpoints.
pub version: String,
pub plasticity: RewardModulatedStdp,
/// Membrane potentials. **Stale while a device-owned GPU backend is attached** and
/// `cuda().is_some_and(|b| b.host_stale())`: the device holds the current copy until
/// [`LifNetwork::sync_host`]. Read it only after a `sync_host`, or use
/// [`LifNetwork::export_state`], which reads the device itself.
pub membrane: Vec<f32>,
/// Refractory counters; stale on the same terms as `membrane`.
pub refractory: Vec<u8>,
pub baseline: Vec<f32>,
pub last_spike_ms: Vec<f64>,
@ -377,8 +311,6 @@ pub struct LifNetwork {
visual_drive: Vec<f32>,
reward_remaining: f64,
sweep: SweepPlan,
/// Why the GPU backend was detached mid-run, until [`LifNetwork::take_backend_fault`].
backend_fault: Option<String>,
/// When set, [`LifNetwork::step`] runs steps 1-4 and 6 on the GPU; see [`cuda`].
#[cfg(feature = "cuda")]
cuda: Option<Box<cuda::CudaLif>>,
@ -491,7 +423,6 @@ impl LifNetwork {
timings: PhaseTimings::default(),
data,
sweep: SweepPlan::sequential(),
backend_fault: None,
#[cfg(feature = "cuda")]
cuda: None,
})
@ -504,87 +435,18 @@ impl LifNetwork {
/// Choose how the per-tick parallel phases are partitioned. Results do not depend on this.
pub fn set_sweep_plan(&mut self, sweep: SweepPlan) {
self.configure_sweep(sweep);
// Test hook: with the `cuda` feature compiled in *and* `FLY_LIF_CUDA=1` in the
// environment, configuring a sweep plan also attaches the GPU backend, syncing the host
// arrays every batch. That is how the existing golden suite is run through the GPU
// without editing a single test. Both conditions are off by default, and with the
// feature absent this line does not exist. A host that picks its backend itself (the
// session runtime) calls `configure_sweep` and `set_backend` instead.
#[cfg(feature = "cuda")]
self.attach_cuda_if_requested();
}
/// [`LifNetwork::set_sweep_plan`] without the `FLY_LIF_CUDA` test hook.
pub fn configure_sweep(&mut self, sweep: SweepPlan) {
let threads = sweep.threads();
self.target_shards = target_shards(&self.data, threads);
self.slot_shards = self.plasticity.slot_shards(threads);
self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data);
self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect();
self.sweep = sweep;
}
/// Run the tick on `backend` from now on. Results do not depend on this.
///
/// [`LifBackend::Cuda`] attaches the GPU backend with device-owned state (or switches one the
/// test hook attached to it): the host's `membrane` and `refractory` then lag the device
/// until [`LifNetwork::sync_host`], and [`LifNetwork::export_state`] reads the device itself
/// while they do. [`LifBackend::Cpu`] syncs and detaches. A build without the `cuda` feature
/// refuses `Cuda` rather than running the CPU kernel under a GPU label.
pub fn set_backend(&mut self, backend: LifBackend) -> Result<()> {
match backend {
LifBackend::Cpu => {
// Spike hook: with the `cuda` feature compiled in *and* `FLY_LIF_CUDA=1` in the
// environment, configuring a sweep plan also attaches the GPU backend. That is how the
// existing golden suite is run through the GPU without editing a single test. Both
// conditions are off by default, and with the feature absent this line does not exist.
#[cfg(feature = "cuda")]
if self.cuda.is_some() {
self.sync_host()?;
self.cuda = None;
}
Ok(())
}
#[cfg(feature = "cuda")]
LifBackend::Cuda { device } => self.attach_device_owned(device),
#[cfg(not(feature = "cuda"))]
LifBackend::Cuda { device } => bail!(
"the CUDA LIF backend (device {device}) was requested, but this build has no \
`cuda` feature"
),
}
}
/// The backend the tick runs on now.
pub fn backend(&self) -> LifBackend {
#[cfg(feature = "cuda")]
if let Some(backend) = self.cuda.as_deref() {
return LifBackend::Cuda {
device: backend.ordinal(),
};
}
LifBackend::Cpu
}
/// Why the GPU backend detached itself during a step, once; `None` if it never did.
pub fn take_backend_fault(&mut self) -> Option<String> {
self.backend_fault.take()
}
/// Whether the host's `membrane` and `refractory` are current. Always true on the CPU.
pub fn host_state_current(&self) -> bool {
#[cfg(feature = "cuda")]
if let Some(backend) = self.cuda.as_deref() {
return !backend.host_stale();
}
true
}
/// Bring the host's `membrane` and `refractory` up to date with the device: a no-op on the
/// CPU or when they already are. The session calls it before a capture, so the full state
/// crosses PCIe only at checkpoints.
pub fn sync_host(&mut self) -> Result<()> {
#[cfg(feature = "cuda")]
return self.sync_host_from_cuda();
#[cfg(not(feature = "cuda"))]
Ok(())
self.attach_cuda_if_requested();
}
pub fn sweep_plan(&self) -> &SweepPlan {
@ -646,10 +508,11 @@ impl LifNetwork {
self.stimulate(duration_ms);
}
/// Run `milliseconds` ticks and return the total spike count.
/// The neurons the last CPU tick emitted, when `count` is what that one-tick
/// [`LifNetwork::step`] returned: exactly the neurons whose `last_spike_ms` it stamped, in the
/// sweep's order. `None` while the GPU backend runs the ticks, whose host copy of the list is
/// not kept per tick ([`LifNetwork::step_frame`] gathers the lists either way). A read-only view; it changes nothing a tick computes.
/// not kept per tick. A read-only view; it changes nothing a tick computes.
pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> {
#[cfg(feature = "cuda")]
if self.cuda.is_some() {
@ -658,18 +521,12 @@ impl LifNetwork {
self.spikes.get(..count)
}
/// Run `milliseconds` ticks and return the total spike count.
///
/// Panics if the GPU backend fails in a way the network cannot continue from; see
/// [`LifNetwork::try_step`].
pub fn step(&mut self, milliseconds: u64) -> u64 {
// The GPU backend runs the same ticks in batches and replays the host-side phases; with the
// feature off this compiles to nothing and the loop below is the whole method.
#[cfg(feature = "cuda")]
if self.cuda.is_some() {
return self
.step_on_cuda(milliseconds, None)
.unwrap_or_else(|error| panic!("CUDA LIF batch failed: {error}"));
return self.step_on_cuda(milliseconds);
}
let mut total = 0u64;
for _ in 0..milliseconds {
@ -678,59 +535,6 @@ impl LifNetwork {
total
}
/// [`LifNetwork::step`], returning a GPU failure the network cannot continue from instead of
/// panicking. On the CPU it cannot fail.
pub fn try_step(&mut self, milliseconds: u64) -> Result<u64> {
#[cfg(feature = "cuda")]
if self.cuda.is_some() {
return self.step_on_cuda(milliseconds, None);
}
Ok(self.step(milliseconds))
}
/// One frame's `ticks` ticks in one call, with every neuron that spiked in any of them OR-ed
/// into `spiked` (bit `n % 8` of byte `n / 8` for neuron `n`, the legacy feed's layout; the
/// caller zeroes it). Returns the total spike count.
///
/// On the CPU this is exactly `ticks` one-tick [`LifNetwork::step`] calls with each tick's
/// [`LifNetwork::tick_spikes`] gathered, which is what the session runtime did per frame. On
/// the GPU it is one batch: the inputs go up once, the spike lists come down once, and
/// `membrane` and `refractory` stay on the device (with device-owned state). An error means
/// the backend failed and the device held the only current state: the network has been
/// moved to the CPU kernel and must be restored from a checkpoint before it steps again. A
/// failure it could continue from on the CPU is not an error; see
/// [`LifNetwork::take_backend_fault`].
pub fn step_frame(&mut self, ticks: u64, spiked: &mut [u8]) -> Result<u64> {
let neurons = self.data.meta.neurons;
if spiked.len() < neurons.div_ceil(8) {
bail!(
"a spike bitset of {} bytes cannot hold {neurons} neurons",
spiked.len()
);
}
#[cfg(feature = "cuda")]
if self.cuda.is_some() {
return self.step_on_cuda(ticks, Some(spiked));
}
let mut total = 0u64;
for _ in 0..ticks {
total += self.step_one_into(Some(&mut *spiked)) as u64;
}
Ok(total)
}
/// One CPU tick, with its spike list OR-ed into `spiked` when given.
#[inline]
fn step_one_into(&mut self, spiked: Option<&mut [u8]>) -> usize {
let count = self.step_one();
if let Some(bits) = spiked {
for &neuron in &self.spikes[..count] {
bits[neuron as usize >> 3] |= 1 << (neuron & 7);
}
}
count
}
fn step_one(&mut self) -> usize {
let neurons = self.data.meta.neurons;
let threshold = self.config.threshold;
@ -993,15 +797,10 @@ impl LifNetwork {
total
}
/// A copy of the whole state. With a device-owned GPU backend whose host arrays are stale,
/// `membrane` and `refractory` are downloaded for the copy (and the host left as it is); a
/// caller that can handle the failure calls [`LifNetwork::sync_host`] first. Panics if that
/// download fails, because a checkpoint of stale arrays would be silently wrong.
pub fn export_state(&self) -> LifState {
let (membrane, refractory) = self.current_arrays();
LifState {
membrane,
refractory,
membrane: self.membrane.clone(),
refractory: self.refractory.clone(),
last_spike_ms: self.last_spike_ms.clone(),
visual_drive: self.visual_drive.clone(),
rng: self.rng.state(),
@ -1013,18 +812,6 @@ impl LifNetwork {
}
}
/// Copies of `membrane` and `refractory` as they are now: the host's, or the device's while
/// the host's are stale.
fn current_arrays(&self) -> (Vec<f32>, Vec<u8>) {
#[cfg(feature = "cuda")]
if let Some(downloaded) = self.stale_device_state() {
return downloaded.unwrap_or_else(|error| {
panic!("the device state cannot be read back for export: {error}")
});
}
(self.membrane.clone(), self.refractory.clone())
}
/// Import plasticity first, then validate before writing anything.
pub fn import_state(&mut self, state: &LifState) -> Result<()> {
if state.membrane.len() != self.membrane.len()

View file

@ -38,19 +38,10 @@
//! # State ownership
//!
//! Between batches the device owns `membrane` and `refractory`. With
//! [`CudaLif::sync_host_each_batch`] set (the default for a backend built with [`CudaLif::new`])
//! they are copied back at the end of every batch, which keeps direct reads of the network's host
//! arrays correct with no further changes: that is what `examples/cuda_exact`'s per-tick mode and
//! the `FLY_LIF_CUDA=1` golden-suite hook rely on.
//!
//! Cleared (what [`LifNetwork::set_backend`] attaches, and what the session runtime runs), the
//! device is the only up-to-date copy between host syncs and the host arrays are *stale*
//! ([`CudaLif::host_stale`]). Per frame only the batch's inputs go up (the noise draws, the visual
//! drive, the plastic gains) and its spike lists come down; [`LifNetwork::sync_host`] copies the
//! two arrays back before a checkpoint, and [`LifNetwork::export_state`] downloads them itself
//! when the host is stale, so a capture can never read old values. That is the difference between
//! about 24 MB and about 0.2 MB over PCIe per frame when the caller steps one tick per call
//! (GPU-01, section 2), and about 1.4 MB vs 0.2 MB when it steps a frame per call.
//! [`CudaLif::sync_host_each_batch`] set (the default) they are copied back at the end of every
//! batch, which keeps `export_state`, the status endpoints and every existing test correct with no
//! further changes. Clear it for throughput work and call [`CudaLif::sync_to_host`] explicitly
//! before a checkpoint.
use std::sync::Arc;
@ -64,88 +55,6 @@ use crate::error::{Error, Result};
use super::LifNetwork;
/// Fault injection for the failure path: a CUDA error raised where a real one would surface, so
/// the fallback can be tested and drilled without breaking a card. Off unless armed. Armed by
/// `FLY_LIF_CUDA_FAULT` (read once, by the first backend built) or by the setters; a comma list of
/// `init` (every attach fails, as with a lost device), `batch=N` (the N-th batch of this process,
/// counted from 0, fails after its kernels ran) and `sync=N` (the N-th device download).
pub mod inject {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::OnceLock;
const NEVER: u64 = u64::MAX;
static INIT: AtomicBool = AtomicBool::new(false);
static BATCH_AT: AtomicU64 = AtomicU64::new(NEVER);
static SYNC_AT: AtomicU64 = AtomicU64::new(NEVER);
static BATCHES: AtomicU64 = AtomicU64::new(0);
static SYNCS: AtomicU64 = AtomicU64::new(0);
static ENV: OnceLock<()> = OnceLock::new();
pub(super) fn load_env() {
ENV.get_or_init(|| {
let Ok(spec) = std::env::var("FLY_LIF_CUDA_FAULT") else {
return;
};
for item in spec.split(',').map(str::trim) {
match item.split_once('=') {
None if item == "init" => INIT.store(true, Ordering::SeqCst),
Some(("batch", n)) => BATCH_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst),
Some(("sync", n)) => SYNC_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst),
_ => eprintln!("FLY_LIF_CUDA_FAULT: ignoring {item:?}"),
}
}
});
}
/// Every attach fails from now on (a lost device), or stops failing.
pub fn fail_attach(on: bool) {
INIT.store(on, Ordering::SeqCst);
}
/// The batch that is `after` batches from now fails, once.
pub fn fail_batch_after(after: u64) {
BATCH_AT.store(BATCHES.load(Ordering::SeqCst) + after, Ordering::SeqCst);
}
/// The device download that is `after` downloads from now fails, once.
pub fn fail_sync_after(after: u64) {
SYNC_AT.store(SYNCS.load(Ordering::SeqCst) + after, Ordering::SeqCst);
}
/// Batches this process has launched so far (a warm-up is many; a game frame is one).
pub fn batches() -> u64 {
BATCHES.load(Ordering::SeqCst)
}
/// Disarms everything.
pub fn clear() {
INIT.store(false, Ordering::SeqCst);
BATCH_AT.store(NEVER, Ordering::SeqCst);
SYNC_AT.store(NEVER, Ordering::SeqCst);
}
pub(super) fn attach() -> super::Result<()> {
load_env();
if INIT.load(Ordering::SeqCst) {
return Err(super::Error::new(
"CUDA init failed: injected fault (CUDA_ERROR_NO_DEVICE)",
));
}
Ok(())
}
fn hit(counter: &AtomicU64, at: &AtomicU64, what: &str) -> super::Result<()> {
let n = counter.fetch_add(1, Ordering::SeqCst);
if n == at.load(Ordering::SeqCst) {
return Err(super::Error::new(format!(
"CUDA {what} failed: injected fault #{n} (CUDA_ERROR_LAUNCH_FAILED)"
)));
}
Ok(())
}
pub(super) fn batch() -> super::Result<()> {
hit(&BATCHES, &BATCH_AT, "batch")
}
pub(super) fn sync() -> super::Result<()> {
hit(&SYNCS, &SYNC_AT, "download")
}
}
/// Threads per block, and therefore neurons per block in the sweep and the compaction. Must match
/// `LIF_BLOCK` in `cuda/lif.cu`, because the spike bitset words are per-warp ballots.
const BLOCK: u32 = 256;
@ -180,12 +89,6 @@ const DEFAULT_MAX_TICKS: usize = 32;
/// neither the build nor the run needs a CUDA toolkit.
const LIF_PTX: &str = include_str!("../../cuda/lif.ptx");
/// A failed batch, and whether the host phases had already been replayed when it failed.
struct BatchFailure {
error: Error,
replayed: bool,
}
fn driver_error(what: &str, error: impl std::fmt::Display) -> Error {
Error::new(format!("CUDA {what} failed: {error}"))
}
@ -246,7 +149,6 @@ pub struct CudaLif {
bucket_rebase_kernel: CudaFunction,
bucket_apply_kernel: CudaFunction,
ordinal: usize,
neurons: usize,
blocks: u32,
max_ticks: usize,
@ -299,14 +201,7 @@ pub struct CudaLif {
host_tick_counts: Vec<u32>,
host_spikes: Vec<u32>,
stimulation_schedule: Vec<bool>,
/// The host arrays were overwritten (an import); upload them before the next batch.
host_dirty: bool,
/// The device ran ticks the host arrays have not seen: `membrane` and `refractory` on the
/// host are older than the device's. Never set while `sync_host_each_batch` holds.
host_stale: bool,
/// Bytes copied host to device and device to host by the batches, for the PCIe budget.
pub uploaded_bytes: u64,
pub downloaded_bytes: u64,
/// Copy `membrane` and `refractory` back at the end of every batch. On by default, so the rest
/// of the crate sees the same host state it would have seen from the CPU kernel.
@ -344,7 +239,6 @@ impl CudaLif {
}
pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result<Self> {
inject::attach()?;
let max_ticks = max_ticks.max(1);
let neurons = network.data.meta.neurons;
if neurons == 0 {
@ -495,7 +389,6 @@ impl CudaLif {
bucket_rebase_kernel: function("lif_bucket_rebase")?,
bucket_apply_kernel: function("lif_bucket_apply")?,
ordinal,
neurons,
blocks,
max_ticks,
@ -510,9 +403,6 @@ impl CudaLif {
host_spikes: Vec::new(),
stimulation_schedule: vec![false; max_ticks],
host_dirty: false,
host_stale: false,
uploaded_bytes: 0,
downloaded_bytes: 0,
batch_start: context
.new_event(Some(CUevent_flags::CU_EVENT_DEFAULT))
.map_err(|error| driver_error("event creation", error))?,
@ -539,33 +429,19 @@ impl CudaLif {
Ok(backend)
}
/// The device ordinal this backend runs on.
pub fn ordinal(&self) -> usize {
self.ordinal
}
/// Ticks this backend accepts per call.
pub fn max_ticks(&self) -> usize {
self.max_ticks
}
/// The host copies of `membrane` and `refractory` have been written; re-upload them before the
/// next batch. Called by [`LifNetwork::import_state`], which overwrites both arrays whole, so
/// the host is the current copy again.
/// next batch. Called by [`LifNetwork::import_state`].
pub fn mark_host_dirty(&mut self) {
self.host_dirty = true;
self.host_stale = false;
}
/// Whether the device holds ticks the network's host `membrane` and `refractory` have not
/// seen. [`LifNetwork::sync_host`] clears it.
pub fn host_stale(&self) -> bool {
self.host_stale
}
/// Copy `membrane` and `refractory` from the device into the network's host arrays.
pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> {
inject::sync()?;
self.stream
.memcpy_dtoh(&self.membrane, &mut network.membrane[..])
.map_err(|error| driver_error("membrane download", error))?;
@ -574,28 +450,7 @@ impl CudaLif {
.map_err(|error| driver_error("refractory download", error))?;
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))?;
self.downloaded_bytes += (self.neurons * 5) as u64;
self.host_stale = false;
Ok(())
}
/// The device's `membrane` and `refractory`, copied out without touching the network: what
/// [`LifNetwork::export_state`] reads while the host arrays are stale.
pub fn download_state(&self) -> Result<(Vec<f32>, Vec<u8>)> {
inject::sync()?;
let mut membrane = vec![0.0f32; self.neurons];
let mut refractory = vec![0u8; self.neurons];
self.stream
.memcpy_dtoh(&self.membrane, &mut membrane[..])
.map_err(|error| driver_error("membrane download", error))?;
self.stream
.memcpy_dtoh(&self.refractory, &mut refractory[..])
.map_err(|error| driver_error("refractory download", error))?;
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))?;
Ok((membrane, refractory))
.map_err(|error| driver_error("synchronize", error))
}
fn upload_state(&mut self, network: &LifNetwork) -> Result<()> {
@ -605,61 +460,12 @@ impl CudaLif {
self.stream
.memcpy_htod(&network.refractory[..], &mut self.refractory)
.map_err(|error| driver_error("refractory upload", error))?;
self.uploaded_bytes += (self.neurons * 5) as u64;
self.host_dirty = false;
Ok(())
}
/// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce,
/// OR-ing every tick's spikes into `spiked` (bit `n` of byte `n / 8` for neuron `n`) when given.
///
/// Every fallible step comes before the replay. A failure therefore leaves the host-side state
/// exactly as it was at the start of the batch except for the RNG and the stimulation
/// countdown, which the caller saved ([`BatchFailure::replayed`] is false); only a failed
/// end-of-batch download in `sync_host_each_batch` mode comes after it.
fn run_batch(
&mut self,
network: &mut LifNetwork,
ticks: usize,
spiked: Option<&mut [u8]>,
) -> std::result::Result<usize, BatchFailure> {
let before = |error: Error| BatchFailure {
error,
replayed: false,
};
let spikes = self.run_device(network, ticks).map_err(before)?;
// The host phases, per tick, in the sequential kernel's order. From here on the device
// is ahead of the host arrays until the next sync.
self.host_stale = true;
let mut at = 0usize;
let mut spiked = spiked;
for tick in 0..ticks {
let count = self.host_tick_counts[tick] as usize;
let list = &self.host_spikes[at..at + count];
network.spikes[..count].copy_from_slice(list);
if let Some(bits) = spiked.as_deref_mut() {
for &neuron in list {
bits[neuron as usize >> 3] |= 1 << (neuron & 7);
}
}
at += count;
network.replay_host_phases(count);
}
if self.sync_host_each_batch {
self.sync_to_host(network).map_err(|error| BatchFailure {
error,
replayed: true,
})?;
}
Ok(spikes)
}
/// The fallible half of [`CudaLif::run_batch`]: draw, upload, launch, download the spike
/// lists. Touches nothing on the host but the RNG, the stimulation countdown and this
/// backend's own staging buffers.
fn run_device(&mut self, network: &mut LifNetwork, ticks: usize) -> Result<usize> {
/// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce.
fn run_batch(&mut self, network: &mut LifNetwork, ticks: usize) -> Result<usize> {
debug_assert!(ticks <= self.max_ticks);
let neurons = self.neurons;
@ -702,9 +508,7 @@ impl CudaLif {
// Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted
// into the transposed array's rank order.
let used = ticks * self.noise_kicks;
let mut uploaded = 0usize;
if used > 0 {
uploaded += used * 8;
let mut view = self.noise_neuron.slice_mut(0..used);
self.stream
.memcpy_htod(&self.host_noise_neuron[..used], &mut view)
@ -715,14 +519,12 @@ impl CudaLif {
.map_err(|error| driver_error("noise upload", error))?;
}
if !network.visual_drive.is_empty() {
uploaded += network.visual_drive.len() * 4;
let mut view = self.visual_drive.slice_mut(0..network.visual_drive.len());
self.stream
.memcpy_htod(&network.visual_drive[..], &mut view)
.map_err(|error| driver_error("visual drive upload", error))?;
}
if !network.plasticity.gains.is_empty() {
uploaded += network.plasticity.gains.len() * 4;
let mut view = self.gains.slice_mut(0..network.plasticity.gains.len());
self.stream
.memcpy_htod(&network.plasticity.gains[..], &mut view)
@ -744,7 +546,6 @@ impl CudaLif {
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))?;
inject::batch()?;
self.kernel_ms += f64::from(
self.batch_start
.elapsed_ms(&self.batch_end)
@ -782,9 +583,22 @@ impl CudaLif {
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))?;
self.uploaded_bytes += uploaded as u64;
self.downloaded_bytes += ((ticks + total) * 4) as u64;
Ok(total)
// The host phases, per tick, in the sequential kernel's order.
let mut at = 0usize;
let mut spikes = 0usize;
for tick in 0..ticks {
let count = self.host_tick_counts[tick] as usize;
network.spikes[..count].copy_from_slice(&self.host_spikes[at..at + count]);
at += count;
spikes += count;
network.replay_host_phases(count);
}
if self.sync_host_each_batch {
self.sync_to_host(network)?;
}
Ok(spikes)
}
/// Record phase mark `index` when phase profiling is on.
@ -1025,110 +839,37 @@ impl LifNetwork {
/// Attach a backend when `FLY_LIF_CUDA=1`, on device `FLY_LIF_CUDA_DEVICE` (default 0).
///
/// The test hook behind [`LifNetwork::set_sweep_plan`]: it attaches in
/// `sync_host_each_batch` mode, so every existing test that reads the host arrays directly runs
/// through the GPU unchanged. A host that chooses its backend itself uses
/// [`LifNetwork::configure_sweep`] and [`LifNetwork::set_backend`] instead.
///
/// Panics on a CUDA failure rather than falling back to the CPU: a run that asked for the GPU
/// and silently got the CPU would report a bit-exactness pass that means nothing.
pub(super) fn attach_cuda_if_requested(&mut self) {
if self.cuda.is_some() {
if self.cuda.is_some() || std::env::var("FLY_LIF_CUDA").as_deref() != Ok("1") {
return;
}
let Ok(super::LifBackend::Cuda { device }) = super::LifBackend::from_env() else {
return;
};
match CudaLif::new(self, device) {
let ordinal = std::env::var("FLY_LIF_CUDA_DEVICE")
.ok()
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(0);
match CudaLif::new(self, ordinal) {
Ok(backend) => self.attach_cuda(backend),
Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"),
}
}
/// Attach a device-owned backend on `device`, or switch an attached one to device-owned state.
pub(super) fn attach_device_owned(&mut self, device: usize) -> Result<()> {
if self.cuda.is_none() {
let backend = CudaLif::new(self, device)?;
self.attach_cuda(backend);
}
let backend = self.cuda.as_deref_mut().expect("attached");
backend.sync_host_each_batch = false;
Ok(())
}
/// Copy the device's `membrane` and `refractory` into the host arrays if they are stale.
pub(super) fn sync_host_from_cuda(&mut self) -> Result<()> {
let Some(mut backend) = self.cuda.take() else {
return Ok(());
};
let outcome = if backend.host_stale() {
backend.sync_to_host(self)
} else {
Ok(())
};
self.cuda = Some(backend);
outcome
}
/// The device arrays when the host's are stale; `None` when the host is current.
pub(super) fn stale_device_state(&self) -> Option<Result<(Vec<f32>, Vec<u8>)>> {
let backend = self.cuda.as_deref()?;
backend.host_stale().then(|| backend.download_state())
}
/// The batched GPU path behind [`LifNetwork::try_step`] and [`LifNetwork::step_frame`].
///
/// On a CUDA failure the backend is detached and the network is on the CPU kernel from then
/// on. If the host arrays were current when the failing batch started (the backend syncs
/// every batch, or nothing ran since the last sync or import), the RNG and the stimulation
/// countdown are put back and the remaining ticks run on the CPU: the result is bit-identical
/// to a run that never had a GPU, and the reason is left in
/// [`LifNetwork::take_backend_fault`]. Otherwise the device held the only current copy of
/// `membrane` and `refractory`, so the network is not resumable and the error is returned:
/// the caller restores it from its last checkpoint.
pub(super) fn step_on_cuda(
&mut self,
milliseconds: u64,
mut spiked: Option<&mut [u8]>,
) -> Result<u64> {
/// The batched GPU path behind [`LifNetwork::step`].
pub(super) fn step_on_cuda(&mut self, milliseconds: u64) -> u64 {
let mut backend = self.cuda.take().expect("a CUDA backend is attached");
let mut total = 0u64;
let mut left = milliseconds;
while left > 0 {
let ticks = left.min(backend.max_ticks() as u64) as usize;
let host_current = !backend.host_stale();
let (rng, reward_remaining) = (self.rng.state(), self.reward_remaining);
match backend.run_batch(self, ticks, spiked.as_deref_mut()) {
match backend.run_batch(self, ticks) {
Ok(spikes) => total += spikes as u64,
Err(failure) => {
drop(backend);
if host_current && !failure.replayed {
self.rng.set_state(rng);
self.reward_remaining = reward_remaining;
self.backend_fault = Some(format!(
"CUDA batch failed ({}); the backend is detached and the network \
continues on the CPU from the current host state",
failure.error
));
for _ in 0..left {
total += self.step_one_into(spiked.as_deref_mut()) as u64;
}
return Ok(total);
}
let message = format!(
"CUDA batch failed ({}); the backend is detached, and the device held the \
only current membrane since the last host sync, so this network must be \
restored from a checkpoint",
failure.error
);
self.backend_fault = Some(message.clone());
return Err(Error::new(message));
}
Err(error) => panic!("CUDA LIF batch failed: {error}"),
}
left -= ticks as u64;
}
self.cuda = Some(backend);
Ok(total)
total
}
/// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike

View file

@ -1,145 +0,0 @@
//! Whether this process may use the GPU for the LIF tick, and the record of why it may not.
//!
//! A GPU failure (a batch, a sync or an attach) is final for the process: [`record_fallback`]
//! marks the GPU unusable and every backend chosen afterwards is the CPU, so a dead or flaky
//! device is never re-attached in a loop. A restart is a new process and tries the device again;
//! if that attach fails it is a fallback too, not a crash. Checkpoints are backend-neutral, so
//! the CPU continues from the same state.
//!
//! The state is per process, and a worker that runs as a child process starts with none. The
//! launcher therefore points its children at a marker file ([`MARKER_ENV`]): each fallback
//! appends a line to it, and the file (not the child's memory) is then the record, shared by the
//! launcher's later workers. The launcher empties the file when it starts, which is what ends
//! the fallback with the process that owns it.
//!
//! [`render_prometheus`] and [`write_textfile`] expose it as `fly_brain_backend{backend=..}` and
//! `fly_brain_backend_fallbacks_total` for the watchdog.
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use super::LifBackend;
/// The marker file's path, set by the launcher for its worker processes.
pub const MARKER_ENV: &str = "FLY_LIF_GPU_MARKER";
/// Where [`write_textfile`] puts the metrics, if set: a node_exporter textfile-collector file.
pub const PROM_ENV: &str = "FLY_BRAIN_BACKEND_PROM";
/// The log line's stable prefix: what `fly-watchdog` and `fly-check` grep for.
pub const LOG_PREFIX: &str = "LIF_GPU_FALLBACK";
static FALLBACKS: AtomicU64 = AtomicU64::new(0);
static LAST_REASON: Mutex<Option<String>> = Mutex::new(None);
fn marker() -> Option<PathBuf> {
std::env::var_os(MARKER_ENV)
.filter(|path| !path.is_empty())
.map(PathBuf::from)
}
fn marker_lines(path: &Path) -> Vec<String> {
std::fs::read_to_string(path)
.map(|text| text.lines().map(str::to_owned).collect())
.unwrap_or_default()
}
/// Empties the marker: the launcher calls this when it starts, so a fallback lasts as long as the
/// process that owns the workers and not across a restart.
pub fn reset_marker(path: &Path) {
let _ = std::fs::remove_file(path);
}
/// Marks the GPU unusable for this process lifetime, counts the fallback and logs it as one
/// `LIF_GPU_FALLBACK` line on stderr (the journal).
pub fn record_fallback(reason: &str) {
let reason = reason.replace(['\n', '\r'], " ");
FALLBACKS.fetch_add(1, Ordering::SeqCst);
*LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = Some(reason.clone());
if let Some(path) = marker() {
if let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let _ = writeln!(file, "{reason}");
}
}
eprintln!("{LOG_PREFIX}: the GPU is unusable for this process, the LIF tick runs on the CPU from here on: {reason}");
}
/// True once any fallback was recorded, here or (with a marker) by a sibling worker.
pub fn gpu_unusable() -> bool {
fallbacks() > 0
}
/// Fallbacks recorded: the marker's lines when there is a marker, else this process's count.
pub fn fallbacks() -> u64 {
match marker() {
Some(path) => marker_lines(&path).len() as u64,
None => FALLBACKS.load(Ordering::SeqCst),
}
}
/// The fallbacks recorded in the marker file at `path` (what a launcher's worker processes wrote).
pub fn marker_fallbacks(path: &Path) -> u64 {
marker_lines(path).len() as u64
}
/// The latest fallback's reason.
pub fn last_reason() -> Option<String> {
match marker() {
Some(path) => marker_lines(&path).pop(),
None => LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()).clone(),
}
}
/// Clears this process's record (tests only; a marker is cleared with [`reset_marker`]).
#[doc(hidden)]
pub fn reset_for_tests() {
FALLBACKS.store(0, Ordering::SeqCst);
*LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// Prometheus text: which backend runs (`1` on exactly one of the two labels), which one was
/// asked for, and the fallbacks so far.
pub fn render_prometheus(active: LifBackend, wanted: LifBackend) -> String {
let on = |backend: &str, is: bool| {
format!("fly_brain_backend{{backend=\"{backend}\"}} {}\n", u8::from(is))
};
let cuda = matches!(active, LifBackend::Cuda { .. });
let mut out = String::new();
out.push_str("# HELP fly_brain_backend 1 for the hardware the LIF tick runs on, 0 for the other. cpu while FLY_LIF_CUDA=1 asks for cuda means the GPU fell back.\n# TYPE fly_brain_backend gauge\n");
out.push_str(&on("cpu", !cuda));
out.push_str(&on("cuda", cuda));
out.push_str(&format!(
"# HELP fly_brain_backend_wanted 1 when FLY_LIF_CUDA=1 asks for the GPU.\n# TYPE fly_brain_backend_wanted gauge\nfly_brain_backend_wanted {}\n",
u8::from(matches!(wanted, LifBackend::Cuda { .. }))
));
out.push_str(&format!(
"# HELP fly_brain_backend_fallbacks_total GPU failures that moved the LIF tick to the CPU (a failed batch or sync, or an attach that failed) since the process started.\n# TYPE fly_brain_backend_fallbacks_total counter\nfly_brain_backend_fallbacks_total {}\n",
fallbacks()
));
out
}
/// Writes [`render_prometheus`] to [`PROM_ENV`] (temp file and rename), if set. A failure is
/// reported on stderr and otherwise ignored: a metric must not stop the brain.
pub fn write_textfile(active: LifBackend, wanted: LifBackend) {
let Some(path) = std::env::var_os(PROM_ENV).filter(|p| !p.is_empty()) else {
return;
};
let path = PathBuf::from(path);
let tmp = path.with_extension(format!("prom.{}", std::process::id()));
let text = render_prometheus(active, wanted);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let written = std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &path));
if let Err(error) = written {
let _ = std::fs::remove_file(&tmp);
eprintln!("lif backend metric: cannot write {}: {error}", path.display());
}
}

View file

@ -33,9 +33,6 @@ type Job = dyn Fn(usize) + Sync;
/// (`1..workers`) runs on `WORKER_CPUS[i - 1]`. Unset -- the default, and always for the legacy
/// loop -- the workers float over the process's CPUs as they always have.
static WORKER_CPUS: OnceLock<Vec<usize>> = OnceLock::new();
/// The CPUs of the process's auxiliary threads (the bus runtime), when [`place_workers_aux`]
/// reserved some outside the sim's set.
static AUX_CPUS: OnceLock<Vec<usize>> = OnceLock::new();
struct Shared {
/// Bumped once per dispatch. A worker runs when this differs from what it last saw.
@ -299,111 +296,6 @@ pub fn place_workers(workers: usize) -> Option<Placement> {
Some(placement)
}
/// Splits `allowed` like [`split_cpus`], after taking `aux` out of it: `aux` must be a non-empty
/// subset of `allowed` and leave at least `workers` CPUs for the sim. Returns the sim's placement
/// (sweep workers, dispatcher and host, never an `aux` CPU) and the aux list. `None` otherwise.
pub fn split_cpus_aux(
allowed: &[usize],
workers: usize,
aux: &[usize],
) -> Option<(Placement, Vec<usize>)> {
let mut aux = aux.to_vec();
aux.sort_unstable();
aux.dedup();
if aux.is_empty() || aux.iter().any(|c| !allowed.contains(c)) {
return None;
}
let rest: Vec<usize> = allowed.iter().copied().filter(|c| !aux.contains(c)).collect();
Some((split_cpus(&rest, workers)?, aux))
}
/// [`place_workers`] with `aux` CPUs reserved for the process's auxiliary threads (the feed
/// publisher and the bus runtime): the sweep workers, the dispatcher and every ordinary thread
/// stay off them, and [`confine_to_aux`] (the bus runtime's `on_thread_start`) puts a thread on
/// them. `None`, and nothing changed, when `aux` is not a subset of the allowed CPUs, leaves too
/// few for the sim, or a placement was already made. Placement decides only the CPU.
pub fn place_workers_aux(workers: usize, aux: &[usize]) -> Option<(Placement, Vec<usize>)> {
if WORKER_CPUS.get().is_some() {
return None;
}
let (placement, aux) = split_cpus_aux(&affinity::allowed()?, workers, aux)?;
if !affinity::set_current(&placement.host) {
return None;
}
WORKER_CPUS.set(placement.workers.clone()).ok()?;
let _ = AUX_CPUS.set(aux.clone());
Some((placement, aux))
}
/// Confines the calling thread to the aux CPUs [`place_workers_aux`] reserved. A no-op (false)
/// when none were: the thread keeps what it inherited.
pub fn confine_to_aux() -> bool {
match AUX_CPUS.get() {
Some(aux) => affinity::set_current(aux),
None => false,
}
}
/// The aux CPUs reserved by [`place_workers_aux`], if any.
pub fn aux_cpus() -> Option<&'static [usize]> {
AUX_CPUS.get().map(Vec::as_slice)
}
/// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its
/// placement by the launcher, which split the service's cpuset, instead of splitting its own mask.
/// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and
/// pins worker `i` of every pool created afterwards to `placement.workers[i - 1]`. False, and
/// nothing changed, when the kernel refuses the host set, when a placement is already recorded,
/// or off Linux. Placement decides only the CPU: no result depends on it.
pub fn apply_placement(placement: &Placement) -> bool {
if WORKER_CPUS.get().is_some() || placement.host.is_empty() {
return false;
}
if !affinity::set_current(&placement.host) {
return false;
}
WORKER_CPUS.set(placement.workers.clone()).is_ok()
}
/// The CPUs the calling thread may run on (`sched_getaffinity`); `None` off Linux.
pub fn allowed_cpus() -> Option<Vec<usize>> {
affinity::allowed()
}
/// Confines the calling thread, and every thread it spawns afterwards, to `cpus`; false (and
/// unchanged) if the kernel refuses or off Linux.
pub fn confine_current(cpus: &[usize]) -> bool {
affinity::set_current(cpus)
}
/// A CPU list as `taskset` and cpusets write it: `1,3,5-7`.
pub fn parse_cpu_list(value: &str) -> Option<Vec<usize>> {
let mut cpus = Vec::new();
for part in value.split(',').map(str::trim).filter(|p| !p.is_empty()) {
match part.split_once('-') {
Some((a, b)) => {
let (a, b): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?);
if a > b {
return None;
}
cpus.extend(a..=b);
}
None => cpus.push(part.parse().ok()?),
}
}
cpus.sort_unstable();
cpus.dedup();
(!cpus.is_empty()).then_some(cpus)
}
/// The inverse of [`parse_cpu_list`], without ranges: `1,3,5`.
pub fn format_cpu_list(cpus: &[usize]) -> String {
cpus.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join(",")
}
#[cfg(target_os = "linux")]
mod affinity {
/// The CPUs the calling thread may run on.
@ -501,29 +393,6 @@ impl<'a, T> SharedSlice<'a, T> {
mod tests {
use super::*;
#[test]
fn aux_cpus_are_taken_out_of_the_sim_set() {
// The release layout plus one page cpu: sweep 3,5,7, host 1, bus threads on 9.
let (placement, aux) = split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[9]).expect("a plan");
assert_eq!(placement.workers, vec![3, 5, 7]);
assert_eq!(placement.host, vec![1]);
assert_eq!(aux, vec![9]);
// No aux cpu is ever a worker or host cpu, whatever its position.
let (p, a) = split_cpus_aux(&[1, 3, 5, 7, 9, 11], 4, &[3, 11, 3]).expect("a plan");
assert_eq!(a, vec![3, 11]);
assert!(p.workers.iter().chain(&p.host).all(|c| !a.contains(c)));
// Refused: not in the allowed set, empty, or too few left for the sim.
assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[9]), None);
assert_eq!(split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[]), None);
assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[7]), None);
}
#[test]
fn confining_to_aux_without_a_reservation_is_a_no_op() {
assert!(aux_cpus().is_none());
assert!(!confine_to_aux());
}
#[test]
fn every_index_runs_exactly_once() {
for workers in [1usize, 2, 3, 7] {
@ -598,16 +467,6 @@ mod tests {
assert_eq!(ran.load(Ordering::Relaxed), 8);
}
#[test]
fn cpu_lists_parse_as_taskset_writes_them() {
assert_eq!(parse_cpu_list("1,3,5,7"), Some(vec![1, 3, 5, 7]));
assert_eq!(parse_cpu_list("9-11, 1 ,10"), Some(vec![1, 9, 10, 11]));
assert_eq!(parse_cpu_list(""), None);
assert_eq!(parse_cpu_list("3-1"), None);
assert_eq!(parse_cpu_list("x"), None);
assert_eq!(format_cpu_list(&[1, 3, 5]), "1,3,5");
}
#[test]
fn the_split_gives_each_worker_a_cpu_and_the_host_the_rest() {
// The release's flysim cpuset, four whole cores, four sweep threads.

View file

@ -1,57 +0,0 @@
//! The GPU fallback record (`lif::health`): one failure makes the GPU unusable for the process,
//! it is counted and logged once per failure, a marker file carries it to sibling worker
//! processes, and the metric text names the backend that runs.
use flybrain_core::lif::LifBackend;
use flybrain_core::lif::health;
#[test]
fn a_failure_marks_the_gpu_unusable_and_is_exported() {
// The only test in this binary: it owns the process-wide record and the environment.
health::reset_for_tests();
assert!(!health::gpu_unusable());
assert_eq!(health::fallbacks(), 0);
let cuda = LifBackend::Cuda { device: 0 };
let before = health::render_prometheus(cuda, cuda);
assert!(before.contains("fly_brain_backend{backend=\"cuda\"} 1"));
assert!(before.contains("fly_brain_backend{backend=\"cpu\"} 0"));
assert!(before.contains("fly_brain_backend_fallbacks_total 0"));
health::record_fallback("device lost\nsecond line");
assert!(health::gpu_unusable());
assert_eq!(health::fallbacks(), 1);
assert_eq!(health::last_reason().as_deref(), Some("device lost second line"));
let after = health::render_prometheus(LifBackend::Cpu, cuda);
assert!(after.contains("fly_brain_backend{backend=\"cpu\"} 1"));
assert!(after.contains("fly_brain_backend{backend=\"cuda\"} 0"));
assert!(after.contains("fly_brain_backend_wanted 1"));
assert!(after.contains("fly_brain_backend_fallbacks_total 1"));
// With a marker the file is the record: a sibling process's failure counts here, and
// resetting it (a new launcher) ends the fallback.
let dir = tempfile::tempdir().expect("tmp");
let marker = dir.path().join("lif-gpu-fallbacks");
let prom = dir.path().join("fly_brain_backend.prom");
// SAFETY: single test in this binary, no other thread reads the environment.
unsafe {
std::env::set_var(health::MARKER_ENV, &marker);
std::env::set_var(health::PROM_ENV, &prom);
}
assert!(!health::gpu_unusable(), "an empty marker is a clean slate");
std::fs::write(&marker, "from a worker process\n").expect("marker");
assert!(health::gpu_unusable());
assert_eq!(health::fallbacks(), 1);
health::record_fallback("second");
assert_eq!(health::fallbacks(), 2);
assert_eq!(health::marker_fallbacks(&marker), 2);
health::write_textfile(LifBackend::Cpu, cuda);
let text = std::fs::read_to_string(&prom).expect("textfile");
assert!(text.contains("fly_brain_backend_fallbacks_total 2"), "{text}");
health::reset_marker(&marker);
assert!(!health::gpu_unusable());
unsafe {
std::env::remove_var(health::MARKER_ENV);
std::env::remove_var(health::PROM_ENV);
}
}

View file

@ -1,6 +1,6 @@
//! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons
//! that tick stamped in `last_spike_ms`, so the union of the lists over a window is the window
//! bitset a scan of `last_spike_ms` gives. GPU-02: `step_frame` gathers the same union in one call.
//! bitset a scan of `last_spike_ms` gives.
mod common;
@ -52,107 +52,3 @@ fn a_ticks_list_is_the_neurons_it_stamped_and_windows_agree_with_the_scan() {
}
assert!(spiking_ticks > 0, "the fixture must spike for the test to mean anything");
}
/// GPU-02: `step_frame` is the session's old per-frame loop -- one-tick `step` calls with each
/// tick's list OR-ed into the bitset -- bit for bit, in the state and in the bitset, at one and
/// at several sweep threads.
#[test]
fn a_frame_step_is_the_one_tick_loop_bit_for_bit() {
use flybrain_core::lif::SweepPlan;
let config = LifConfig { noise_amount: 40.0, ..LifConfig::default() };
for threads in [1, 3] {
let build = || {
let mut network = LifNetwork::new(
Arc::new(visual_toy_dataset()),
config.clone(),
PlasticityConfig::default(),
)
.expect("a network");
network.configure_sweep(SweepPlan::with_threads(threads).expect("a plan"));
network
};
let (mut looped, mut framed) = (build(), build());
let neurons = looped.last_spike_ms.len();
let mut spiking_frames = 0;
for frame in 0..120u64 {
if frame % 25 == 0 {
looped.stimulate(30.0);
framed.stimulate(30.0);
}
if frame % 10 == 9 {
let ms = looped.ms;
looped.plasticity.reinforce(0.5, ms);
framed.plasticity.reinforce(0.5, ms);
}
let ticks = 16 + frame % 2;
let mut want = vec![0u8; neurons.div_ceil(8)];
let mut want_total = 0u64;
for _ in 0..ticks {
let count = looped.step(1) as usize;
want_total += count as u64;
for &n in looped.tick_spikes(count).expect("the CPU kernel keeps its list") {
want[n as usize >> 3] |= 1 << (n & 7);
}
}
let mut got = vec![0u8; neurons.div_ceil(8)];
let total = framed.step_frame(ticks, &mut got).expect("the CPU cannot fail");
assert_eq!(total, want_total, "frame {frame} at {threads} threads");
assert_eq!(got, want, "frame {frame} at {threads} threads");
assert_eq!(framed.export_state(), looped.export_state());
spiking_frames += usize::from(total > 0);
}
assert!(spiking_frames > 0, "the fixture must spike for the test to mean anything");
assert!(framed.host_state_current());
assert!(framed.take_backend_fault().is_none());
}
}
#[test]
fn a_frame_step_refuses_a_bitset_too_small_for_the_network() {
let mut network = LifNetwork::new(
Arc::new(visual_toy_dataset()),
LifConfig::default(),
PlasticityConfig::default(),
)
.expect("a network");
let neurons = network.last_spike_ms.len();
let mut short = vec![0u8; neurons.div_ceil(8) - 1];
assert!(network.step_frame(17, &mut short).is_err());
assert_eq!(network.ms, 0.0, "a refused frame steps nothing");
}
/// The deployment switch: only `FLY_LIF_CUDA=1` asks for the GPU, as before GPU-02, and a device
/// that is not an ordinal is refused rather than read as 0.
#[test]
fn the_backend_switch_reads_like_the_old_env_hook() {
use flybrain_core::lif::LifBackend;
assert_eq!(LifBackend::from_values(None, None), Ok(LifBackend::Cpu));
assert_eq!(LifBackend::from_values(Some("0"), Some("3")), Ok(LifBackend::Cpu));
assert_eq!(LifBackend::from_values(Some("yes"), None), Ok(LifBackend::Cpu));
assert_eq!(LifBackend::from_values(Some("1"), None), Ok(LifBackend::Cuda { device: 0 }));
assert_eq!(
LifBackend::from_values(Some("1"), Some("1")),
Ok(LifBackend::Cuda { device: 1 })
);
assert!(LifBackend::from_values(Some("1"), Some("GPU-abc")).is_err());
assert_eq!(LifBackend::Cuda { device: 1 }.label(), "cuda:1");
assert_eq!(LifBackend::Cpu.label(), "cpu");
}
/// Without the feature, asking for the GPU is an error, never a CPU run under a GPU label; the CPU
/// backend is accepted and changes nothing.
#[cfg(not(feature = "cuda"))]
#[test]
fn a_cpu_build_refuses_the_gpu_backend() {
use flybrain_core::lif::LifBackend;
let mut network = LifNetwork::new(
Arc::new(visual_toy_dataset()),
LifConfig::default(),
PlasticityConfig::default(),
)
.expect("a network");
assert!(network.set_backend(LifBackend::Cuda { device: 0 }).is_err());
assert!(network.set_backend(LifBackend::Cpu).is_ok());
assert_eq!(network.backend(), LifBackend::Cpu);
assert!(!LifBackend::cuda_compiled());
}

View file

@ -202,15 +202,6 @@ pub enum PlaceKind {
Person,
/// Something to press A at: the starter's Pokéball, an item ball, a sign.
Object,
/// An errand in one room, step by step: its people first, and once none is left to talk to,
/// the things in it -- objects, signs, and the cartridge's own hidden events, such as the PC
/// a Bill's-house cell separator is started from (row 73, `docs/design/macros.md` 12.35).
///
/// Not a list of steps, and no step is named: the room's state says which step is next, because
/// the cartridge shows and hides the people as the errand moves on. A person who has had their
/// conversation is in the talked ledger; a thing pressed is too; and what is left is the next
/// step.
Errand,
}
impl MapPlace {
@ -233,11 +224,6 @@ impl MapPlace {
pub const fn object(map: u8) -> Self {
Self { map, tile: None, warp: None, edge: None, target: Some(PlaceKind::Object) }
}
/// A place that is an errand in one room: its people, then its things ([`PlaceKind::Errand`]).
pub const fn errand(map: u8) -> Self {
Self { map, tile: None, warp: None, edge: None, target: Some(PlaceKind::Errand) }
}
}
/// Reasons an adapter refuses a checkpoint.

View file

@ -460,29 +460,6 @@ impl Wram {
self
}
/// The cartridge's hidden-event table with one map in it: `HiddenEventMaps` listing `map`,
/// `HiddenEventPointers` pointing at a list of `(y, x, argument)` entries (six bytes each, the
/// routine's `dba` a bank-$11 address).
pub fn hidden_table(&mut self, map: u8, entries: &[(u8, u8, u8)]) -> &mut Self {
use super::state::poke::hidden::{ENTRY_BYTES, MAPS_ADDRESS, POINTERS_ADDRESS, TABLE_BANK};
let list = 0x7000u16;
let mut put = |address: u16, byte: u8| {
self.rom.insert((TABLE_BANK, address), byte);
};
put(MAPS_ADDRESS, map);
put(MAPS_ADDRESS + 1, 0xff);
put(POINTERS_ADDRESS, (list & 0xff) as u8);
put(POINTERS_ADDRESS + 1, (list >> 8) as u8);
for (index, (y, x, argument)) in entries.iter().enumerate() {
let base = list + index as u16 * ENTRY_BYTES;
for (offset, byte) in [*y, *x, *argument, TABLE_BANK, 0x00, 0x60].into_iter().enumerate() {
put(base + offset as u16, byte);
}
}
put(list + entries.len() as u16 * ENTRY_BYTES, 0xff);
self
}
/// The cartridge's `ItemUsePtrTable`, one pointer per item id, grouped the way the pinned
/// commit groups them: the balls share one routine, the potions, drinks, status heals and
/// revives another, the four X stat items another, the four PP restores another, and every

View file

@ -286,8 +286,6 @@ pub enum TalkTarget {
Sprite(u8),
/// A sign, by its text id.
Sign(u8),
/// A hidden event of the cartridge's own table, by its position in this map's list (row 73).
Hidden(u8),
}
/// One thing a macro can be *aimed at*, as the session's target ledgers name it.
@ -691,13 +689,6 @@ impl Talked {
self.0.insert((map, target));
}
/// Forget everything talked to on `map` (row 73's errand: the cartridge shows the room's
/// people again after the fly leaves, and a conversation had on the last visit is not this
/// one's).
pub fn forget_map(&mut self, map: u8) {
self.0.retain(|(at, _)| *at != map);
}
/// How many things this session has talked to, for a log line and the tests.
pub fn len(&self) -> usize {
self.0.len()

View file

@ -107,11 +107,6 @@ pub struct PokemonPalette {
nearest: Option<(u8, u32)>,
/// Whether the last `observe` was the frame that number fell on.
nearer: bool,
/// The map the fly was last seen standing in while the ladder's objective was an errand in
/// it (row 73). On leaving it with the errand still the objective, the talked entries of that
/// room are forgotten: Route 25 re-shows Bill, and a Bill whose bag was full never handed
/// over the ticket, so a conversation had on the last visit must not retire this one's.
errand_seen: Option<u8>,
/// The map of the last frame that was not a warp's tear, and how many tear frames have run
/// since (row 58, [`PokemonPalette::tear`], [`TEAR_FRAMES`]).
///
@ -155,7 +150,6 @@ impl PokemonPalette {
grids: MapGrids::default(),
nearest: None,
nearer: false,
errand_seen: None,
settled: None,
tear_frames: 0,
naming_since: None,
@ -322,7 +316,7 @@ impl MacroPalette for PokemonPalette {
// name gets the whole bound and a restore starts it again.
self.naming_since = naming.map(|_| self.naming_since.unwrap_or(self.now_ms));
let naming_elapsed = self.naming_since.map_or(0.0, |since| (self.now_ms - since).max(0.0));
let (scene, bindings, raw, standing, stepping, approach, errand) = {
let (scene, bindings, raw, standing, stepping, approach) = {
let Self {
machine,
mode,
@ -378,28 +372,12 @@ impl MacroPalette for PokemonPalette {
let hops = geography::hops(palette::region_here(&mut state)?, objective.map)?;
Some((objective.map, hops))
});
// Row 73: whether the objective is an errand, and in which room.
let errand = standing.and_then(|_| {
let objective = palette::objective_place(&mut state)?;
(objective.target == Some(crate::adapter::PlaceKind::Errand)).then_some(objective.map)
});
*cached = Some(palette);
(scene, bindings, raw, standing, stepping, approach, errand)
(scene, bindings, raw, standing, stepping, approach)
};
// Section 12.7: the macro layer's own answer to "has the run stood here", because the
// adapter's reward ledger cannot record a doormat.
if let Some(player) = standing {
if let Some(room) = self.errand_seen
&& player.map != room
{
if errand == Some(room) {
self.talked.forget_map(room);
}
self.errand_seen = None;
}
if errand == Some(player.map) {
self.errand_seen = Some(player.map);
}
// New ground under the fly is the one thing that can change which tiles of this map
// it can reach, so it is what clears the map's frontier mark (section 12.14). A tile
// the ledger already had changes nothing and clears nothing.
@ -616,7 +594,7 @@ mod tests {
use crate::pokemon_red::fake_wram::{self, REDS_HOUSE_1F, WALL_TILE, Wram};
use crate::pokemon_red::macros::geography::Amenity;
use crate::pokemon_red::maps;
use crate::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState, TalkLedger, TalkTarget};
use crate::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState};
/// A ledger with one exit in it, for the wiring test below.
struct OneVisited(MapExit);
@ -806,54 +784,6 @@ mod tests {
assert!(palette.nearer_the_objective(), "out of the front door is nearer still");
}
/// A ledger whose objective is the errand in one room (row 73).
struct ErrandIn(u8);
impl RunLedger for ErrandIn {
fn exit_visited(&self, _exit: MapExit) -> bool {
false
}
fn objective(&self) -> Option<crate::adapter::MapPlace> {
Some(crate::adapter::MapPlace::errand(self.0))
}
}
#[test]
fn an_errand_rooms_talked_entries_are_forgotten_when_the_fly_leaves_it() {
// Row 73 review N3. The talked ledger is the session's and never forgot, but the
// cartridge re-shows Bill after the fly leaves (Route 25's script resets his event), and a
// Bill whose bag was full never gave the ticket: a conversation had on the last visit
// retired this one's, and rung 16 was unreachable until a restart.
let mut wram = Wram::new();
wram.started().map(maps::BILLS_HOUSE, 8, 8, 2, 6).facing(0).house_collision();
let mut palette = PokemonPalette::new(7);
let ledger = ErrandIn(maps::BILLS_HOUSE);
palette.observe(&mut wram, &ledger);
palette.talked.record(maps::BILLS_HOUSE, TalkTarget::Sprite(1));
// A conversation elsewhere is not the errand's and stays.
palette.talked.record(maps::VIRIDIAN_CITY, TalkTarget::Sprite(2));
palette.observe(&mut wram, &ledger);
assert_eq!(palette.talked(), 2, "still in the room: nothing is forgotten");
wram.map(maps::ROUTE_25, 40, 10, 45, 4);
palette.observe(&mut wram, &ledger);
palette.observe(&mut wram, &ledger);
assert!(!palette.talked.talked(maps::BILLS_HOUSE, TalkTarget::Sprite(1)), "left: asked again");
assert!(palette.talked.talked(maps::VIRIDIAN_CITY, TalkTarget::Sprite(2)), "other rooms keep theirs");
// And a room that is not the objective's errand keeps its entries on leaving.
let mut wram = Wram::new();
wram.started().map(maps::BILLS_HOUSE, 8, 8, 2, 6).facing(0).house_collision();
let mut palette = PokemonPalette::new(7);
let elsewhere = Bound(maps::PEWTER_GYM);
palette.observe(&mut wram, &elsewhere);
palette.talked.record(maps::BILLS_HOUSE, TalkTarget::Sprite(1));
wram.map(maps::ROUTE_25, 40, 10, 45, 4);
palette.observe(&mut wram, &elsewhere);
assert_eq!(palette.talked(), 1);
}
#[test]
fn standing_on_new_ground_is_what_clears_a_maps_frontier_mark() {
// Section 12.14's other half, wired: the mark is written by a `GO FRONTIER` that could

View file

@ -173,12 +173,6 @@ const LINKS: &[(u8, u8)] = &[
// which from the back door's arrival is the back door. Which piece each door opens onto is
// [`SPLIT`]'s business.
(maps::CERULEAN_BADGE_HOUSE, maps::CERULEAN_CITY),
// The trashed house (row 73): its front door is the town's, the hole in its back wall the
// south's ([`SPLIT`]). It is the only road from the town to Route 5, rung 17's.
(maps::CERULEAN_TRASHED_HOUSE, maps::CERULEAN_CITY),
// Bill's house, rung 16's room (row 73): Route 25's door at (45, 3), and the house's two
// doormats back to the route (`LAST_MAP`).
(maps::BILLS_HOUSE, maps::ROUTE_25),
(maps::ROCK_TUNNEL_1F, maps::ROUTE_10),
(maps::INDIGO_PLATEAU_LOBBY, maps::INDIGO_PLATEAU),
];
@ -258,9 +252,6 @@ const B2F_SOUTH: u8 = 2;
const CERULEAN_TOWN: u8 = 0;
#[cfg(test)]
const CERULEAN_YARD: u8 = 1;
/// [`SPLIT`]'s third piece of Cerulean: the ground behind the trashed house (row 73).
#[cfg(test)]
const CERULEAN_SOUTH: u8 = 2;
/// Every map whose ground is in pieces, with each piece's doors and neighbours.
///
@ -392,33 +383,21 @@ const SPLIT: &[Split] = &[
(3, 30, 19),
(4, 13, 25),
(5, 25, 25),
(7, 27, 9),
(8, 9, 11),
],
next: &[
Region::whole(maps::ROUTE_24),
Region::whole(maps::ROUTE_5),
Region::piece(maps::ROUTE_4, EAST_SIDE),
Region::whole(maps::ROUTE_9),
Region::whole(maps::CERULEAN_POKECENTER),
Region::whole(maps::CERULEAN_GYM),
Region::whole(maps::CERULEAN_MART),
Region::whole(maps::CERULEAN_BADGE_HOUSE),
Region::whole(maps::CERULEAN_TRASHED_HOUSE),
],
},
Piece { doors: &[(9, 9, 9)], next: &[Region::whole(maps::CERULEAN_BADGE_HOUSE)] },
// Row 73: everything behind the trashed house. The town's own ground ends at row 28 --
// the gap at (16, 28) and (17, 28) opens onto a wall and the trainer-tips sign -- and
// the south of the map, the road down to Route 5, and the east edge onto Route 9 are
// reached through the house: in by the front door at (27, 11), out by the hole in its
// back wall, which lands on (27, 9) in the Rocket's yard, and from there east and down
// (scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's).
Piece {
doors: &[(7, 27, 9)],
next: &[
Region::whole(maps::ROUTE_5),
Region::whole(maps::ROUTE_9),
Region::whole(maps::CERULEAN_TRASHED_HOUSE),
],
},
],
},
];
@ -998,31 +977,6 @@ mod tests {
assert!(warp_on(west, 1) && !warp_on(west, 2) && !edge_on(west, maps::CERULEAN_CITY));
}
#[test]
fn the_road_south_out_of_cerulean_is_through_the_trashed_house() {
// Row 73. The town's ground ends at row 28; Route 5 and Route 9 are on the ground behind
// the trashed house, reached in by its front door (Cerulean's warp 0) and out by the hole
// in its back wall, which lands on (27, 9) (warp 7). Scout B3: 0 of 6 seeds past the
// town's south edge in 43 brain minutes each while the house was off the graph.
let town = Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN);
let south = Region::piece(maps::CERULEAN_CITY, CERULEAN_SOUTH);
let house = Region::whole(maps::CERULEAN_TRASHED_HOUSE);
assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 0), Some(town), "the front door is the town's");
assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 7), Some(south), "the hole lands behind the house");
assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_5), Some(south));
assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_9), Some(south));
assert_eq!(next_step(town, maps::ROUTE_5), Some(house));
assert_eq!(next_step(house, maps::ROUTE_5), Some(south));
assert_eq!(next_step(south, maps::ROUTE_5), Some(Region::whole(maps::ROUTE_5)));
assert_eq!(next_step(house, maps::CERULEAN_GYM), Some(town));
assert_eq!(region_at(maps::CERULEAN_CITY, 27, 9), south);
assert_eq!(region_at(maps::CERULEAN_CITY, 27, 12), town);
assert!(!edge_on(town, maps::ROUTE_5) && edge_on(south, maps::ROUTE_5));
assert!(warp_on(south, 7) && !warp_on(town, 7) && !warp_on(south, 0));
// Rung 17's road from Bill's house is now one the graph knows end to end.
assert!(hops(Region::whole(maps::BILLS_HOUSE), maps::VERMILION_CITY).is_some());
}
#[test]
fn the_road_from_pewter_to_cerulean_is_through_mt_moon_one_chamber_at_a_time() {
// Row 59. Every step of the road, as the pieces the fly stands in, measured from the

View file

@ -2021,9 +2021,6 @@ pub fn facing_target(state: &mut dyn MacroState) -> Option<TalkTarget> {
if let Some(target) = path::target_at(state, ahead) {
return Some(target);
}
if let Some(target) = objective_hidden_ahead(state, ahead, player.facing) {
return Some(target);
}
// **Over a counter**, which is the symmetric half of [`counter_aims`] and was missing from it
// (2026-09-17, measured on the cartridge in the Viridian mart). The game doubles its own
// talking range over the tileset's counter tiles, so a fly standing at a counter facing the
@ -2114,17 +2111,7 @@ pub fn objective_goals(state: &mut dyn MacroState) -> Vec<Aim> {
// to walk to: `GO OBJECTIVE` walked to him, then back to the leader, and `TALK` was
// the one press it never made room for. A fly facing a person the rung is waiting on
// has nothing left for a walk to do.
// A hidden event is faced only from the side it answers (row 73): beside Bill's PC
// facing it sideways is not the arrival, and the walk goes on to the tile below it.
let mut arrived = false;
for (tile, target) in &targets {
if Some(*tile) == ahead
&& required_facing(state, *target).is_none_or(|need| need == player.facing)
{
arrived = true;
}
}
if arrived {
if targets.iter().any(|(tile, _)| Some(*tile) == ahead) {
return Vec::new();
}
let mut ranked: Vec<(u32, Tile, TalkTarget)> = targets
@ -2133,12 +2120,8 @@ pub fn objective_goals(state: &mut dyn MacroState) -> Vec<Aim> {
.collect();
ranked.sort_unstable();
let Some((_, tile, target)) = ranked.first().copied() else { return Vec::new() };
let need = required_facing(state, target);
let mut aims = Vec::with_capacity(4);
for facing in FACINGS {
if need.is_some_and(|need| need != opposite(facing)) {
continue;
}
let Some(stand) = tile.step(facing) else { continue };
// Not a tile a script pushes the fly off (row 37); `approach` excludes the same.
if state.pushed_tile(stand.x, stand.y) {
@ -2252,88 +2235,15 @@ pub fn objective_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)>
// Not objects: every item ball in the game is a toggleable object, so a ball the run has
// picked up and one out of sight read alike from outside the window.
PlaceKind::Object => path::interactable_targets(state),
// Row 73: an errand in one room is its people first, and its things -- sprites, signs and
// the cartridge's hidden events -- once no person is left to talk to. Bill's house is the
// case: Bill (a Pokémon) asks for the cell separator and walks into the machine, the
// separator is a PC no sprite or sign stands for, and Bill comes out of the machine to
// hand over the ticket. The cartridge hides and shows the people as the errand moves, so
// the room's own state says which step is next; nothing here names a step.
//
// People first, because a thing pressed out of turn is in the talked ledger for the
// session: Bill's PC pressed before Bill has asked prints "the monitor" and does nothing,
// and a PC recorded as talked to would never be the errand's next step again.
PlaceKind::Errand => {
let mut people = path::person_targets(state);
people.extend(path::offscreen_person_targets(state));
let people = open_targets(state, people);
if !people.is_empty() {
return people;
}
let mut things = path::interactable_targets(state);
things.extend(path::hidden_targets(state).into_iter().map(|(tile, target, _)| (tile, target)));
things
}
};
open_targets(state, targets)
}
/// Whichever of `targets` the objective is still waiting on: not talked to, and not resting in
/// the blocked ledger. [`objective_targets`]' own filter, for each list it builds.
fn open_targets(state: &mut dyn MacroState, targets: Vec<(Tile, TalkTarget)>) -> Vec<(Tile, TalkTarget)> {
targets
.into_iter()
.filter(|(tile, target)| {
!state.talked(*target)
&& !state.blocked(TargetKey::Thing(*target))
&& servable(state, *tile, *target)
.filter(|(_, target)| {
!state.talked(*target) && !state.blocked(TargetKey::Thing(*target))
})
.collect()
}
/// Whether some tile the objective's `target` can be pressed from is not one a script pushes the
/// fly off (row 37). Only a one-sided hidden event can fail this: its single stand tile is the
/// only door in, and with that tile pushed the walk has no aim, so it never ends in a refusal
/// that earns a blocked entry -- and while a target waits the exits are withheld, so the room
/// became a trap. A target nobody can stand in front of is not one the rung is waiting on, and
/// it leaves the list at once: the exits are back the frame the pushed tile is learned.
fn servable(state: &mut dyn MacroState, tile: Tile, target: TalkTarget) -> bool {
let Some(need) = required_facing(state, target) else { return true };
FACINGS.into_iter().filter(|facing| need == opposite(*facing)).any(|facing| {
tile.step(facing).is_some_and(|stand| !state.pushed_tile(stand.x, stand.y))
})
}
/// The one side the objective's `target` is pressed from, when the cartridge names one: a hidden
/// event whose routine checks the player's facing (row 73, Bill's PC). `None` for every sprite and
/// sign, which answer from any side.
fn required_facing(state: &mut dyn MacroState, target: TalkTarget) -> Option<Facing> {
let TalkTarget::Hidden(_) = target else { return None };
path::hidden_targets(state)
.into_iter()
.find(|(_, hidden, _)| *hidden == target)
.and_then(|(_, _, facing)| facing)
}
/// The objective's hidden event on the tile ahead, faced from the side it answers (row 73).
///
/// The half of [`facing_target`] that is not the map's sprites and signs. Only the objective's
/// own next step is reported, never any other hidden event: a poster faced on the way past is not
/// a reason for `TALK`, and a PC pressed out of turn would retire the errand's own step
/// ([`objective_targets`]).
fn objective_hidden_ahead(state: &mut dyn MacroState, ahead: Tile, facing: Facing) -> Option<TalkTarget> {
// Most tiles of most maps are no hidden event's, and this is asked on every overworld frame.
if !path::hidden_targets(state).iter().any(|(tile, _, _)| *tile == ahead) {
return None;
}
let (_, target) = objective_targets(state)
.into_iter()
.find(|(tile, target)| *tile == ahead && matches!(target, TalkTarget::Hidden(_)))?;
match required_facing(state, target) {
Some(need) if need != facing => None,
_ => Some(target),
}
}
/// The exits the ledger has already recorded, for the log line.
pub fn visited_exits(state: &mut dyn MacroState) -> Vec<ExitId> {
path::exits(state)

View file

@ -366,24 +366,6 @@ pub fn interactable_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget
out
}
/// The map's hidden events with the key the talked ledger records them under, and the one side
/// each is pressed from when the cartridge names one (row 73).
///
/// Kept apart from [`interactable_targets`] on purpose, which is `GO ITEM`'s list: a hidden event
/// is every PC, poster, trash can and hidden item in Kanto, and a fly sent to each of them is a
/// fly reading posters. The one reader is the ladder's own errand list
/// ([`super::palette::objective_targets`]), which needs the one the rung is waiting on.
pub fn hidden_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget, Option<Facing>)> {
let mut out: Vec<(Tile, TalkTarget, Option<Facing>)> = state
.hidden_events()
.iter()
.map(|event| (Tile::new(event.x, event.y), TalkTarget::Hidden(event.index), event.facing))
.collect();
out.sort_unstable_by_key(|(tile, target, _)| (*tile, *target));
out.dedup_by_key(|(tile, _, _)| *tile);
out
}
/// Every person on the map with the key the talked ledger records them under.
pub fn person_targets(state: &mut dyn MacroState) -> Vec<(Tile, TalkTarget)> {
let mut out: Vec<(Tile, TalkTarget)> = state

View file

@ -413,31 +413,6 @@ pub struct Sign {
pub text_id: u8,
}
/// One hidden event on the current map: a tile the cartridge answers an A press at from its own
/// ROM table (`HiddenEventMaps` / `HiddenEventPointers`, `data/events/hidden_events.asm`) rather
/// than from a sprite or a sign (row 73, `docs/design/macros.md` 12.35).
///
/// Bill's cell-separator PC, the Pokémon Center PCs, posters, bookshelves of one room, trash cans
/// and hidden items are all this. Nothing about one reaches WRAM until it has been pressed
/// (`CheckForHiddenEvent` searches the table on every A in the overworld), so the tile is read from
/// the cartridge image and the tile named here is the one to *face*, like a [`Sign`]'s.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HiddenEvent {
pub x: u8,
pub y: u8,
/// The entry's position in this map's list, which is the identity the cartridge gives it
/// (`wHiddenEventIndex` counts the same way) and nothing more.
pub index: u8,
/// The one side the cartridge answers the press from, when the entry names one.
///
/// The table's third byte is the routine's argument, and where it is a `SPRITE_FACING_*`
/// value it is the side the routine checks before it does anything (`BillsHousePC` returns at
/// once unless the player faces up). `None` for any other argument -- an item id, a text id,
/// `ANY_FACING` -- which leaves all four sides. An argument that is an item or a text id and
/// happens to equal a facing value only narrows the approach to one side; it never adds one.
pub facing: Option<Facing>,
}
/// Whether a tile can be walked onto.
///
/// `Unknown` is load-bearing: the tile ids a walkability test needs live in the screen buffer, so
@ -799,14 +774,6 @@ pub trait GameState {
/// is visible, and not inherit it from here.
fn signs(&mut self) -> Vec<Sign>;
/// The current map's hidden events, from the cartridge's own table (row 73).
///
/// Defaulted to none, which narrows: a seam with no cartridge image behind it knows the
/// sprites and the signs and nothing more, which is what every reader had before row 73.
fn hidden_events(&mut self) -> Vec<HiddenEvent> {
Vec::new()
}
/// Whether the player could stand on this tile of the current map.
fn walkable(&mut self, x: u8, y: u8) -> Walkable;

View file

@ -40,8 +40,7 @@ use super::super::maps;
use super::plan;
use super::state::{
Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState, MapSize,
HiddenEvent, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu,
Status, TextBox,
Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu, Status, TextBox,
Walkable, Warp,
};
@ -96,8 +95,6 @@ struct World {
/// Sprites the cartridge is not drawing only because they are off the screen (row 58).
offscreen: Vec<Npc>,
signs: Vec<Sign>,
/// The map's hidden events, as the cartridge's own table lists them (row 73).
hidden: Vec<HiddenEvent>,
list: List,
cursor: u8,
@ -279,7 +276,6 @@ impl World {
npcs: Vec::new(),
offscreen: Vec::new(),
signs: Vec::new(),
hidden: Vec::new(),
list: List::None,
cursor: 0,
cursor_max: 0,
@ -795,10 +791,6 @@ impl GameState for World {
self.signs.clone()
}
fn hidden_events(&mut self) -> Vec<HiddenEvent> {
self.hidden.clone()
}
fn walkable(&mut self, x: u8, y: u8) -> Walkable {
let tile = Tile::new(x, y);
let offscreen = self.window && {
@ -6623,120 +6615,3 @@ fn row69_confirm_on_a_keyboard_that_does_not_close_is_blocked() {
world.glue_naming = true;
assert_eq!(run(&mut world, MacroKind::Confirm).unwrap(), MacroAbort::Blocked);
}
/// Bill's house on the step the live ring never got past (row 73): the fly on the doormat, Bill
/// (a Pokémon, a person sprite) at (6, 5), the cell separator's PC a hidden event at (1, 4) that is
/// pressed facing up, and rung 16's place the house as an errand.
fn bills_house() -> World {
let mut world = World::room().at(2, 7);
world.map = maps::BILLS_HOUSE;
world.size = MapSize { width: 8, height: 8 };
world.facing = Facing::Up;
// The back wall, the PC's own tile with it.
world = world.wall(&[(0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), (1, 4)]);
world.warps = vec![
Warp { x: 2, y: 7, destination_warp: 0, destination_map: LAST_MAP },
Warp { x: 3, y: 7, destination_warp: 0, destination_map: LAST_MAP },
];
world.npcs = vec![Npc { slot: 1, picture: 0x2a, x: 6, y: 5, facing: Facing::Down }];
world.hidden = vec![HiddenEvent { x: 1, y: 4, index: 0, facing: Some(Facing::Up) }];
world.objective = Some(Objective {
map: world.map,
tile: None,
warp: None,
edge: None,
target: Some(PlaceKind::Errand),
});
world
}
#[test]
fn an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting() {
// Row 73, live on v0.7.5: rung 16 was `at(ROUTE_25)`, so inside Bill's house `GO OBJECTIVE`
// and `GO OUT` were both the door, 30 to 60 times per ten brain minutes. As an errand, Bill is
// the target and the ways out are withheld while he is waiting (12.5's rule).
let mut world = bills_house();
assert_eq!(super::palette::objective_targets(&mut world), vec![(Tile::new(6, 5), TalkTarget::Sprite(1))]);
assert!(on_the_pad(&mut world, MacroKind::GoObjective));
assert!(!on_the_pad(&mut world, MacroKind::GoOut), "the house is not left while Bill is waiting");
// The PC is not the errand's step yet: faced out of turn it is not `TALK`'s, because a PC
// pressed before Bill has asked prints the monitor and would be in the talked ledger for good.
let mut world = bills_house().at(1, 5);
world.facing = Facing::Up;
assert!(!on_the_pad(&mut world, MacroKind::Talk));
assert_eq!(super::palette::facing_target(&mut world), None);
}
#[test]
fn a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side() {
// Bill has asked and walked into the machine: the cartridge has hidden his sprite and nobody
// else is in the room. The next step is the cell separator's PC, which no sprite or sign
// stands for -- the hidden event the scout pressed by hand on the cartridge (row 73).
let mut world = bills_house().at(3, 5);
world.npcs.clear();
world.talked.insert(TalkTarget::Sprite(1));
assert_eq!(super::palette::objective_targets(&mut world), vec![(Tile::new(1, 4), TalkTarget::Hidden(0))]);
assert!(!on_the_pad(&mut world, MacroKind::GoOut), "still not left: the PC is waiting");
// `BillsHousePC` answers only a player facing up, so the walk's one aim is the tile below it.
let aims: Vec<(Tile, Option<Facing>)> =
objective_goals(&mut world).iter().map(|aim| (aim.tile, aim.face)).collect();
assert_eq!(aims, vec![(Tile::new(1, 5), Some(Facing::Up))]);
// Beside it, facing it sideways, is not the arrival: nothing would answer the press.
let mut beside = bills_house().at(2, 4);
beside.npcs.clear();
beside.talked.insert(TalkTarget::Sprite(1));
beside.facing = Facing::Left;
assert!(!on_the_pad(&mut beside, MacroKind::Talk));
assert!(on_the_pad(&mut beside, MacroKind::GoObjective));
// Below it, facing up: `TALK` is the press and the walk is done.
let mut below = bills_house().at(1, 5);
below.npcs.clear();
below.talked.insert(TalkTarget::Sprite(1));
below.facing = Facing::Up;
assert_eq!(super::palette::facing_target(&mut below), Some(TalkTarget::Hidden(0)));
assert!(on_the_pad(&mut below, MacroKind::Talk));
assert!(!on_the_pad(&mut below, MacroKind::GoObjective));
// Pressed: Bill steps out of the machine, and he is the errand's last step.
below.talked.insert(TalkTarget::Hidden(0));
below.npcs = vec![Npc { slot: 2, picture: 0x13, x: 4, y: 4, facing: Facing::Down }];
assert_eq!(super::palette::objective_targets(&mut below), vec![(Tile::new(4, 4), TalkTarget::Sprite(2))]);
}
#[test]
fn a_one_sided_target_whose_only_stand_tile_is_pushed_is_not_waited_for() {
// Row 73 review N4. The PC answers only from below; if the cartridge pushes the fly off
// that tile the walk has no aim, so no walk ever ends `blocked`, and while a target waited the
// exits were withheld for good. The target leaves the list and the way out is back.
let mut world = bills_house().at(3, 5);
world.npcs.clear();
world.talked.insert(TalkTarget::Sprite(1));
assert_eq!(super::palette::objective_targets(&mut world).len(), 1);
assert!(!on_the_pad(&mut world, MacroKind::GoOut));
world.pushes.insert(Tile::new(1, 5));
assert!(super::palette::objective_targets(&mut world).is_empty(), "nobody can stand in front of it");
assert!(on_the_pad(&mut world, MacroKind::GoOut), "so the room is not a trap");
// A pushed tile somewhere else changes nothing.
let mut other = bills_house().at(3, 5);
other.npcs.clear();
other.talked.insert(TalkTarget::Sprite(1));
other.pushes.insert(Tile::new(2, 5));
assert_eq!(super::palette::objective_targets(&mut other).len(), 1);
}
#[test]
fn a_hidden_event_is_nobody_elses_target() {
// A hidden event is every PC, poster and trash can in Kanto. Outside the errand that names it
// no macro aims at one and `TALK` is not dealt in front of one: `GO ITEM` is what it was.
let mut world = bills_house().at(1, 5);
world.npcs.clear();
world.facing = Facing::Up;
world.objective = Some(Objective { map: maps::ROUTE_25, tile: None, warp: None, edge: None, target: None });
assert!(super::palette::untalked_objects(&mut world).is_empty());
assert!(!on_the_pad(&mut world, MacroKind::GoItem));
assert!(!on_the_pad(&mut world, MacroKind::Talk));
assert_eq!(super::palette::facing_target(&mut world), None);
}

View file

@ -84,22 +84,12 @@ pub const MT_MOON_1F: u8 = 0x3b;
pub const MT_MOON_B1F: u8 = 0x3c;
pub const MT_MOON_B2F: u8 = 0x3d;
pub const CERULEAN_POKECENTER: u8 = 0x40;
/// The house the Rockets robbed (row 73): the id before `CERULEAN_TRADE_HOUSE` and
/// `CERULEAN_POKECENTER` `$40`, and confirmed by the cartridge rather than by counting -- Cerulean
/// City's warp table names `$3e` at (27, 11) and at (27, 9), its front door and the hole in its
/// back wall.
pub const CERULEAN_TRASHED_HOUSE: u8 = 0x3e;
pub const CERULEAN_GYM: u8 = 0x41;
pub const CERULEAN_MART: u8 = 0x43;
/// Route 4's Pokémon Center, the one beside Mt. Moon's mouth: the id straight after
/// `CERULEAN_MART` `$43`, and confirmed by the cartridge rather than by counting -- Route 4's warp
/// table names `$44` at (11, 5) (`tests/rom_macros_mode.rs`, row 59's door survey).
pub const MT_MOON_POKECENTER: u8 = 0x44;
/// Bill's house on Route 25, where rung 16 (the S.S. Ticket) is earned (row 73). Confirmed by the
/// cartridge rather than by counting: Route 25's warp table names `$58` at (45, 3), and the
/// cartridge's own hidden-event map list (`HiddenEventMaps`) carries `$58` at the position the
/// disassembly lists `BILLS_HOUSE` in (`tests/rom_macros_mode.rs`, row 73).
pub const BILLS_HOUSE: u8 = 0x58;
pub const ROCK_TUNNEL_1F: u8 = 0x52;
pub const INDIGO_PLATEAU_LOBBY: u8 = 0xae;
/// The house beside Cerulean's west road whose back door is the one way into the closed yard at

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