Compare commits

..

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

69 changed files with 394 additions and 5730 deletions

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.")

View file

@ -187,7 +187,6 @@ 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) |
@ -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.
@ -565,45 +561,3 @@ a staging file, reading a sealed one, up to 256 KiB) run in place rather than on
-- 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

@ -541,51 +541,6 @@ multiplayer and more flies follow. The topology, its rules and the shadow proced
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

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

@ -589,10 +589,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

View file

@ -129,12 +129,6 @@ page_on_feed() {
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
@ -201,24 +195,24 @@ status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
say "configured: ${conf}"
say "running: ${run}"
echo "configured: ${conf}"
echo "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)"
echo " 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}"
echo "${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"
echo "edge healthz: ok"
else
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
echo "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)"
echo "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
echo "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 echo "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage

View file

@ -518,12 +518,6 @@ check() {
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,8 +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
@ -177,9 +175,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
@ -716,39 +711,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).
#
@ -1371,7 +1333,6 @@ main() {
check_flystage
check_flycast
check_encoder
check_backend
check_mediamtx
check_flypush
check_disk

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

@ -1182,49 +1182,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 +1427,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

View file

@ -867,23 +867,6 @@ if command -v python3 >/dev/null 2>&1; then
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
@ -1659,8 +1642,6 @@ 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
@ -1722,21 +1703,6 @@ 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" \

View file

@ -505,7 +505,6 @@ dependencies = [
"flybrain-gb",
"flybus",
"flysim-store",
"libc",
"serde_json",
"tempfile",
"tokio",
@ -535,7 +534,6 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"tempfile",
]
[[package]]

View file

@ -342,31 +342,6 @@ async fn a_request_body_over_the_envelope_gets_directs_answer() {
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)]

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

View file

@ -528,26 +528,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(),
@ -606,14 +586,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| {

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

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

@ -417,10 +417,6 @@ struct Endpoints {
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>>,
}
@ -552,40 +548,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,8 +562,6 @@ 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),
@ -610,7 +571,6 @@ impl Launcher {
},
store_root: store_root.into(),
sockets,
gpu_marker,
next_socket: AtomicU64::new(0),
listeners: Mutex::new(Vec::new()),
};
@ -1050,9 +1010,7 @@ impl Launcher {
.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,
@ -1713,9 +1671,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;
@ -461,10 +460,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 +511,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 +869,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 +933,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 +1169,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",
@ -1631,19 +1551,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

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

@ -162,23 +162,17 @@ pub struct HandlerCtx<'a> {
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.
/// Staging writers allocated ahead of need (BUS-01). 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 allocating one
/// is a router round trip on the step's critical path. The pool remembers the last few
/// `(content type, length)` shapes [`HandlerCtx::seal`] asked for and, after each reply, allocates
/// a writer for every remembered shape that has none, off the critical path. A seal that finds a
/// ready writer of its exact shape writes and seals it; one that does not allocates as before. A
/// writer is an artifact like any other: unsealed, it is released when dropped, and the bytes it
/// seals are the bytes written, so nothing a caller sees depends on the pool.
#[derive(Default)]
pub struct WriterPool {
state: Mutex<PoolState>,
@ -188,51 +182,27 @@ pub struct WriterPool {
struct PoolState {
/// The most recent distinct shapes, newest last.
recent: Vec<(String, u64)>,
ready: Vec<flybus::ArtifactWriter>,
ready: Vec<((String, u64), 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
}
/// Shapes the pool keeps writers for: an environment's three reply artifacts, with the audio
/// chunk's two lengths, and an agent's one.
const POOL_SHAPES: usize = 4;
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));
let shape = (content_type.to_owned(), 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);
}
st.ready.retain(|(s, _)| *s != gone);
}
st.recent.push(shape.clone());
let at = st.ready.iter().position(|(s, _)| *s == shape)?;
Some(st.ready.swap_remove(at).1)
}
/// Allocates, in the background, a writer for every remembered shape that has none.
@ -242,10 +212,7 @@ impl WriterPool {
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)
})
.filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s))
.cloned()
.collect();
st.allocating.extend(wanted.iter().cloned());
@ -260,7 +227,7 @@ impl WriterPool {
if let Ok(writer) = writer
&& st.recent.contains(&shape)
{
st.ready.push(writer);
st.ready.push((shape, writer));
}
});
}
@ -323,36 +290,26 @@ 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 => {
// A writer allocated ahead for this shape saves the allocation's round trip ([`WriterPool`]).
let Some(mut writer) = self.writers.take(content_type, bytes.len() as u64) else {
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))?
}
return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await;
};
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)
writer
.seal()
.await
.map_err(|e| crate::media::store_error("seal", &e.message))
}
}
@ -519,42 +476,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())
}
}
}
@ -820,7 +751,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 +762,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 +776,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 +797,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 +907,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.
@ -988,7 +918,6 @@ async fn execute<E: WorkerEndpoint>(
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
@ -1050,88 +979,22 @@ async fn execute<E: WorkerEndpoint>(
}
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;
answer.send(outcome, &reply.artifacts).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).
// The next step's writers, 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);
}
}
@ -1164,7 +1027,7 @@ answering BACKEND_FAILURE",
request.scope.clone(),
e,
);
answer.send(outcome, &[], Vec::new()).await;
answer.send(outcome, &[]).await;
}
}
}
@ -1338,7 +1201,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

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

View file

