Compare commits

..

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

47 changed files with 376 additions and 4391 deletions

View file

@ -187,7 +187,6 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` | | The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
| The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) | | The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) | | Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
| Sealing on send (amendment 2026-10-02, BUS-02): an `rpc.call`/`rpc.reply`/`publish` attachment naming the sender's own writer is sealed (its declared prefix, copied outside the state lock) before the command is admitted, the writer becomes the sender's hold, `recycle` reissues the staging file as a new writer, and a refused sealing send releases every writer it named | conforms | `router/state.rs::{sealing_attachments, finish_sealing_send}`, `router/mod.rs::read_loop` (`SealThenAdmit`), `store.rs::{seal_prefix, rename}`, `client/handles.rs::{ArtifactWriter::into_unsealed, Responder::reply_sealing}` | `tests/sealing.rs::{a_reply_seals_and_recycles_its_writers, a_refused_sealing_send_releases_its_writers}` (both), `tests/artifacts.rs::unsealed_artifacts_cannot_be_used` (both) |
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) | | A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) | | No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) | | Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
@ -346,7 +345,7 @@ behind "latest replaces only queued messages": the replacement never turns into
## The crate README's differences from the draft ## The crate README's differences from the draft
Each of the differences the crate lists, kept with the sentence that allows it or fixed. Each of the ten differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict | | README difference | Verdict |
| --- | --- | | --- | --- |
@ -360,8 +359,6 @@ Each of the differences the crate lists, kept with the sentence that allows it o
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) | | 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
| 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` | | 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` |
| 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) | | 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) |
| 11. Read locations in deliveries | Kept. The bus-v1 amendment of 2026-10-01 (BUS-01) |
| 12. Sealing sends, `recycle`, and no `rpc.responder.release` after an admitted reply | Kept. The bus-v1 amendment of 2026-10-02 (BUS-02); section 8.1's immutability holds because the sealed bytes are still a copy, and a reply the router admitted already ended the reply authority the release would give up |
## Measured on the dev VM ## Measured on the dev VM

View file

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

View file

@ -541,51 +541,6 @@ multiplayer and more flies follow. The topology, its rules and the shadow proced
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0 ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
hides. 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) ### 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 **2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no

View file

@ -1043,10 +1043,3 @@ 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 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 fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a
wall-clock rate. wall-clock rate.
- 2026-10-02 (v0.7.8, groundwork for the GPU and the bus): the GPU brain steps a whole frame per
call with its state resident on the card (about 230 KB a frame crosses PCIe instead of 24 MB),
bit-exact against the CPU through rollback, restore and checkpoints; a dead GPU makes the process
CPU-only and the replacement restores the last checkpoint on the CPU (cuda feature, off; operator
decision: the live brain moves to the release host's Quadro after a 3 h shadow). Cheaper flybus
round trips (seal on reply, recycled zero-filled staging writers, frames encoded once); the
session's own transport stays on the in-process lane. No behaviour change on the live stream.

View file

@ -589,10 +589,6 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# so FLY_ENCODER-style flipping between backends across restarts keeps the # so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move. # checkpoint: the compatibility string this script gates on does not move.
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}"
# Where the session worker writes fly_brain_backend (which hardware runs the
# LIF tick, and the GPU fallback count): the same textfile directory as
# fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA").
echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom"
# On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the
# kill switch: POST /chat answers 403 and the feed header omits `chat`, so # kill switch: POST /chat answers 403 and the feed header omits `chat`, so
# the CHAT panel blanks without touching flybridge or the page. flysim reads # the CHAT panel blanks without touching flybridge or the page. flysim reads

View file

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

View file

@ -48,8 +48,6 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5). # encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}"
# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick.
: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}"
: "${FLY_PROC_DIR:=/proc}" : "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
@ -177,9 +175,6 @@ write_textfile_metrics() {
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "# TYPE fly_watchdog_encoder_degraded gauge"
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)"
echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend."
echo "# TYPE fly_watchdog_backend_degraded gauge"
echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)"
# Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
# is -1 until the first probe completes, the same "unknown, not # is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or # broken" convention fly_watchdog_encoder_degraded uses; a value at or
@ -716,39 +711,6 @@ check_encoder() {
"and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv"
} }
# ============================================================================
# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the
# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks
# for the card and the CPU is what runs, the GPU fell back (operator decision
# 2026-10-02: automatic, the stream keeps going, logged here, no paging).
#
# Like check 8 this takes NO remediation. A restart cannot repair a dead card
# and costs the run its in-memory state; the fallback is a CPU run from the
# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the
# card to a human. fly_brain_backend is not duplicated into this file's own
# .prom, for the reason check 8 gives.
# ============================================================================
check_backend() {
local wanted live fallbacks
if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then
# No session worker has written it (the legacy loop, a CPU deploy, or not started yet).
echo -1 > "${WD_RUN_DIR}/backend_degraded"
return 0
fi
wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
live="$(awk '/^fly_brain_backend\{/ && $NF == 1 {
if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \
"$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then
echo 1 > "${WD_RUN_DIR}/backend_degraded"
log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \
"Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'"
else
echo 0 > "${WD_RUN_DIR}/backend_degraded"
fi
}
# ============================================================================ # ============================================================================
# Check 9: capture freeze (infra/docs/capture-freeze.md). # Check 9: capture freeze (infra/docs/capture-freeze.md).
# #
@ -1371,7 +1333,6 @@ main() {
check_flystage check_flystage
check_flycast check_flycast
check_encoder check_encoder
check_backend
check_mediamtx check_mediamtx
check_flypush check_flypush
check_disk check_disk

View file

@ -1182,49 +1182,13 @@ loud which backend is configured. Two separate switches, deliberately:
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed | | build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* | | run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file: backend from flysim's own log, not from the env file:
```sh ```sh
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend'
``` ```
The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables
(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without
the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with
`BACKEND_FAILURE`; a build with it logs `LIF backend cuda:<n> attached, device-owned state` when
the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the
card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual
drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the
feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too.
**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no
paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches
a dead card in a loop:
- A CUDA error on a frame whose host state was current (the first frame after a start or a
restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there.
- Any other CUDA error mid-run fails the agent (the device held the only current copy of the
membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on
the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact,
so the CPU run equals one that never had a GPU.
- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and
a CPU worker, not a failed `Agent.Initialize`.
- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still
dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU.
Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure,
with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs),
`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the
textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and
`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises
`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It
takes no remediation and pages no one (a restart cannot fix a dead card and would cost the
run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host,
and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2`
(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0`
and redeploy if the card is not coming back soon.
It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`. targets, `sm_75`.
@ -1463,50 +1427,6 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
whichever container got there first lock the card out from under the other. whichever container got there first lock the card out from under the other.
## GPU on a build box (dev and benchmarks)
A build box is a container with the host's `/dev/nvidia*` device nodes passed through but no
userspace driver installed — used for the `cuda` feature tests and the GPU benchmarks. The
release container follows the lockstep runbook above; this path is only for build boxes,
no root, no system install, one userspace per test run.
**Get the host's module version** — the .run must match exactly:
```sh
ssh the host cat /proc/driver/nvidia/version # the "Kernel Module" line
# or: ssh the host cat /sys/module/nvidia/version
```
**Install under your home.** Download the matching `NVIDIA-Linux-x86_64-<ver>.run`, verify
its SHA256 against the checksum NVIDIA publishes, and `--extract-only`:
```sh
VER=580.76.05 # whatever the host module reports
mkdir -p ~/tmp/nvidia-$VER && cd ~/tmp/nvidia-$VER
U=https://download.nvidia.com/XFree86/Linux-x86_64/$VER/NVIDIA-Linux-x86_64-$VER.run
curl -fSLO $U && curl -fSLO $U.sha256sum
sha256sum -c NVIDIA-Linux-x86_64-$VER.run.sha256sum # must print OK
sh NVIDIA-Linux-x86_64-$VER.run --extract-only --target ~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
```
**Use it only for the test run.** Prepend the extracted directory to `LD_LIBRARY_PATH`
(`libcuda.so`, `libnvidia-ptxjitcompiler.so`) and `PATH` (`nvidia-smi`); the kernel
modules are the host's, so nothing else is needed:
```sh
NV=~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH FLY_CARGO_FEATURES=cuda \
cargo test --release -p flybrain-core --features cuda
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH \
cargo run --release -p flybrain-core --features cuda --example cuda_bench
```
**Shared card.** The build box shares the GPU with the LLM workload. Before and after each
timing run, `nvidia-smi` for other compute processes on the device; re-run flagged timings
(benchmarks yield to the other workload — a contended run is not a measurement).
**Never on the release container** — that path is the lockstep one above.
## The host reboot order ## The host reboot order
Fly containers have no special reboot ordering requirement relative to each other Fly containers have no special reboot ordering requirement relative to each other

View file

@ -1659,8 +1659,6 @@ mkdir -p "$ff_dir/bin" "$ff_dir/release" "$ff_dir/proc/4242" "$ff_dir/run"
cat > "$ff_dir/bin/systemctl" <<'FFSTUB' cat > "$ff_dir/bin/systemctl" <<'FFSTUB'
#!/usr/bin/env bash #!/usr/bin/env bash
echo "$*" >> "$FF_DIR/systemctl.log" 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 case "$1" in
restart) n=$(( $(cat "$FF_DIR/invocation" 2>/dev/null || echo 1) + 1 )); echo "$n" > "$FF_DIR/invocation" 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 # the new flysim's environment is whatever fly.env says now
@ -1722,21 +1720,6 @@ else
fail "fly-feed status wrong: $ff_out" fail "fly-feed status wrong: $ff_out"
fi 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_reset direct direct
FF_ARGS=(bus) FF_ARGS=(bus)
if fly_feed && [ "$(grep -c '^FLY_FEED_VIA=' "$ff_env")" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env" \ if fly_feed && [ "$(grep -c '^FLY_FEED_VIA=' "$ff_env")" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env" \

View file

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

View file

@ -342,31 +342,6 @@ async fn a_request_body_over_the_envelope_gets_directs_answer() {
assert_eq!(rig.bus.router.stats().artifacts, 0); 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, /// 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. /// `date` aside, for a request of every kind.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)]

View file

@ -175,68 +175,6 @@ async fn a_header_too_large_for_an_envelope_travels_as_an_artifact_and_arrives_i
assert!(direct == edge); 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)] #[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() { 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(); let snapshot = snapshot_of(&fixture_messages("shop")[5]).unwrap();

View file

@ -231,29 +231,15 @@ async fn hoarding_subscriber() -> Outcome {
// Every subscription the seat may open, each keeping every delivery at the in-flight cap: // 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"). // the worst case the store has to hold (`feedbus::limits`, flybus.md "Feed sizing").
let seats = feedbus::limits().max_subscriptions_per_client; 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(); let mut hoards = Vec::new();
for _ in 0..seats { for _ in 0..seats {
let mut subscription = loop { let mut subscription = client
match client
.subscribe( .subscribe(
feedbus::TOPIC, feedbus::TOPIC,
SubscriptionConfig::latest().in_flight(2).replay(true), SubscriptionConfig::latest().in_flight(2).replay(true),
) )
.await .await
{ .unwrap();
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 { hoards.push(tokio::spawn(async move {
let mut kept = Vec::new(); let mut kept = Vec::new();
while let Some(message) = subscription.next().await { while let Some(message) = subscription.next().await {

View file

@ -21,11 +21,6 @@ path = "src/bin/flysim-session.rs"
name = "fly-shadow" name = "fly-shadow"
path = "src/bin/fly-shadow.rs" 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] [dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01). # The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" } fly-session = { path = "../fly-session" }

View file

@ -528,26 +528,6 @@ fn truncate(value: &Value) -> String {
} }
} }
/// A `/stimulate` refused because a pulse is still running (429) answers the pulse's remaining
/// brain time at the frame the loop drained the request on. The script sends each request on its
/// frame's snapshot, while the loop sleeps; on a loaded box a request can still reach the loop
/// after its next drain and be drained one frame later (BUS-02 review N7: seen once, the session
/// over bus/process under load 16-22). A refusal changes no state (no event, no journal line, no
/// admission), so the only trace of that is a `retryAfterMs` exactly one emulated frame
/// (16.74 brain ms, so 16 or 17 once rounded up) apart; anything else is still a difference.
fn one_frame_late_refusal(label: &str, status: u16, a: &Value, b: &Value) -> bool {
let retry = |v: &Value| {
let map = v.as_object()?;
if map.len() != 1 {
return None;
}
map.get("retryAfterMs")?.as_u64()
};
label.starts_with("POST /stimulate")
&& status == 429
&& matches!((retry(a), retry(b)), (Some(x), Some(y)) if (16..=17).contains(&x.abs_diff(y)))
}
fn compare(legacy: &Recording, session: &Recording, label: &str) { fn compare(legacy: &Recording, session: &Recording, label: &str) {
assert_eq!( assert_eq!(
legacy.running.len(), legacy.running.len(),
@ -606,14 +586,6 @@ fn compare(legacy: &Recording, session: &Recording, label: &str) {
} }
v 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)); same(&format!("{label}: {la} body"), &strip(ba), &strip(bb));
} }
let status = |v: &Value| { let status = |v: &Value| {

View file

@ -18,11 +18,6 @@ path = "src/lib.rs"
name = "fly-session" name = "fly-session"
path = "src/bin/fly-session.rs" 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] [dependencies]
# The domain contract (scalars, payloads, canonical digests, the trace format) and the bus. # The domain contract (scalars, payloads, canonical digests, the trace format) and the bus.
# Everything else this crate needs is std or Tokio. # Everything else this crate needs is std or Tokio.

View file

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

View file

@ -417,10 +417,6 @@ struct Endpoints {
own: Via, own: Via,
store_root: PathBuf, store_root: PathBuf,
sockets: 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, next_socket: AtomicU64,
listeners: Mutex<Vec<UnixListenerHandle>>, listeners: Mutex<Vec<UnixListenerHandle>>,
} }
@ -579,13 +575,6 @@ pub fn die_with_parent(command: &mut std::process::Command) {
} }
impl Launcher { 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. /// Connects the supervisor and prepares the launcher. Nothing is started yet.
pub async fn start( pub async fn start(
router: Router, router: Router,
@ -599,8 +588,6 @@ impl Launcher {
std::fs::create_dir_all(&sockets).map_err(|e| { std::fs::create_dir_all(&sockets).map_err(|e| {
flybus::BusError::new(flybus::ErrorCode::StoreFailure, format!("sockets: {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 { let endpoints = Endpoints {
router, router,
via: mode.transport(via), via: mode.transport(via),
@ -610,7 +597,6 @@ impl Launcher {
}, },
store_root: store_root.into(), store_root: store_root.into(),
sockets, sockets,
gpu_marker,
next_socket: AtomicU64::new(0), next_socket: AtomicU64::new(0),
listeners: Mutex::new(Vec::new()), listeners: Mutex::new(Vec::new()),
}; };
@ -1050,7 +1036,6 @@ impl Launcher {
.arg(flybrain_core::pool::format_cpu_list(&cpus.sweep)); .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()); command.stdin(std::process::Stdio::null());
die_with_parent(&mut command); die_with_parent(&mut command);
let child = command.spawn().map_err(|e| { let child = command.spawn().map_err(|e| {
@ -1713,9 +1698,6 @@ pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usiz
dataset_dir: spec.dataset_dir.clone(), dataset_dir: spec.dataset_dir.clone(),
profile: spec.profile, profile: spec.profile,
macro_channels: spec.macro_channels.clone(), macro_channels: spec.macro_channels.clone(),
// The deployment's switch, read where the worker runs: a thread, or a child process
// that inherited the launcher's environment.
lif_backend: flybrain_core::lif::LifBackend::from_env(),
} }
} }

View file

@ -42,8 +42,7 @@ use flybrain_core::envelope::{
agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope,
}; };
use flybrain_core::json::JsonValue; use flybrain_core::json::JsonValue;
use flybrain_core::lif::health as lif_health; use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version};
use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version};
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::clock::TickAccumulator; use crate::clock::TickAccumulator;
@ -461,10 +460,6 @@ pub struct LegacyAgentConfig {
pub profile: LegacyProfileKind, pub profile: LegacyProfileKind,
/// The composition's `executor.macroChannels`, in composition order; empty in raw mode. /// The composition's `executor.macroChannels`, in composition order; empty in raw mode.
pub macro_channels: Vec<String>, 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)] #[derive(Clone, Debug, PartialEq, Eq)]
@ -516,9 +511,9 @@ pub struct LegacyAgentWorker {
/// The brain time before the in-flight transition's ticks: the spike window's start. /// The brain time before the in-flight transition's ticks: the spike window's start.
transition_start_ms: f64, transition_start_ms: f64,
/// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike /// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike
/// lists during Prepare (PERF-01; on the GPU too since GPU-02). It is the bitset /// lists during Prepare (PERF-01). It is the bitset `spike_bitset` would scan out of
/// `spike_bitset` would scan out of `last_spike_ms` for the same window, without the /// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the
/// 139,255-neuron scan. `None` only before a Prepare: Commit then scans. /// kernel keeps no per-tick list (the GPU backend): Commit scans as before.
tick_spikes: Option<Vec<u8>>, tick_spikes: Option<Vec<u8>>,
staged: Option<StagedAgent>, staged: Option<StagedAgent>,
activated: BTreeSet<Id>, activated: BTreeSet<Id>,
@ -874,63 +869,6 @@ impl LegacyAgentWorker {
/// Builds a network and readout over `dataset`, before any state is installed, and checks /// 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. /// 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( fn build_agent(
&self, &self,
dataset: Arc<BrainDataset>, dataset: Arc<BrainDataset>,
@ -995,21 +933,8 @@ impl LegacyAgentWorker {
if self.config.worker_threads > 1 { if self.config.worker_threads > 1 {
let plan = SweepPlan::with_threads(self.config.worker_threads) let plan = SweepPlan::with_threads(self.config.worker_threads)
.map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?; .map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?;
// Without the core's `FLY_LIF_CUDA` test hook: the backend is this worker's choice. agent.set_sweep_plan(plan);
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 fingerprint = self.profile.dataset_fingerprint.clone();
let graph = AgentGraph { let graph = AgentGraph {
dataset_digest: dataset_digest(&fingerprint), dataset_digest: dataset_digest(&fingerprint),
@ -1244,27 +1169,22 @@ impl LegacyAgentWorker {
let phase_before = agent.network.timings().total_ns(); let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings(); let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.ticks"); let ticks_span = crate::profile::span("agent.ticks");
// The frame's ticks in one call (GPU-02): on the CPU the one-tick loop `step(ticks)` // One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped
// runs, on the GPU one batch with the state left on the device. Either way each tick's // are its spike list, so the transition's bitset is their union.
// 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 bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)];
if let Err(e) = agent.network.step_frame(ticks, &mut bits) { let mut listed = true;
// The device state was the only current copy, so this worker cannot go on: it fails for _ in 0..ticks {
// and the replacement restores the last checkpoint on the CPU (the GPU is out for let count = agent.network.step(1) as usize;
// the process). match agent.network.tick_spikes(count) {
Self::gpu_failed(&self.config, &format!("{e}; the agent fails, a replacement restores the last checkpoint on the CPU")); Some(list) if listed => {
return Err(applied( for &neuron in list {
ErrorCode::BackendFailure, bits[neuron as usize >> 3] |= 1 << (neuron & 7);
format!("the brain ticks failed: {e}"),
));
} }
if let Some(fault) = agent.network.take_backend_fault() {
// The host state was current: the frame finished on the CPU in this call, and this
// worker continues there.
Self::gpu_failed(&self.config, &fault);
} }
self.tick_spikes = Some(bits); _ => listed = false,
}
}
self.tick_spikes = listed.then_some(bits);
drop(ticks_span); drop(ticks_span);
crate::profile::record( crate::profile::record(
"agent.ticks.phase_clock", "agent.ticks.phase_clock",
@ -1631,19 +1551,6 @@ impl LegacyAgentWorker {
)); ));
} }
let params: CaptureParams = ctx.params()?; 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 // 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 // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
// connectome -- run after the lock is released (`HandlerReply::deferred`), so the next // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next

View file

@ -991,11 +991,6 @@ impl LegacyRig {
self.launch(agent_id).await 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) { pub async fn stop(mut self) {
self.launcher.reap_all(&id("done")).await; self.launcher.reap_all(&id("done")).await;
} }
@ -1582,53 +1577,12 @@ pub async fn run_on_worker_from_then_capture(
Ok((records, captured.expect("a capture was asked for"))) 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( async fn run_script(
rig: &mut LegacyRig, rig: &mut LegacyRig,
agent_id: &Id, agent_id: &Id,
script: &LegacyScript, script: &LegacyScript,
start: Option<(&flybrain_core::agent::AgentState, u64)>, start: Option<(&flybrain_core::agent::AgentState, u64)>,
capture_at_end: bool, 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> { ) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
let mut driver = rig.driver(agent_id, script); let mut driver = rig.driver(agent_id, script);
let first = match start { let first = match start {
@ -1640,12 +1594,7 @@ async fn run_script_with(
} }
}; };
let mut records = vec![first]; let mut records = vec![first];
// The last checkpoint, for a recovery: (step, records so far, the capture, and the driver for (index, step) in script.steps.iter().enumerate() {
// 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 { let mut record = match step {
ScriptStep::Frame { ScriptStep::Frame {
sugar, sugar,
@ -1653,31 +1602,9 @@ async fn run_script_with(
rewards, rewards,
next_context, next_context,
} => { } => {
match driver driver
.frame(index + 1, sugar, *frame, rewards, next_context) .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 } => { ScriptStep::Rollback { frame, context } => {
driver.rollback(index + 1, *frame, context).await? driver.rollback(index + 1, *frame, context).await?
@ -1705,20 +1632,8 @@ async fn run_script_with(
if script.checkpoints.contains(&index) { if script.checkpoints.contains(&index) {
let captured = driver.capture().await?; let captured = driver.capture().await?;
record.state = Some(payload_state_digest(&captured.bytes)?); 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); records.push(record);
index += 1;
} }
let captured = if capture_at_end { let captured = if capture_at_end {
Some(driver.capture().await?.bytes) Some(driver.capture().await?.bytes)

View file

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

View file

@ -162,23 +162,17 @@ pub struct HandlerCtx<'a> {
pub incoming: &'a Incoming, pub incoming: &'a Incoming,
/// Staging writers allocated ahead for the reply artifacts this worker seals every step. /// Staging writers allocated ahead for the reply artifacts this worker seals every step.
pub(crate) writers: &'a WriterPool, pub(crate) writers: &'a WriterPool,
/// The reply artifacts [`HandlerCtx::seal`] wrote and left for the reply to seal (BUS-02).
pub(crate) unsealed: &'a Mutex<Vec<flybus::Unsealed>>,
} }
/// Staging writers allocated ahead of need (BUS-01), and handed back by the router after each /// Staging writers allocated ahead of need (BUS-01). A bus worker seals the same shapes of reply
/// reply (BUS-02). A bus worker seals the same shapes of reply artifact every step -- the /// artifact every step -- the environment a 92,160-byte frame, a 65,536-byte memory image and an
/// environment a 92,160-byte frame, a 65,536-byte memory image and an audio chunk of one of two /// audio chunk of one of two lengths, the agent a 17,407-byte spike bitset -- and allocating one
/// lengths, the agent a 17,407-byte spike bitset and its feed status, a JSON document of varying /// is a router round trip on the step's critical path. The pool remembers the last few
/// length -- and allocating one is a router round trip. The pool remembers the last few /// `(content type, length)` shapes [`HandlerCtx::seal`] asked for and, after each reply, allocates
/// `(content type, capacity)` shapes [`HandlerCtx::seal`] asked for; a capacity is the length /// a writer for every remembered shape that has none, off the critical path. A seal that finds a
/// rounded up to 4 KiB, so the two audio lengths and every feed status share one writer. A seal /// ready writer of its exact shape writes and seals it; one that does not allocates as before. A
/// takes a ready writer of its content type with room for its bytes, writes them, and leaves /// writer is an artifact like any other: unsealed, it is released when dropped, and the bytes it
/// the artifact for the reply to seal (bus-v1 section 12 amendment 2026-10-02): the reply /// seals are the bytes written, so nothing a caller sees depends on the pool.
/// 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)] #[derive(Default)]
pub struct WriterPool { pub struct WriterPool {
state: Mutex<PoolState>, state: Mutex<PoolState>,
@ -188,51 +182,27 @@ pub struct WriterPool {
struct PoolState { struct PoolState {
/// The most recent distinct shapes, newest last. /// The most recent distinct shapes, newest last.
recent: Vec<(String, u64)>, recent: Vec<(String, u64)>,
ready: Vec<flybus::ArtifactWriter>, ready: Vec<((String, u64), flybus::ArtifactWriter)>,
allocating: Vec<(String, u64)>, allocating: Vec<(String, u64)>,
} }
/// Shapes the pool keeps writers for: an environment's three reply artifacts and an agent's /// Shapes the pool keeps writers for: an environment's three reply artifacts, with the audio
/// two, with room to spare. /// chunk's two lengths, and an agent's one.
const POOL_SHAPES: usize = 6; const POOL_SHAPES: usize = 4;
/// 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 { impl WriterPool {
fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> { fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> {
let mut st = self.state.lock().expect("never poisoned"); let mut st = self.state.lock().expect("never poisoned");
let shape = (content_type.to_owned(), pool_capacity(len)); let shape = (content_type.to_owned(), len);
if let Some(at) = st.recent.iter().position(|s| *s == shape) { if let Some(at) = st.recent.iter().position(|s| *s == shape) {
st.recent.remove(at); st.recent.remove(at);
} else if st.recent.len() >= POOL_SHAPES { } else if st.recent.len() >= POOL_SHAPES {
let gone = st.recent.remove(0); let gone = st.recent.remove(0);
st.ready st.ready.retain(|(s, _)| *s != gone);
.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. /// Allocates, in the background, a writer for every remembered shape that has none.
@ -242,10 +212,7 @@ impl WriterPool {
let wanted: Vec<_> = st let wanted: Vec<_> = st
.recent .recent
.iter() .iter()
.filter(|s| { .filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s))
!st.ready.iter().any(|w| (w.content_type(), w.byte_length()) == (s.0.as_str(), s.1))
&& !st.allocating.contains(s)
})
.cloned() .cloned()
.collect(); .collect();
st.allocating.extend(wanted.iter().cloned()); st.allocating.extend(wanted.iter().cloned());
@ -260,7 +227,7 @@ impl WriterPool {
if let Ok(writer) = writer if let Ok(writer) = writer
&& st.recent.contains(&shape) && st.recent.contains(&shape)
{ {
st.ready.push(writer); st.ready.push((shape, writer));
} }
}); });
} }
@ -323,36 +290,26 @@ impl HandlerCtx<'_> {
} }
/// One immutable reply artifact holding `bytes`. Over the local lane it is an in-memory /// 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 /// 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 /// it is allocated, written and sealed in the router's store as before.
/// 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> { pub async fn seal(&self, content_type: &str, bytes: Vec<u8>) -> DomainResult<flybus::Artifact> {
if self.is_local() { if self.is_local() {
return Ok(flybus::Artifact::in_memory(content_type, bytes)); return Ok(flybus::Artifact::in_memory(content_type, bytes));
} }
let len = bytes.len() as u64; // A writer allocated ahead for this shape saves the allocation's round trip ([`WriterPool`]).
let mut writer = match self.writers.take(content_type, len) { let Some(mut writer) = self.writers.take(content_type, bytes.len() as u64) else {
Some(writer) => writer,
None => {
let _span = crate::profile::span("shell.seal.allocated"); let _span = crate::profile::span("shell.seal.allocated");
self.client return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await;
.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"); let _span = crate::profile::span("shell.seal.pooled");
use std::io::Write as _; use std::io::Write as _;
writer writer
.write_all(&bytes) .write_all(&bytes)
.map_err(|e| crate::media::store_error("write", &e.to_string()))?; .map_err(|e| crate::media::store_error("write", &e.to_string()))?;
let unsealed = writer.into_unsealed(); writer
let artifact = unsealed.artifact().clone(); .seal()
self.unsealed.lock().expect("never poisoned").push(unsealed); .await
Ok(artifact) .map_err(|e| crate::media::store_error("seal", &e.message))
} }
} }
@ -519,42 +476,16 @@ enum Answer {
Local(tokio::sync::oneshot::Sender<LocalReply>), 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 { impl Answer {
/// Answers the call. Over the bus, the artifacts left unsealed by [`HandlerCtx::seal`] are async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) {
/// 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 { match self {
Answer::Bus(responder) => { Answer::Bus(responder) => {
let list: Vec<(&str, &flybus::Artifact)> = let list: Vec<(&str, &flybus::Artifact)> =
artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect(); artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
if unsealed.is_empty() {
let _ = responder.reply(outcome.to_outcome(), &list).await; 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) => { Answer::Local(tx) => {
let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() }); let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() });
Sent::Done(Vec::new())
} }
} }
} }
@ -820,7 +751,7 @@ impl<E: WorkerEndpoint> Shell<E> {
DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")), DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")),
request.scope.clone(), request.scope.clone(),
); );
answer.send(outcome, &[], Vec::new()).await; answer.send(outcome, &[]).await;
return; return;
}; };
@ -831,7 +762,7 @@ impl<E: WorkerEndpoint> Shell<E> {
Ok(body) => body, Ok(body) => body,
Err(e) => { Err(e) => {
let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone()); let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone());
answer.send(outcome, &[], Vec::new()).await; answer.send(outcome, &[]).await;
return; return;
} }
}; };
@ -845,7 +776,7 @@ impl<E: WorkerEndpoint> Shell<E> {
}, },
(OpClass::StepMutation, None) => { (OpClass::StepMutation, None) => {
let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None); let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None);
answer.send(outcome, &[], Vec::new()).await; answer.send(outcome, &[]).await;
return; return;
} }
_ => OperationKey { _ => OperationKey {
@ -866,12 +797,12 @@ impl<E: WorkerEndpoint> Shell<E> {
}; };
match admission { match admission {
Admission::Replay(reply) => { Admission::Replay(reply) => {
answer.send(reply.outcome.clone(), &reply.artifacts, Vec::new()).await; answer.send(reply.outcome.clone(), &reply.artifacts).await;
return; return;
} }
Admission::Refuse(e) => { Admission::Refuse(e) => {
let outcome = refuse(e, request.scope.clone()); let outcome = refuse(e, request.scope.clone());
answer.send(outcome, &[], Vec::new()).await; answer.send(outcome, &[]).await;
return; return;
} }
Admission::Execute => {} Admission::Execute => {}
@ -976,7 +907,6 @@ async fn execute<E: WorkerEndpoint>(
let Admitted { class, key, serial, body, method, request, incoming } = admitted; let Admitted { class, key, serial, body, method, request, incoming } = admitted;
let (worker_id, incarnation_id, status, cache) = let (worker_id, incarnation_id, status, cache) =
(&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache); (&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache);
let unsealed = Mutex::new(Vec::new());
let outcome = { let outcome = {
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
// never held across a bus round trip taken by anything else. // never held across a bus round trip taken by anything else.
@ -988,7 +918,6 @@ async fn execute<E: WorkerEndpoint>(
client: &shell.client, client: &shell.client,
incoming: &incoming, incoming: &incoming,
writers: &shell.writers, writers: &shell.writers,
unsealed: &unsealed,
}; };
if matches!(incoming, Incoming::Bus(_)) && long_method(&method) && blocking_allowed() { 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 // A long bus request's handler runs with this worker thread handed over to blocking
@ -1050,88 +979,22 @@ async fn execute<E: WorkerEndpoint>(
} }
let cache_span = crate::profile::span("shell.record.cache"); let cache_span = crate::profile::span("shell.record.cache");
let cached = CachedReply::with_artifacts(outcome.clone(), holds); let cached = CachedReply::with_artifacts(outcome.clone(), holds);
let unsealed = std::mem::take(&mut *unsealed.lock().expect("never poisoned"));
// The cache records the reply before it is sent, so a duplicate never re-executes;
// but until the reply that seals this handler's artifacts is admitted they are
// still writers, and a replay attaching one would seal it into the duplicate's
// reply (or be refused) and refuse the original (BUS-02 review N2). So a sealing
// reply is sent with the cache held: a duplicate waits for it in admission and
// replays sealed handles, or the failure below. A reply that seals nothing (the
// lane's, or a handler's without artifacts of its own) holds nothing.
let mut held = Some(cache.lock().await);
{ {
let c = held.as_mut().expect("just taken"); let mut c = cache.lock().await;
match class { match class {
OpClass::StepMutation => { OpClass::StepMutation => c.record(key, serial, body, cached),
c.record(key.clone(), serial.clone(), body.clone(), cached) OpClass::Lifecycle => c.record_lifecycle(serial, body, cached),
} OpClass::ReadOnly => c.record_readonly(serial, 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()); status.set_completed(request.request_id.clone());
if unsealed.is_empty() {
held = None;
}
drop(cache_span); drop(cache_span);
#[cfg(test)]
sealing_tests::gate(worker_id).await;
let reply_span = crate::profile::span("shell.reply"); let reply_span = crate::profile::span("shell.reply");
let sent = answer.send(outcome, &reply.artifacts, unsealed).await; answer.send(outcome, &reply.artifacts).await;
drop(reply_span); drop(reply_span);
let recycled = match sent { // The next step's writers, allocated while the caller goes on (bus requests only:
Sent::Done(recycled) => { // the lane seals nothing into the store).
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(_)) { if matches!(incoming, Incoming::Bus(_)) {
shell.writers.give(recycled);
shell.writers.refill(&shell.client); shell.writers.refill(&shell.client);
} }
} }
@ -1164,7 +1027,7 @@ answering BACKEND_FAILURE",
request.scope.clone(), request.scope.clone(),
e, e,
); );
answer.send(outcome, &[], Vec::new()).await; answer.send(outcome, &[]).await;
} }
} }
} }
@ -1338,7 +1201,3 @@ async fn acknowledge(
let result = AcknowledgeResult { acknowledged }; let result = AcknowledgeResult { acknowledged };
Ok(object(result.to_json())) Ok(object(result.to_json()))
} }
#[cfg(test)]
#[path = "worker_sealing_tests.rs"]
mod sealing_tests;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -21,9 +21,6 @@ use crate::version::version_for;
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
pub mod 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. /// Version of the default configuration; kept verbatim so existing checkpoints stay loadable.
pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2"; pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2";
@ -60,64 +57,6 @@ pub struct Stimulation {
pub drive: f64, 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)] #[derive(Debug, Clone, PartialEq)]
pub struct LifConfig { pub struct LifConfig {
/// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`. /// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`.
@ -336,12 +275,7 @@ pub struct LifNetwork {
/// Version string of this configuration; pin it in checkpoints. /// Version string of this configuration; pin it in checkpoints.
pub version: String, pub version: String,
pub plasticity: RewardModulatedStdp, 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>, pub membrane: Vec<f32>,
/// Refractory counters; stale on the same terms as `membrane`.
pub refractory: Vec<u8>, pub refractory: Vec<u8>,
pub baseline: Vec<f32>, pub baseline: Vec<f32>,
pub last_spike_ms: Vec<f64>, pub last_spike_ms: Vec<f64>,
@ -377,8 +311,6 @@ pub struct LifNetwork {
visual_drive: Vec<f32>, visual_drive: Vec<f32>,
reward_remaining: f64, reward_remaining: f64,
sweep: SweepPlan, 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`]. /// When set, [`LifNetwork::step`] runs steps 1-4 and 6 on the GPU; see [`cuda`].
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
cuda: Option<Box<cuda::CudaLif>>, cuda: Option<Box<cuda::CudaLif>>,
@ -491,7 +423,6 @@ impl LifNetwork {
timings: PhaseTimings::default(), timings: PhaseTimings::default(),
data, data,
sweep: SweepPlan::sequential(), sweep: SweepPlan::sequential(),
backend_fault: None,
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
cuda: None, cuda: None,
}) })
@ -504,87 +435,18 @@ impl LifNetwork {
/// Choose how the per-tick parallel phases are partitioned. Results do not depend on this. /// Choose how the per-tick parallel phases are partitioned. Results do not depend on this.
pub fn set_sweep_plan(&mut self, sweep: SweepPlan) { 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(); let threads = sweep.threads();
self.target_shards = target_shards(&self.data, threads); self.target_shards = target_shards(&self.data, threads);
self.slot_shards = self.plasticity.slot_shards(threads); self.slot_shards = self.plasticity.slot_shards(threads);
self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data); self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data);
self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect(); self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect();
self.sweep = sweep; 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
/// Run the tick on `backend` from now on. Results do not depend on this. // 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.
/// [`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")] #[cfg(feature = "cuda")]
if self.cuda.is_some() { self.attach_cuda_if_requested();
self.sync_host()?;
self.cuda = None;
}
Ok(())
}
#[cfg(feature = "cuda")]
LifBackend::Cuda { device } => self.attach_device_owned(device),
#[cfg(not(feature = "cuda"))]
LifBackend::Cuda { device } => bail!(
"the CUDA LIF backend (device {device}) was requested, but this build has no \
`cuda` feature"
),
}
}
/// The backend the tick runs on now.
pub fn backend(&self) -> LifBackend {
#[cfg(feature = "cuda")]
if let Some(backend) = self.cuda.as_deref() {
return LifBackend::Cuda {
device: backend.ordinal(),
};
}
LifBackend::Cpu
}
/// Why the GPU backend detached itself during a step, once; `None` if it never did.
pub fn take_backend_fault(&mut self) -> Option<String> {
self.backend_fault.take()
}
/// Whether the host's `membrane` and `refractory` are current. Always true on the CPU.
pub fn host_state_current(&self) -> bool {
#[cfg(feature = "cuda")]
if let Some(backend) = self.cuda.as_deref() {
return !backend.host_stale();
}
true
}
/// Bring the host's `membrane` and `refractory` up to date with the device: a no-op on the
/// CPU or when they already are. The session calls it before a capture, so the full state
/// crosses PCIe only at checkpoints.
pub fn sync_host(&mut self) -> Result<()> {
#[cfg(feature = "cuda")]
return self.sync_host_from_cuda();
#[cfg(not(feature = "cuda"))]
Ok(())
} }
pub fn sweep_plan(&self) -> &SweepPlan { pub fn sweep_plan(&self) -> &SweepPlan {
@ -646,10 +508,11 @@ impl LifNetwork {
self.stimulate(duration_ms); 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 /// 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 /// [`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 /// sweep's order. `None` while the GPU backend runs the ticks, whose host copy of the list is
/// not kept per tick ([`LifNetwork::step_frame`] gathers the lists either way). A read-only view; it changes nothing a tick computes. /// not kept per tick. A read-only view; it changes nothing a tick computes.
pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> { pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> {
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
if self.cuda.is_some() { if self.cuda.is_some() {
@ -658,18 +521,12 @@ impl LifNetwork {
self.spikes.get(..count) 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 { pub fn step(&mut self, milliseconds: u64) -> u64 {
// The GPU backend runs the same ticks in batches and replays the host-side phases; with the // The GPU backend runs the same ticks in batches and replays the host-side phases; with the
// feature off this compiles to nothing and the loop below is the whole method. // feature off this compiles to nothing and the loop below is the whole method.
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
if self.cuda.is_some() { if self.cuda.is_some() {
return self return self.step_on_cuda(milliseconds);
.step_on_cuda(milliseconds, None)
.unwrap_or_else(|error| panic!("CUDA LIF batch failed: {error}"));
} }
let mut total = 0u64; let mut total = 0u64;
for _ in 0..milliseconds { for _ in 0..milliseconds {
@ -678,59 +535,6 @@ impl LifNetwork {
total 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 { fn step_one(&mut self) -> usize {
let neurons = self.data.meta.neurons; let neurons = self.data.meta.neurons;
let threshold = self.config.threshold; let threshold = self.config.threshold;
@ -993,15 +797,10 @@ impl LifNetwork {
total 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 { pub fn export_state(&self) -> LifState {
let (membrane, refractory) = self.current_arrays();
LifState { LifState {
membrane, membrane: self.membrane.clone(),
refractory, refractory: self.refractory.clone(),
last_spike_ms: self.last_spike_ms.clone(), last_spike_ms: self.last_spike_ms.clone(),
visual_drive: self.visual_drive.clone(), visual_drive: self.visual_drive.clone(),
rng: self.rng.state(), rng: self.rng.state(),
@ -1013,18 +812,6 @@ impl LifNetwork {
} }
} }
/// Copies of `membrane` and `refractory` as they are now: the host's, or the device's while
/// the host's are stale.
fn current_arrays(&self) -> (Vec<f32>, Vec<u8>) {
#[cfg(feature = "cuda")]
if let Some(downloaded) = self.stale_device_state() {
return downloaded.unwrap_or_else(|error| {
panic!("the device state cannot be read back for export: {error}")
});
}
(self.membrane.clone(), self.refractory.clone())
}
/// Import plasticity first, then validate before writing anything. /// Import plasticity first, then validate before writing anything.
pub fn import_state(&mut self, state: &LifState) -> Result<()> { pub fn import_state(&mut self, state: &LifState) -> Result<()> {
if state.membrane.len() != self.membrane.len() if state.membrane.len() != self.membrane.len()

View file

@ -38,19 +38,10 @@
//! # State ownership //! # State ownership
//! //!
//! Between batches the device owns `membrane` and `refractory`. With //! Between batches the device owns `membrane` and `refractory`. With
//! [`CudaLif::sync_host_each_batch`] set (the default for a backend built with [`CudaLif::new`]) //! [`CudaLif::sync_host_each_batch`] set (the default) they are copied back at the end of every
//! they are copied back at the end of every batch, which keeps direct reads of the network's host //! batch, which keeps `export_state`, the status endpoints and every existing test correct with no
//! arrays correct with no further changes: that is what `examples/cuda_exact`'s per-tick mode and //! further changes. Clear it for throughput work and call [`CudaLif::sync_to_host`] explicitly
//! the `FLY_LIF_CUDA=1` golden-suite hook rely on. //! before a checkpoint.
//!
//! 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; use std::sync::Arc;
@ -64,88 +55,6 @@ use crate::error::{Error, Result};
use super::LifNetwork; 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 /// 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. /// `LIF_BLOCK` in `cuda/lif.cu`, because the spike bitset words are per-warp ballots.
const BLOCK: u32 = 256; const BLOCK: u32 = 256;
@ -180,12 +89,6 @@ const DEFAULT_MAX_TICKS: usize = 32;
/// neither the build nor the run needs a CUDA toolkit. /// neither the build nor the run needs a CUDA toolkit.
const LIF_PTX: &str = include_str!("../../cuda/lif.ptx"); 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 { fn driver_error(what: &str, error: impl std::fmt::Display) -> Error {
Error::new(format!("CUDA {what} failed: {error}")) Error::new(format!("CUDA {what} failed: {error}"))
} }
@ -246,7 +149,6 @@ pub struct CudaLif {
bucket_rebase_kernel: CudaFunction, bucket_rebase_kernel: CudaFunction,
bucket_apply_kernel: CudaFunction, bucket_apply_kernel: CudaFunction,
ordinal: usize,
neurons: usize, neurons: usize,
blocks: u32, blocks: u32,
max_ticks: usize, max_ticks: usize,
@ -299,14 +201,7 @@ pub struct CudaLif {
host_tick_counts: Vec<u32>, host_tick_counts: Vec<u32>,
host_spikes: Vec<u32>, host_spikes: Vec<u32>,
stimulation_schedule: Vec<bool>, stimulation_schedule: Vec<bool>,
/// The host arrays were overwritten (an import); upload them before the next batch.
host_dirty: bool, 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 /// 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. /// of the crate sees the same host state it would have seen from the CPU kernel.
@ -344,7 +239,6 @@ impl CudaLif {
} }
pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result<Self> { pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result<Self> {
inject::attach()?;
let max_ticks = max_ticks.max(1); let max_ticks = max_ticks.max(1);
let neurons = network.data.meta.neurons; let neurons = network.data.meta.neurons;
if neurons == 0 { if neurons == 0 {
@ -495,7 +389,6 @@ impl CudaLif {
bucket_rebase_kernel: function("lif_bucket_rebase")?, bucket_rebase_kernel: function("lif_bucket_rebase")?,
bucket_apply_kernel: function("lif_bucket_apply")?, bucket_apply_kernel: function("lif_bucket_apply")?,
ordinal,
neurons, neurons,
blocks, blocks,
max_ticks, max_ticks,
@ -510,9 +403,6 @@ impl CudaLif {
host_spikes: Vec::new(), host_spikes: Vec::new(),
stimulation_schedule: vec![false; max_ticks], stimulation_schedule: vec![false; max_ticks],
host_dirty: false, host_dirty: false,
host_stale: false,
uploaded_bytes: 0,
downloaded_bytes: 0,
batch_start: context batch_start: context
.new_event(Some(CUevent_flags::CU_EVENT_DEFAULT)) .new_event(Some(CUevent_flags::CU_EVENT_DEFAULT))
.map_err(|error| driver_error("event creation", error))?, .map_err(|error| driver_error("event creation", error))?,
@ -539,33 +429,19 @@ impl CudaLif {
Ok(backend) Ok(backend)
} }
/// The device ordinal this backend runs on.
pub fn ordinal(&self) -> usize {
self.ordinal
}
/// Ticks this backend accepts per call. /// Ticks this backend accepts per call.
pub fn max_ticks(&self) -> usize { pub fn max_ticks(&self) -> usize {
self.max_ticks self.max_ticks
} }
/// The host copies of `membrane` and `refractory` have been written; re-upload them before the /// The host copies of `membrane` and `refractory` have been written; re-upload them before the
/// next batch. Called by [`LifNetwork::import_state`], which overwrites both arrays whole, so /// next batch. Called by [`LifNetwork::import_state`].
/// the host is the current copy again.
pub fn mark_host_dirty(&mut self) { pub fn mark_host_dirty(&mut self) {
self.host_dirty = true; 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. /// Copy `membrane` and `refractory` from the device into the network's host arrays.
pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> { pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> {
inject::sync()?;
self.stream self.stream
.memcpy_dtoh(&self.membrane, &mut network.membrane[..]) .memcpy_dtoh(&self.membrane, &mut network.membrane[..])
.map_err(|error| driver_error("membrane download", error))?; .map_err(|error| driver_error("membrane download", error))?;
@ -574,28 +450,7 @@ impl CudaLif {
.map_err(|error| driver_error("refractory download", error))?; .map_err(|error| driver_error("refractory download", error))?;
self.stream self.stream
.synchronize() .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<()> { fn upload_state(&mut self, network: &LifNetwork) -> Result<()> {
@ -605,61 +460,12 @@ impl CudaLif {
self.stream self.stream
.memcpy_htod(&network.refractory[..], &mut self.refractory) .memcpy_htod(&network.refractory[..], &mut self.refractory)
.map_err(|error| driver_error("refractory upload", error))?; .map_err(|error| driver_error("refractory upload", error))?;
self.uploaded_bytes += (self.neurons * 5) as u64;
self.host_dirty = false; self.host_dirty = false;
Ok(()) Ok(())
} }
/// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce, /// 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. fn run_batch(&mut self, network: &mut LifNetwork, ticks: usize) -> Result<usize> {
///
/// 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); debug_assert!(ticks <= self.max_ticks);
let neurons = self.neurons; let neurons = self.neurons;
@ -702,9 +508,7 @@ impl CudaLif {
// Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted // Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted
// into the transposed array's rank order. // into the transposed array's rank order.
let used = ticks * self.noise_kicks; let used = ticks * self.noise_kicks;
let mut uploaded = 0usize;
if used > 0 { if used > 0 {
uploaded += used * 8;
let mut view = self.noise_neuron.slice_mut(0..used); let mut view = self.noise_neuron.slice_mut(0..used);
self.stream self.stream
.memcpy_htod(&self.host_noise_neuron[..used], &mut view) .memcpy_htod(&self.host_noise_neuron[..used], &mut view)
@ -715,14 +519,12 @@ impl CudaLif {
.map_err(|error| driver_error("noise upload", error))?; .map_err(|error| driver_error("noise upload", error))?;
} }
if !network.visual_drive.is_empty() { 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()); let mut view = self.visual_drive.slice_mut(0..network.visual_drive.len());
self.stream self.stream
.memcpy_htod(&network.visual_drive[..], &mut view) .memcpy_htod(&network.visual_drive[..], &mut view)
.map_err(|error| driver_error("visual drive upload", error))?; .map_err(|error| driver_error("visual drive upload", error))?;
} }
if !network.plasticity.gains.is_empty() { if !network.plasticity.gains.is_empty() {
uploaded += network.plasticity.gains.len() * 4;
let mut view = self.gains.slice_mut(0..network.plasticity.gains.len()); let mut view = self.gains.slice_mut(0..network.plasticity.gains.len());
self.stream self.stream
.memcpy_htod(&network.plasticity.gains[..], &mut view) .memcpy_htod(&network.plasticity.gains[..], &mut view)
@ -744,7 +546,6 @@ impl CudaLif {
self.stream self.stream
.synchronize() .synchronize()
.map_err(|error| driver_error("synchronize", error))?; .map_err(|error| driver_error("synchronize", error))?;
inject::batch()?;
self.kernel_ms += f64::from( self.kernel_ms += f64::from(
self.batch_start self.batch_start
.elapsed_ms(&self.batch_end) .elapsed_ms(&self.batch_end)
@ -782,9 +583,22 @@ impl CudaLif {
self.stream self.stream
.synchronize() .synchronize()
.map_err(|error| driver_error("synchronize", error))?; .map_err(|error| driver_error("synchronize", error))?;
self.uploaded_bytes += uploaded as u64;
self.downloaded_bytes += ((ticks + total) * 4) as u64; // The host phases, per tick, in the sequential kernel's order.
Ok(total) let mut at = 0usize;
let mut spikes = 0usize;
for tick in 0..ticks {
let count = self.host_tick_counts[tick] as usize;
network.spikes[..count].copy_from_slice(&self.host_spikes[at..at + count]);
at += count;
spikes += count;
network.replay_host_phases(count);
}
if self.sync_host_each_batch {
self.sync_to_host(network)?;
}
Ok(spikes)
} }
/// Record phase mark `index` when phase profiling is on. /// Record phase mark `index` when phase profiling is on.
@ -1025,110 +839,37 @@ impl LifNetwork {
/// Attach a backend when `FLY_LIF_CUDA=1`, on device `FLY_LIF_CUDA_DEVICE` (default 0). /// 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 /// 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. /// and silently got the CPU would report a bit-exactness pass that means nothing.
pub(super) fn attach_cuda_if_requested(&mut self) { pub(super) fn attach_cuda_if_requested(&mut self) {
if self.cuda.is_some() { if self.cuda.is_some() || std::env::var("FLY_LIF_CUDA").as_deref() != Ok("1") {
return; return;
} }
let Ok(super::LifBackend::Cuda { device }) = super::LifBackend::from_env() else { let ordinal = std::env::var("FLY_LIF_CUDA_DEVICE")
return; .ok()
}; .and_then(|value| value.parse::<usize>().ok())
match CudaLif::new(self, device) { .unwrap_or(0);
match CudaLif::new(self, ordinal) {
Ok(backend) => self.attach_cuda(backend), Ok(backend) => self.attach_cuda(backend),
Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"), Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"),
} }
} }
/// Attach a device-owned backend on `device`, or switch an attached one to device-owned state. /// The batched GPU path behind [`LifNetwork::step`].
pub(super) fn attach_device_owned(&mut self, device: usize) -> Result<()> { pub(super) fn step_on_cuda(&mut self, milliseconds: u64) -> u64 {
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 backend = self.cuda.take().expect("a CUDA backend is attached");
let mut total = 0u64; let mut total = 0u64;
let mut left = milliseconds; let mut left = milliseconds;
while left > 0 { while left > 0 {
let ticks = left.min(backend.max_ticks() as u64) as usize; let ticks = left.min(backend.max_ticks() as u64) as usize;
let host_current = !backend.host_stale(); match backend.run_batch(self, ticks) {
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, Ok(spikes) => total += spikes as u64,
Err(failure) => { Err(error) => panic!("CUDA LIF batch failed: {error}"),
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; left -= ticks as u64;
} }
self.cuda = Some(backend); self.cuda = Some(backend);
Ok(total) total
} }
/// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike /// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike

View file

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

View file

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

View file

@ -1,6 +1,6 @@
//! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons //! `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 //! that tick stamped in `last_spike_ms`, so the union of the lists over a window is the window
//! bitset a scan of `last_spike_ms` gives. GPU-02: `step_frame` gathers the same union in one call. //! bitset a scan of `last_spike_ms` gives.
mod common; mod common;
@ -52,107 +52,3 @@ fn a_ticks_list_is_the_neurons_it_stamped_and_windows_agree_with_the_scan() {
} }
assert!(spiking_ticks > 0, "the fixture must spike for the test to mean anything"); 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,8 +11,7 @@ description = "A small local RPC and pub/sub bus with immutable file-backed arti
# `flock`, `posix_fallocate` and `O_NOFOLLOW`; everything else is std or Tokio. # `flock`, `posix_fallocate` and `O_NOFOLLOW`; everything else is std or Tokio.
libc = "0.2" libc = "0.2"
serde = { workspace = true } serde = { workspace = true }
# `raw_value`: the router forwards payloads it validated as pre-encoded JSON (BUS-02). serde_json = { workspace = true }
serde_json = { workspace = true, features = ["raw_value"] }
sha2 = { workspace = true } sha2 = { workspace = true }
tokio = { version = "1", features = ["rt", "net", "io-util", "sync", "time", "macros"] } tokio = { version = "1", features = ["rt", "net", "io-util", "sync", "time", "macros"] }

View file

@ -186,16 +186,6 @@ let kept = frame.retain().await?; // an independent explicit hold
- Sealing copies staging into a fresh read-only (0444) file and unlinks staging. A descriptor - 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 the producer kept or duplicated afterwards writes only to the unlinked staging inode. Sealing
therefore needs quota for both copies while it runs. 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 ### Errors
@ -342,13 +332,6 @@ before admission are `not-dispatched`. A command in flight when the connection i
`rpc.request`, `rpc.result` or `topic.message` delivery carries `readLocation`, the location `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 `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. 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 ## Limitations
@ -386,8 +369,6 @@ before admission are `not-dispatched`. A command in flight when the connection i
cargo test -p flybus # unit + integration cargo test -p flybus # unit + integration
cargo test --release -p flybus --test perf -- --ignored --nocapture # the measurement above 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 -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 Every integration test runs twice, once over the in-memory transport and once over a Unix
@ -410,15 +391,6 @@ socket, through the same router code:
fan-out and collected after the last consumer; extracted artifacts and holds; atomic fan-out and collected after the last consumer; extracted artifacts and holds; atomic
admission; release watermarks; connection-scoped owners; abandoned futures; disconnects; and admission; release watermarks; connection-scoped owners; abandoned futures; disconnects; and
router restarts. 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 - `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. 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 - `tests/bus_acceptance.rs`: the implementation guide's BUS-01/02/03 acceptance bullets that the

View file

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

View file

@ -12,9 +12,9 @@ use std::sync::Arc;
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand, WriterGrant}; use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand};
use crate::error::{BusError, Dispatch, ErrorCode}; use crate::error::{BusError, Dispatch, ErrorCode};
use crate::store::{open_read, open_write, resolve}; use crate::store::{open_read, resolve};
use crate::wire::{ArtifactRef, Attachment, Fields, GENERATION, Identity, Location}; use crate::wire::{ArtifactRef, Attachment, Fields, GENERATION, Identity, Location};
pub(crate) struct OwnerGuard { pub(crate) struct OwnerGuard {
@ -238,7 +238,7 @@ impl Artifact {
"read location names another store", "read location names another store",
)); ));
} }
let path = resolve(&shared.store_root, &loc.store_id, &loc, &shared.dirs)?; let path = resolve(&shared.store_root, &loc.store_id, &loc)?;
let file = open_read(&path) let file = open_read(&path)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("open: {e}")))?; .map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("open: {e}")))?;
let len = file let len = file
@ -363,8 +363,6 @@ pub struct ArtifactWriter {
pub(crate) artifact_id: String, pub(crate) artifact_id: String,
pub(crate) byte_length: u64, pub(crate) byte_length: u64,
pub(crate) written: u64, pub(crate) written: u64,
pub(crate) store_id: String,
pub(crate) content_type: String,
} }
impl ArtifactWriter { impl ArtifactWriter {
@ -376,44 +374,8 @@ impl ArtifactWriter {
self.byte_length self.byte_length
} }
/// Bytes written so far: what a sealing send seals ([`Responder::reply_sealing`]). /// Closes the writable handle and seals, returning the immutable artifact on an explicit
pub fn written(&self) -> u64 { /// hold. Bytes not written read as zeros: the staging file is preallocated.
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> { pub async fn seal(self) -> Result<Artifact, BusError> {
self.seal_with_digest(None).await self.seal_with_digest(None).await
} }
@ -577,30 +539,6 @@ impl Request {
} }
} }
/// A writer's artifact waiting for the send that seals it ([`ArtifactWriter::into_unsealed`]).
pub struct Unsealed {
artifact: Artifact,
capacity: u64,
content_type: String,
}
impl Unsealed {
/// The handle the sealed artifact will have; attach it to the sealing send.
pub fn artifact(&self) -> &Artifact {
&self.artifact
}
}
/// What a sealing reply ([`Responder::reply_sealing`]) produced.
pub struct SealedReply {
/// As [`Responder::reply`]: routed to the caller, or the caller had detached.
pub routed: bool,
/// With `recycle`, a fresh writer of the same allocation for each artifact sealed. Its
/// staging file is the sealed artifact's, zero-filled: it reads as zeros, as a new
/// allocation does.
pub writers: Vec<ArtifactWriter>,
}
/// Replies to one request, whether or not the request delivery is still held. /// Replies to one request, whether or not the request delivery is still held.
#[derive(Clone)] #[derive(Clone)]
pub struct Responder { pub struct Responder {
@ -629,100 +567,18 @@ impl Responder {
.shared .shared
.command("rpc.reply", body, atts, keep, Hook::None) .command("rpc.reply", body, atts, keep, Hook::None)
.await?; .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")?) 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(crate) struct ReplyGuard {
pub conn: Arc<ClientConn>, pub conn: Arc<ClientConn>,
pub call_id: String, pub call_id: String,
pub request_delivery_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 { impl Drop for ReplyGuard {
fn drop(&mut self) { fn drop(&mut self) {
if self.replied.load(std::sync::atomic::Ordering::Acquire) {
return;
}
self.conn.shared.push_control(Control::ResponderReleased { self.conn.shared.push_control(Control::ResponderReleased {
call_id: self.call_id.clone(), call_id: self.call_id.clone(),
request_delivery_id: self.request_delivery_id.clone(), request_delivery_id: self.request_delivery_id.clone(),

View file

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

View file

@ -44,17 +44,6 @@ pub(crate) enum Extra {
Service(ServiceGuard, mpsc::UnboundedReceiver<Request>), Service(ServiceGuard, mpsc::UnboundedReceiver<Request>),
Subscription(SubscriptionGuard, mpsc::UnboundedReceiver<Message>), Subscription(SubscriptionGuard, mpsc::UnboundedReceiver<Message>),
Call(CallGuard), 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 /// What the reactor does with a reply before handing it over. Handles are built here, inside
@ -68,8 +57,6 @@ pub(crate) enum Hook {
Subscribe, Subscribe,
Call(String), Call(String),
Cancel(String), Cancel(String),
/// `value.writers`, when present, are new writers (a recycling sealing send).
Writers,
} }
pub(crate) struct OutCommand { pub(crate) struct OutCommand {
@ -127,8 +114,6 @@ pub(crate) struct ClientState {
pub(crate) struct Shared { pub(crate) struct Shared {
pub info: SessionInfo, pub info: SessionInfo,
pub store_root: PathBuf, pub store_root: PathBuf,
/// The store directories this connection resolved (BUS-02 review N6: per connection).
pub dirs: crate::store::DirCache,
state: Mutex<ClientState>, state: Mutex<ClientState>,
wake: Notify, wake: Notify,
control_capacity: usize, control_capacity: usize,
@ -159,7 +144,6 @@ impl Shared {
Shared { Shared {
info, info,
store_root, store_root,
dirs: crate::store::DirCache::default(),
state: Mutex::new(ClientState { state: Mutex::new(ClientState {
closed: None, closed: None,
shutting_down: false, shutting_down: false,
@ -461,7 +445,6 @@ pub(crate) async fn write_loop(shared: Arc<Shared>, mut wr: WriteHalf<Transport>
_ = shutdown.wait_for(|v| *v) => break, _ = shutdown.wait_for(|v| *v) => break,
} }
} }
Next::Exit => break, Next::Exit => break,
} }
} }
@ -631,11 +614,9 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
)); ));
} }
serial_field(&mut f, "serviceIncarnation", "svc")?; serial_field(&mut f, "serviceIncarnation", "svc")?;
validate_writers(&mut f)?;
} }
"rpc.reply" => { "rpc.reply" => {
f.boolean("routed")?; f.boolean("routed")?;
validate_writers(&mut f)?;
} }
"rpc.responder.release" => { "rpc.responder.release" => {
f.boolean("released")?; f.boolean("released")?;
@ -665,7 +646,6 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
f.u64_string("topicSequence")?; f.u64_string("topicSequence")?;
f.u64_string("subscribers")?; f.u64_string("subscribers")?;
f.u64_string("replaced")?; f.u64_string("replaced")?;
validate_writers(&mut f)?;
} }
"delivery.consumed" | "artifact.release" => { "delivery.consumed" | "artifact.release" => {
f.u64_string("released")?; f.u64_string("released")?;
@ -693,29 +673,6 @@ fn validate_reply_value(op: &str, value: &Map<String, Value>) -> Result<(), Wire
f.finish() 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>> { fn owner_guard(conn: &Weak<ClientConn>, id: String, delivery: bool) -> Option<Arc<OwnerGuard>> {
Some(Arc::new(OwnerGuard { Some(Arc::new(OwnerGuard {
id, id,
@ -747,36 +704,6 @@ fn complete(
value, value,
extra: Extra::None, 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)) => { (Hook::Owner, Ok(value)) => {
let id = Fields::of(&value, "reply").id("ownerId")?; let id = Fields::of(&value, "reply").id("ownerId")?;
match owner_guard(conn, id, false) { match owner_guard(conn, id, false) {
@ -899,22 +826,12 @@ fn u64_field(f: &mut Fields<'_>, key: &'static str) -> Result<u64, WireError> {
parse_u64(s).ok_or_else(|| WireError(format!("{key} is not a U64"))) 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( fn on_delivery(
shared: &Arc<Shared>, shared: &Arc<Shared>,
conn: &Weak<ClientConn>, conn: &Weak<ClientConn>,
mut env: Envelope, env: Envelope,
) -> Result<(), WireError> { ) -> Result<(), WireError> {
let mut body = std::mem::take(&mut env.body); let mut f = Fields::of(&env.body, "delivery");
let mut f = Fields::of(&body, "delivery");
let delivery_id = f.id("deliveryId")?; let delivery_id = f.id("deliveryId")?;
let delivery_serial = parse_serial_id("dlv", &delivery_id) let delivery_serial = parse_serial_id("dlv", &delivery_id)
.filter(|n| *n > 0) .filter(|n| *n > 0)
@ -937,16 +854,14 @@ fn on_delivery(
return Err(WireError("service incarnation is not svc-<U64>".into())); return Err(WireError("service incarnation is not svc-<U64>".into()));
} }
let method = f.method("method")?; let method = f.method("method")?;
f.object("payload")?; let payload = f.object("payload")?.clone();
f.finish()?; f.finish()?;
let payload = take_object(&mut body, "payload");
accept_delivery_serial(shared, delivery_serial)?; accept_delivery_serial(shared, delivery_serial)?;
let req = Request { let req = Request {
reply_guard: Arc::new(ReplyGuard { reply_guard: Arc::new(ReplyGuard {
conn: guard.conn.clone(), conn: guard.conn.clone(),
call_id: call_id.clone(), call_id: call_id.clone(),
request_delivery_id: delivery_id.clone(), request_delivery_id: delivery_id.clone(),
replied: std::sync::atomic::AtomicBool::new(false),
}), }),
guard, guard,
call_id, call_id,
@ -976,9 +891,8 @@ fn on_delivery(
if parse_serial_id("svc", &service_incarnation).is_none() { if parse_serial_id("svc", &service_incarnation).is_none() {
return Err(WireError("service incarnation is not svc-<U64>".into())); return Err(WireError("service incarnation is not svc-<U64>".into()));
} }
f.object("outcome")?; let outcome = f.object("outcome")?.clone();
f.finish()?; f.finish()?;
let outcome = take_object(&mut body, "outcome");
accept_delivery_serial(shared, delivery_serial)?; accept_delivery_serial(shared, delivery_serial)?;
let res = RpcResult { let res = RpcResult {
guard, guard,
@ -1009,9 +923,8 @@ fn on_delivery(
} }
let topic_sequence = u64_field(&mut f, "topicSequence")?; let topic_sequence = u64_field(&mut f, "topicSequence")?;
let replaced = u64_field(&mut f, "replaced")?; let replaced = u64_field(&mut f, "replaced")?;
f.object("payload")?; let payload = f.object("payload")?.clone();
f.finish()?; f.finish()?;
let payload = take_object(&mut body, "payload");
accept_delivery_serial(shared, delivery_serial)?; accept_delivery_serial(shared, delivery_serial)?;
let msg = Message { let msg = Message {
guard, guard,
@ -1098,37 +1011,3 @@ fn on_notice(shared: &Arc<Shared>, env: Envelope) -> Result<(), WireError> {
} }
Ok(()) 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::{ pub use client::{
Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message, Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message,
Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, SealedReply, Service, Unsealed, Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service,
ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo, ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo,
}; };
pub use error::{BusError, Dispatch, ErrorCode}; pub use error::{BusError, Dispatch, ErrorCode};

View file

@ -331,64 +331,6 @@ async fn read_loop<R: AsyncRead + Unpin>(
}; };
inner.with_state(|s| s.finish_allocate(job, created)); 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 => { 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 // 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 // waits for it as it waits for any command (BUS-01). The outcome is the

View file

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

View file

@ -108,37 +108,27 @@ impl Store {
.mode(0o600) .mode(0o600)
.custom_flags(libc::O_NOFOLLOW) .custom_flags(libc::O_NOFOLLOW)
.open(&path)?; .open(&path)?;
let result = reserve(&file, len); let reserve = || -> io::Result<()> {
if len == 0 {
return Ok(());
}
let off_len = libc::off_t::try_from(len)
.map_err(|_| io::Error::other("length overflows off_t"))?;
// SAFETY: posix_fallocate on a valid descriptor opened for writing.
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, off_len) };
match rc {
0 => Ok(()),
libc::EOPNOTSUPP | libc::EINVAL => file.set_len(len),
e => Err(io::Error::from_raw_os_error(e)),
}
};
let result = reserve();
if result.is_err() { if result.is_err() {
let _ = fs::remove_file(&path); let _ = fs::remove_file(&path);
} }
result 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, /// 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 /// when given, the SHA-256. On failure the partial sealed file is removed; the staging file
/// is left for the caller either way. /// is left for the caller either way.
@ -169,36 +159,6 @@ impl Store {
result 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. /// Unlinks a store file; a missing file is not an error.
pub(crate) fn remove(&self, rel: &str) { pub(crate) fn remove(&self, rel: &str) {
let _ = fs::remove_file(self.path(rel)); let _ = fs::remove_file(self.path(rel));
@ -211,23 +171,6 @@ impl Drop for Store {
} }
} }
/// Reserves `len` bytes of `file` (zero-filled), so a full disk fails here and not in the
/// producer's write.
fn reserve(file: &File, len: u64) -> io::Result<()> {
if len == 0 {
return Ok(());
}
let off_len =
libc::off_t::try_from(len).map_err(|_| io::Error::other("length overflows off_t"))?;
// SAFETY: posix_fallocate on a valid descriptor opened for writing.
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, off_len) };
match rc {
0 => Ok(()),
libc::EOPNOTSUPP | libc::EINVAL => file.set_len(len),
e => Err(io::Error::from_raw_os_error(e)),
}
}
fn read_retry(r: &mut File, buf: &mut [u8]) -> io::Result<usize> { fn read_retry(r: &mut File, buf: &mut [u8]) -> io::Result<usize> {
loop { loop {
match r.read(buf) { match r.read(buf) {
@ -244,9 +187,7 @@ fn copy_exact(
digest: Option<&str>, digest: Option<&str>,
) -> Result<(), SealFailure> { ) -> Result<(), SealFailure> {
let mut hasher = digest.map(|_| Sha256::new()); let mut hasher = digest.map(|_| Sha256::new());
// Sized to the copy (BUS-02): a fixed 256 KiB buffer is a fresh mapping, and its page let mut buf = vec![0u8; 256 * 1024];
// 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; let mut remaining = len;
while remaining > 0 { while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize; let want = remaining.min(buf.len() as u64) as usize;
@ -279,68 +220,6 @@ fn copy_exact(
Ok(()) 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. /// Deletes store directories under `root` that carry the marker and whose lock is free.
/// Directories without the marker are never touched. /// Directories without the marker are never touched.
fn clean_orphans(root: &Path) -> io::Result<()> { fn clean_orphans(root: &Path) -> io::Result<()> {
@ -371,12 +250,7 @@ fn clean_orphans(root: &Path) -> io::Result<()> {
/// Resolves a location grant beneath `<root>/<store_id>`. Absolute paths, `..`, anything but /// 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. /// plain `[a-z0-9._-]` components, and symlinks that lead outside the store are refused.
pub(crate) fn resolve( pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result<PathBuf, BusError> {
root: &Path,
store_id: &str,
loc: &Location,
dirs: &DirCache,
) -> Result<PathBuf, BusError> {
if loc.store_id != store_id { if loc.store_id != store_id {
return Err(BusError::new( return Err(BusError::new(
ErrorCode::ArtifactGone, ErrorCode::ArtifactGone,
@ -406,66 +280,18 @@ pub(crate) fn resolve(
_ => return Err(refuse("parent, root or current-directory component")), _ => return Err(refuse("parent, root or current-directory component")),
} }
} }
// The directory part (`sealed`, `staging`) is resolved once per store directory and let base = root.join(&loc.store_id);
// connection, and cached ([`DirCache`], BUS-02): canonicalizing the whole path is a readlink per component, twice, on every open let base = base
// of every artifact. The file itself is then checked with one lstat: a symlink there is .canonicalize()
// 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}")))?; .map_err(|e| refuse(&format!("store directory: {e}")))?;
let parent = match dir { let full = base.join(rel).canonicalize().map_err(|e| match e.kind() {
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"), io::ErrorKind::NotFound => BusError::new(ErrorCode::ArtifactGone, "artifact file is gone"),
_ => refuse(&e.to_string()), _ => refuse(&e.to_string()),
})?, })?;
}; if !full.starts_with(&base) {
if !parent.starts_with(&base) {
return Err(refuse("escapes the store")); return Err(refuse("escapes the store"));
} }
let full = parent.join(file); Ok(full)
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> { pub(crate) fn open_read(path: &Path) -> io::Result<File> {
@ -501,7 +327,7 @@ mod tests {
fs::write(store.join("sealed/a-1"), b"ok").unwrap(); fs::write(store.join("sealed/a-1"), b"ok").unwrap();
fs::write(root.path().join("secret"), b"no").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(); std::os::unix::fs::symlink(root.path().join("secret"), store.join("sealed/a-2")).unwrap();
assert!(resolve(root.path(), "store-x", &loc("sealed/a-1"), &DirCache::default()).is_ok()); assert!(resolve(root.path(), "store-x", &loc("sealed/a-1")).is_ok());
for bad in [ for bad in [
"", "",
"/etc/passwd", "/etc/passwd",
@ -512,7 +338,7 @@ mod tests {
"sealed/a-2", "sealed/a-2",
] { ] {
assert!( assert!(
resolve(root.path(), "store-x", &loc(bad), &DirCache::default()).is_err(), resolve(root.path(), "store-x", &loc(bad)).is_err(),
"{bad:?}" "{bad:?}"
); );
} }
@ -521,7 +347,7 @@ mod tests {
relative_path: "sealed/a-1".into(), relative_path: "sealed/a-1".into(),
}; };
assert_eq!( assert_eq!(
resolve(root.path(), "store-x", &other, &DirCache::default()).unwrap_err().code, resolve(root.path(), "store-x", &other).unwrap_err().code,
ErrorCode::ArtifactGone ErrorCode::ArtifactGone
); );
} }

View file

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

View file

@ -86,6 +86,11 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) {
let store = a["writeLocation"]["storeId"].clone(); let store = a["writeLocation"]["storeId"].clone();
let reference = json!({"storeId": store, "artifactId": a["artifactId"], "generation": "1", "byteLength": "8", let reference = json!({"storeId": store, "artifactId": a["artifactId"], "generation": "1", "byteLength": "8",
"contentType": "application/octet-stream", "digest": null}); "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 let r = raw
.call( .call(
"artifact.open", "artifact.open",
@ -100,20 +105,7 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) {
) )
.await; .await;
assert_eq!(code(&r), "ARTIFACT_UNSEALED"); assert_eq!(code(&r), "ARTIFACT_UNSEALED");
// Since the 2026-10-02 amendment (bus-v1 section 12), a sending command that names its own assert_eq!(code(&raw.seal(&a, Value::Null).await), "OK");
// 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!( assert_eq!(
code(&raw.seal(&a, Value::Null).await), code(&raw.seal(&a, Value::Null).await),
"OWNER_INVALID", "OWNER_INVALID",

View file

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

View file

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