Compare commits

...

17 commits

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

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

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

- N3: the router empties and re-reserves a recycled writer's staging file before reissuing it,
  so no artifact sealed from it (by prefix or whole) carries the previous artifact's bytes;
  ArtifactWriter::seal's doc now holds for every writer. contractDigest text says so.
- N2: a sealing reply is sent with the worker's result cache held, so a duplicate replays the
  sealed artifacts instead of attaching the still-unsealed writer.
- N1: a refused sealing reply is answered as the handler's own seal failure was before BUS-02
  (BACKEND_FAILURE, mutation applied), cached the same way, worker marked failed, and logged.
- N5: a failed staging rename unlinks the writer's own staging file.
- N4: recycle without a sealing attachment is refused even when false; one writer named by two
  attachments is refused as INVALID_ENVELOPE; the SDK checks writers on rpc.call and publish
  replies too.
- N6: the store-directory cache is per client connection; bus-v1 notes the residual case.
- N7: the fly-edge stall test waits for the feed topic; SERVE-01 parity accepts a refused
  /stimulate drained one frame late (retryAfterMs one frame apart, nothing else).
- tests: the review's adversarial lifecycle suite (sealing_lifecycle.rs); recycled-writer content,
  rename failure and recycle edges (sealing.rs); replay-vs-sealing and typed refusal in the worker
  shell; smaller-after-larger artifacts through fly-edge and fly-control-edge.
2026-10-02 10:14:23 +00:00
acamilo
5dad5b3cd7 Merge main into port/gpu-02 2026-10-02 07:49:17 +00:00
acamilo
7d817d8cee GPU-02: the session steps a frame per call, the CUDA backend keeps its state on the device
LifNetwork::step_frame runs a game frame's ticks in one call and ORs every
tick's spikes into the transition's bitset. On the CPU it is exactly the
one-tick loop the session ran; on the GPU it is one batch, with membrane
and refractory left on the device (device-owned state): per frame only the
noise draws, visual drive and plastic gains go up and the spike lists come
down, instead of 1.4 MB per tick (about 24 MB per frame) with the old
step(1) loop and per-batch host sync.

- LifBackend (cpu / cuda:<ordinal>) from FLY_LIF_CUDA / FLY_LIF_CUDA_DEVICE,
  set_backend, configure_sweep (set_sweep_plan without the test hook),
  sync_host, host_state_current, try_step, take_backend_fault.
- export_state downloads the device arrays itself while the host copy is
  stale, so no capture can read old values; the session syncs before
  State.Capture.
- A CUDA failure detaches the backend: if the host state was current the
  frame continues bit-exactly on the CPU, otherwise the agent fails and a
  restore in that worker runs on the CPU. Warm-up no longer panics.
- The legacy agent worker picks its backend explicitly and refuses a GPU it
  cannot have (no feature, no device) at Agent.Initialize instead of
  running the CPU under a GPU label. The FLY_LIF_CUDA hook in
  set_sweep_plan stays for the golden suite and the legacy loop.
- cuda passthrough features on fly-session and fly-legacy-session, so
  FLY_CARGO_FEATURES=cuda reaches flysim-session, fly-shadow, fly-session.
- Tests: step_frame vs the one-tick loop (state and bitset, 1 and 3
  threads), the backend switch; cuda_exact frame mode; a cuda-feature
  session test (FAFB, rollback, restore, checkpoints) against the CPU
  reference.
2026-10-02 07:49:17 +00:00
acamilo
29b51ff336 docs: implementation guide BUS-02 (port slice) entry 2026-10-02 05:30:31 +00:00
acamilo
6bc447a5bd docs: flybus README and bus conformance rows for sealing sends (BUS-02) 2026-10-02 05:23:08 +00:00
acamilo
0a35b393aa flybus: sealing sends, encode-once router, cheaper client hot path (BUS-02)
- bus-v1 section 12 amendment 2026-10-02: an rpc.call/rpc.reply/publish attachment may name the
  sender's own unsealed writer; the router seals its declared prefix on admission (copy outside
  the state lock), the writer becomes the sender's hold, and with recycle:true the staging
  allocation comes back as a new writer in the reply. A refused sealing send releases every
  writer it named. contractDigest changes.
- SDK: ArtifactWriter::into_unsealed, Responder::reply_sealing; no rpc.responder.release after an
  admitted reply; delivery payloads moved, not cloned; Fields without hashing.
- Router: every frame encoded once (id spliced at selection); admitted payloads forwarded as
  pre-encoded JSON instead of deep copies; seal copies via copy_file_range with a sized buffer;
  client location resolution caches the store directories.
- fly-session: result attachments kept as delivered (no artifact.retain round trip per
  attachment); reply artifacts sealed by the reply that carries them, writers recycled into a
  capacity-bucketed pool.
- tests: sealing.rs; artifacts.rs updated to the amendment. examples/rtt.rs measures a round trip.
2026-10-02 04:28:05 +00:00
47 changed files with 4391 additions and 376 deletions