@ -222,10 +222,6 @@ const RUNG_PLACES: [Option<MapPlace>; RANK_LADDER.len()] = {
const fn object(map: u8) -> Option<MapPlace> {
Some(MapPlace::object(map))
}
/// A rung earned by an errand in one room: its people, then its things.
const fn errand(map: u8) -> Option<MapPlace> {
Some(MapPlace::errand(map))
}
[
None, // 0 BOOT: nowhere.
at(maps::REDS_HOUSE_2F), // 1 BEDROOM
@ -248,12 +244,7 @@ const RUNG_PLACES: [Option<MapPlace>; RANK_LADDER.len()] = {
at(maps::CERULEAN_CITY), // 13 CERULEAN CITY
person(maps::CERULEAN_GYM), // 14 CASCADE BADGE, likewise
at(maps::ROUTE_24), // 15 NUGGET BRIDGE, north out of Cerulean
// 16 MET BILL: the S.S. Ticket is Bill's thanks for an errand in his house -- talk to
// him (he is a Pokémon), press the cell separator's PC (a hidden event, not a sprite),
// talk to him again. One room, people then things: an errand (row 73). It was
// `at(ROUTE_25)`, and a fly on Route 25 was already "there", so inside the house
// `GO OBJECTIVE` was the door out to the route.
errand(maps::BILLS_HOUSE),
at(maps::ROUTE_25), // 16 MET BILL, whose house is on Route 25
at(maps::VERMILION_CITY), // 17 VERMILION CITY
at(maps::VERMILION_CITY), // 18 HM CUT, on the S.S. Anne at Vermilion's dock
None, // 19 THUNDER BADGE: Vermilion Gym, id not derived

View file

@ -33,7 +33,7 @@ use super::macros::geography::Amenity;
use super::mapgrid::{self, MapGrids};
use super::macros::state::{
BagItem, Battle, BattleKind, BattleMenu, Connections, Cursor, EnemyMon, Facing, GameState,
HiddenEvent, MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu,
MapGrid, MapSize, Mon, Move, Naming, Npc, Party, Pc, Player, Scene, Shop, ShopScreen, Sign, StartMenu,
Status, TextBox, Walkable, Warp,
};
use super::symbols::ram;
@ -348,31 +348,6 @@ pub mod poke {
pub const TYPE_ELECTRIC: u8 = 0x17;
}
/// The cartridge's hidden-event tables (row 73, `docs/design/macros.md` 12.35).
///
/// `engine/overworld/hidden_events.asm`: `CheckForHiddenEvent` walks `HiddenEventMaps`, one
/// map id per byte to a `$ff`, and with the index it found there reads a little-endian pointer
/// out of `HiddenEventPointers` to that map's list. Both tables and every list are in the
/// routine's own `SECTION "Hidden Events Core"`, which `layout.link` places in ROM bank `$11`.
/// At the pinned commit the two tables are at `$11:$6A40` and `$11:$6A96`: read from the
/// operands of the routine's `ld hl, HiddenEventMaps` and `ld hl, HiddenEventPointers` on the
/// cartridge, and pinned by the ROM-gated test that reads them back from there. A list entry is
/// six bytes (`hidden_event`): y, x, the routine's argument, and the routine as `dba`.
pub mod hidden {
pub const TABLE_BANK: u8 = 0x11;
pub const MAPS_ADDRESS: u16 = 0x6a40;
pub const POINTERS_ADDRESS: u16 = 0x6a96;
pub const ENTRY_BYTES: u16 = 6;
/// More maps than the table has (85 at the pinned commit), and more entries than any one
/// map's list (the Game Corner's 48 slot machines and coins are the longest): a walk that
/// runs past either is not walking the table the disassembly describes, and answers
/// nothing.
pub const MAX_MAPS: u16 = 128;
pub const MAX_ENTRIES: u16 = 64;
/// `SPRITE_FACING_DOWN`, `_UP`, `_LEFT`, `_RIGHT` (`constants/sprite_data_constants.asm`).
pub const FACINGS: [u8; 4] = [0x00, 0x04, 0x08, 0x0c];
}
/// The cartridge's item-use dispatch and the ids that name its routines (row 63,
/// `docs/design/macros.md` 12.27).
pub mod items {
@ -2080,66 +2055,6 @@ pub fn signs(memory: &mut dyn MemoryReader) -> Vec<Sign> {
signs
}
/// The current map's hidden events, read from the cartridge's own table ([`poke::hidden`]).
///
/// Empty on a map the table does not list, when the seam has no cartridge image behind it, and
/// when the bytes are not the shape the disassembly describes -- a map list with no end, a pointer
/// outside the bank's window, a list longer than any map's. An entry whose tile is off the loaded map is skipped, not fatal. A table
/// this module cannot read is not one it reports, so a wrong address narrows (`GO OBJECTIVE` has
/// one less thing to aim at) and never invents a tile.
pub fn hidden_events(memory: &mut dyn MemoryReader) -> Vec<HiddenEvent> {
hidden_events_inner(memory).unwrap_or_default()
}
fn hidden_events_inner(memory: &mut dyn MemoryReader) -> Option<Vec<HiddenEvent>> {
use poke::hidden::*;
let size = map_size(memory)?;
let map = read(memory, ram::wCurMap);
let mut index = None;
for position in 0..MAX_MAPS {
let id = memory.read_rom(TABLE_BANK, MAPS_ADDRESS + position)?;
if id == 0xff {
break;
}
if id > poke::MAX_MAP_ID || position + 1 == MAX_MAPS {
return None;
}
if id == map && index.is_none() {
index = Some(position);
}
}
let Some(position) = index else { return Some(Vec::new()) };
let at = POINTERS_ADDRESS + 2 * position;
let list = u16::from_le_bytes([memory.read_rom(TABLE_BANK, at)?, memory.read_rom(TABLE_BANK, at + 1)?]);
if !(0x4000..0x8000).contains(&list) {
return None;
}
let mut out = Vec::new();
for entry in 0..MAX_ENTRIES {
let base = list.checked_add(entry * ENTRY_BYTES)?;
let y = memory.read_rom(TABLE_BANK, base)?;
if y == 0xff {
return Some(out);
}
let x = memory.read_rom(TABLE_BANK, base + 1)?;
let argument = memory.read_rom(TABLE_BANK, base + 2)?;
let routine =
u16::from_le_bytes([memory.read_rom(TABLE_BANK, base + 4)?, memory.read_rom(TABLE_BANK, base + 5)?]);
if routine >= 0x8000 {
return None;
}
// The cartridge has entries off their own map (the Safari Zone gate's inaccessible
// nugget, the rest houses' copied Pokecenter PC): the map's other entries are still
// good, so only the bad one is skipped. The entry index stays the list position.
if x >= size.width || y >= size.height {
continue;
}
let facing = FACINGS.contains(&argument).then(|| facing_from(argument));
out.push(HiddenEvent { x, y, index: entry as u8, facing });
}
None
}
/// Which of the current map's edges lead to another map, from `wCurMapConnections`.
pub fn connections(memory: &mut dyn MemoryReader) -> Connections {
let bits = read(memory, ram::wCurMapConnections);
@ -2330,10 +2245,6 @@ impl GameState for PokeState<'_> {
signs(self.memory)
}
fn hidden_events(&mut self) -> Vec<HiddenEvent> {
hidden_events(self.memory)
}
fn walkable(&mut self, x: u8, y: u8) -> Walkable {
walkable(self.memory, x, y)
}

View file

@ -1462,23 +1462,3 @@ fn the_naming_screen_reads_unknown_in_a_battle_and_title_before_the_game() {
wram.naming_screen(0, 7);
assert_eq!(crate::pokemon_red::scene::detect(&mut wram), Scene::Title);
}
#[test]
fn an_off_map_hidden_event_is_skipped_and_the_maps_other_entries_are_kept() {
// Row 73 review N1. The Safari Zone gate lists a nugget at (10, 1) on an 8 x 6 map, and the
// rest houses a copied Pokecenter PC at (13, 3) on 8 x 8 maps: one entry off its own map used
// to void the list.
let mut wram = Wram::new();
// Two blocks by two is a 4 x 4 tile map.
wram.map(0x5d, 2, 2, 1, 1).hidden_table(0x5d, &[(1, 10, 0x00), (2, 1, 0x04), (9, 1, 0x08), (0, 3, 0x17)]);
let events = hidden_events(&mut wram);
assert_eq!(
events.iter().map(|event| (event.x, event.y, event.index)).collect::<Vec<_>>(),
vec![(1, 2, 1), (3, 0, 3)],
"the entries on the map, under their own list positions"
);
// A list with nothing wrong in it is what it was.
let mut wram = Wram::new();
wram.map(0x5d, 2, 2, 1, 1).hidden_table(0x5d, &[(2, 1, 0x04)]);
assert_eq!(hidden_events(&mut wram).len(), 1);
}

View file

@ -1273,8 +1273,6 @@ fn the_objective_is_the_next_unreached_rungs_place_where_the_catalog_knows_one()
assert_eq!(RUNG_PLACES[11].map(|place| place.map), Some(maps::PEWTER_GYM), "BOULDER BADGE");
assert_eq!(RUNG_PLACES[14].map(|place| place.map), Some(maps::CERULEAN_GYM), "CASCADE BADGE");
assert_eq!(RUNG_PLACES[19], None, "THUNDER BADGE: Vermilion Gym's id is not derived");
// Row 73: the ticket is an errand inside Bill's house, not the route the house is on.
assert_eq!(RUNG_PLACES[16], Some(crate::adapter::MapPlace::errand(maps::BILLS_HOUSE)), "MET BILL");
// And past the top of the ladder there is no next rung at all.
assert_eq!(RUNG_PLACES.len(), RANK_LADDER.len());
assert_eq!(rung_place(&f.reward.seen, RANK_LADDER.len()), None);

View file

@ -11,8 +11,7 @@ description = "A small local RPC and pub/sub bus with immutable file-backed arti
# `flock`, `posix_fallocate` and `O_NOFOLLOW`; everything else is std or Tokio.
libc = "0.2"
serde = { workspace = true }
# `raw_value`: the router forwards payloads it validated as pre-encoded JSON (BUS-02).
serde_json = { workspace = true, features = ["raw_value"] }
serde_json = { workspace = true }
sha2 = { workspace = true }
tokio = { version = "1", features = ["rt", "net", "io-util", "sync", "time", "macros"] }

View file

@ -186,16 +186,6 @@ let kept = frame.retain().await?; // an independent explicit hold
- Sealing copies staging into a fresh read-only (0444) file and unlinks staging. A descriptor
the producer kept or duplicated afterwards writes only to the unlinked staging inode. Sealing
therefore needs quota for both copies while it runs.
- **Sealing sends** (bus-v1 section 12, amendment 2026-10-02). `writer.into_unsealed()` ends
writing and returns an `Unsealed` whose `artifact()` is the handle the sealed artifact will have
(its first `written()` bytes, on the hold the writer becomes). Attach that handle to
`responder.reply_sealing(outcome, attachments, unsealed, recycle)`: the router seals it as it
admits the reply, with no `artifact.seal` round trip, and with `recycle` hands each staging
allocation back as a fresh writer (`SealedReply::writers`), with no `artifact.allocate` either.
The router zero-fills a reissued staging file first, so a recycled writer reads as zeros like a
new allocation and never carries the previous artifact's bytes into the next one, however it
is sealed. The handle is valid once the reply is admitted. The router accepts sealing attachments on
`rpc.call` and `publish` too; the SDK exposes them for replies.
### Errors
@ -342,13 +332,6 @@ before admission are `not-dispatched`. A command in flight when the connection i
`rpc.request`, `rpc.result` or `topic.message` delivery carries `readLocation`, the location
`artifact.open` would return under that delivery's ownership; a client attachment that carries
one is refused as an unknown field. `wire::CONTRACT` (and so `contractDigest`) says so.
12. **Sealing sends** (amendment 2026-10-02, BUS-02). An `rpc.call`, `rpc.reply` or `publish`
attachment may name the sender's own unsealed writer (`ref.byteLength` at most its
allocation, digest null); the router seals that prefix before admitting the command and the
writer becomes the sender's hold. A body `recycle: true` reissues each sealed writer's
staging file, zero-filled, as a new writer, listed in the reply value's `writers`. A refused sealing send
releases every writer it named. The SDK no longer sends `rpc.responder.release` after a
reply the router admitted (it was a no-op). `wire::CONTRACT` says so.
## Limitations
@ -386,8 +369,6 @@ before admission are `not-dispatched`. A command in flight when the connection i
cargo test -p flybus # unit + integration
cargo test --release -p flybus --test perf -- --ignored --nocapture # the measurement above
cargo run -p flybus --example demo # counter RPC, observer, held frame
cargo run --release -p flybus --example rtt -- --spawned [--reply-artifact 92160 --read --sealing]
# one RPC round trip's latency
```
Every integration test runs twice, once over the in-memory transport and once over a Unix
@ -410,15 +391,6 @@ socket, through the same router code:
fan-out and collected after the last consumer; extracted artifacts and holds; atomic
admission; release watermarks; connection-scoped owners; abandoned futures; disconnects; and
router restarts.
- `tests/sealing.rs`: sealing sends (amendment 2026-10-02): a reply that seals a writer's
written prefix and recycles its allocation three times over one staging file, the caller's
and the responder's handles reading the same bytes; refusals before and after the seal that
release every writer named; `recycle` validation; a recycled writer sealing normally, and
never exposing its previous artifact's bytes (a smaller artifact after a larger one, by prefix
and whole); a failed rename leaving no staging file behind.
- `tests/sealing_lifecycle.rs`: the BUS-02 review's adversarial lifecycle checks: refusal after
the seal, quota, a seal failing mid-send, no owner budget, no aliasing, a sender vanishing
mid-seal, fan-out.
- `tests/integration.rs`: two agents called in parallel with a forwarded frame, an environment
service, committed snapshot publication, a slow latest consumer and a bounded recorder.
- `tests/bus_acceptance.rs`: the implementation guide's BUS-01/02/03 acceptance bullets that the

View file

@ -1,257 +0,0 @@
//! Round-trip latency of one RPC through the router, the cost every session transition pays
//! several times (BUS-02). The router and the caller share one process (as the session's
//! router and coordinator do); the service is a child process on a Unix socket (process mode)
//! or a task in the same process over an in-memory pipe (`--in-memory`).
//!
//! ```text
//! cargo run --release -p flybus --example rtt -- [--calls N] [--payload BYTES] [--reply-artifact BYTES]
//! [--router-workers N] [--in-memory] [--read]
//! ```
//!
//! `--reply-artifact` makes the service seal an artifact of that size into every reply (a
//! writer allocated ahead, as the session's writer pool does) and `--read` makes the caller read
//! it. Prints p50/p90/p99 in microseconds. Local synthetic timings, no capacity claim.
use std::time::{Duration, Instant};
use flybus::{Client, ClientConfig, Policy, Router, RouterConfig, ServiceConfig};
use serde_json::{Map, Value};
#[derive(Clone, Copy)]
struct Opts {
calls: usize,
payload: usize,
reply_artifact: usize,
router_workers: usize,
in_memory: bool,
read: bool,
spawned: bool,
sealing: bool,
}
fn opts(args: &[String]) -> Opts {
let mut o = Opts {
calls: 2000,
payload: 512,
reply_artifact: 0,
router_workers: 2,
in_memory: false,
read: false,
spawned: false,
sealing: false,
};
let mut i = 0;
while i < args.len() {
let next = |i: usize| args.get(i + 1).and_then(|v| v.parse::<usize>().ok()).unwrap_or(0);
match args[i].as_str() {
"--calls" => {
o.calls = next(i);
i += 1;
}
"--payload" => {
o.payload = next(i);
i += 1;
}
"--reply-artifact" => {
o.reply_artifact = next(i);
i += 1;
}
"--router-workers" => {
o.router_workers = next(i).max(1);
i += 1;
}
"--in-memory" => o.in_memory = true,
"--read" => o.read = true,
"--spawned" => o.spawned = true,
"--sealing" => o.sealing = true,
_ => {}
}
i += 1;
}
o
}
fn payload(bytes: usize) -> Map<String, Value> {
let mut m = Map::new();
m.insert("blob".into(), Value::String("x".repeat(bytes)));
m
}
async fn serve(client: Client, reply_artifact: usize, sealing: bool) {
let mut svc = client.register("bench.echo", ServiceConfig::default()).await.unwrap();
let mut ahead = None;
while let Some(req) = svc.next().await {
if sealing && reply_artifact > 0 {
// Sealed by the router as it admits the reply; the staging file comes back as the
// next writer (`--sealing`).
let mut w = match ahead.take() {
Some(w) => w,
None => client
.artifacts()
.allocate(reply_artifact as u64, "application/octet-stream")
.await
.unwrap(),
};
use std::io::Write;
w.write_all(&vec![7u8; reply_artifact]).unwrap();
let unsealed = w.into_unsealed();
let blob = unsealed.artifact().clone();
let out = req
.responder()
.reply_sealing(payload(64), &[("blob", &blob)], vec![unsealed], true)
.await
.unwrap();
ahead = out.writers.into_iter().next();
continue;
}
let mut atts = Vec::new();
if reply_artifact > 0 {
let mut w = match ahead.take() {
Some(w) => w,
None => client
.artifacts()
.allocate(reply_artifact as u64, "application/octet-stream")
.await
.unwrap(),
};
use std::io::Write;
w.write_all(&vec![7u8; reply_artifact]).unwrap();
atts.push(("blob", w.seal().await.unwrap()));
}
let refs: Vec<(&str, &flybus::Artifact)> = atts.iter().map(|(n, a)| (*n, a)).collect();
let _ = req.reply(payload(64), &refs).await;
drop(req);
if reply_artifact > 0 {
ahead = Some(
client
.artifacts()
.allocate(reply_artifact as u64, "application/octet-stream")
.await
.unwrap(),
);
}
}
}
fn child(sock: &str, root: &str, reply_artifact: usize, sealing: bool) {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
// As a session participant serves: on the runtime's one worker, not the blocked main thread.
let (sock, root) = (sock.to_owned(), root.to_owned());
let handle = rt.handle().clone();
rt.block_on(async move {
handle
.spawn(async move {
let client = Client::connect_unix(sock, ClientConfig::new("svc", root)).await.unwrap();
serve(client, reply_artifact, sealing).await;
})
.await
.unwrap();
});
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("--child") {
child(&args[1], &args[2], args[3].parse().unwrap(), args[4] == "1");
return;
}
let o = opts(&args);
let dir = std::env::temp_dir().join(format!("flybus-rtt-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let root = dir.join("store");
let sock = dir.join("bus.sock");
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(o.router_workers)
.enable_all()
.build()
.unwrap();
let spawned = o.spawned;
let (root2, sock2) = (root.clone(), sock.clone());
let body = async move {
let (root, sock) = (root2, sock2);
let mut child_proc = None;
let mut config = RouterConfig::new(&root);
config.policy = Policy::open();
let router = Router::new(config).unwrap();
let _listener = router.listen_unix(&sock).await.unwrap();
if o.in_memory {
let c = Client::connect(router.connect_in_memory(), ClientConfig::new("svc", &root))
.await
.unwrap();
tokio::spawn(serve(c, o.reply_artifact, o.sealing));
} else {
child_proc = Some(
std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--child",
sock.to_str().unwrap(),
root.to_str().unwrap(),
&o.reply_artifact.to_string(),
if o.sealing { "1" } else { "0" },
])
.spawn()
.unwrap(),
);
}
let caller = Client::connect(router.connect_in_memory(), ClientConfig::new("caller", &root))
.await
.unwrap();
// Wait for the service to register.
loop {
match caller.call_and_wait("bench.echo", None, "Echo", payload(8), &[]).await {
Ok(_) => break,
Err(_) => tokio::time::sleep(Duration::from_millis(20)).await,
}
}
let mut samples = Vec::with_capacity(o.calls);
for i in 0..o.calls + 100 {
let t = Instant::now();
let result = caller
.call_and_wait("bench.echo", None, "Echo", payload(o.payload), &[])
.await
.unwrap();
if o.read && o.reply_artifact > 0 {
let a = result.artifact("blob").unwrap();
let bytes = a.read_all().await.unwrap();
assert_eq!(bytes.len(), o.reply_artifact);
}
drop(result);
if i >= 100 {
samples.push(t.elapsed());
}
}
samples.sort();
let p = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6;
println!(
"rtt mode={} sealing={} payload={} reply_artifact={} read={} router_workers={} calls={}: p50={:.0}us p90={:.0}us p99={:.0}us",
if o.in_memory { "in-memory" } else { "process" },
o.sealing,
o.payload,
o.reply_artifact,
o.read,
o.router_workers,
o.calls,
p(0.5),
p(0.9),
p(0.99)
);
child_proc
};
// `--spawned`: the caller runs on a runtime worker, beside the router's tasks, instead of on
// the thread that blocks on the runtime.
let child_proc = if spawned {
let handle = rt.handle().clone();
rt.block_on(async move { handle.spawn(body).await.unwrap() })
} else {
rt.block_on(body)
};
if let Some(mut c) = child_proc {
let _ = c.kill();
let _ = c.wait();
}
let _ = std::fs::remove_dir_all(&dir);
}

View file

@ -12,9 +12,9 @@ use std::sync::Arc;
use serde_json::{Map, Value};
use tokio::sync::{mpsc, oneshot};
use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand, WriterGrant};
use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand};
use crate::error::{BusError, Dispatch, ErrorCode};
use crate::store::{open_read, open_write, resolve};
use crate::store::{open_read, resolve};
use crate::wire::{ArtifactRef, Attachment, Fields, GENERATION, Identity, Location};
pub(crate) struct OwnerGuard {
@ -238,7 +238,7 @@ impl Artifact {
"read location names another store",
));
}
let path = resolve(&shared.store_root, &loc.store_id, &loc, &shared.dirs)?;
let path = resolve(&shared.store_root, &loc.store_id, &loc)?;
let file = open_read(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("open: {e}")))?;
let len = file
@ -363,8 +363,6 @@ pub struct ArtifactWriter {
pub(crate) artifact_id: String,
pub(crate) byte_length: u64,
pub(crate) written: u64,
pub(crate) store_id: String,
pub(crate) content_type: String,
}
impl ArtifactWriter {
@ -376,44 +374,8 @@ impl ArtifactWriter {
self.byte_length
}
/// Bytes written so far: what a sealing send seals ([`Responder::reply_sealing`]).
pub fn written(&self) -> u64 {
self.written
}
pub fn content_type(&self) -> &str {
&self.content_type
}
/// Ends writing and returns the artifact as a sealing send will seal it: its first
/// [`written`](Self::written) bytes, under this writer's owner, which becomes the hold
/// (bus-v1 section 12 amendment 2026-10-02). The handle is usable once a send that attaches
/// it -- [`Responder::reply_sealing`] -- is admitted; before that it is only a name for it.
pub fn into_unsealed(mut self) -> Unsealed {
drop(self.file.take());
let reference = ArtifactRef {
store_id: self.store_id.clone(),
artifact_id: self.artifact_id.clone(),
generation: GENERATION,
byte_length: self.written,
content_type: self.content_type.clone(),
digest: None,
};
Unsealed {
artifact: Artifact {
reference: Arc::new(reference),
holder: Holder::Bus(self.owner.clone()),
location: None,
},
capacity: self.byte_length,
content_type: std::mem::take(&mut self.content_type),
}
}
/// Closes the writable handle and seals the whole allocation, returning the immutable
/// artifact on an explicit hold. Bytes not written read as zeros: the staging file is
/// preallocated, and a recycled writer's ([`SealedReply::writers`]) is reset to zeros when
/// the router reissues it, so no artifact ever carries bytes of the one before it.
/// Closes the writable handle and seals, returning the immutable artifact on an explicit
/// hold. Bytes not written read as zeros: the staging file is preallocated.
pub async fn seal(self) -> Result<Artifact, BusError> {
self.seal_with_digest(None).await
}
@ -577,30 +539,6 @@ impl Request {
}
}
/// A writer's artifact waiting for the send that seals it ([`ArtifactWriter::into_unsealed`]).
pub struct Unsealed {
artifact: Artifact,
capacity: u64,
content_type: String,
}
impl Unsealed {
/// The handle the sealed artifact will have; attach it to the sealing send.
pub fn artifact(&self) -> &Artifact {
&self.artifact
}
}
/// What a sealing reply ([`Responder::reply_sealing`]) produced.
pub struct SealedReply {
/// As [`Responder::reply`]: routed to the caller, or the caller had detached.
pub routed: bool,
/// With `recycle`, a fresh writer of the same allocation for each artifact sealed. Its
/// staging file is the sealed artifact's, zero-filled: it reads as zeros, as a new
/// allocation does.
pub writers: Vec<ArtifactWriter>,
}
/// Replies to one request, whether or not the request delivery is still held.
#[derive(Clone)]
pub struct Responder {
@ -629,100 +567,18 @@ impl Responder {
.shared
.command("rpc.reply", body, atts, keep, Hook::None)
.await?;
// An admitted reply ends this call's reply authority at the router (routed or, for a
// detached caller, retired), so there is nothing left to release (BUS-02): the
// `rpc.responder.release` the guard would send is a no-op command on every call.
self.guard
.replied
.store(true, std::sync::atomic::Ordering::Release);
Ok(Fields::of(&reply.value, "reply").boolean("routed")?)
}
}
impl Responder {
/// Replies with `attachments`, among which the artifacts of `unsealed` are sealed by the
/// router as it admits the reply (bus-v1 section 12 amendment 2026-10-02): each becomes an
/// immutable artifact exactly as if it had been sealed and then attached, without the
/// `artifact.seal` round trip. With `recycle` the router reissues each one's staging
/// allocation as a new writer, which saves the next `artifact.allocate`. Refused, nothing
/// is admitted and every unsealed artifact is gone.
pub async fn reply_sealing(
&self,
outcome: Map<String, Value>,
attachments: &[(&str, &Artifact)],
unsealed: Vec<Unsealed>,
recycle: bool,
) -> Result<SealedReply, BusError> {
let (atts, keep) = attachment_list(attachments)?;
let shapes: Vec<(String, u64, String)> = unsealed
.into_iter()
.filter_map(|u| {
let name = atts
.iter()
.find(|a| a.reference.artifact_id == u.artifact.reference.artifact_id)?
.name
.clone();
Some((name, u.capacity, u.content_type))
})
.collect();
let mut body = Map::new();
body.insert("callId".into(), self.call_id.clone().into());
body.insert(
"requestDeliveryId".into(),
self.request_delivery_id.clone().into(),
);
body.insert("outcome".into(), Value::Object(outcome));
if recycle && !shapes.is_empty() {
body.insert("recycle".into(), true.into());
}
let shared = &self.guard.conn.shared;
let reply = shared
.command("rpc.reply", body, atts, keep, Hook::Writers)
.await?;
self.guard
.replied
.store(true, std::sync::atomic::Ordering::Release);
let routed = Fields::of(&reply.value, "reply").boolean("routed")?;
let grants = match reply.extra {
Extra::Writers(grants) => grants,
_ => Vec::new(),
};
let mut writers = Vec::with_capacity(grants.len());
for WriterGrant { name, artifact_id, owner, location } in grants {
let Some((_, capacity, content_type)) = shapes.iter().find(|(n, _, _)| *n == name)
else {
continue;
};
let path = resolve(&shared.store_root, &location.store_id, &location, &shared.dirs)?;
let file = open_write(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("staging: {e}")))?;
writers.push(ArtifactWriter {
file: Some(file),
owner,
artifact_id,
byte_length: *capacity,
written: 0,
store_id: location.store_id,
content_type: content_type.clone(),
});
}
Ok(SealedReply { routed, writers })
}
}
pub(crate) struct ReplyGuard {
pub conn: Arc<ClientConn>,
pub call_id: String,
pub request_delivery_id: String,
/// Set once the router admitted a reply: the authority is spent, no release is sent.
pub replied: std::sync::atomic::AtomicBool,
}
impl Drop for ReplyGuard {
fn drop(&mut self) {
if self.replied.load(std::sync::atomic::Ordering::Acquire) {
return;
}
self.conn.shared.push_control(Control::ResponderReleased {
call_id: self.call_id.clone(),
request_delivery_id: self.request_delivery_id.clone(),

View file

@ -15,7 +15,7 @@ use tokio::sync::oneshot;
use handles::attachment_list;
pub use handles::{
IN_MEMORY_STORE_ID, Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder,
RpcResult, SealedReply, Service, Subscription, Unsealed,
RpcResult, Service, Subscription,
};
use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared};
@ -584,7 +584,7 @@ impl Artifacts<'_> {
return Err(BusError::lost("router issued a malformed artifact id"));
}
let loc = Location::from_json(f.value("writeLocation")?)?;
let path = resolve(&shared.store_root, &loc.store_id, &loc, &shared.dirs)?;
let path = resolve(&shared.store_root, &loc.store_id, &loc)?;
let file = open_write(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("staging: {e}")))?;
Ok(ArtifactWriter {
@ -593,8 +593,6 @@ impl Artifacts<'_> {
artifact_id,
byte_length,
written: 0,
store_id: loc.store_id,
content_type: content_type.to_owned(),
})
}
}

