Merge port/bus-02 (reviewed: APPROVE-WITH-NOTES; N1-N7 fixed with tests, live speakers soaked): cheaper bus round trips (seal-on-reply, recycled zero-filled staging writers, encode once); session bus transport still off

This commit is contained in:
acamilo 2026-10-02 12:25:09 +00:00
commit e4d9d7c9ff
25 changed files with 2479 additions and 215 deletions

View file

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

View file

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

View file

@ -541,6 +541,51 @@ multiplayer and more flies follow. The topology, its rules and the shadow proced
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
hides.
### BUS-02 (port slice) — A cheaper bus transition
**2026-10-02: built** on `port/bus-02` off `port/bus-01`, awaiting review. Goal: make the
session-over-flybus transport cheap enough to carry the live fly (operator: run on the bus with
real sockets, because more consoles and more flies follow). The wire change is [bus-v1](bus-v1.md)
section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched.
- **Where a bus transition's time went** (a build box with the release CPU model and the release
cpuset's shape, router traffic counted per frame, cross-process timestamps per hop). About 35
commands a transition went through the router -- three calls and their replies, but also five
`artifact.seal`, six `artifact.allocate`, five `artifact.retain`, four `artifact.release`, six
`delivery.consumed` and three no-op `rpc.responder.release` -- and the router encoded every frame
twice and deep-copied every payload three or four times. The session's host CPU (the dispatcher's
CPU, which the router, the coordinator and the world share) was about 96% busy in every arm, so
bus cost was frame time almost one for one.
- **What changed.** Sealing sends (bus-v1 amendment: a reply seals the writers it attaches and
recycles their staging files as new writers, so a reply's media cost no seal or allocate round
trip); result attachments kept as delivered instead of retained; no responder release after an
admitted reply; the router encodes each frame once and forwards an admitted payload as bytes;
seal copies with `copy_file_range`; client location resolution cached; the session's writer pool
keyed by capacity (4 KiB buckets) so the variable-length feed status no longer misses it. About
14 commands a transition remain (three calls, three replies, consumes, cache releases).
- **Measured.** Before/after tables in the run report `claude-bus-02`. Unpaced, same rounds:
`bus/process` 17.1-17.2 ms a frame before, 14.9-15.8 after; paced at 1.0, the frame-work metric
17.4 before, 15.0 after (the lane 12.5, legacy 10.7). The bus still costs 2.5 to 3.5 ms a frame
more than the lane on that box, short of the 1.5 ms target, so the lane stays live. Also found:
BUS-01's numbers had the bus store on a disk-backed directory; on tmpfs (as the release, under
`/run`) its own binaries were 2.5 ms a frame faster.
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`) in `local`, `bus/thread` and `bus/process` (the FAFB parity suites, all arms).
- **Review notes (2026-10-02).** The review approved with notes; since the feed and the control
API already run over flybus in production, the router and SDK changes carry live traffic, so
every note was treated as live-path correctness. A recycled writer's staging file is zero-filled
when the router reissues it (about 10 us a 92,160-byte reply on tmpfs), so no artifact sealed from it -- by prefix or
whole -- carries the previous artifact's bytes (N3). A sealing reply is sent with the worker's
result cache held, so a duplicate replays the sealed artifacts rather than racing the reply
with an unsealed writer (N2). A refused sealing reply is answered as the handler's own seal
failure was before this slice (`BACKEND_FAILURE`, mutation applied), cached the same way, and
logged (N1). A failed staging rename leaves no file (N5). `recycle` without a sealing
attachment is refused even when false, a writer named by two attachments is refused, and the
SDK checks `writers` on every sealing send's reply (N4). The store-directory cache is per
connection (N6). Two test races are closed: the fly-edge stall test waits for the feed topic,
and SERVE-01's parity accepts a refused `/stimulate` drained one frame late (N7). The review's
adversarial lifecycle tests are in `flybus/tests/sealing_lifecycle.rs`.
### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no

View file

@ -342,6 +342,31 @@ async fn a_request_body_over_the_envelope_gets_directs_answer() {
assert_eq!(rig.bus.router.stats().artifacts, 0);
}
/// Request bodies that ride as artifacts, larger ones first (BUS-02 review N3): each artifact is
/// exactly its own body, never a tail of the one before -- a stale byte past a smaller body's end
/// would make it a different request (or not JSON), and its answer would differ from direct's.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_smaller_request_body_after_a_larger_one_is_exactly_its_own() {
let rig = rig(|_| {}).await;
for (size, fill) in [(300_000usize, 'a'), (120_000, 'b'), (70_000, 'c'), (66_000, 'd')] {
for uri in ["/chat", "/stimulate"] {
let text = fill.to_string().repeat(size);
let (method, uri, content_type, body) = json_case(
Method::POST,
uri,
json!({"by": "viewer", "source": "points", "text": text, "message": text}),
);
let direct = exchange(rig.direct(), &method, uri, content_type, &body).await;
let edge = exchange(rig.via_edge(), &method, uri, content_type, &body).await;
assert_eq!(direct, edge, "{uri} ({} bytes, {fill:?})", body.len());
}
}
assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0);
tokio::time::sleep(Duration::from_millis(200)).await;
let stats = rig.bus.router.stats();
assert_eq!((stats.artifacts, stats.store_bytes), (0, 0), "every request artifact released");
}
/// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's,
/// `date` aside, for a request of every kind.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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