View file

@ -187,6 +187,7 @@ 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) |
@ -345,7 +346,7 @@ behind "latest replaces only queued messages": the replacement never turns into
## The crate README's differences from the draft
Each of the ten differences the crate lists, kept with the sentence that allows it or fixed.
Each of the differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict |
| --- | --- |
@ -359,6 +360,8 @@ Each of the ten differences the crate lists, kept with the sentence that allows
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
| 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,7 +207,11 @@ roots, so an idempotent repeat may report zero. Queue/credit requests are intege
and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters.
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. They
local store root; absolute paths, parent traversal and symlink escapes are rejected (the
reference SDK caches a store's canonical directories per connection, BUS-02, and still checks
each file with an lstat and an `O_NOFOLLOW` open; a store directory replaced by a symlink after a
connection first used it is not re-checked by that connection, which the store's 0700 owner-only
directory makes a same-user act). They
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
committed into application schemas or source configuration.
@ -561,3 +565,45 @@ 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,6 +541,51 @@ 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

@ -1043,3 +1043,10 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
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,6 +589,10 @@ 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,6 +129,12 @@ 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
@ -195,24 +201,24 @@ status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
echo "configured: ${conf}"
echo "running: ${run}"
say "configured: ${conf}"
say "running: ${run}"
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
echo " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
say " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
fi
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
echo "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
say "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
url="$(metrics_url "$run")"
if [ "$run" = bus ]; then
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
echo "edge healthz: ok"
say "edge healthz: ok"
else
echo "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
fi
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)"
say "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
fi
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
say "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
if [ -f "$FEED_LOG" ]; then say "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage

View file

@ -48,6 +48,8 @@ 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
@ -175,6 +177,9 @@ write_textfile_metrics() {
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
echo "# 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
@ -711,6 +716,39 @@ 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).
#
@ -1333,6 +1371,7 @@ main() {
check_flystage
check_flycast
check_encoder
check_backend
check_mediamtx
check_flypush
check_disk

View file

@ -1182,13 +1182,49 @@ loud which backend is configured. Two separate switches, deliberately:
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file:
```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`.
@ -1427,6 +1463,50 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
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

@ -1659,6 +1659,8 @@ 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
@ -1720,6 +1722,21 @@ 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

@ -535,6 +535,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"tempfile",
]
[[package]]

View file