View file

@ -44,17 +44,6 @@ pub(crate) enum Extra {
Service(ServiceGuard, mpsc::UnboundedReceiver<Request>),
Subscription(SubscriptionGuard, mpsc::UnboundedReceiver<Message>),
Call(CallGuard),
/// The writers a sealing send's reply reissued (`recycle`), with their owners.
Writers(Vec<WriterGrant>),
}
/// One recycled writer a sealing send's reply granted (bus-v1 section 12 amendment
/// 2026-10-02): the attachment it was, and the new artifact its staging file now is.
pub(crate) struct WriterGrant {
pub name: String,
pub artifact_id: String,
pub owner: Arc<OwnerGuard>,
pub location: crate::wire::Location,
}
/// What the reactor does with a reply before handing it over. Handles are built here, inside
@ -68,8 +57,6 @@ pub(crate) enum Hook {
Subscribe,
Call(String),
Cancel(String),
/// `value.writers`, when present, are new writers (a recycling sealing send).
Writers,
}
pub(crate) struct OutCommand {
@ -127,8 +114,6 @@ pub(crate) struct ClientState {
pub(crate) struct Shared {
pub info: SessionInfo,
pub store_root: PathBuf,
/// The store directories this connection resolved (BUS-02 review N6: per connection).
pub dirs: crate::store::DirCache,
state: Mutex<ClientState>,
wake: Notify,
control_capacity: usize,
@ -159,7 +144,6 @@ impl Shared {
Shared {
info,
store_root,
dirs: crate::store::DirCache::default(),
state: Mutex::new(ClientState {
closed: None,
shutting_down: false,
@ -461,7 +445,6 @@ pub(crate) async fn write_loop(shared: Arc<Shared>, mut wr: WriteHalf<Transport>
_ = shutdown.wait_for(|v| *v) => break,
}
}
Next::Exit => break,
}
}
@ -631,11 +614,9 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
));
}
serial_field(&mut f, "serviceIncarnation", "svc")?;
validate_writers(&mut f)?;
}
"rpc.reply" => {
f.boolean("routed")?;
validate_writers(&mut f)?;
}
"rpc.responder.release" => {
f.boolean("released")?;
@ -665,7 +646,6 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
f.u64_string("topicSequence")?;
f.u64_string("subscribers")?;
f.u64_string("replaced")?;
validate_writers(&mut f)?;
}
"delivery.consumed" | "artifact.release" => {
f.u64_string("released")?;
@ -693,29 +673,6 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
f.finish()
}
/// The optional `writers` of a sealing send's reply (bus-v1 section 12 amendment 2026-10-02).
fn validate_writers(f: &mut Fields<'_>) -> Result<(), WireError> {
let Some(list) = f.optional("writers") else {
return Ok(());
};
let list = list
.as_array()
.filter(|l| (1..=crate::wire::MAX_ATTACHMENTS).contains(&l.len()))
.ok_or_else(|| WireError("writers must be an array of 1..=32 grants".into()))?;
for w in list {
let mut g = Fields::new(w, "writer")?;
g.id("name")?;
serial_field(&mut g, "artifactId", "a")?;
if g.u64_string("generation")? != GENERATION {
return Err(WireError("unsupported artifact generation".into()));
}
serial_field(&mut g, "ownerId", "own")?;
crate::wire::Location::from_json(g.value("writeLocation")?)?;
g.finish()?;
}
Ok(())
}
fn owner_guard(conn: &Weak<ClientConn>, id: String, delivery: bool) -> Option<Arc<OwnerGuard>> {
Some(Arc::new(OwnerGuard {
id,
@ -747,36 +704,6 @@ fn complete(
value,
extra: Extra::None,
}),
(Hook::Writers, Ok(value)) => {
// Every granted writer gets its guard here, inside the reactor, so a caller that
// abandoned the reply still releases them.
let mut grants = Vec::new();
let mut closed = false;
if let Some(Value::Array(list)) = value.get("writers") {
for w in list {
let mut g = Fields::new(w, "writer")?;
let name = g.id("name")?;
let artifact_id = g.id("artifactId")?;
let owner_id = g.id("ownerId")?;
let location = crate::wire::Location::from_json(g.value("writeLocation")?)?;
match owner_guard(conn, owner_id, false) {
Some(owner) => grants.push(WriterGrant { name, artifact_id, owner, location }),
None => {
closed = true;
break;
}
}
}
}
if closed {
Err(BusError::lost("client closed"))
} else {
Ok(Reply {
value,
extra: Extra::Writers(grants),
})
}
}
(Hook::Owner, Ok(value)) => {
let id = Fields::of(&value, "reply").id("ownerId")?;
match owner_guard(conn, id, false) {
@ -899,22 +826,12 @@ fn u64_field(f: &mut Fields<'_>, key: &'static str) -> Result<u64, WireError> {
parse_u64(s).ok_or_else(|| WireError(format!("{key} is not a U64")))
}
/// Moves an object field out of a validated body (BUS-02: the payload is the one large part of a
/// delivery, and it used to be deep-copied out of the tree it was parsed into).
fn take_object(body: &mut Map<String, Value>, key: &str) -> Map<String, Value> {
match body.remove(key) {
Some(Value::Object(m)) => m,
_ => Map::new(),
}
}
fn on_delivery(
shared: &Arc<Shared>,
conn: &Weak<ClientConn>,
mut env: Envelope,
env: Envelope,
) -> Result<(), WireError> {
let mut body = std::mem::take(&mut env.body);
let mut f = Fields::of(&body, "delivery");
let mut f = Fields::of(&env.body, "delivery");
let delivery_id = f.id("deliveryId")?;
let delivery_serial = parse_serial_id("dlv", &delivery_id)
.filter(|n| *n > 0)
@ -937,16 +854,14 @@ fn on_delivery(
return Err(WireError("service incarnation is not svc-<U64>".into()));
}
let method = f.method("method")?;
f.object("payload")?;
let payload = f.object("payload")?.clone();
f.finish()?;
let payload = take_object(&mut body, "payload");
accept_delivery_serial(shared, delivery_serial)?;
let req = Request {
reply_guard: Arc::new(ReplyGuard {
conn: guard.conn.clone(),
call_id: call_id.clone(),
request_delivery_id: delivery_id.clone(),
replied: std::sync::atomic::AtomicBool::new(false),
}),
guard,
call_id,
@ -976,9 +891,8 @@ fn on_delivery(
if parse_serial_id("svc", &service_incarnation).is_none() {
return Err(WireError("service incarnation is not svc-<U64>".into()));
}
f.object("outcome")?;
let outcome = f.object("outcome")?.clone();
f.finish()?;
let outcome = take_object(&mut body, "outcome");
accept_delivery_serial(shared, delivery_serial)?;
let res = RpcResult {
guard,
@ -1009,9 +923,8 @@ fn on_delivery(
}
let topic_sequence = u64_field(&mut f, "topicSequence")?;
let replaced = u64_field(&mut f, "replaced")?;
f.object("payload")?;
let payload = f.object("payload")?.clone();
f.finish()?;
let payload = take_object(&mut body, "payload");
accept_delivery_serial(shared, delivery_serial)?;
let msg = Message {
guard,
@ -1098,37 +1011,3 @@ fn on_notice(shared: &Arc<Shared>, env: Envelope) -> Result<(), WireError> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// The wire allows a recycling `rpc.call` or `publish` (bus-v1 section 12 amendment
/// 2026-10-02), so their reply values may carry `writers`, checked as an `rpc.reply`'s are
/// (BUS-02 review N4).
#[test]
fn every_sealing_send_reply_may_carry_writers() {
let writers = serde_json::json!([{
"name": "x", "artifactId": "a-2", "generation": "1", "ownerId": "own-3",
"writeLocation": {"storeId": "store-1", "relativePath": "staging/a-2"},
}]);
let with = |mut v: serde_json::Value| {
v["writers"] = writers.clone();
v.as_object().unwrap().clone()
};
let call = with(serde_json::json!({"accepted": true, "serviceIncarnation": "svc-1"}));
let publish =
with(serde_json::json!({"topicSequence": "1", "subscribers": "0", "replaced": "0"}));
let reply = with(serde_json::json!({"routed": true}));
assert!(validate_reply_value("rpc.call", &call).is_ok());
assert!(validate_reply_value("publish", &publish).is_ok());
assert!(validate_reply_value("rpc.reply", &reply).is_ok());
let mut bad = publish.clone();
bad.insert("writers".into(), serde_json::json!([]));
assert!(validate_reply_value("publish", &bad).is_err());
// Not on a command that cannot seal.
let mut declare = serde_json::json!({"declared": true, "topicIncarnation": "top-1"});
declare["writers"] = writers;
assert!(validate_reply_value("topic.declare", declare.as_object().unwrap()).is_err());
}
}

View file

@ -26,7 +26,7 @@ mod transport;
pub use client::{
Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message,
Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, SealedReply, Service, Unsealed,
Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service,
ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo,
};
pub use error::{BusError, Dispatch, ErrorCode};

View file

@ -331,64 +331,6 @@ async fn read_loop<R: AsyncRead + Unpin>(
};
inner.with_state(|s| s.finish_allocate(job, created));
}
Outcome::SealThenAdmit(job) => {
// The writers a sending command attaches are sealed before it is admitted
// (bus-v1 section 12 amendment 2026-10-02): the copies run here, outside the
// state lock, and this connection's next command waits for the admission, so
// its commands stay in order. A recycled writer's staging file is kept,
// renamed for the artifact it becomes and zero-filled, as a fresh allocation
// is (BUS-02 review N3); otherwise it goes with the copy.
let total: u64 = job.seals.iter().map(|s| s.len).sum();
let plan: Vec<(u64, u64, u64, Option<u64>)> = job
.seals
.iter()
.map(|s| (s.serial, s.len, s.capacity, s.recycle))
.collect();
let i = inner.clone();
let run = move || {
plan.into_iter()
.map(|(serial, len, capacity, recycle)| {
let r = i.store.seal_prefix(serial, len);
let staging = crate::store::staging_rel(serial);
match recycle {
Some(next) if r.is_ok() => {
match i.store.rename(&staging, &crate::store::staging_rel(next)) {
// A failed reset is a failed seal: the send is refused
// and `finish_sealing_send` unlinks the renamed file.
Ok(()) => i
.store
.reset_staging(next, capacity)
.map_err(SealFailure::Io),
// Not renamed: the staging file is still under its
// own name, and nothing else would unlink it (N5).
Err(e) => {
i.store.remove(&staging);
Err(SealFailure::Io(e))
}
}
}
_ => {
i.store.remove(&staging);
r
}
}
})
.collect::<Vec<_>>()
};
let results = if total <= crate::store::INLINE_IO_BYTES {
run()
} else {
let n = job.seals.len();
tokio::task::spawn_blocking(run).await.unwrap_or_else(|e| {
(0..n)
.map(|_| Err(SealFailure::Io(io::Error::other(e.to_string()))))
.collect()
})
};
if let Outcome::Close = inner.with_state(|s| s.finish_sealing_send(job, results)) {
return;
}
}
Outcome::Seal(job) if job.len <= crate::store::INLINE_IO_BYTES => {
// A small seal copies in place, for the same reason; the connection's reader
// waits for it as it waits for any command (BUS-01). The outcome is the

View file

@ -15,8 +15,6 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use serde::Serialize;
use serde_json::value::RawValue;
use serde_json::{Map, Value};
use tokio::sync::{Notify, watch};
@ -26,8 +24,7 @@ use crate::policy::{Grants, Policy};
use crate::store::{sealed_rel, staging_rel};
use crate::wire::{
ArtifactRef, Attachment, Envelope, Fields, GENERATION, Identity, Kind, MAJOR, MAX_BATCH,
MAX_CREDIT, MAX_ENVELOPE_BYTES, MINOR, Unnumbered, WireError, id_batch, parse_serial_id,
serial_id,
MAX_CREDIT, MAX_ENVELOPE_BYTES, MINOR, WireError, id_batch, parse_serial_id, serial_id,
};
pub(crate) type ConnKey = u64;
@ -158,9 +155,6 @@ pub(crate) enum Outcome {
Allocate(AllocJob),
/// Copy staging into the sealed file (off the routing path), then call `finish_seal`.
Seal(SealJob),
/// Seal the writers a sending command attaches (off the routing path), then call
/// `finish_sealing_send`, which admits the command (BUS-02).
SealThenAdmit(SealingSend),
/// The connection was closed; stop reading.
Close,
}
@ -182,36 +176,18 @@ pub(crate) struct SealJob {
pub owner: u64,
}
/// One writer a sending command attaches, sealed as the command is admitted (bus-v1 section 12
/// amendment 2026-10-02).
pub(crate) struct SendSeal {
/// The writer's artifact.
pub serial: u64,
/// The length sealed: the attachment's `byteLength`, at most the allocation.
pub len: u64,
/// The staging allocation.
pub capacity: u64,
pub owner: u64,
/// With `recycle`, the artifact the staging file is reissued as, once sealed.
pub recycle: Option<u64>,
}
pub(crate) struct SealingSend {
pub conn: ConnKey,
pub env: Envelope,
pub seals: Vec<SendSeal>,
}
pub(crate) enum NextFrame {
Frame(Vec<u8>),
Idle,
Gone,
}
/// A router frame, encoded once when it is built (BUS-02); its envelope id is spliced in when the
/// scheduler selects it.
pub(crate) struct Outbound {
frame: Unnumbered,
kind: Kind,
op: String,
reply_to: Option<String>,
body: Map<String, Value>,
attachments: Vec<Attachment>,
/// Conservative encoded size using the longest router envelope id.
bytes: usize,
}
@ -348,7 +324,7 @@ struct TopicMsg {
topic: String,
topic_incarnation: String,
sequence: u64,
payload: Box<RawValue>,
payload: Map<String, Value>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
bytes: usize,
@ -385,7 +361,7 @@ struct Svc {
struct ResultMsg {
responder: Identity,
outcome: Box<RawValue>,
outcome: Map<String, Value>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
}
@ -410,8 +386,7 @@ struct Call {
service_incarnation: String,
service_conn: ConnKey,
method: String,
/// The validated payload, encoded once at admission and forwarded verbatim (BUS-02).
payload: Box<RawValue>,
payload: Map<String, Value>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
phase: Phase,
@ -486,10 +461,10 @@ fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec<At
.collect()
}
fn frame_len<B: Serialize>(
fn frame_len(
kind: Kind,
op: &str,
body: B,
body: Map<String, Value>,
attachments: Vec<Attachment>,
) -> usize {
let id = serial_id("bus", MAX_SERIAL);
@ -507,113 +482,47 @@ fn frame_len<B: Serialize>(
.unwrap_or(usize::MAX)
}
/// An identity as delivery bodies carry it ([`Identity::to_json`]'s members, in order).
#[derive(Serialize)]
struct IdentityBody<'a> {
#[serde(rename = "clientId")]
client_id: &'a str,
#[serde(rename = "clientIncarnation")]
client_incarnation: &'a str,
}
impl<'a> From<&'a Identity> for IdentityBody<'a> {
fn from(i: &'a Identity) -> IdentityBody<'a> {
IdentityBody { client_id: &i.client_id, client_incarnation: &i.client_incarnation }
}
}
/// `rpc.request` (bus-v1 section 5), members in the order the router always sent them; the
/// payload is the admitted bytes, not a copy of a parsed tree (BUS-02).
#[derive(Serialize)]
struct RequestBody<'a> {
#[serde(rename = "deliveryId")]
delivery_id: &'a str,
#[serde(rename = "callId")]
call_id: &'a str,
caller: IdentityBody<'a>,
target: &'a str,
#[serde(rename = "serviceIncarnation")]
service_incarnation: &'a str,
method: &'a str,
payload: &'a RawValue,
}
/// `rpc.result`.
#[derive(Serialize)]
struct ResultBody<'a> {
#[serde(rename = "deliveryId")]
delivery_id: &'a str,
#[serde(rename = "callId")]
call_id: &'a str,
responder: IdentityBody<'a>,
#[serde(rename = "serviceIncarnation")]
service_incarnation: &'a str,
outcome: &'a RawValue,
}
/// `topic.message`.
#[derive(Serialize)]
struct TopicBody<'a> {
#[serde(rename = "deliveryId")]
delivery_id: &'a str,
#[serde(rename = "subscriptionId")]
subscription_id: &'a str,
topic: &'a str,
#[serde(rename = "topicIncarnation")]
topic_incarnation: &'a str,
#[serde(rename = "topicSequence")]
topic_sequence: String,
replaced: String,
payload: &'a RawValue,
}
/// Encodes an admitted payload once (BUS-02). It was parsed strictly on the way in, so it
/// re-encodes; a failure here is the caller's refusal like any oversized envelope.
fn raw(value: &Map<String, Value>) -> Result<Box<RawValue>, BusError> {
serde_json::value::to_raw_value(value)
.map_err(|e| BusError::new(ErrorCode::InvalidEnvelope, format!("payload: {e}")))
}
impl Call {
fn request_body<'a>(&'a self, delivery_id: &'a str) -> RequestBody<'a> {
RequestBody {
delivery_id,
call_id: &self.call_id,
caller: (&self.caller_identity).into(),
target: &self.target,
service_incarnation: &self.service_incarnation,
method: &self.method,
payload: &self.payload,
}
fn request_body(&self, delivery_id: &str) -> Map<String, Value> {
obj(vec![
("deliveryId", delivery_id.into()),
("callId", self.call_id.clone().into()),
("caller", self.caller_identity.to_json()),
("target", self.target.clone().into()),
(
"serviceIncarnation",
self.service_incarnation.clone().into(),
),
("method", self.method.clone().into()),
("payload", Value::Object(self.payload.clone())),
])
}
fn result_body<'a>(&'a self, delivery_id: &'a str, result: &'a ResultMsg) -> ResultBody<'a> {
ResultBody {
delivery_id,
call_id: &self.call_id,
responder: (&result.responder).into(),
service_incarnation: &self.service_incarnation,
outcome: &result.outcome,
}
fn result_body(&self, delivery_id: &str, result: &ResultMsg) -> Map<String, Value> {
obj(vec![
("deliveryId", delivery_id.into()),
("callId", self.call_id.clone().into()),
("responder", result.responder.to_json()),
(
"serviceIncarnation",
self.service_incarnation.clone().into(),
),
("outcome", Value::Object(result.outcome.clone())),
])
}
}
impl TopicMsg {
fn body<'a>(
&'a self,
delivery_id: &'a str,
subscription_id: &'a str,
replaced: u64,
) -> TopicBody<'a> {
TopicBody {
delivery_id,
subscription_id,
topic: &self.topic,
topic_incarnation: &self.topic_incarnation,
topic_sequence: self.sequence.to_string(),
replaced: replaced.to_string(),
payload: &self.payload,
}
fn body(&self, delivery_id: &str, subscription_id: &str, replaced: u64) -> Map<String, Value> {
obj(vec![
("deliveryId", delivery_id.into()),
("subscriptionId", subscription_id.into()),
("topic", self.topic.clone().into()),
("topicIncarnation", self.topic_incarnation.clone().into()),
("topicSequence", self.sequence.to_string().into()),
("replaced", replaced.to_string().into()),
("payload", Value::Object(self.payload.clone())),
])
}
}
@ -742,34 +651,41 @@ impl State {
}
/// Builds a router-originated item without assigning its envelope id. IDs are assigned only
/// after the scheduler selects an item, so fairness cannot reorder numbered envelopes. The
/// item is encoded here, once (BUS-02), with the id left to splice in.
fn outbound<B: Serialize>(
/// after the scheduler selects an item, so fairness cannot reorder numbered envelopes.
fn outbound(
&self,
kind: Kind,
op: &str,
reply_to: Option<String>,
body: B,
body: Map<String, Value>,
attachments: Vec<Attachment>,
) -> Option<Outbound> {
let head = crate::wire::EnvelopeHead {
major: MAJOR,
minor: MINOR,
id: "",
reply_to: reply_to.as_deref(),
let mut env = Envelope::new(serial_id("bus", MAX_SERIAL), kind, op, body.clone());
env.reply_to = reply_to;
env.attachments = attachments.clone();
let bytes = env.encode().ok()?.len();
Some(Outbound {
kind,
op,
};
let max_id = serial_id("bus", MAX_SERIAL).len();
let frame = Unnumbered::encode(&head, &body, &attachments, max_id).ok()?;
let bytes = frame.len() + max_id;
Some(Outbound { frame, bytes })
op: op.to_owned(),
reply_to: env.reply_to,
body,
attachments,
bytes,
})
}
fn encode_outbound(&mut self, c: ConnKey, item: Outbound) -> Option<Vec<u8>> {
let conn = self.conns.get_mut(&c)?;
conn.out_serial += 1;
Some(item.frame.number(&serial_id("bus", conn.out_serial)))
let mut env = Envelope::new(
serial_id("bus", conn.out_serial),
item.kind,
&item.op,
item.body,
);
env.reply_to = item.reply_to;
env.attachments = item.attachments;
env.encode().ok()
}
/// Queues a reply or notice on the control lane; closes the connection if the lane is full.
@ -1198,7 +1114,7 @@ impl State {
// -----------------------------------------------------------------------------------------
// Commands
pub(crate) fn handle(&mut self, c: ConnKey, mut env: Envelope) -> Outcome {
pub(crate) fn handle(&mut self, c: ConnKey, env: Envelope) -> Outcome {
let Some(conn) = self.conns.get_mut(&c) else {
return Outcome::Close;
};
@ -1228,34 +1144,6 @@ impl State {
);
}
let op = env.op.clone();
if matches!(op.as_str(), "rpc.call" | "rpc.reply" | "publish") {
match self.sealing_attachments(c, &mut env) {
Ok(None) => {}
Ok(Some(seals)) => {
return Outcome::SealThenAdmit(SealingSend { conn: c, env, seals });
}
Err(e) => {
// Refused before anything was sealed: the writers it named are released
// all the same, as a refused sealing send releases them (bus-v1 section 12,
// amendment 2026-10-02).
for a in &env.attachments {
let Some(owner) = parse_serial_id("own", &a.owner_id) else {
continue;
};
if matches!(
self.conns[&c].owners.get(&OwnerKey::Hold(owner)),
Some(Owner::Writer { sealing: false, .. })
) && let Some(w) = self.take_owner(c, OwnerKey::Hold(owner))
{
self.release_owner(c, w);
}
}
self.reply(c, &env.id, &op, Err(e));
self.flush_notices();
return if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close };
}
}
}
let result = if !env.attachments.is_empty()
&& !matches!(op.as_str(), "rpc.call" | "rpc.reply" | "publish")
{
@ -1304,242 +1192,6 @@ impl State {
}
}
// -----------------------------------------------------------------------------------------
// Sealing on send (bus-v1 section 12 amendment 2026-10-02, BUS-02)
/// Finds the attachments of a sending command that name one of the sender's own writers
/// rather than a sealed artifact, validates each as `artifact.seal` would, and marks them
/// sealing. `None` when there are none (the command takes the ordinary path). Takes the
/// body's `recycle` member, which only such a command may carry.
fn sealing_attachments(
&mut self,
c: ConnKey,
env: &mut Envelope,
) -> Result<Option<Vec<SendSeal>>, BusError> {
// Present at all, `recycle` needs a sealing attachment: the amendment refuses it
// otherwise, `false` included (BUS-02 review N4).
let recycle = match env.body.remove("recycle") {
None => None,
Some(Value::Bool(b)) => Some(b),
Some(_) => return err(ErrorCode::InvalidEnvelope, "recycle must be a boolean"),
};
let mut found: Vec<(u64, u64, u64)> = Vec::new();
for a in &env.attachments {
let Some(owner) = parse_serial_id("own", &a.owner_id) else {
continue;
};
let Some(Owner::Writer { artifact, sealing }) =
self.conns[&c].owners.get(&OwnerKey::Hold(owner))
else {
continue;
};
let (artifact, sealing) = (*artifact, *sealing);
if parse_serial_id("a", &a.reference.artifact_id) != Some(artifact) {
// Another artifact under a writer's owner id: check_owned refuses it later.
continue;
}
if found.iter().any(|(s, _, _)| *s == artifact) {
return err(
ErrorCode::InvalidEnvelope,
format!("attachment {:?} names a writer another attachment already seals", a.name),
);
}
if sealing {
return err(ErrorCode::OwnerInvalid, "a seal is already in progress");
}
let art = &self.artifacts[&artifact];
let r = &a.reference;
if r.store_id != self.store_id
|| r.generation != GENERATION
|| r.content_type != art.content_type
|| r.digest.is_some()
|| r.byte_length > art.byte_length
{
return err(
ErrorCode::ArtifactMismatch,
format!(
"attachment {:?} does not describe its writer: same store, generation and \
content type, a null digest and at most the allocated length",
a.name
),
);
}
found.push((artifact, owner, r.byte_length));
}
if found.is_empty() {
if recycle.is_some() {
return err(ErrorCode::InvalidEnvelope, "recycle without a writer attached");
}
return Ok(None);
}
let recycle = recycle.unwrap_or(false);
let sealed: u64 = found.iter().map(|(_, _, len)| len).sum();
if self.store_bytes.saturating_add(sealed) > self.limits.max_store_bytes {
return err(ErrorCode::QuotaExceeded, "no room for the sealing copies");
}
self.store_bytes += sealed;
let mut seals = Vec::with_capacity(found.len());
for (serial, owner, len) in found {
let art = self.artifacts.get_mut(&serial).expect("a writer's artifact is registered");
art.state = ArtState::Sealing;
let capacity = art.byte_length;
self.conns.get_mut(&c).expect("present").owners.insert(
OwnerKey::Hold(owner),
Owner::Writer { artifact: serial, sealing: true },
);
let recycle = recycle.then(|| {
self.next_artifact += 1;
self.next_artifact
});
seals.push(SendSeal { serial, len, capacity, owner, recycle });
}
Ok(Some(seals))
}
/// Completes a sealing send: every copy has been made (`results`, in `job.seals` order) and,
/// for a recycled writer, its staging file moved to the new artifact's name. Then the
/// command is admitted exactly as an ordinary one whose attachments the sender had sealed
/// first; a refused command releases what it sealed, as a sender dropping its holds would.
pub(crate) fn finish_sealing_send(
&mut self,
job: SealingSend,
results: Vec<Result<(), crate::store::SealFailure>>,
) -> Outcome {
let SealingSend { conn: c, env, seals } = job;
let live = |s: &State, seal: &SendSeal| {
s.conns.get(&c).is_some_and(|conn| {
matches!(conn.owners.get(&OwnerKey::Hold(seal.owner)),
Some(Owner::Writer { artifact, sealing: true }) if *artifact == seal.serial)
})
};
let all_live = seals.iter().all(|seal| live(self, seal));
let failure = results.iter().find_map(|r| r.as_ref().err()).map(|e| match e {
crate::store::SealFailure::Mismatch(m) => BusError::new(ErrorCode::ArtifactMismatch, m.clone()),
crate::store::SealFailure::Io(e) => {
BusError::new(ErrorCode::StoreFailure, format!("seal: {e}"))
}
});
if failure.is_some() || !all_live {
// Nothing is admitted: every writer named is released and every copy unlinked.
for seal in &seals {
if self.artifacts.remove(&seal.serial).is_some() {
self.store_bytes -= seal.len + seal.capacity;
}
self.unlinks.push(sealed_rel(seal.serial));
self.unlinks.push(staging_rel(seal.recycle.unwrap_or(seal.serial)));
if live(self, seal) {
self.take_owner(c, OwnerKey::Hold(seal.owner));
}
}
if !self.conns.contains_key(&c) {
return Outcome::Close;
}
let e = failure
.unwrap_or_else(|| BusError::new(ErrorCode::ArtifactGone, "the writer was released during the seal"));
self.reply(c, &env.id, &env.op, Err(e));
self.flush_notices();
return if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close };
}
// Sealed: each writer's owner becomes the sender's hold, as after `artifact.seal`.
let mut writers = Vec::new();
for seal in &seals {
let art = self.artifacts.get_mut(&seal.serial).expect("sealing artifact is registered");
art.state = ArtState::Sealed;
art.byte_length = seal.len;
art.digest = None;
art.roots = 1;
let content_type = art.content_type.clone();
self.conns.get_mut(&c).expect("present").owners.insert(
OwnerKey::Hold(seal.owner),
Owner::Hold { artifact: seal.serial },
);
match seal.recycle {
// The staging file goes on as a new writer of the same allocation.
Some(next) if self.ordinary_budget_left(c) => {
self.artifacts.insert(
next,
Art {
state: ArtState::Writing,
byte_length: seal.capacity,
content_type,
digest: None,
roots: 0,
},
);
let conn = self.conns.get_mut(&c).expect("present");
conn.hold_issued += 1;
let owner = conn.hold_issued;
self.insert_owner(
c,
OwnerKey::Hold(owner),
Owner::Writer { artifact: next, sealing: false },
);
writers.push((seal.serial, next, owner));
}
Some(next) => {
self.store_bytes -= seal.capacity;
self.unlinks.push(staging_rel(next));
}
// The staging file was unlinked with the copy; its reservation ends here.
None => self.store_bytes -= seal.capacity,
}
}
let op = env.op.clone();
let result = match op.as_str() {
"rpc.call" => self.op_call(c, &env),
"rpc.reply" => self.op_reply(c, &env),
"publish" => self.op_publish(c, &env),
_ => unreachable!("only sending commands seal"),
};
let result = match result {
Ok(mut value) => {
if !writers.is_empty() {
let list = writers
.iter()
.map(|(sealed, next, owner)| {
let name = env
.attachments
.iter()
.find(|a| parse_serial_id("a", &a.reference.artifact_id) == Some(*sealed))
.map(|a| a.name.clone())
.unwrap_or_default();
let loc = crate::wire::Location {
store_id: self.store_id.clone(),
relative_path: staging_rel(*next),
};
Value::Object(obj(vec![
("name", name.into()),
("artifactId", serial_id("a", *next).into()),
("generation", GENERATION.to_string().into()),
("ownerId", serial_id("own", *owner).into()),
("writeLocation", loc.to_json()),
]))
})
.collect();
value.insert("writers".into(), Value::Array(list));
}
Ok(value)
}
Err(e) => {
// Refused: the holds the seals made and the recycled writers go with it.
for seal in &seals {
if let Some(owner) = self.take_owner(c, OwnerKey::Hold(seal.owner)) {
self.release_owner(c, owner);
}
}
for (_, _, owner) in &writers {
if let Some(owner) = self.take_owner(c, OwnerKey::Hold(*owner)) {
self.release_owner(c, owner);
}
}
Err(e)
}
};
self.reply(c, &env.id, &op, result);
self.flush_notices();
if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close }
}
fn grants(&self, c: ConnKey) -> &Grants {
&self.conns[&c].hello.as_ref().expect("after hello").grants
}
@ -1838,7 +1490,7 @@ content type, a null digest and at most the allocated length",
let target = f.name("target").map_err(wire)?;
let expected = f.nullable_id("expectedIncarnation").map_err(wire)?;
let method = f.method("method").map_err(wire)?;
let payload = raw(f.object("payload").map_err(wire)?)?;
let payload = f.object("payload").map_err(wire)?.clone();
f.finish().map_err(wire)?;
let Some(call_serial) = parse_serial_id("call", &call_id) else {
return err(ErrorCode::InvalidEnvelope, "callId must be call-<U64>");
@ -1932,7 +1584,7 @@ content type, a null digest and at most the allocated length",
let mut f = Fields::of(&env.body, "rpc.reply");
let call_id = f.id("callId").map_err(wire)?;
let delivery_id = f.id("requestDeliveryId").map_err(wire)?;
let outcome = raw(f.object("outcome").map_err(wire)?)?;
let outcome = f.object("outcome").map_err(wire)?.clone();
f.finish().map_err(wire)?;
let Some(n) = parse_serial_id("dlv", &delivery_id) else {
return err(
@ -2370,7 +2022,7 @@ content type, a null digest and at most the allocated length",
fn op_publish(&mut self, c: ConnKey, env: &Envelope) -> Result<Map<String, Value>, BusError> {
let mut f = Fields::of(&env.body, "publish");
let topic = f.name("topic").map_err(wire)?;
let payload = raw(f.object("payload").map_err(wire)?)?;
let payload = f.object("payload").map_err(wire)?.clone();
f.finish().map_err(wire)?;
if !Grants::allows(&self.grants(c).publish, &topic) {
return err(
@ -2896,7 +2548,6 @@ content type, a null digest and at most the allocated length",
let call = &self.calls[&key];
let body = call.result_body(&did, &msg);
let atts = attachments_with_owner(&msg.attachments, &did);
let frame = self.outbound(Kind::Delivery, "rpc.result", None, body, atts);
self.insert_owner(
c,
OwnerKey::Delivery(n),
@ -2905,7 +2556,7 @@ content type, a null digest and at most the allocated length",
kind: DeliveryKind::Result { call: key },
},
);
return frame;
return self.outbound(Kind::Delivery, "rpc.result", None, body, atts);
}
// Requests for services this connection registered, round robin.
let conn = &self.conns[&c];
@ -2932,16 +2583,13 @@ content type, a null digest and at most the allocated length",
conn.requests.insert(n, key);
conn.reply_capabilities += 1;
let call = self.calls.get_mut(&key).expect("queued call is registered");
// Dispatched before a byte of it is written. (The frame is built below, under the
// same lock, before anything can write it.)
// Dispatched before a byte of it is written.
call.phase = Phase::Dispatched { delivery: n };
call.reply_capability = true;
let did = serial_id("dlv", n);
let call = &self.calls[&key];
let body = call.request_body(&did);
let atts = attachments_with_owner(&call.attachments, &did);
let artifacts = call.artifacts.clone();
let frame = self.outbound(Kind::Delivery, "rpc.request", None, body, atts);
self.insert_owner(
c,
OwnerKey::Delivery(n),
@ -2954,7 +2602,7 @@ content type, a null digest and at most the allocated length",
},
},
);
return frame;
return self.outbound(Kind::Delivery, "rpc.request", None, body, atts);
}
None
}
@ -2982,10 +2630,8 @@ content type, a null digest and at most the allocated length",
conn.delivery_issued += 1;
let n = conn.delivery_issued;
let did = serial_id("dlv", n);
let sid = serial_id("sub", id);
let body = msg.body(&did, &sid, replaced);
let body = msg.body(&did, &serial_id("sub", id), replaced);
let atts = attachments_with_owner(&msg.attachments, &did);
let frame = self.outbound(Kind::Delivery, "topic.message", None, body, atts);
self.insert_owner(
c,
OwnerKey::Delivery(n),
@ -2994,7 +2640,7 @@ content type, a null digest and at most the allocated length",
kind: DeliveryKind::Topic { sub: id },
},
);
return frame;
return self.outbound(Kind::Delivery, "topic.message", None, body, atts);
}
None
}

View file

@ -108,37 +108,27 @@ impl Store {
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(&path)?;
let result = reserve(&file, len);
let reserve = || -> io::Result<()> {
if len == 0 {
return Ok(());
}
let off_len = libc::off_t::try_from(len)
.map_err(|_| io::Error::other("length overflows off_t"))?;
// SAFETY: posix_fallocate on a valid descriptor opened for writing.
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, off_len) };
match rc {
0 => Ok(()),
libc::EOPNOTSUPP | libc::EINVAL => file.set_len(len),
e => Err(io::Error::from_raw_os_error(e)),
}
};
let result = reserve();
if result.is_err() {
let _ = fs::remove_file(&path);
}
result
}
/// Makes a recycled writer's staging file what a fresh allocation is: `len` bytes, all zero
/// (BUS-02 review N3). The file still holds the artifact it was sealed from; a producer that
/// wrote fewer bytes into its next life and sealed the whole allocation would otherwise
/// publish the previous artifact's tail. The zeros are written over the blocks already
/// there, which stay allocated: freeing them (truncating, or punching a hole) and faulting
/// them back in on the next write cost four times as much on tmpfs (a 92,160-byte frame:
/// about 36 us a reply against 9). The length is set last, in case the producer resized
/// the file.
pub(crate) fn reset_staging(&self, serial: u64, len: u64) -> io::Result<()> {
use std::os::unix::fs::FileExt;
let file = OpenOptions::new()
.write(true)
.custom_flags(libc::O_NOFOLLOW)
.open(self.path(&staging_rel(serial)))?;
let zeros = vec![0u8; len.clamp(1, 256 * 1024) as usize];
let mut at = 0;
while at < len {
let n = (len - at).min(zeros.len() as u64) as usize;
file.write_all_at(&zeros[..n], at)?;
at += n as u64;
}
file.set_len(len)
}
/// Copies exactly `len` staging bytes into a fresh sealed file, checking the length and,
/// when given, the SHA-256. On failure the partial sealed file is removed; the staging file
/// is left for the caller either way.
@ -169,36 +159,6 @@ impl Store {
result
}
/// Copies the first `len` staging bytes into a fresh sealed file (BUS-02: a writer attached
/// to a sending command seals the bytes its attachment declares, at most its allocation).
/// The staging file is left for the caller.
pub(crate) fn seal_prefix(&self, serial: u64, len: u64) -> Result<(), SealFailure> {
let mut src = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(self.path(&staging_rel(serial)))?;
let dst_path = self.path(&sealed_rel(serial));
let mut dst = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(&dst_path)?;
let result = copy_prefix(&mut src, &mut dst, len).and_then(|()| {
dst.set_permissions(fs::Permissions::from_mode(0o444))?;
Ok(())
});
if result.is_err() {
let _ = fs::remove_file(&dst_path);
}
result
}
/// Renames a store file within the store (a recycled writer's staging file).
pub(crate) fn rename(&self, from: &str, to: &str) -> io::Result<()> {
fs::rename(self.path(from), self.path(to))
}
/// Unlinks a store file; a missing file is not an error.
pub(crate) fn remove(&self, rel: &str) {
let _ = fs::remove_file(self.path(rel));
@ -211,23 +171,6 @@ impl Drop for Store {
}
}
/// Reserves `len` bytes of `file` (zero-filled), so a full disk fails here and not in the
/// producer's write.
fn reserve(file: &File, len: u64) -> io::Result<()> {
if len == 0 {
return Ok(());
}
let off_len =
libc::off_t::try_from(len).map_err(|_| io::Error::other("length overflows off_t"))?;
// SAFETY: posix_fallocate on a valid descriptor opened for writing.
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, off_len) };
match rc {
0 => Ok(()),
libc::EOPNOTSUPP | libc::EINVAL => file.set_len(len),
e => Err(io::Error::from_raw_os_error(e)),
}
}
fn read_retry(r: &mut File, buf: &mut [u8]) -> io::Result<usize> {
loop {
match r.read(buf) {
@ -244,9 +187,7 @@ fn copy_exact(
digest: Option<&str>,
) -> Result<(), SealFailure> {
let mut hasher = digest.map(|_| Sha256::new());
// Sized to the copy (BUS-02): a fixed 256 KiB buffer is a fresh mapping, and its page
// faults, on every seal of a frame-sized artifact.
let mut buf = vec![0u8; (len.saturating_add(1)).clamp(1, 256 * 1024) as usize];
let mut buf = vec![0u8; 256 * 1024];
let mut remaining = len;
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
@ -279,68 +220,6 @@ fn copy_exact(
Ok(())
}
fn copy_prefix(src: &mut File, dst: &mut File, len: u64) -> Result<(), SealFailure> {
// In the kernel where it can (`copy_file_range`: one copy, no bounce through a user buffer;
// on the store's tmpfs that halves a frame's seal), else through a buffer.
let mut done: u64 = 0;
while done < len {
let want = (len - done).min(1 << 30) as usize;
// SAFETY: two valid descriptors; null offsets use and advance each file's position.
let n = unsafe {
libc::copy_file_range(
src.as_raw_fd(),
std::ptr::null_mut(),
dst.as_raw_fd(),
std::ptr::null_mut(),
want,
0,
)
};
if n < 0 {
let e = io::Error::last_os_error();
if e.kind() == io::ErrorKind::Interrupted {
continue;
}
if done == 0
&& matches!(
e.raw_os_error(),
Some(libc::ENOSYS | libc::EXDEV | libc::EINVAL | libc::EOPNOTSUPP)
)
{
return copy_prefix_buffered(src, dst, len);
}
return Err(SealFailure::Io(e));
}
if n == 0 {
return Err(SealFailure::Mismatch(format!(
"staging holds {done} of {len} declared bytes"
)));
}
done += n as u64;
}
Ok(())
}
fn copy_prefix_buffered(src: &mut File, dst: &mut File, len: u64) -> Result<(), SealFailure> {
// Sized to the copy: a frame or a memory image is one read and one write, and the buffer is
// small enough to come from the heap rather than a fresh mapping each time.
let mut buf = vec![0u8; len.clamp(1, 256 * 1024) as usize];
let mut remaining = len;
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = read_retry(src, &mut buf[..want])?;
if n == 0 {
return Err(SealFailure::Mismatch(format!(
"staging holds {} of {len} declared bytes",
len - remaining
)));
}
dst.write_all(&buf[..n])?;
remaining -= n as u64;
}
Ok(())
}
/// Deletes store directories under `root` that carry the marker and whose lock is free.
/// Directories without the marker are never touched.
fn clean_orphans(root: &Path) -> io::Result<()> {
@ -371,12 +250,7 @@ fn clean_orphans(root: &Path) -> io::Result<()> {
/// Resolves a location grant beneath `<root>/<store_id>`. Absolute paths, `..`, anything but
/// plain `[a-z0-9._-]` components, and symlinks that lead outside the store are refused.
pub(crate) fn resolve(
root: &Path,
store_id: &str,
loc: &Location,
dirs: &DirCache,
) -> Result<PathBuf, BusError> {
pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result<PathBuf, BusError> {
if loc.store_id != store_id {
return Err(BusError::new(
ErrorCode::ArtifactGone,
@ -406,66 +280,18 @@ pub(crate) fn resolve(
_ => return Err(refuse("parent, root or current-directory component")),
}
}
// The directory part (`sealed`, `staging`) is resolved once per store directory and
// connection, and cached ([`DirCache`], BUS-02): canonicalizing the whole path is a readlink per component, twice, on every open
// of every artifact. The file itself is then checked with one lstat: a symlink there is
// refused like one that escapes (the open that follows uses O_NOFOLLOW as well).
let (dir, file) = match loc.relative_path.rsplit_once('/') {
Some((dir, file)) => (Some(dir), file),
None => (None, loc.relative_path.as_str()),
};
let base = dirs
.canonical(&root.join(&loc.store_id), None)
let base = root.join(&loc.store_id);
let base = base
.canonicalize()
.map_err(|e| refuse(&format!("store directory: {e}")))?;
let parent = match dir {
None => base.clone(),
Some(dir) => dirs.canonical(&root.join(&loc.store_id), Some(dir)).map_err(|e| match e.kind() {
let full = base.join(rel).canonicalize().map_err(|e| match e.kind() {
io::ErrorKind::NotFound => BusError::new(ErrorCode::ArtifactGone, "artifact file is gone"),
_ => refuse(&e.to_string()),
})?,
};
if !parent.starts_with(&base) {
})?;
if !full.starts_with(&base) {
return Err(refuse("escapes the store"));
}
let full = parent.join(file);
match fs::symlink_metadata(&full) {
Ok(m) if m.file_type().is_symlink() => Err(refuse("escapes the store")),
Ok(_) => Ok(full),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
Err(BusError::new(ErrorCode::ArtifactGone, "artifact file is gone"))
}
Err(e) => Err(refuse(&e.to_string())),
}
}
/// The canonical store directories one client connection has resolved (BUS-02): a store's
/// directories are made by its router when the store is created and never move. The cache is
/// the connection's, not the process's (BUS-02 review N6), so a directory is resolved again by
/// every new connection -- after a router restart, for one -- and nothing outlives the store
/// incarnation it was resolved for. Within one connection a directory replaced after its first
/// use is not re-checked; the file itself still is (an lstat, then an O_NOFOLLOW open), and
/// the store is the user's own directory (mode 0700), so replacing it needs the user already.
#[derive(Default)]
pub(crate) struct DirCache(std::sync::Mutex<std::collections::HashMap<PathBuf, PathBuf>>);
impl DirCache {
/// `store.join(dir).canonicalize()`, cached.
fn canonical(&self, store: &Path, dir: Option<&str>) -> io::Result<PathBuf> {
let key = match dir {
Some(dir) => store.join(dir),
None => store.to_path_buf(),
};
if let Some(hit) = self.0.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
return Ok(hit.clone());
}
let resolved = key.canonicalize()?;
let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
if map.len() > 256 {
map.clear();
}
map.insert(key, resolved.clone());
Ok(resolved)
}
Ok(full)
}
pub(crate) fn open_read(path: &Path) -> io::Result<File> {
@ -501,7 +327,7 @@ mod tests {
fs::write(store.join("sealed/a-1"), b"ok").unwrap();
fs::write(root.path().join("secret"), b"no").unwrap();
std::os::unix::fs::symlink(root.path().join("secret"), store.join("sealed/a-2")).unwrap();
assert!(resolve(root.path(), "store-x", &loc("sealed/a-1"), &DirCache::default()).is_ok());
assert!(resolve(root.path(), "store-x", &loc("sealed/a-1")).is_ok());
for bad in [
"",
"/etc/passwd",
@ -512,7 +338,7 @@ mod tests {
"sealed/a-2",
] {
assert!(
resolve(root.path(), "store-x", &loc(bad), &DirCache::default()).is_err(),
resolve(root.path(), "store-x", &loc(bad)).is_err(),
"{bad:?}"
);
}
@ -521,7 +347,7 @@ mod tests {
relative_path: "sealed/a-1".into(),
};
assert_eq!(
resolve(root.path(), "store-x", &other, &DirCache::default()).unwrap_err().code,
resolve(root.path(), "store-x", &other).unwrap_err().code,
ErrorCode::ArtifactGone
);
}

View file

@ -37,8 +37,6 @@ pub const CONTRACT: &str = "flybus 1.0
frame: u32le length, 1..=65536 bytes of strict UTF-8 JSON
envelope: protocol major minor id replyTo kind op body attachments
attachment: name ref ownerId [readLocation(storeId relativePath): in a router delivery only]
sealing attachment: in rpc.call rpc.reply publish, ownerId may be the sender's own unsealed writer of ref.artifactId; ref.byteLength <= its allocation, digest null; the router seals that prefix on admission and the writer becomes the sender's hold
recycle: optional boolean member of an rpc.call rpc.reply publish body with a sealing attachment, refused in any other body; the reply value then carries writers[name artifactId generation ownerId writeLocation], each sealed writer's staging allocation reissued zero-filled as a fresh allocation
ref: storeId artifactId generation byteLength contentType digest
reply: ok value | ok error{code message dispatch}
bus.hello: clientId clientIncarnation supportedMajors -> routerId connectionId selectedMajor selectedMinor contractDigest limits
@ -259,16 +257,11 @@ impl<'de> Visitor<'de> for StrictVisitor {
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
let mut out = Map::new();
while let Some(key) = map.next_key::<String>()? {
if out.contains_key(&key) {
return Err(de::Error::custom(format!("duplicate key {key:?}")));
}
let v = map.next_value_seed(StrictSeed)?;
// One hash per key (BUS-02).
match out.entry(key) {
serde_json::map::Entry::Vacant(slot) => {
slot.insert(v);
}
serde_json::map::Entry::Occupied(slot) => {
return Err(de::Error::custom(format!("duplicate key {:?}", slot.key())));
}
}
out.insert(key, v);
}
Ok(Value::Object(out))
}
@ -280,8 +273,7 @@ impl<'de> Visitor<'de> for StrictVisitor {
/// Reads the fields of one JSON object, then refuses any it did not read.
pub struct Fields<'a> {
map: &'a Map<String, Value>,
// A handful of keys per object: a vector beats hashing them (BUS-02).
seen: Vec<&'static str>,
seen: HashSet<&'static str>,
what: &'static str,
}
@ -296,19 +288,19 @@ impl<'a> Fields<'a> {
pub fn of(map: &'a Map<String, Value>, what: &'static str) -> Fields<'a> {
Fields {
map,
seen: Vec::with_capacity(8),
seen: HashSet::new(),
what,
}
}
/// A field that may be absent; read (so [`Fields::finish`] accepts it) when present.
pub fn optional(&mut self, key: &'static str) -> Option<&'a Value> {
self.seen.push(key);
self.seen.insert(key);
self.map.get(key)
}
pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> {
self.seen.push(key);
self.seen.insert(key);
match self.map.get(key) {
Some(v) => Ok(v),
None => err(format!("{}: missing field {key:?}", self.what)),
@ -405,7 +397,7 @@ impl<'a> Fields<'a> {
/// Refuses fields that were not read.
pub fn finish(self) -> Result<(), WireError> {
if let Some(extra) = self.map.keys().find(|k| !self.seen.contains(&k.as_str())) {
if let Some(extra) = self.map.keys().find(|k| !self.seen.contains(k.as_str())) {
return err(format!("{}: unknown field {extra:?}", self.what));
}
Ok(())
@ -746,13 +738,13 @@ pub struct EnvelopeHead<'a> {
/// field order -- without copying the body into a value tree first (BUS-01: the body is the one
/// large part of a message, and it used to be copied twice on the way out). Refuses anything over
/// [`MAX_ENVELOPE_BYTES`].
pub fn encode_parts<B: serde::Serialize + ?Sized>(
pub fn encode_parts(
head: &EnvelopeHead<'_>,
body: &B,
body: &Map<String, Value>,
attachments: &[Attachment],
) -> Result<Vec<u8>, WireError> {
#[derive(serde::Serialize)]
struct Out<'a, B: serde::Serialize + ?Sized> {
struct Out<'a> {
protocol: &'static str,
major: u64,
minor: u64,
@ -761,7 +753,7 @@ pub fn encode_parts<B: serde::Serialize + ?Sized>(
reply_to: Option<&'a str>,
kind: &'static str,
op: &'a str,
body: &'a B,
body: &'a Map<String, Value>,
attachments: Vec<Value>,
}
let out = Out {
@ -786,65 +778,6 @@ pub fn encode_parts<B: serde::Serialize + ?Sized>(
}
/// An envelope encoded once, before its id is known (BUS-02). A router assigns envelope ids
/// only when its scheduler selects a frame, and it used to serialize every frame twice -- once
/// to size it, once to send it -- and deep-copy its body for each. This holds the bytes encoded
/// with an empty id and where the id goes; [`Unnumbered::number`] splices the id in, which is
/// the same bytes a whole encode with that id produces.
#[derive(Clone, Debug)]
pub struct Unnumbered {
bytes: Vec<u8>,
id_at: usize,
}
impl Unnumbered {
/// Encodes with an empty id. Refuses an envelope that would exceed [`MAX_ENVELOPE_BYTES`]
/// once given an id of up to `max_id_len` bytes.
pub fn encode<B: serde::Serialize + ?Sized>(
head: &EnvelopeHead<'_>,
body: &B,
attachments: &[Attachment],
max_id_len: usize,
) -> Result<Unnumbered, WireError> {
debug_assert!(head.id.is_empty());
let bytes = encode_parts(head, body, attachments)?;
if bytes.len() + max_id_len > MAX_ENVELOPE_BYTES {
return err(format!(
"envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}",
bytes.len() + max_id_len
));
}
// The id is the first `"id":` member: protocol, major and minor precede it and none of
// them can contain that text.
const KEY: &[u8] = b"\"id\":\"";
let id_at = bytes
.windows(KEY.len())
.position(|w| w == KEY)
.map(|at| at + KEY.len())
.ok_or_else(|| WireError("encoded envelope has no id".into()))?;
Ok(Unnumbered { bytes, id_at })
}
/// The encoded length without an id.
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// The final bytes with `id` (an `Id`, which needs no JSON escaping) in place.
pub fn number(self, id: &str) -> Vec<u8> {
debug_assert!(is_id(id));
let mut out = Vec::with_capacity(self.bytes.len() + id.len());
out.extend_from_slice(&self.bytes[..self.id_at]);
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(&self.bytes[self.id_at..]);
out
}
}
// ---------------------------------------------------------------------------------------------
// Framing

View file

@ -86,6 +86,11 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) {
let store = a["writeLocation"]["storeId"].clone();
let reference = json!({"storeId": store, "artifactId": a["artifactId"], "generation": "1", "byteLength": "8",
"contentType": "application/octet-stream", "digest": null});
let att = json!([{"name": "x", "ref": reference, "ownerId": a["ownerId"]}]);
let r = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}}), att)
.await;
assert_eq!(code(&r), "ARTIFACT_UNSEALED");
let r = raw
.call(
"artifact.open",
@ -100,20 +105,7 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) {
)
.await;
assert_eq!(code(&r), "ARTIFACT_UNSEALED");
// Since the 2026-10-02 amendment (bus-v1 section 12), a sending command that names its own
// writer seals it as it is admitted: the writer is then a hold, and seals no more.
let att = json!([{"name": "x", "ref": reference, "ownerId": a["ownerId"]}]);
let r = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}}), att)
.await;
assert_eq!(code(&r), "OK");
let r = raw
.call(
"artifact.open",
json!({"ref": reference, "ownerId": a["ownerId"]}),
)
.await;
assert_eq!(code(&r), "OK", "the writer became the sender's hold");
assert_eq!(code(&raw.seal(&a, Value::Null).await), "OK");
assert_eq!(
code(&raw.seal(&a, Value::Null).await),
"OWNER_INVALID",

View file

@ -589,72 +589,6 @@ both_transports!(
hello_reports_the_contract_digest_and_valid_limits,
);
// -------------------------------------------------------------------------------------------
// Review note N3 (BUS-01): the SDK refuses a router whose contract digest is not its own, at
// Hello, with the explicit version-mismatch error. The wire change that added `readLocation`
// moved the digest, so a client and router built from different sources must not talk.
/// Serves one Hello on `server` the way the router does, announcing `digest`.
async fn answer_hello_with(server: tokio::io::DuplexStream, digest: String) {
let (mut rd, mut wr) = tokio::io::split(server);
let bytes = read_frame(&mut rd).await.unwrap().expect("a hello frame");
let hello = Envelope::decode(&bytes).unwrap();
assert_eq!(hello.op, "bus.hello");
let value = json!({
"routerId": "router-1", "connectionId": "conn-1",
"selectedMajor": 1, "selectedMinor": 0,
"contractDigest": digest,
"limits": Limits::default().to_json(),
});
let mut body = Map::new();
body.insert("ok".into(), json!(true));
body.insert("value".into(), value);
let mut reply = Envelope::new("bus-1".into(), Kind::Reply, "bus.hello", body);
reply.reply_to = Some(hello.id);
write_frame(&mut wr, &reply.encode().unwrap()).await.unwrap();
// Keep the connection open until the client has decided.
tokio::time::sleep(Duration::from_secs(2)).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_client_refuses_a_router_with_a_different_contract_digest_at_hello() {
let dir = tempfile::tempdir().unwrap();
let wrong = "0".repeat(64);
assert_ne!(wrong, contract_digest());
let (client_end, server_end) = tokio::io::duplex(64 * 1024);
tokio::spawn(answer_hello_with(server_end, wrong));
let refused = within(
"hello",
flybus::Client::connect(
flybus::Transport::from_stream(client_end),
flybus::ClientConfig::new("digest-client", dir.path()),
),
)
.await;
let Err(err) = refused else {
panic!("a mismatched digest must be refused");
};
assert_eq!(err.code, flybus::ErrorCode::VersionMismatch);
assert_eq!(err.message, "router speaks a different contract");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_same_fake_router_with_the_right_digest_is_accepted() {
let dir = tempfile::tempdir().unwrap();
let (client_end, server_end) = tokio::io::duplex(64 * 1024);
tokio::spawn(answer_hello_with(server_end, contract_digest()));
let client = within(
"hello",
flybus::Client::connect(
flybus::Transport::from_stream(client_end),
flybus::ClientConfig::new("digest-client", dir.path()),
),
)
.await
.expect("a matching digest is accepted");
assert_eq!(client.info().contract_digest, contract_digest());
}
// -------------------------------------------------------------------------------------------
// bus-v1 §11 acceptance test 1: "In-memory transport must pass the same tests as Unix
// sockets." Every test above already runs on both (that is what `both_transports!` is for);

View file

@ -1,287 +0,0 @@
//! Sealing sends (bus-v1 section 12, amendment 2026-10-02): a sending command that attaches its
//! sender's own writer seals it as the command is admitted, optionally recycling the staging
//! allocation as a new writer; a refused one releases every writer it named.
mod common;
use std::io::Write;
use common::{Via, code, env, obj, within};
use flybus::ServiceConfig;
use serde_json::json;
/// A reply that seals its writers: the caller reads exactly the bytes written, the responder's
/// handle is the hold its writer became, and the recycled writer serves the next reply.
async fn a_reply_seals_and_recycles_its_writers(via: Via) {
let e = env(via).await;
let svc_client = e.client("svc").await;
let mut svc = svc_client
.register("t.echo", ServiceConfig::default())
.await
.unwrap();
let caller = e.client("caller").await;
let server = tokio::spawn(async move {
let mut writer = svc_client
.artifacts()
.allocate(4096, "application/x-frame")
.await
.unwrap();
let mut held = Vec::new();
for round in 0..3u8 {
let req = svc.next().await.unwrap();
// Fewer bytes than the allocation: the sealed artifact is the prefix written.
let body = vec![round; 1000 + usize::from(round)];
writer.write_all(&body).unwrap();
assert_eq!(writer.written(), body.len() as u64);
let unsealed = writer.into_unsealed();
let artifact = unsealed.artifact().clone();
let out = req
.responder()
.reply_sealing(obj(json!({"round": round})), &[("frame", &artifact)], vec![unsealed], true)
.await
.unwrap();
assert!(out.routed);
assert!(artifact.is_hold(), "the writer became the responder's hold");
assert_eq!(out.writers.len(), 1, "the allocation comes back as a new writer");
writer = out.writers.into_iter().next().unwrap();
assert_eq!(writer.byte_length(), 4096);
assert_eq!(writer.written(), 0);
assert_eq!(writer.content_type(), "application/x-frame");
held.push(artifact);
}
(held, writer)
});
for round in 0..3u8 {
let result = within(
"sealed reply",
caller.call_and_wait("t.echo", None, "Echo", obj(json!({})), &[]),
)
.await
.unwrap();
let frame = result.artifact("frame").unwrap();
let r = frame.reference();
assert_eq!(r.byte_length, 1000 + u64::from(round));
assert_eq!(r.content_type, "application/x-frame");
assert_eq!(r.digest, None);
assert_eq!(frame.read_all().await.unwrap(), vec![round; 1000 + usize::from(round)]);
}
let (held, writer) = within("server", server).await.unwrap();
// The responder's holds read the same bytes as the caller's deliveries.
for (round, artifact) in held.iter().enumerate() {
assert_eq!(artifact.read_all().await.unwrap(), vec![round as u8; 1000 + round]);
}
assert_eq!(e.files("staging"), 1, "one staging file served every reply");
drop((held, writer));
e.settle("collected", |s| s.artifacts == 0 && s.store_bytes == 0)
.await;
e.settle_files("sealed", 0).await;
e.settle_files("staging", 0).await;
}
/// A sealing attachment must describe its writer, and a refused sealing send -- refused before
/// or after the seal -- releases every writer it named.
async fn a_refused_sealing_send_releases_its_writers(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(
code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await),
"OK"
);
let reference = |a: &serde_json::Map<String, serde_json::Value>, len: &str| {
json!({"storeId": a["writeLocation"]["storeId"], "artifactId": a["artifactId"],
"generation": "1", "byteLength": len, "contentType": "application/octet-stream",
"digest": null})
};
// Longer than the allocation: refused, and the writer is gone.
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "9"), "ownerId": a["ownerId"]}]);
let r = raw.call_with("publish", json!({"topic": "t.x", "payload": {}}), att).await;
assert_eq!(code(&r), "ARTIFACT_MISMATCH");
assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID");
// Sealed, then the command is refused (no such topic): the seal goes with it.
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]);
let r = raw.call_with("publish", json!({"topic": "t.nobody", "payload": {}}), att).await;
assert_eq!(code(&r), "NO_TOPIC");
let r = raw
.call("artifact.open", json!({"ref": reference(&a, "8"), "ownerId": a["ownerId"]}))
.await;
assert_eq!(code(&r), "OWNER_INVALID");
// `recycle` needs a writer to recycle, and must be a boolean.
let r = raw
.call("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}))
.await;
assert_eq!(code(&r), "INVALID_ENVELOPE");
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]);
let r = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": 1}), att)
.await;
assert_eq!(code(&r), "INVALID_ENVELOPE");
// A recycling publish returns the new writer, named by attachment.
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "5"), "ownerId": a["ownerId"]}]);
let v = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att)
.await
.unwrap();
let writers = v["writers"].as_array().unwrap();
assert_eq!(writers.len(), 1);
assert_eq!(writers[0]["name"], "x");
let next = writers[0].as_object().unwrap().clone();
assert_ne!(next["artifactId"], a["artifactId"]);
// The recycled writer is an ordinary writer: it seals the whole allocation.
assert_eq!(code(&raw.seal(&next, json!(null)).await), "OK");
e.settle("only the two seals remain", |s| s.sealed_artifacts == 2)
.await;
}
/// A recycled writer is a fresh allocation in content too (review N3): a smaller artifact
/// after a larger one carries none of the larger one's bytes, sealed by prefix (a sealing
/// reply) or whole (`seal()`), and the reissued staging file itself reads as zeros.
async fn a_recycled_writer_never_shows_the_previous_artifact(via: Via) {
let e = env(via).await;
let svc_client = e.client("svc").await;
let mut svc = svc_client
.register("t.frames", ServiceConfig::default())
.await
.unwrap();
let caller = e.client("caller").await;
let server = tokio::spawn(async move {
let mut writer = svc_client
.artifacts()
.allocate(8192, "application/x-frame")
.await
.unwrap();
// Large, then small, then smaller: each reply seals what its round wrote.
for (round, len) in [(0xA0u8, 8000usize), (0xB1, 100), (0xC2, 3)] {
let req = svc.next().await.unwrap();
writer.write_all(&vec![round; len]).unwrap();
let unsealed = writer.into_unsealed();
let artifact = unsealed.artifact().clone();
let out = req
.responder()
.reply_sealing(obj(json!({})), &[("frame", &artifact)], vec![unsealed], true)
.await
.unwrap();
writer = out.writers.into_iter().next().unwrap();
}
// The last recycled writer, sealed whole after writing a little.
writer.write_all(&[0xD3; 5]).unwrap();
writer.seal().await.unwrap()
});
for (round, len) in [(0xA0u8, 8000usize), (0xB1, 100), (0xC2, 3)] {
let result = within(
"sealed reply",
caller.call_and_wait("t.frames", None, "Frame", obj(json!({})), &[]),
)
.await
.unwrap();
let frame = result.artifact("frame").unwrap();
assert_eq!(frame.read_all().await.unwrap(), vec![round; len], "round {round:#x}");
}
let whole = within("server", server).await.unwrap();
let bytes = whole.read_all().await.unwrap();
assert_eq!(bytes.len(), 8192);
assert_eq!(&bytes[..5], &[0xD3; 5]);
assert!(
bytes[5..].iter().all(|b| *b == 0),
"unwritten bytes of a recycled writer read as zeros, not the previous artifacts'"
);
// On the wire: the reissued staging file is the allocation's length, all zeros.
let mut raw = e.raw_hello("raw").await;
assert_eq!(
code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await),
"OK"
);
let (a, p) = raw.allocate(4096).await;
std::fs::write(&p, vec![0xEE; 4096]).unwrap();
let att = json!([{"name": "x", "ref": reference(&a, "4096"), "ownerId": a["ownerId"]}]);
let v = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att)
.await
.unwrap();
let next = v["writers"][0].as_object().unwrap().clone();
let staging = std::fs::read(raw.path(&next["writeLocation"])).unwrap();
assert_eq!(staging, vec![0u8; 4096]);
// And whole-sealed untouched, it is an artifact of zeros.
let r = raw.seal(&next, json!(null)).await.unwrap();
let open = raw
.call("artifact.open", json!({"ref": r["ref"], "ownerId": next["ownerId"]}))
.await
.unwrap();
assert_eq!(std::fs::read(raw.path(&open["readLocation"])).unwrap(), vec![0u8; 4096]);
}
/// A rename that fails after a good copy (review N5) refuses the send and leaves no staging file:
/// neither the writer's own nor one under the recycled name.
async fn a_failed_recycle_rename_leaves_no_staging_file(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(
code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await),
"OK"
);
let (a, p) = raw.allocate(8).await;
std::fs::write(&p, b"12345678").unwrap();
// The recycled writer is the next artifact serial; a directory in its place makes the
// rename fail (EISDIR) once the copy has been made.
let serial: u64 = a["artifactId"].as_str().unwrap().strip_prefix("a-").unwrap().parse().unwrap();
let blocker = p.with_file_name(format!("a-{}", serial + 1));
std::fs::create_dir(&blocker).unwrap();
let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]);
let r = raw
.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att)
.await;
assert_eq!(code(&r), "STORE_FAILURE");
assert!(!p.exists(), "the writer's own staging file was unlinked");
std::fs::remove_dir(&blocker).unwrap();
assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID");
e.settle("nothing held", |s| s.artifacts == 0 && s.store_bytes == 0).await;
e.settle_files("sealed", 0).await;
e.settle_files("staging", 0).await;
}
/// `recycle` is refused in a body with no sealing attachment, `false` included, and one writer
/// may not be named by two attachments of the same command (review N4).
async fn recycle_and_duplicate_writer_edges_are_refused(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(
code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await),
"OK"
);
let r = raw
.call("publish", json!({"topic": "t.x", "payload": {}, "recycle": false}))
.await;
assert_eq!(code(&r), "INVALID_ENVELOPE");
let (a, _) = raw.allocate(8).await;
let att = json!([
{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]},
{"name": "y", "ref": reference(&a, "8"), "ownerId": a["ownerId"]},
]);
let r = raw.call_with("publish", json!({"topic": "t.x", "payload": {}}), att).await;
assert_eq!(code(&r), "INVALID_ENVELOPE");
// Refused, the send released the writer it named, as any refused sealing send does.
assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID");
e.settle("nothing held", |s| s.artifacts == 0 && s.store_bytes == 0).await;
}
fn reference(a: &serde_json::Map<String, serde_json::Value>, len: &str) -> serde_json::Value {
json!({"storeId": a["writeLocation"]["storeId"], "artifactId": a["artifactId"],
"generation": "1", "byteLength": len, "contentType": "application/octet-stream",
"digest": null})
}
both_transports!(
a_reply_seals_and_recycles_its_writers,
a_refused_sealing_send_releases_its_writers,
a_recycled_writer_never_shows_the_previous_artifact,
a_failed_recycle_rename_leaves_no_staging_file,
recycle_and_duplicate_writer_edges_are_refused,
);

View file

@ -1,195 +0,0 @@
//! Adversarial lifecycle checks of sealing sends (bus-v1 section 12, amendment 2026-10-02),
//! from the BUS-02 review: whatever refuses or interrupts a sealing send -- the command, the
//! quota, a seal, the owner budget, the sender vanishing -- leaves no bytes, artifact or store
//! file behind; a recycled staging file never aliases what was sealed from it; and every
//! fan-out delivery reads its own bytes.
mod common;
use std::os::unix::fs::MetadataExt;
use common::{Via, code, env, env_with};
use flybus::{Limits, Policy};
use serde_json::{Map, Value, json};
fn reference(a: &Map<String, Value>, len: &str) -> Value {
json!({"storeId": a["writeLocation"]["storeId"], "artifactId": a["artifactId"],
"generation": "1", "byteLength": len, "contentType": "application/octet-stream",
"digest": null})
}
async fn clean(e: &common::Env, what: &str) {
e.settle(what, |s| s.artifacts == 0 && s.store_bytes == 0).await;
e.settle_files("sealed", 0).await;
e.settle_files("staging", 0).await;
}
/// Refused after the seal, with recycle: nothing leaks (bytes, artifacts, files).
async fn refused_after_seal_with_recycle_leaks_nothing(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
let (a, p) = raw.allocate(300_000).await; // over INLINE_IO_BYTES: spawn_blocking path
std::fs::write(&p, vec![7u8; 300_000]).unwrap();
let (b, _) = raw.allocate(8).await;
let att = json!([
{"name": "x", "ref": reference(&a, "299999"), "ownerId": a["ownerId"]},
{"name": "y", "ref": reference(&b, "8"), "ownerId": b["ownerId"]},
]);
let r = raw
.call_with("publish", json!({"topic": "t.nobody", "payload": {}, "recycle": true}), att)
.await;
assert_eq!(code(&r), "NO_TOPIC");
clean(&e, "refused after seal").await;
}
/// Quota refusal: the writer is released and accounting returns to zero.
async fn quota_refusal_releases(via: Via) {
let limits = Limits { max_store_bytes: 12, max_artifact_bytes: 12, max_retained_bytes: 12, ..Limits::default() };
let e = env_with(via, limits, Policy::open()).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), "OK");
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]);
let r = raw.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await;
assert_eq!(code(&r), "QUOTA_EXCEEDED");
assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID");
clean(&e, "quota").await;
// A prefix fits where the whole would not: 8 allocated + 4 sealed = 12.
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "4"), "ownerId": a["ownerId"]}]);
let v = raw.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await.unwrap();
let w = v["writers"][0].as_object().unwrap().clone();
e.settle("prefix + recycled staging", |s| s.store_bytes == 12 && s.artifacts == 2).await;
let r = raw.call("artifact.release", json!({"ownerIds": [a["ownerId"], w["ownerId"]]})).await.unwrap();
assert_eq!(r["released"], "2");
clean(&e, "released").await;
}
/// The seal fails (staging truncated by the producer) on the second of two writers, the first
/// already renamed for recycling: both released, every file gone.
async fn seal_failure_mid_send_cleans_up(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), "OK");
let (a, _) = raw.allocate(8).await;
let (b, pb) = raw.allocate(8).await;
std::fs::OpenOptions::new().write(true).open(&pb).unwrap().set_len(0).unwrap();
let att = json!([
{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]},
{"name": "y", "ref": reference(&b, "8"), "ownerId": b["ownerId"]},
]);
let r = raw.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await;
assert_eq!(code(&r), "ARTIFACT_MISMATCH");
assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID");
clean(&e, "seal failure").await;
}
/// No owner budget for the recycled writer: it is left out, its staging file goes, accounting holds.
async fn recycle_without_budget(via: Via) {
let limits = Limits { max_owners_per_client: 65, reserved_owners_per_client: 64, ..Limits::default() };
let e = env_with(via, limits, Policy::open()).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), "OK");
let (a, _) = raw.allocate(8).await;
let att = json!([{"name": "x", "ref": reference(&a, "5"), "ownerId": a["ownerId"]}]);
let v = raw.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await.unwrap();
assert!(v.get("writers").is_none(), "no budget, no writer: {v:?}");
e.settle("only the sealed prefix", |s| s.store_bytes == 5 && s.artifacts == 1).await;
e.settle_files("staging", 0).await;
let r = raw.call("artifact.release", json!({"ownerIds": [a["ownerId"]]})).await.unwrap();
assert_eq!(r["released"], "1");
clean(&e, "released").await;
}
/// The recycled staging file is not the sealed inode; writing it leaves the sealed bytes alone;
/// releasing the old owner twice never touches the new writer (owner ids never reused).
async fn recycled_file_never_aliases_sealed(via: Via) {
let e = env(via).await;
let mut raw = e.raw_hello("raw").await;
assert_eq!(code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), "OK");
let (a, pa) = raw.allocate(8).await;
std::fs::write(&pa, b"AAAAAAAA").unwrap();
let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]);
let v = raw.call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await.unwrap();
let w = v["writers"][0].as_object().unwrap().clone();
let pw = raw.path(&w["writeLocation"]);
let open = raw.call("artifact.open", json!({"ref": reference(&a, "8"), "ownerId": a["ownerId"]})).await.unwrap();
let ps = raw.path(&open["readLocation"]);
assert_ne!(std::fs::metadata(&ps).unwrap().ino(), std::fs::metadata(&pw).unwrap().ino());
assert_eq!(std::fs::metadata(&ps).unwrap().mode() & 0o777, 0o444);
let held = std::fs::File::open(&ps).unwrap();
std::fs::write(&pw, b"BBBBBBBB").unwrap();
assert_eq!(std::fs::read(&ps).unwrap(), b"AAAAAAAA");
drop(held);
// Release the old owner twice: the second is a no-op; the new writer still seals.
let r = raw.call("artifact.release", json!({"ownerIds": [a["ownerId"]]})).await.unwrap();
assert_eq!(r["released"], "1");
let r = raw.call("artifact.release", json!({"ownerIds": [a["ownerId"]]})).await.unwrap();
assert_eq!(r["released"], "0");
let r = raw.seal(&w, json!(null)).await.unwrap();
assert_eq!(r["ref"]["byteLength"], "8");
let rd = raw.call("artifact.open", json!({"ref": r["ref"], "ownerId": w["ownerId"]})).await.unwrap();
assert_eq!(std::fs::read(raw.path(&rd["readLocation"])).unwrap(), b"BBBBBBBB");
let r = raw.call("artifact.release", json!({"ownerIds": [w["ownerId"]]})).await.unwrap();
assert_eq!(r["released"], "1");
clean(&e, "all released").await;
}
/// A client that sends a large sealing send and vanishes: nothing leaks.
async fn sender_vanishes_mid_seal(via: Via) {
let e = env(via).await;
let mut keep = e.raw_hello("keeper").await;
assert_eq!(code(&keep.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), "OK");
for i in 0..5 {
let mut raw = e.raw_hello(&format!("raw{i}")).await;
let (a, p) = raw.allocate(8 << 20).await;
std::fs::write(&p, vec![1u8; 8 << 20]).unwrap();
let att = json!([{"name": "x", "ref": reference(&a, &(8u64 << 20).to_string()), "ownerId": a["ownerId"]}]);
raw.command("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att).await;
drop(raw);
e.settle("gone", |s| s.connections == 1).await;
}
clean(&e, "vanished").await;
}
/// A subscriber holding a delivered artifact while the publisher recycles and republishes:
/// each delivery reads its own bytes (fan-out to two subscribers).
async fn fanout_reads_own_bytes(via: Via) {
use std::io::Write;
let e = env(via).await;
let publisher = e.client("pub").await;
let s1c = e.client("s1").await;
let s2c = e.client("s2").await;
publisher.declare_topic("t.f", flybus::Retained::None).await.unwrap();
let mut s1 = s1c.subscribe("t.f", flybus::SubscriptionConfig::bounded()).await.unwrap();
let mut s2 = s2c.subscribe("t.f", flybus::SubscriptionConfig::bounded()).await.unwrap();
let mut w = publisher.artifacts().allocate(4096, "application/octet-stream").await.unwrap();
for round in 0..3u8 {
w.write_all(&[round; 100]).unwrap();
let u = w.into_unsealed();
let a = u.artifact().clone();
publisher.publish("t.f", serde_json::Map::new(), &[("x", &a)]).await.unwrap();
drop(u);
w = publisher.artifacts().allocate(4096, "application/octet-stream").await.unwrap();
}
let mut got1 = Vec::new();
let mut got2 = Vec::new();
for _ in 0..3 {
got1.push(s1.next().await.unwrap());
got2.push(s2.next().await.unwrap());
}
for (i, (m1, m2)) in got1.iter().zip(&got2).enumerate() {
assert_eq!(m1.artifact("x").unwrap().read_all().await.unwrap(), vec![i as u8; 100]);
assert_eq!(m2.artifact("x").unwrap().read_all().await.unwrap(), vec![i as u8; 100]);
}
}
both_transports!(
refused_after_seal_with_recycle_leaks_nothing,
quota_refusal_releases,
seal_failure_mid_send_cleans_up,
recycle_without_budget,
recycled_file_never_aliases_sealed,
sender_vanishes_mid_seal,
fanout_reads_own_bytes,
);

View file

@ -361,10 +361,9 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil
let feed_hz = (headers.len() - 1) as f64 * 1000.0 / published_span_ms;
let arrival_hz = (headers.len() - 1) as f64 / first_at.elapsed().as_secs_f64();
eprintln!(
"[timing] {} snapshots published over {:.3} s: {feed_hz:.2} Hz (contract: a 30 Hz wall-clock\n\
\x20 timer while running; one snapshot per loop pass at most, so the rate is the\n\
\x20 timer's on an idle box and falls with the box's load). Client-side arrival\n\
\x20 rate {arrival_hz:.2} Hz.",
"[timing] {} snapshots published over {:.3} s: {feed_hz:.2} Hz (contract: 30 Hz while\n\
\x20 running; the ceiling is one snapshot per two 16.74 ms emulator frames,\n\
\x20 29.86 Hz). Client-side arrival rate {arrival_hz:.2} Hz.",
headers.len(),
published_span_ms / 1000.0
);
@ -372,29 +371,12 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil
"[timing] first snapshot {:.3} s after connecting",
first_at.duration_since(connected_at).as_secs_f64()
);
// The publish cadence is a wall-clock timer (`docs/feed-protocol.md`: "30 snapshots per
// second wall-clock while running"), so how many emulator frames sit between two snapshots
// is not fixed: 2 on an idle box (33.5 ms), but 1 or 3 whenever the timer and the 16.74 ms
// frame clock drift against each other, and 1 per snapshot for most of a run when the box is
// loaded and the loop is behind real time. Asserting 25..31 Hz here failed ~1 run in 3 with
// sibling tests booting sims in parallel (22.5 Hz in the v0.7.6 gate). The wall rate is
// therefore only logged, with a bound that tells "running" from the 2 Hz idle path.
assert!(
feed_hz > 2.5,
"the feed published at {feed_hz:.2} Hz, which is the paused/booting cadence, not a running one"
(25.0..31.0).contains(&feed_hz),
"the feed published at {feed_hz:.2} Hz, which is not the contract's 30 Hz"
);
// What is deterministic is the structure: contiguous seq, the emulator advancing at least one
// frame per snapshot, and the brain clock advancing exactly with the frames it ran (the
// 1 ms kernel takes 16 or 17 ticks per 16.74 ms frame, carrying the remainder).
for pair in headers.windows(2) {
assert_eq!(pair[1].seq, pair[0].seq + 1, "a snapshot was dropped between publishes");
let frames = pair[1].frame.checked_sub(pair[0].frame).expect("frame went backwards");
assert!(frames >= 1, "a running snapshot with no emulator frame behind it");
let brain = pair[1].brain_ms - pair[0].brain_ms;
assert!(
(16.0 * frames as f64 - 0.5..=17.0 * frames as f64 + 0.5).contains(&brain),
"{brain} ms of brain time over {frames} frames, expected 16 or 17 ticks each"
);
}
let (_, metrics) = http_blocking(service.control_port, "GET", "/metrics", None).unwrap();
for name in ["fly_lag_seconds", "fly_realtime_factor", "fly_feed_clients"] {
@ -638,12 +620,7 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil
.expect("open")
.expect("readable");
if let Message::Binary(bytes) = message {
// `/healthz` can answer while the first thing on the feed is still the 2 Hz boot
// header (frame 0, before the restore reaches the loop): wait for a running one.
let header = split(&bytes).0;
if header.status == flysim::snapshot::FeedStatus::Running {
resumed = Some(header);
}
resumed = Some(split(&bytes).0);
}
}
let resumed = resumed.unwrap();