@ -342,6 +342,31 @@ 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,6 +175,68 @@ 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,15 +231,29 @@ 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 = client
.subscribe(
feedbus::TOPIC,
SubscriptionConfig::latest().in_flight(2).replay(true),
)
.await
.unwrap();
let mut subscription = loop {
match 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:?}"),
}
};
hoards.push(tokio::spawn(async move {
let mut kept = Vec::new();
while let Some(message) = subscription.next().await {

View file

@ -21,6 +21,11 @@ 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,6 +528,26 @@ 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(),
@ -586,6 +606,14 @@ 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,6 +18,11 @@ 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.

View file

@ -281,6 +281,20 @@ 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,6 +417,10 @@ 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>>,
}
@ -575,6 +579,13 @@ pub fn die_with_parent(command: &mut std::process::Command) {
}
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,
@ -588,6 +599,8 @@ 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),
@ -597,6 +610,7 @@ impl Launcher {
},
store_root: store_root.into(),
sockets,
gpu_marker,
next_socket: AtomicU64::new(0),
listeners: Mutex::new(Vec::new()),
};
@ -1036,6 +1050,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| {
@ -1698,6 +1713,9 @@ 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,7 +42,8 @@ use flybrain_core::envelope::{
agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope,
};
use flybrain_core::json::JsonValue;
use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version};
use flybrain_core::lif::health as lif_health;
use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version};
use serde_json::{Value, json};
use crate::clock::TickAccumulator;
@ -460,6 +461,10 @@ 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)]
@ -511,9 +516,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). 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.
/// 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.
tick_spikes: Option<Vec<u8>>,
staged: Option<StagedAgent>,
activated: BTreeSet<Id>,
@ -869,6 +874,63 @@ 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>,
@ -933,8 +995,21 @@ 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}")))?;
agent.set_sweep_plan(plan);
// Without the core's `FLY_LIF_CUDA` test hook: the backend is this worker's choice.
agent.network.configure_sweep(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),
@ -1169,22 +1244,27 @@ impl LegacyAgentWorker {
let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.ticks");
// One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped
// are its spike list, so the transition's bitset is their union.
// 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`.
let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)];
let mut listed = true;
for _ in 0..ticks {
let count = agent.network.step(1) as usize;
match agent.network.tick_spikes(count) {
Some(list) if listed => {
for &neuron in list {
bits[neuron as usize >> 3] |= 1 << (neuron & 7);
}
}
_ => listed = false,
}
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}"),
));
}
self.tick_spikes = listed.then_some(bits);
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);
drop(ticks_span);
crate::profile::record(
"agent.ticks.phase_clock",
@ -1551,6 +1631,19 @@ 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,6 +991,11 @@ 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;
}
@ -1577,12 +1582,53 @@ 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 {
@ -1594,7 +1640,12 @@ async fn run_script(
}
};
let mut records = vec![first];
for (index, step) in script.steps.iter().enumerate() {
// 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];
let mut record = match step {
ScriptStep::Frame {
sugar,
@ -1602,9 +1653,31 @@ async fn run_script(
rewards,
next_context,
} => {
driver
match driver
.frame(index + 1, sugar, *frame, rewards, next_context)
.await?
.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),
}
}
ScriptStep::Rollback { frame, context } => {
driver.rollback(index + 1, *frame, context).await?
@ -1632,8 +1705,20 @@ async fn run_script(
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,29 +186,15 @@ 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}")))?;
// 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();
// 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).
let mut artifacts = BTreeMap::new();
for retain in retains {
if let Ok((name, artifact)) = retain.await {
artifacts.insert(name, artifact);
for name in &self.want_artifacts {
if let Ok(artifact) = result.artifact(name) {
artifacts.insert(name.clone(), artifact);
}
}
drop(result);

View file

@ -162,17 +162,23 @@ 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). 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.
/// Staging writers allocated ahead of need (BUS-01), and handed back by the router after each
/// reply (BUS-02). A bus worker seals the same shapes of reply artifact every step -- the
/// environment a 92,160-byte frame, a 65,536-byte memory image and an audio chunk of one of two
/// lengths, the agent a 17,407-byte spike bitset and its feed status, a JSON document of varying
/// length -- and allocating one is a router round trip. The pool remembers the last few
/// `(content type, capacity)` shapes [`HandlerCtx::seal`] asked for; a capacity is the length
/// rounded up to 4 KiB, so the two audio lengths and every feed status share one writer. A seal
/// takes a ready writer of its content type with room for its bytes, writes them, and leaves
/// the artifact for the reply to seal (bus-v1 section 12 amendment 2026-10-02): the reply
/// recycles each writer's allocation, the pool takes the recycled writers back, and only a shape
/// with no writer is allocated, off the critical path, after the reply. A writer is an artifact
/// like any other: unsealed, it is released when dropped, and the bytes sealed are exactly the
/// bytes written, so nothing a caller sees depends on the pool.
#[derive(Default)]
pub struct WriterPool {
state: Mutex<PoolState>,
@ -182,27 +188,51 @@ pub struct WriterPool {
struct PoolState {
/// The most recent distinct shapes, newest last.
recent: Vec<(String, u64)>,
ready: Vec<((String, u64), flybus::ArtifactWriter)>,
ready: Vec<flybus::ArtifactWriter>,
allocating: Vec<(String, u64)>,
}
/// 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;
/// Shapes the pool keeps writers for: an environment's three reply artifacts and an agent's
/// two, with room to spare.
const POOL_SHAPES: usize = 6;
/// The allocation a reply artifact of `len` bytes is written into.
fn pool_capacity(len: u64) -> u64 {
len.max(1).div_ceil(4096) * 4096
}
impl WriterPool {
fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> {
let mut st = self.state.lock().expect("never poisoned");
let shape = (content_type.to_owned(), len);
let shape = (content_type.to_owned(), pool_capacity(len));
if let Some(at) = st.recent.iter().position(|s| *s == shape) {
st.recent.remove(at);
} else if st.recent.len() >= POOL_SHAPES {
let gone = st.recent.remove(0);
st.ready.retain(|(s, _)| *s != gone);
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.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.
@ -212,7 +242,10 @@ impl WriterPool {
let wanted: Vec<_> = st
.recent
.iter()
.filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s))
.filter(|s| {
!st.ready.iter().any(|w| (w.content_type(), w.byte_length()) == (s.0.as_str(), s.1))
&& !st.allocating.contains(s)
})
.cloned()
.collect();
st.allocating.extend(wanted.iter().cloned());
@ -227,7 +260,7 @@ impl WriterPool {
if let Ok(writer) = writer
&& st.recent.contains(&shape)
{
st.ready.push((shape, writer));
st.ready.push(writer);
}
});
}
@ -290,26 +323,36 @@ 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
/// it is allocated, written and sealed in the router's store as before.
/// 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.
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));
}
// 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");
return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await;
let len = bytes.len() as u64;
let mut writer = match self.writers.take(content_type, len) {
Some(writer) => writer,
None => {
let _span = crate::profile::span("shell.seal.allocated");
self.client
.artifacts()
.allocate(pool_capacity(len), content_type)
.await
.map_err(|e| crate::media::store_error("allocate", &e.message))?
}
};
let _span = crate::profile::span("shell.seal.pooled");
use std::io::Write as _;
writer
.write_all(&bytes)
.map_err(|e| crate::media::store_error("write", &e.to_string()))?;
writer
.seal()
.await
.map_err(|e| crate::media::store_error("seal", &e.message))
let unsealed = writer.into_unsealed();
let artifact = unsealed.artifact().clone();
self.unsealed.lock().expect("never poisoned").push(unsealed);
Ok(artifact)
}
}
@ -476,16 +519,42 @@ 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 {
async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) {
/// 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 {
match self {
Answer::Bus(responder) => {
let list: Vec<(&str, &flybus::Artifact)> =
artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
let _ = responder.reply(outcome.to_outcome(), &list).await;
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())
}
}
}
@ -751,7 +820,7 @@ impl<E: WorkerEndpoint> Shell<E> {
DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")),
request.scope.clone(),
);
answer.send(outcome, &[]).await;
answer.send(outcome, &[], Vec::new()).await;
return;
};
@ -762,7 +831,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, &[]).await;
answer.send(outcome, &[], Vec::new()).await;
return;
}
};
@ -776,7 +845,7 @@ impl<E: WorkerEndpoint> Shell<E> {
},
(OpClass::StepMutation, None) => {
let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None);
answer.send(outcome, &[]).await;
answer.send(outcome, &[], Vec::new()).await;
return;
}
_ => OperationKey {
@ -797,12 +866,12 @@ impl<E: WorkerEndpoint> Shell<E> {
};
match admission {
Admission::Replay(reply) => {
answer.send(reply.outcome.clone(), &reply.artifacts).await;
answer.send(reply.outcome.clone(), &reply.artifacts, Vec::new()).await;
return;
}
Admission::Refuse(e) => {
let outcome = refuse(e, request.scope.clone());
answer.send(outcome, &[]).await;
answer.send(outcome, &[], Vec::new()).await;
return;
}
Admission::Execute => {}
@ -907,6 +976,7 @@ 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.
@ -918,6 +988,7 @@ 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
@ -979,22 +1050,88 @@ 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 mut c = cache.lock().await;
let c = held.as_mut().expect("just taken");
match class {
OpClass::StepMutation => c.record(key, serial, body, cached),
OpClass::Lifecycle => c.record_lifecycle(serial, body, cached),
OpClass::ReadOnly => c.record_readonly(serial, cached),
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),
}
}
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");
answer.send(outcome, &reply.artifacts).await;
let sent = answer.send(outcome, &reply.artifacts, unsealed).await;
drop(reply_span);
// The next step's writers, allocated while the caller goes on (bus requests only:
// the lane seals nothing into the store).
let recycled = match sent {
Sent::Done(recycled) => {
drop(held);
recycled
}
Sent::SealRefused(answer, error) => {
// The handler's artifacts could not be stored. Before BUS-02 the handler's
// own seal failed and returned this error; it is answered, cached and
// reported exactly as that was (BUS-02 review N1), instead of reaching the
// caller as a bus-level failed call.
eprintln!(
"worker {worker_id}: {method}: the reply's artifacts were not sealed ({}: {}); \
answering BACKEND_FAILURE",
error.code.as_str(),
error.message
);
let e = crate::media::store_error("seal", &error.message);
let mut c = held.take().expect("a sealing reply holds the cache");
match class {
OpClass::StepMutation => c.record(
key,
serial,
body,
CachedReply::new(failure_outcome(
&request.request_id,
worker_id,
incarnation_id,
request.scope.clone(),
e.clone(),
)),
),
OpClass::Lifecycle => c.forget_lifecycle(&serial),
OpClass::ReadOnly => c.forget_readonly(&serial),
}
drop(c);
status.set_state(WorkerState::Failed);
status.set_active(None);
let outcome = failure(
&request.request_id,
worker_id,
incarnation_id,
request.scope.clone(),
e,
);
let _ = answer.send(outcome, &[], Vec::new()).await;
Vec::new()
}
};
// The next step's writers: the ones the reply recycled, and any shape without one
// allocated while the caller goes on (bus requests only: the lane seals nothing into
// the store).
if matches!(incoming, Incoming::Bus(_)) {
shell.writers.give(recycled);
shell.writers.refill(&shell.client);
}
}
@ -1027,7 +1164,7 @@ async fn execute<E: WorkerEndpoint>(
request.scope.clone(),
e,
);
answer.send(outcome, &[]).await;
answer.send(outcome, &[], Vec::new()).await;
}
}
}
@ -1201,3 +1338,7 @@ async fn acknowledge(
let result = AcknowledgeResult { acknowledged };
Ok(object(result.to_json()))
}
#[cfg(test)]
#[path = "worker_sealing_tests.rs"]
mod sealing_tests;

View file

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

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

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

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

View file

@ -21,13 +21,23 @@
//! ```
//!
//! Optional arguments: a dataset directory, then the tick count, then the CPU thread count for the
//! reference run (default 4).
//! 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).
use std::sync::Arc;
use std::time::Instant;
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::lif::{LifConfig, LifNetwork, SweepPlan};
use flybrain_core::lif::{LifBackend, LifConfig, LifNetwork, LifState, SweepPlan};
use flybrain_core::plasticity::PlasticityConfig;
#[cfg(feature = "cuda")]
@ -101,6 +111,95 @@ 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");
@ -121,6 +220,14 @@ 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!(
@ -129,6 +236,11 @@ 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(
@ -142,7 +254,7 @@ fn main() {
let mut gpu = build();
cpu.set_sweep_plan(SweepPlan::with_threads(threads).expect("a pool"));
let backend = CudaLif::new(&gpu, 0).expect("the CUDA backend must start");
let backend = CudaLif::new(&gpu, device).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),
@ -213,85 +325,7 @@ fn main() {
let left = cpu.export_state();
let right = gpu.export_state();
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,
)
});
divergence = compare_states(tick, &cpu.role_names, &left, &right);
if divergence.is_some() {
break;
}
@ -327,3 +361,147 @@ 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,8 +220,10 @@ impl NeuralAgent {
bail!("Agent is already warmed up");
}
self.network.plasticity.enabled = false;
self.network.step(self.warmup_ms);
// `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.plasticity.enabled = true;
stepped?;
let rates = self.network.rates.clone();
self.decoder.calibrate(&rates);
if let Some(frame) = first_frame {

View file

@ -21,6 +21,9 @@ 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";
@ -57,6 +60,64 @@ 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))`.
@ -275,7 +336,12 @@ 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>,
@ -311,6 +377,8 @@ 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>>,
@ -423,6 +491,7 @@ impl LifNetwork {
timings: PhaseTimings::default(),
data,
sweep: SweepPlan::sequential(),
backend_fault: None,
#[cfg(feature = "cuda")]
cuda: None,
})
@ -435,18 +504,87 @@ 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;
// 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.
}
/// 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 => {
#[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")]
self.attach_cuda_if_requested();
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(())
}
pub fn sweep_plan(&self) -> &SweepPlan {
@ -508,11 +646,10 @@ 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. A read-only view; it changes nothing a tick computes.
/// not kept per tick ([`LifNetwork::step_frame`] gathers the lists either way). 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() {
@ -521,12 +658,18 @@ 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);
return self
.step_on_cuda(milliseconds, None)
.unwrap_or_else(|error| panic!("CUDA LIF batch failed: {error}"));
}
let mut total = 0u64;
for _ in 0..milliseconds {
@ -535,6 +678,59 @@ 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;
@ -797,10 +993,15 @@ 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: self.membrane.clone(),
refractory: self.refractory.clone(),
membrane,
refractory,
last_spike_ms: self.last_spike_ms.clone(),
visual_drive: self.visual_drive.clone(),
rng: self.rng.state(),
@ -812,6 +1013,18 @@ 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,10 +38,19 @@
//! # State ownership
//!
//! Between batches the device owns `membrane` and `refractory`. With
//! [`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.
//! [`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.
use std::sync::Arc;
@ -55,6 +64,88 @@ 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;
@ -89,6 +180,12 @@ 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}"))
}
@ -149,6 +246,7 @@ pub struct CudaLif {
bucket_rebase_kernel: CudaFunction,
bucket_apply_kernel: CudaFunction,
ordinal: usize,
neurons: usize,
blocks: u32,
max_ticks: usize,
@ -201,7 +299,14 @@ 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.
@ -239,6 +344,7 @@ 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 {
@ -389,6 +495,7 @@ impl CudaLif {
bucket_rebase_kernel: function("lif_bucket_rebase")?,
bucket_apply_kernel: function("lif_bucket_apply")?,
ordinal,
neurons,
blocks,
max_ticks,
@ -403,6 +510,9 @@ 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))?,
@ -429,19 +539,33 @@ 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`].
/// next batch. Called by [`LifNetwork::import_state`], which overwrites both arrays whole, so
/// the host is the current copy again.
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))?;
@ -450,7 +574,28 @@ impl CudaLif {
.map_err(|error| driver_error("refractory download", error))?;
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))
.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))
}
fn upload_state(&mut self, network: &LifNetwork) -> Result<()> {
@ -460,12 +605,61 @@ 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.
fn run_batch(&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,
/// 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> {
debug_assert!(ticks <= self.max_ticks);
let neurons = self.neurons;
@ -508,7 +702,9 @@ 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)
@ -519,12 +715,14 @@ 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)
@ -546,6 +744,7 @@ 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)
@ -583,22 +782,9 @@ impl CudaLif {
self.stream
.synchronize()
.map_err(|error| driver_error("synchronize", error))?;
// 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)
self.uploaded_bytes += uploaded as u64;
self.downloaded_bytes += ((ticks + total) * 4) as u64;
Ok(total)
}
/// Record phase mark `index` when phase profiling is on.
@ -839,37 +1025,110 @@ 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() || std::env::var("FLY_LIF_CUDA").as_deref() != Ok("1") {
if self.cuda.is_some() {
return;
}
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) {
let Ok(super::LifBackend::Cuda { device }) = super::LifBackend::from_env() else {
return;
};
match CudaLif::new(self, device) {
Ok(backend) => self.attach_cuda(backend),
Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"),
}
}
/// The batched GPU path behind [`LifNetwork::step`].
pub(super) fn step_on_cuda(&mut self, milliseconds: u64) -> u64 {
/// 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> {
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;
match backend.run_batch(self, ticks) {
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()) {
Ok(spikes) => total += spikes as u64,
Err(error) => panic!("CUDA LIF batch failed: {error}"),
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));
}
}
left -= ticks as u64;
}
self.cuda = Some(backend);
total
Ok(total)
}
/// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike

View file

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

@ -0,0 +1,57 @@
//! 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.
//! bitset a scan of `last_spike_ms` gives. GPU-02: `step_frame` gathers the same union in one call.
mod common;
@ -52,3 +52,107 @@ 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

@ -11,7 +11,8 @@ 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 }
serde_json = { workspace = true }
# `raw_value`: the router forwards payloads it validated as pre-encoded JSON (BUS-02).
serde_json = { workspace = true, features = ["raw_value"] }
sha2 = { workspace = true }
tokio = { version = "1", features = ["rt", "net", "io-util", "sync", "time", "macros"] }

View file

@ -186,6 +186,16 @@ 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
@ -332,6 +342,13 @@ 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
@ -369,6 +386,8 @@ 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
@ -391,6 +410,15 @@ 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

@ -0,0 +1,257 @@
//! 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};
use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand, WriterGrant};
use crate::error::{BusError, Dispatch, ErrorCode};
use crate::store::{open_read, resolve};
use crate::store::{open_read, open_write, 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)?;
let path = resolve(&shared.store_root, &loc.store_id, &loc, &shared.dirs)?;
let file = open_read(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("open: {e}")))?;
let len = file
@ -363,6 +363,8 @@ 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 {
@ -374,8 +376,44 @@ impl ArtifactWriter {
self.byte_length
}
/// 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.
/// 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.
pub async fn seal(self) -> Result<Artifact, BusError> {
self.seal_with_digest(None).await
}
@ -539,6 +577,30 @@ 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 {
@ -567,18 +629,100 @@ 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, Service, Subscription,
RpcResult, SealedReply, Service, Subscription, Unsealed,
};
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)?;
let path = resolve(&shared.store_root, &loc.store_id, &loc, &shared.dirs)?;
let file = open_write(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("staging: {e}")))?;
Ok(ArtifactWriter {
@ -593,6 +593,8 @@ impl Artifacts<'_> {
artifact_id,
byte_length,
written: 0,
store_id: loc.store_id,
content_type: content_type.to_owned(),
})
}
}

View file

@ -44,6 +44,17 @@ 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
@ -57,6 +68,8 @@ 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 {
@ -114,6 +127,8 @@ 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,
@ -144,6 +159,7 @@ impl Shared {
Shared {
info,
store_root,
dirs: crate::store::DirCache::default(),
state: Mutex::new(ClientState {
closed: None,
shutting_down: false,
@ -445,6 +461,7 @@ pub(crate) async fn write_loop(shared: Arc<Shared>, mut wr: WriteHalf<Transport>
_ = shutdown.wait_for(|v| *v) => break,
}
}
Next::Exit => break,
}
}
@ -614,9 +631,11 @@ 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")?;
@ -646,6 +665,7 @@ 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")?;
@ -673,6 +693,29 @@ 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,
@ -704,6 +747,36 @@ 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) {
@ -826,12 +899,22 @@ 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>,
env: Envelope,
mut env: Envelope,
) -> Result<(), WireError> {
let mut f = Fields::of(&env.body, "delivery");
let mut body = std::mem::take(&mut env.body);
let mut f = Fields::of(&body, "delivery");
let delivery_id = f.id("deliveryId")?;
let delivery_serial = parse_serial_id("dlv", &delivery_id)
.filter(|n| *n > 0)
@ -854,14 +937,16 @@ fn on_delivery(
return Err(WireError("service incarnation is not svc-<U64>".into()));
}
let method = f.method("method")?;
let payload = f.object("payload")?.clone();
f.object("payload")?;
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,
@ -891,8 +976,9 @@ fn on_delivery(
if parse_serial_id("svc", &service_incarnation).is_none() {
return Err(WireError("service incarnation is not svc-<U64>".into()));
}
let outcome = f.object("outcome")?.clone();
f.object("outcome")?;
f.finish()?;
let outcome = take_object(&mut body, "outcome");
accept_delivery_serial(shared, delivery_serial)?;
let res = RpcResult {
guard,
@ -923,8 +1009,9 @@ fn on_delivery(
}
let topic_sequence = u64_field(&mut f, "topicSequence")?;
let replaced = u64_field(&mut f, "replaced")?;
let payload = f.object("payload")?.clone();
f.object("payload")?;
f.finish()?;
let payload = take_object(&mut body, "payload");
accept_delivery_serial(shared, delivery_serial)?;
let msg = Message {
guard,
@ -1011,3 +1098,37 @@ 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, Service,
Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, SealedReply, Service, Unsealed,
ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo,
};
pub use error::{BusError, Dispatch, ErrorCode};

View file

@ -331,6 +331,64 @@ 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,6 +15,8 @@
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};
@ -24,7 +26,8 @@ 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, WireError, id_batch, parse_serial_id, serial_id,
MAX_CREDIT, MAX_ENVELOPE_BYTES, MINOR, Unnumbered, WireError, id_batch, parse_serial_id,
serial_id,
};
pub(crate) type ConnKey = u64;
@ -155,6 +158,9 @@ 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,
}
@ -176,18 +182,36 @@ 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 {
kind: Kind,
op: String,
reply_to: Option<String>,
body: Map<String, Value>,
attachments: Vec<Attachment>,
frame: Unnumbered,
/// Conservative encoded size using the longest router envelope id.
bytes: usize,
}
@ -324,7 +348,7 @@ struct TopicMsg {
topic: String,
topic_incarnation: String,
sequence: u64,
payload: Map<String, Value>,
payload: Box<RawValue>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
bytes: usize,
@ -361,7 +385,7 @@ struct Svc {
struct ResultMsg {
responder: Identity,
outcome: Map<String, Value>,
outcome: Box<RawValue>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
}
@ -386,7 +410,8 @@ struct Call {
service_incarnation: String,
service_conn: ConnKey,
method: String,
payload: Map<String, Value>,
/// The validated payload, encoded once at admission and forwarded verbatim (BUS-02).
payload: Box<RawValue>,
attachments: Vec<(String, ArtifactRef)>,
artifacts: Vec<u64>,
phase: Phase,
@ -461,10 +486,10 @@ fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec<At
.collect()
}
fn frame_len(
fn frame_len<B: Serialize>(
kind: Kind,
op: &str,
body: Map<String, Value>,
body: B,
attachments: Vec<Attachment>,
) -> usize {
let id = serial_id("bus", MAX_SERIAL);
@ -482,47 +507,113 @@ fn frame_len(
.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(&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 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 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())),
])
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,
}
}
}
impl TopicMsg {
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())),
])
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,
}
}
}
@ -651,41 +742,34 @@ 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.
fn outbound(
/// 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>(
&self,
kind: Kind,
op: &str,
reply_to: Option<String>,
body: Map<String, Value>,
body: B,
attachments: Vec<Attachment>,
) -> Option<Outbound> {
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 {
let head = crate::wire::EnvelopeHead {
major: MAJOR,
minor: MINOR,
id: "",
reply_to: reply_to.as_deref(),
kind,
op: op.to_owned(),
reply_to: env.reply_to,
body,
attachments,
bytes,
})
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 })
}
fn encode_outbound(&mut self, c: ConnKey, item: Outbound) -> Option<Vec<u8>> {
let conn = self.conns.get_mut(&c)?;
conn.out_serial += 1;
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()
Some(item.frame.number(&serial_id("bus", conn.out_serial)))
}
/// Queues a reply or notice on the control lane; closes the connection if the lane is full.
@ -1114,7 +1198,7 @@ impl State {
// -----------------------------------------------------------------------------------------
// Commands
pub(crate) fn handle(&mut self, c: ConnKey, env: Envelope) -> Outcome {
pub(crate) fn handle(&mut self, c: ConnKey, mut env: Envelope) -> Outcome {
let Some(conn) = self.conns.get_mut(&c) else {
return Outcome::Close;
};
@ -1144,6 +1228,34 @@ 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")
{
@ -1192,6 +1304,242 @@ 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
}
@ -1490,7 +1838,7 @@ impl State {
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 = f.object("payload").map_err(wire)?.clone();
let payload = raw(f.object("payload").map_err(wire)?)?;
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>");
@ -1584,7 +1932,7 @@ impl State {
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 = f.object("outcome").map_err(wire)?.clone();
let outcome = raw(f.object("outcome").map_err(wire)?)?;
f.finish().map_err(wire)?;
let Some(n) = parse_serial_id("dlv", &delivery_id) else {
return err(
@ -2022,7 +2370,7 @@ impl State {
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 = f.object("payload").map_err(wire)?.clone();
let payload = raw(f.object("payload").map_err(wire)?)?;
f.finish().map_err(wire)?;
if !Grants::allows(&self.grants(c).publish, &topic) {
return err(
@ -2548,6 +2896,7 @@ impl State {
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),
@ -2556,7 +2905,7 @@ impl State {
kind: DeliveryKind::Result { call: key },
},
);
return self.outbound(Kind::Delivery, "rpc.result", None, body, atts);
return frame;
}
// Requests for services this connection registered, round robin.
let conn = &self.conns[&c];
@ -2583,13 +2932,16 @@ impl State {
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.
// Dispatched before a byte of it is written. (The frame is built below, under the
// same lock, before anything can write it.)
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),
@ -2602,7 +2954,7 @@ impl State {
},
},
);
return self.outbound(Kind::Delivery, "rpc.request", None, body, atts);
return frame;
}
None
}
@ -2630,8 +2982,10 @@ impl State {
conn.delivery_issued += 1;
let n = conn.delivery_issued;
let did = serial_id("dlv", n);
let body = msg.body(&did, &serial_id("sub", id), replaced);
let sid = serial_id("sub", id);
let body = msg.body(&did, &sid, 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),
@ -2640,7 +2994,7 @@ impl State {
kind: DeliveryKind::Topic { sub: id },
},
);
return self.outbound(Kind::Delivery, "topic.message", None, body, atts);
return frame;
}
None
}

View file

@ -108,27 +108,37 @@ impl Store {
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(&path)?;
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();
let result = reserve(&file, len);
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.
@ -159,6 +169,36 @@ 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));
@ -171,6 +211,23 @@ 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) {
@ -187,7 +244,9 @@ fn copy_exact(
digest: Option<&str>,
) -> Result<(), SealFailure> {
let mut hasher = digest.map(|_| Sha256::new());
let mut buf = vec![0u8; 256 * 1024];
// 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 remaining = len;
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
@ -220,6 +279,68 @@ 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<()> {
@ -250,7 +371,12 @@ 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) -> Result<PathBuf, BusError> {
pub(crate) fn resolve(
root: &Path,
store_id: &str,
loc: &Location,
dirs: &DirCache,
) -> Result<PathBuf, BusError> {
if loc.store_id != store_id {
return Err(BusError::new(
ErrorCode::ArtifactGone,
@ -280,18 +406,66 @@ pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result<Pat
_ => return Err(refuse("parent, root or current-directory component")),
}
}
let base = root.join(&loc.store_id);
let base = base
.canonicalize()
// 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)
.map_err(|e| refuse(&format!("store directory: {e}")))?;
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 !full.starts_with(&base) {
let parent = match dir {
None => base.clone(),
Some(dir) => dirs.canonical(&root.join(&loc.store_id), Some(dir)).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) {
return Err(refuse("escapes the store"));
}
Ok(full)
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)
}
}
pub(crate) fn open_read(path: &Path) -> io::Result<File> {
@ -327,7 +501,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")).is_ok());
assert!(resolve(root.path(), "store-x", &loc("sealed/a-1"), &DirCache::default()).is_ok());
for bad in [
"",
"/etc/passwd",
@ -338,7 +512,7 @@ mod tests {
"sealed/a-2",
] {
assert!(
resolve(root.path(), "store-x", &loc(bad)).is_err(),
resolve(root.path(), "store-x", &loc(bad), &DirCache::default()).is_err(),
"{bad:?}"
);
}
@ -347,7 +521,7 @@ mod tests {
relative_path: "sealed/a-1".into(),
};
assert_eq!(
resolve(root.path(), "store-x", &other).unwrap_err().code,
resolve(root.path(), "store-x", &other, &DirCache::default()).unwrap_err().code,
ErrorCode::ArtifactGone
);
}

View file

@ -37,6 +37,8 @@ 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
@ -257,11 +259,16 @@ 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)?;
out.insert(key, v);
// 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())));
}
}
}
Ok(Value::Object(out))
}
@ -273,7 +280,8 @@ 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>,
seen: HashSet<&'static str>,
// A handful of keys per object: a vector beats hashing them (BUS-02).
seen: Vec<&'static str>,
what: &'static str,
}
@ -288,19 +296,19 @@ impl<'a> Fields<'a> {
pub fn of(map: &'a Map<String, Value>, what: &'static str) -> Fields<'a> {
Fields {
map,
seen: HashSet::new(),
seen: Vec::with_capacity(8),
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.insert(key);
self.seen.push(key);
self.map.get(key)
}
pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> {
self.seen.insert(key);
self.seen.push(key);
match self.map.get(key) {
Some(v) => Ok(v),
None => err(format!("{}: missing field {key:?}", self.what)),
@ -397,7 +405,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(())
@ -738,13 +746,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(
pub fn encode_parts<B: serde::Serialize + ?Sized>(
head: &EnvelopeHead<'_>,
body: &Map<String, Value>,
body: &B,
attachments: &[Attachment],
) -> Result<Vec<u8>, WireError> {
#[derive(serde::Serialize)]
struct Out<'a> {
struct Out<'a, B: serde::Serialize + ?Sized> {
protocol: &'static str,
major: u64,
minor: u64,
@ -753,7 +761,7 @@ pub fn encode_parts(
reply_to: Option<&'a str>,
kind: &'static str,
op: &'a str,
body: &'a Map<String, Value>,
body: &'a B,
attachments: Vec<Value>,
}
let out = Out {
@ -778,6 +786,65 @@ pub fn encode_parts(
}
/// 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,11 +86,6 @@ 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",
@ -105,7 +100,20 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) {
)
.await;
assert_eq!(code(&r), "ARTIFACT_UNSEALED");
assert_eq!(code(&raw.seal(&a, Value::Null).await), "OK");
// 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),
"OWNER_INVALID",

View file

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

@ -0,0 +1,195 @@
//! 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,
);