View file

@ -5132,341 +5132,3 @@ fn row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered() {
assert!(turn_after.is_some(), "the forced switch was never answered: {:?}", drive.starts);
assert_eq!(out, 1, "the Pokémon still standing (the Zubat, slot 1) was sent out");
}
/// Route 25, Bill's house on it, and the flag rung 16 is (`constants/map_constants.asm`,
/// `constants/event_constants.asm`; `docs/design/ladder.md` verified bit 1372).
const ROUTE_25: u32 = 0x24;
const BILLS_HOUSE: u32 = 0x58;
const EVENT_GOT_SS_TICKET: u16 = 1372;
/// A row-73 checkpoint named by `var`, or `None` to skip.
///
/// Scout B3's, from the v0.7.5 tree and the live row-71 checkpoint (rung 15), plus the live one
/// itself (`FLY_ROW71_CHECKPOINT`, rom-env's existing name):
///
/// - `FLY_ROW73_DOOR_CHECKPOINT` (`scout-b3-bills-ring-door`): the same ring, just inside the door.
/// - `FLY_ROW73_PC_CHECKPOINT` (`scout-b3-bills-pc-step`): a carry-forward by scripted presses --
/// Bill has asked for the cell separator and walked into the machine, and the next step is the
/// PC, a hidden event no sprite or sign stands for.
fn row73_checkpoint(var: &str) -> Option<flysim::store::Checkpoint> {
std::env::var_os(var).map(|path| {
flysim::store::load(std::path::Path::new(&path))
.expect("the checkpoint should be a FLYSIM01 envelope")
})
}
/// Row 73: the hidden-event table the macros read is the cartridge's own, and Bill's PC is in it.
///
/// The two addresses are pinned the way `ItemUsePtrTable`'s is: they are the operands of
/// `CheckForHiddenEvent`'s own `ld hl, HiddenEventMaps` (followed by its `ld a, [hli] / ld b, a /
/// cp $ff`) and `ld hl, HiddenEventPointers` (followed by `add hl, de`), found in the routine's
/// bank. Then, standing in Bill's house, the seam reads one hidden event, the PC at (1, 4), pressed
/// facing up -- the entry the scout's scripted presses found by hand.
#[test]
fn row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it() {
use flybrain_gb::pokemon_red::macros::state::{Facing, HiddenEvent};
use flybrain_gb::pokemon_red::state::{self, poke::hidden};
let rom = skip_without_rom!();
let gb = emulator(&rom);
let bank: Vec<u8> = (0x4000u16..0x8000)
.map(|address| gb.read_rom_bank(hidden::TABLE_BANK, address).expect("bank $11 is in the image"))
.collect();
let [maps_low, maps_high] = hidden::MAPS_ADDRESS.to_le_bytes();
let [pointers_low, pointers_high] = hidden::POINTERS_ADDRESS.to_le_bytes();
let maps_load = [0x21, maps_low, maps_high, 0x2a, 0x47, 0xfe, 0xff];
let pointers_load = [0x21, pointers_low, pointers_high, 0x19];
let at = |needle: &[u8]| bank.windows(needle.len()).position(|window| window == needle);
let maps_at = at(&maps_load).expect("CheckForHiddenEvent loads HiddenEventMaps from the pinned address");
let pointers_at =
at(&pointers_load).expect("CheckForHiddenEvent loads HiddenEventPointers from the pinned address");
assert!(pointers_at > maps_at && pointers_at - maps_at < 32, "one routine: {maps_at:#x} {pointers_at:#x}");
// Every map's list ends inside the bounds `state::hidden_events` holds the table to, so no map's
// events are refused for being long (the Game Corner's 48 are the longest).
let byte = |address: u16| bank[usize::from(address - 0x4000)];
let mut maps = 0u16;
while byte(hidden::MAPS_ADDRESS + maps) != 0xff {
assert!(maps < hidden::MAX_MAPS, "the map list ends");
let at = hidden::POINTERS_ADDRESS + 2 * maps;
let list = u16::from_le_bytes([byte(at), byte(at + 1)]);
let entries = (0..).take_while(|entry| byte(list + entry * hidden::ENTRY_BYTES) != 0xff).count();
assert!(entries < usize::from(hidden::MAX_ENTRIES), "map {:#04x}: {entries}", byte(hidden::MAPS_ADDRESS + maps));
maps += 1;
}
assert_eq!(maps, 85, "the pinned commit's 85 maps with hidden events");
let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house");
assert_eq!(
state::hidden_events(&mut run.gb),
vec![HiddenEvent { x: 1, y: 4, index: 0, facing: Some(Facing::Up) }],
"Bill's house has one hidden event, the cell separator's PC"
);
}
/// Row 73, the trap: from inside the ring at Bill's door, macros mode earns rung 16 (the S.S.
/// Ticket).
///
/// **Live on v0.7.5** (scout B3, six seeds, 2.8 brain hours): rung 16's place was `at(ROUTE_25)`,
/// so a fly on Route 25 was already "there". `GO ROUTE` walked it into Bill's house, and inside
/// `GO OBJECTIVE` -- an exit into the objective's own map is toward it -- and `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. Behind that, the errand's middle step is the cell separator's PC, a
/// hidden event no macro could press, so even a fly that talked to Bill could not earn the rung.
///
/// The claims, over the stub rotation (no brain, a readout that never names a macro): the fly
/// does not leave the house before the errand is done, and `EVENT_GOT_SS_TICKET` is set within the
/// budget. On main the flag is never set.
///
/// ```sh
/// FLY_ROM=/path/to/pokemon-red.gb \
/// FLY_ROW73_DOOR_CHECKPOINT=.local/checkpoints/scout-b3-bills-ring-door.checkpoint \
/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row73
/// ```
#[test]
fn row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door() {
let rom = skip_without_rom!();
let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house");
assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket");
let (_, out) = row73_drive_to_the_ticket(&mut run, 36_000);
assert_eq!(out, 0, "the house was left before the errand was done");
}
/// Row 73, the whole road: from the live row-71 checkpoint (v0.7.3, rung 15, in a wild battle on
/// Route 25) macros mode finishes the battle, walks to Bill's house and earns the ticket. Route
/// 25's own warp table is what pins `maps::BILLS_HOUSE`.
#[test]
fn row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket() {
let rom = skip_without_rom!();
let Some(checkpoint) = row73_checkpoint("FLY_ROW71_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW71_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.gb.read_wram(flybrain_gb::pokemon_red::symbols::ram::wCurMap), ROUTE_25 as u8);
assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket");
let warps = flybrain_gb::pokemon_red::state::warps(&mut run.gb);
assert!(
warps.iter().any(|warp| (warp.x, warp.y, u32::from(warp.destination_map)) == (45, 3, BILLS_HOUSE)),
"Route 25's door at (45, 3) leads to $58: {warps:?}"
);
row73_drive_to_the_ticket(&mut run, 216_000);
}
/// Row 73, the hidden event alone: Bill is in the machine, the next step is the PC, and macros mode
/// presses it and earns the ticket. On main no button on any pad presses a hidden event.
#[test]
fn row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket() {
let rom = skip_without_rom!();
let Some(checkpoint) = row73_checkpoint("FLY_ROW73_PC_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW73_PC_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house");
assert!(!run.event(EVENT_GOT_SS_TICKET), "the checkpoint has no ticket");
row73_drive_to_the_ticket(&mut run, 36_000);
}
/// Row 73 review N3: the errand is recoverable inside one session. The talked ledger is the
/// session's and the cartridge re-shows Bill once the fly has left (Route 25's script resets his
/// event), so a conversation had on the last visit must not retire this one's: the room's talked
/// entries are forgotten when the fly leaves it with the errand still the objective.
///
/// From the door checkpoint, over the stub rotation: wait for the first `TALK` in the house, then
/// walk the fly out by hand (the macros withhold the exits while the errand waits, which is the
/// point), and the stub earns the ticket from there, in the same session.
#[test]
fn row73_the_errand_survives_leaving_the_house_mid_conversation() {
let rom = skip_without_rom!();
let Some(checkpoint) = row73_checkpoint("FLY_ROW73_DOOR_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW73_DOOR_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), BILLS_HOUSE, "the checkpoint is inside Bill's house");
let mut talked = false;
for _ in 0..24_000 {
run.frame();
if run.talk_starts_by_map.get(&BILLS_HOUSE).copied().unwrap_or(0) > 0 {
talked = true;
break;
}
}
assert!(talked, "no TALK in the house: {:?}", run.talk_starts_by_map);
assert!(!run.event(EVENT_GOT_SS_TICKET), "the ticket is not earned by the first conversation");
// Out by hand: along the room to the doormat's columns (2 and 3) and down, pressing B between
// the cartridge's own text.
let mut out = false;
let mut last = None;
for frame in 0..4_800u32 {
let here = flybrain_gb::pokemon_red::state::player(&mut run.gb);
last = here.map(|player| (player.map, player.x, player.y));
let heading = match here {
Some(player) if player.x < 2 => flybrain_gb::buttons::RIGHT,
Some(player) if player.x > 3 => flybrain_gb::buttons::LEFT,
_ => flybrain_gb::buttons::DOWN,
};
run.gb.set_buttons(if frame % 16 < 12 { heading } else { flybrain_gb::buttons::B });
run.gb.run_frame().expect("a frame should complete");
run.ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, run.ms);
if run.map() != BILLS_HOUSE && run.map() != u32::MAX {
out = true;
break;
}
}
assert!(out, "the fly could not be walked out of the house, last at {last:?}");
run.gb.set_buttons(0);
// Back to the macros, in the same session: the errand is Bill's again, and the ticket is earned.
row73_drive_to_the_ticket(&mut run, 120_000);
}
/// Drive the stub rotation until the ticket's flag is set, counting the house's doors on the way:
/// `(into, out)`.
fn row73_drive_to_the_ticket(run: &mut Run, budget: u32) -> (u32, u32) {
let mut previous = run.map();
let (mut into, mut out) = (0u32, 0u32);
let mut got = None;
for frame in 0..budget {
run.frame();
let map = run.map();
if map != previous && map != u32::MAX {
into += u32::from(map == BILLS_HOUSE);
out += u32::from(previous == BILLS_HOUSE);
previous = map;
}
if run.event(EVENT_GOT_SS_TICKET) {
got = Some(frame);
break;
}
}
eprintln!(
"ticket at {got:?} ({:.1} brain minutes), into the house {into} times, out {out}, rank {}, \
talk on pad by map {:?}, talk starts {:?}, macros {:?}",
run.ms / 60_000.0,
run.adapter.progress().rank,
run.talk_on_pad_by_map,
run.talk_starts_by_map,
run.started
);
assert!(got.is_some(), "no S.S. Ticket in {budget} frames: route {:?}, macros {:?}", run.route, run.started);
(into, out)
}
const ROUTE_5: u32 = 0x10;
const CERULEAN_TRASHED_HOUSE: u32 = 0x3e;
/// Where `GO OBJECTIVE` aims from here, read through the seam the macros read: the tiles.
fn row73_objective_aims(run: &mut Run) -> Vec<(u8, u8)> {
let ledger = AdapterLedger(&run.adapter);
let mut state = flybrain_gb::pokemon_red::state::PokeState::with_ledger(&mut run.gb, &ledger);
flybrain_gb::pokemon_red::macros::palette::objective_goals(&mut state)
.iter()
.map(|aim| (aim.tile.x, aim.tile.y))
.collect()
}
/// Row 73's third trap, on the seam: after the ticket, `GO OBJECTIVE` in the town aims at the
/// trashed house's front door, and inside the house at the hole in its back wall.
///
/// On main the house is off the graph: in the town the objective toward Vermilion aimed at ground
/// the town's piece cannot reach (scout B3: `blocked` at (17, 28)), and inside the house the only
/// way toward an outdoor objective was the front door it came in by. From
/// `FLY_ROW73_SOUTH_CHECKPOINT` (`scout-b3-cerulean-south-half`, seed 4, 40 brain minutes, standing
/// at (10, 26) in the town's south-west) and `FLY_ROW73_TRASHED_CHECKPOINT` (the same run's seed 6,
/// going through the house's front door).
#[test]
fn row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors() {
let rom = skip_without_rom!();
if let Some(checkpoint) = row73_checkpoint("FLY_ROW73_SOUTH_CHECKPOINT") {
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert_eq!(run.map(), CERULEAN_CITY, "the checkpoint is in Cerulean");
assert!(run.event(EVENT_GOT_SS_TICKET), "the checkpoint has the ticket");
assert_eq!(row73_objective_aims(&mut run), vec![(27, 11)], "the trashed house's front door");
} else {
eprintln!("skipped: no FLY_ROW73_SOUTH_CHECKPOINT");
}
let Some(checkpoint) = row73_checkpoint("FLY_ROW73_TRASHED_CHECKPOINT") else {
eprintln!("skipped: no FLY_ROW73_TRASHED_CHECKPOINT");
return;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
// Through the door with no button down: the warp's tear settles inside the house.
for _ in 0..240 {
run.gb.set_buttons(0);
run.gb.run_frame().expect("a frame should complete");
run.ms += MS_PER_FRAME;
run.adapter.sample(&mut run.gb, run.ms);
}
assert_eq!(run.map(), CERULEAN_TRASHED_HOUSE, "inside the trashed house");
let warps = flybrain_gb::pokemon_red::state::warps(&mut run.gb);
assert!(
warps.iter().any(|warp| (warp.x, warp.y, warp.destination_warp) == (3, 0, 7)),
"the hole in the back wall is the house's warp to Cerulean's (27, 9): {warps:?}"
);
assert_eq!(row73_objective_aims(&mut run), vec![(3, 0)], "the hole in the back wall");
}
/// Row 73's third trap, after the ticket: the road south out of Cerulean is through the trashed
/// house, and macros mode takes it to Route 5.
///
/// **Scout B3** (six seeds, 43 brain minutes each, from the ticket's carry-forward): 0 of 6 past
/// row 28 of Cerulean. The town's ground ends there; Route 5 is on the ground behind the trashed
/// house, in by its front door and out by the hole in its back wall, and 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, 60 to 100 map changes per ten brain minutes.
///
/// `FLY_ROW73_TRASHED_CHECKPOINT` (`scout-b3-cerulean-trashed-house`): seed 6, 40 brain minutes
/// in, going through the house's front door. `FLY_ROW73_TICKET_CHECKPOINT`
/// (`scout-b3-post-bill-ticket`): the carry-forward the Cerulean runs started from, in Bill's
/// house with the ticket. The claim from each: the fly is on Route 5 within the budget, and from
/// Bill's house in under half of what main needs.
#[test]
fn row73_the_fly_takes_the_trashed_house_south_to_route_5() {
let rom = skip_without_rom!();
// Deterministic under the stub: on main the two take 54,442 and 63,880 frames, on the branch
// 52,081 and 27,067. The rotation does stumble through the house on main -- `GO ROUTE` takes
// every door in turn -- so this is the regression guard, and the seam test above is the claim
// main fails.
for (var, budget) in [("FLY_ROW73_TRASHED_CHECKPOINT", 72_000u32), ("FLY_ROW73_TICKET_CHECKPOINT", 48_000)] {
let Some(checkpoint) = row73_checkpoint(var) else {
eprintln!("skipped: no {var}");
continue;
};
let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint);
assert!(run.event(EVENT_GOT_SS_TICKET), "{var}: the checkpoint has the ticket");
let mut previous = run.map();
let (mut changes, mut into_the_house) = (0u32, 0u32);
let mut south = None;
for frame in 0..budget {
run.frame();
let map = run.map();
if map != previous && map != u32::MAX {
changes += 1;
into_the_house += u32::from(map == CERULEAN_TRASHED_HOUSE);
previous = map;
}
if map == ROUTE_5 {
south = Some(frame);
break;
}
}
let tail: Vec<u32> = run.route.iter().rev().take(24).rev().copied().collect();
eprintln!(
"{var}: Route 5 at {south:?}, {changes} map changes, into the trashed house \
{into_the_house} times, rank {}, last maps {tail:?}, macros {:?}",
run.adapter.progress().rank,
run.started
);
assert!(south.is_some(), "{var}: not on Route 5 in {budget} frames: last maps {tail:?}");
}
}