flybus: deliveries carry read locations; small store I/O in place; no body copies

A delivery's attachments now name the read location their ownership
grants (bus-v1 section 12, amendment 2026-10-01; contractDigest changes),
so a delivered artifact is read without an artifact.open round trip. A
client attachment that carries one is refused as an unknown field.

SDK and router only, no wire change: staging allocation, seals and
read_all up to 256 KiB run in place instead of on the blocking pool;
Artifact::is_hold tells an explicit hold from a delivery's handle; an
envelope is encoded from borrowed parts and decoded without copying its
body.
This commit is contained in:
acamilo 2026-10-01 23:57:29 +00:00
parent 46e25ef3fc
commit 49f5496d2a
12 changed files with 346 additions and 51 deletions

View file

@ -105,7 +105,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` | | Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) | | The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies | `wire.rs::Location`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse | | Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) | | `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) | | Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
@ -189,7 +189,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) | | Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) | | A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) | | No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) | | Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` | | All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |

View file

@ -534,3 +534,30 @@ before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for par
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
the same date); section 8's ownership rules apply to every artifact a router stores, which these the same date); section 8's ownership rules apply to every artifact a router stores, which these
never are. never are.
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
a frame for an answer the router already knows when it delivers.
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
`artifact.open` would return for that artifact under that delivery's ownership. It is still
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
symlink checks, and never placed in an application body.
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
field, and the connection closes as for any malformed envelope.
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
client that prefers to ask.
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
that needs the bytes kept alive can keep a clone instead of taking a second hold.

View file

@ -174,7 +174,13 @@ let kept = frame.retain().await?; // an independent explicit hold
``` ```
- `Artifact` is a read-only, cloneable handle on one owner: a delivery or an explicit hold. - `Artifact` is a read-only, cloneable handle on one owner: a delivery or an explicit hold.
Its last clone (including any `ArtifactFile`) releases that owner. Its last clone (including any `ArtifactFile`) releases that owner. `is_hold()` is true for an
explicit hold (a sealed writer, a `retain`): keeping a clone of one keeps the bytes, and costs
no delivery credit.
- A handle that came in a delivery opens and reads without a router round trip: the delivery
names each attachment's read location (bus-v1 section 12, amendment 2026-10-01). Any other
handle asks the router (`artifact.open`) first. Up to 256 KiB, `read_all()` reads in place
rather than on the blocking pool.
- `ArtifactWriter` is unique. Dropping it unsealed releases the staging storage. Writes past - `ArtifactWriter` is unique. Dropping it unsealed releases the staging storage. Writes past
the allocated length fail. Unwritten bytes read as zeros. the allocated length fail. Unwritten bytes read as zeros.
- Sealing copies staging into a fresh read-only (0444) file and unlinks staging. A descriptor - Sealing copies staging into a fresh read-only (0444) file and unlinks staging. A descriptor
@ -272,7 +278,8 @@ before admission are `not-dispatched`. A command in flight when the connection i
call returns `routed:false` and creates no roots. Unregistering a service fails its queued call returns `routed:false` and creates no roots. Unregistering a service fails its queued
calls; dispatched calls can still be answered while a `Request` or `Responder` retains reply calls; dispatched calls can still be answered while a `Request` or `Responder` retains reply
capability. Both cancel/consume orderings retire cleanly. capability. Both cancel/consume orderings retire cleanly.
- **Seals** copy (and hash, when a digest was given) on Tokio's blocking pool, alongside the - **Seals** copy (and hash, when a digest was given) on Tokio's blocking pool (up to 256 KiB in
place on the reader, which on the store's tmpfs is cheaper than the hop), alongside the
connection's reader, so a large copy does not hold up that client's releases. If the writer is released or disconnects connection's reader, so a large copy does not hold up that client's releases. If the writer is released or disconnects
mid-seal, the copy is discarded and the artifact is never published. mid-seal, the copy is discarded and the artifact is never published.
@ -321,6 +328,10 @@ before admission are `not-dispatched`. A command in flight when the connection i
final release atomically retires the correlation and caller slot and emits `call.failed` final release atomically retires the correlation and caller slot and emits `call.failed`
with dispatch `dispatched`: `CALL_GONE` while the route remains live, or `NO_SERVICE` after with dispatch `dispatched`: `CALL_GONE` while the route remains live, or `NO_SERVICE` after
route loss. route loss.
11. **Read locations in deliveries** (amendment 2026-10-01, BUS-01). Every attachment of an
`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.
## Limitations ## Limitations

View file

@ -52,22 +52,29 @@ pub(crate) fn attachment_list(
name: (*name).to_owned(), name: (*name).to_owned(),
reference: a.reference.as_ref().clone(), reference: a.reference.as_ref().clone(),
owner_id: owner.id.clone(), owner_id: owner.id.clone(),
read_location: None,
}); });
keep.push(owner.clone()); keep.push(owner.clone());
} }
Ok((atts, keep)) Ok((atts, keep))
} }
fn find( /// One attachment of a delivery, with the read location the router issued for it (bus-v1
list: &[(String, ArtifactRef)], /// section 12 amendment 2026-10-01; `None` from a router that issues none).
guard: &Arc<OwnerGuard>, #[derive(Clone, Debug)]
name: &str, pub(crate) struct Delivered {
) -> Result<Artifact, BusError> { pub name: String,
pub reference: ArtifactRef,
pub location: Option<Arc<Location>>,
}
fn find(list: &[Delivered], guard: &Arc<OwnerGuard>, name: &str) -> Result<Artifact, BusError> {
list.iter() list.iter()
.find(|(n, _)| n == name) .find(|d| d.name == name)
.map(|(_, r)| Artifact { .map(|d| Artifact {
reference: Arc::new(r.clone()), reference: Arc::new(d.reference.clone()),
holder: Holder::Bus(guard.clone()), holder: Holder::Bus(guard.clone()),
location: d.location.clone(),
}) })
.ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}"))) .ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}")))
} }
@ -88,6 +95,9 @@ fn find(
pub struct Artifact { pub struct Artifact {
pub(crate) reference: Arc<ArtifactRef>, pub(crate) reference: Arc<ArtifactRef>,
pub(crate) holder: Holder, pub(crate) holder: Holder,
/// Where the bytes are, when the router said so in the delivery that granted this handle:
/// [`Artifact::open`] then needs no `artifact.open` round trip (BUS-01).
pub(crate) location: Option<Arc<Location>>,
} }
/// What keeps an artifact's bytes alive. /// What keeps an artifact's bytes alive.
@ -129,6 +139,7 @@ impl Artifact {
digest: None, digest: None,
}), }),
holder: Holder::Memory(bytes), holder: Holder::Memory(bytes),
location: None,
} }
} }
@ -154,6 +165,7 @@ impl Artifact {
Ok(Artifact { Ok(Artifact {
reference: self.reference.clone(), reference: self.reference.clone(),
holder: Holder::Memory(bytes.into()), holder: Holder::Memory(bytes.into()),
location: None,
}) })
} }
@ -162,6 +174,14 @@ impl Artifact {
matches!(self.holder, Holder::Memory(_)) matches!(self.holder, Holder::Memory(_))
} }
/// True when this handle's owner is an explicit hold of its own connection -- a sealed
/// writer or a [`Artifact::retain`] -- rather than a delivery. Keeping a clone of such a handle
/// keeps the bytes as long as a [`Artifact::retain`] would, and consumes no delivery credit,
/// so a holder that only needs the bytes to stay alive need not take another hold (BUS-01).
pub fn is_hold(&self) -> bool {
matches!(&self.holder, Holder::Bus(owner) if !owner.delivery)
}
/// The bytes of an in-memory artifact, without a copy; `None` for a sealed one. /// The bytes of an in-memory artifact, without a copy; `None` for a sealed one.
pub fn memory(&self) -> Option<&Arc<[u8]>> { pub fn memory(&self) -> Option<&Arc<[u8]>> {
match &self.holder { match &self.holder {
@ -190,10 +210,16 @@ impl Artifact {
}); });
} }
}; };
let shared = &owner.conn.shared;
// The delivery that granted this handle said where the bytes are (BUS-01); otherwise the
// router is asked. Either way the location is store-issued and resolved below the store
// root, and the owner this handle keeps holds the bytes while the file is open.
let loc = match &self.location {
Some(loc) => loc.as_ref().clone(),
None => {
let mut body = Map::new(); let mut body = Map::new();
body.insert("ref".into(), self.reference.to_json()); body.insert("ref".into(), self.reference.to_json());
body.insert("ownerId".into(), owner.id.clone().into()); body.insert("ownerId".into(), owner.id.clone().into());
let shared = &owner.conn.shared;
let reply = shared let reply = shared
.command( .command(
"artifact.open", "artifact.open",
@ -203,7 +229,9 @@ impl Artifact {
Hook::None, Hook::None,
) )
.await?; .await?;
let loc = Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)?; Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)?
}
};
if loc.store_id != self.reference.store_id { if loc.store_id != self.reference.store_id {
return Err(BusError::new( return Err(BusError::new(
ErrorCode::ArtifactGone, ErrorCode::ArtifactGone,
@ -229,12 +257,21 @@ impl Artifact {
}) })
} }
/// Reads the whole artifact (on the blocking pool; an in-memory one is copied in place). /// Reads the whole artifact: on the blocking pool, or in place up to
/// [`crate::store::INLINE_IO_BYTES`] (a tmpfs read of that size is cheaper than the pool hop);
/// an in-memory one is copied in place.
pub async fn read_all(&self) -> Result<Vec<u8>, BusError> { pub async fn read_all(&self) -> Result<Vec<u8>, BusError> {
if let Holder::Memory(bytes) = &self.holder { if let Holder::Memory(bytes) = &self.holder {
return Ok(bytes.to_vec()); return Ok(bytes.to_vec());
} }
let mut file = self.open().await?; let mut file = self.open().await?;
if file.len() <= crate::store::INLINE_IO_BYTES {
let mut out = Vec::with_capacity(file.len() as usize);
return file
.read_to_end(&mut out)
.map(|_| out)
.map_err(|e| BusError::new(ErrorCode::StoreFailure, e.to_string()));
}
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
let mut out = Vec::with_capacity(file.len() as usize); let mut out = Vec::with_capacity(file.len() as usize);
file.read_to_end(&mut out).map(|_| out) file.read_to_end(&mut out).map(|_| out)
@ -268,6 +305,7 @@ impl Artifact {
Extra::Owner(owner) => Ok(Artifact { Extra::Owner(owner) => Ok(Artifact {
reference: self.reference.clone(), reference: self.reference.clone(),
holder: Holder::Bus(owner), holder: Holder::Bus(owner),
location: self.location.clone(),
}), }),
_ => Err(BusError::lost("retain reply without an owner")), _ => Err(BusError::lost("retain reply without an owner")),
} }
@ -365,6 +403,7 @@ impl ArtifactWriter {
Ok(Artifact { Ok(Artifact {
reference: Arc::new(reference), reference: Arc::new(reference),
holder: Holder::Bus(self.owner.clone()), holder: Holder::Bus(self.owner.clone()),
location: None,
}) })
} }
} }
@ -405,7 +444,7 @@ pub struct Message {
pub(crate) topic_sequence: u64, pub(crate) topic_sequence: u64,
pub(crate) replaced: u64, pub(crate) replaced: u64,
pub(crate) payload: Map<String, Value>, pub(crate) payload: Map<String, Value>,
pub(crate) attachments: Vec<(String, ArtifactRef)>, pub(crate) attachments: Vec<Delivered>,
} }
impl Message { impl Message {
@ -432,7 +471,7 @@ impl Message {
&self.payload &self.payload
} }
pub fn attachment_names(&self) -> impl Iterator<Item = &str> { pub fn attachment_names(&self) -> impl Iterator<Item = &str> {
self.attachments.iter().map(|(n, _)| n.as_str()) self.attachments.iter().map(|d| d.name.as_str())
} }
/// An artifact handle sharing this delivery's guard. /// An artifact handle sharing this delivery's guard.
pub fn artifact(&self, name: &str) -> Result<Artifact, BusError> { pub fn artifact(&self, name: &str) -> Result<Artifact, BusError> {
@ -451,7 +490,7 @@ pub struct Request {
pub(crate) service_incarnation: String, pub(crate) service_incarnation: String,
pub(crate) method: String, pub(crate) method: String,
pub(crate) payload: Map<String, Value>, pub(crate) payload: Map<String, Value>,
pub(crate) attachments: Vec<(String, ArtifactRef)>, pub(crate) attachments: Vec<Delivered>,
} }
impl Request { impl Request {
@ -554,7 +593,7 @@ pub struct RpcResult {
pub(crate) responder: Identity, pub(crate) responder: Identity,
pub(crate) service_incarnation: String, pub(crate) service_incarnation: String,
pub(crate) outcome: Map<String, Value>, pub(crate) outcome: Map<String, Value>,
pub(crate) attachments: Vec<(String, ArtifactRef)>, pub(crate) attachments: Vec<Delivered>,
} }
impl RpcResult { impl RpcResult {

View file

@ -20,7 +20,8 @@ use tokio::sync::{Notify, mpsc, oneshot, watch};
use super::SessionInfo; use super::SessionInfo;
use super::handles::{ use super::handles::{
CallGuard, Message, OwnerGuard, ReplyGuard, Request, RpcResult, ServiceGuard, SubscriptionGuard, CallGuard, Delivered, Message, OwnerGuard, ReplyGuard, Request, RpcResult, ServiceGuard,
SubscriptionGuard,
}; };
use crate::error::{BusError, Dispatch, ErrorCode}; use crate::error::{BusError, Dispatch, ErrorCode};
use crate::transport::Transport; use crate::transport::Transport;
@ -388,9 +389,16 @@ fn next_outgoing(shared: &Shared) -> Next {
}; };
st.next_msg += 1; st.next_msg += 1;
let n = st.next_msg; let n = st.next_msg;
let mut env = Envelope::new(serial_id("msg", n), Kind::Command, cmd.op, cmd.body.clone()); let id = serial_id("msg", n);
env.attachments = cmd.attachments.clone(); let head = crate::wire::EnvelopeHead {
match env.encode() { major: crate::wire::MAJOR,
minor: crate::wire::MINOR,
id: &id,
reply_to: None,
kind: Kind::Command,
op: cmd.op,
};
match crate::wire::encode_parts(&head, &cmd.body, &cmd.attachments) {
Ok(bytes) => { Ok(bytes) => {
st.pending.insert( st.pending.insert(
n, n,
@ -786,7 +794,7 @@ fn complete(
Ok(()) Ok(())
} }
fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<(String, ArtifactRef)>, WireError> { fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<Delivered>, WireError> {
env.attachments env.attachments
.iter() .iter()
.map(|a| { .map(|a| {
@ -795,7 +803,20 @@ fn attachments(env: &Envelope, delivery_id: &str) -> Result<Vec<(String, Artifac
"delivery attachment owner is not the delivery".into(), "delivery attachment owner is not the delivery".into(),
)); ));
} }
Ok((a.name.clone(), a.reference.clone())) if a
.read_location
.as_ref()
.is_some_and(|loc| loc.store_id != a.reference.store_id)
{
return Err(WireError(
"delivery attachment read location names another store".into(),
));
}
Ok(Delivered {
name: a.name.clone(),
reference: a.reference.clone(),
location: a.read_location.clone().map(Arc::new),
})
}) })
.collect() .collect()
} }

View file

@ -304,18 +304,41 @@ async fn read_loop<R: AsyncRead + Unpin>(
return; return;
} }
}; };
// A read location is the router's to issue, in a delivery (BUS-01 amendment): a client
// attachment that carries one is malformed.
if env.attachments.iter().any(|a| a.read_location.is_some()) {
inner.with_state(|s| {
s.reject_frame(c, "attachment: unknown field \"readLocation\"".into())
});
return;
}
let was_hello = !negotiated && env.op == "bus.hello"; let was_hello = !negotiated && env.op == "bus.hello";
match inner.with_state(|s| s.handle(c, env)) { match inner.with_state(|s| s.handle(c, env)) {
Outcome::Done => {} Outcome::Done => {}
Outcome::Close => return, Outcome::Close => return,
Outcome::Allocate(job) => { Outcome::Allocate(job) => {
let (i, serial, len) = (inner.clone(), job.serial, job.len); let (i, serial, len) = (inner.clone(), job.serial, job.len);
let created = // A small staging file (a frame, a memory image) is created in place: on the
// store's tmpfs that is a few microseconds, less than the hop to the blocking pool
// and back, which an artifact-per-call protocol pays on its critical path
// (BUS-01). A large one still goes to the blocking pool.
let created = if len <= crate::store::INLINE_IO_BYTES {
i.store.create_staging(serial, len)
} else {
tokio::task::spawn_blocking(move || i.store.create_staging(serial, len)) tokio::task::spawn_blocking(move || i.store.create_staging(serial, len))
.await .await
.unwrap_or_else(|e| Err(io::Error::other(e))); .unwrap_or_else(|e| Err(io::Error::other(e)))
};
inner.with_state(|s| s.finish_allocate(job, created)); inner.with_state(|s| s.finish_allocate(job, created));
} }
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
// spawned path's, step for step.
let result = inner.store.seal(job.serial, job.len, job.digest.as_deref());
inner.store.remove(&crate::store::staging_rel(job.serial));
inner.with_state(|s| s.finish_seal(job, result));
}
Outcome::Seal(job) => { Outcome::Seal(job) => {
let inner = inner.clone(); let inner = inner.clone();
tokio::spawn(async move { tokio::spawn(async move {

View file

@ -442,12 +442,21 @@ fn dedup(serials: Vec<u64>) -> Vec<u64> {
serials.into_iter().filter(|s| seen.insert(*s)).collect() serials.into_iter().filter(|s| seen.insert(*s)).collect()
} }
/// A delivery's attachments, each with the read location its delivery ownership grants
/// (bus-v1 section 12 amendment 2026-10-01): every attachment the router admitted is a sealed
/// artifact of this store, read at its sealed path.
fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec<Attachment> { fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec<Attachment> {
list.iter() list.iter()
.map(|(name, r)| Attachment { .map(|(name, r)| Attachment {
name: name.clone(), name: name.clone(),
reference: r.clone(), reference: r.clone(),
owner_id: owner.to_owned(), owner_id: owner.to_owned(),
read_location: crate::wire::parse_serial_id("a", &r.artifact_id).map(|serial| {
crate::wire::Location {
store_id: r.store_id.clone(),
relative_path: sealed_rel(serial),
}
}),
}) })
.collect() .collect()
} }
@ -458,10 +467,18 @@ fn frame_len(
body: Map<String, Value>, body: Map<String, Value>,
attachments: Vec<Attachment>, attachments: Vec<Attachment>,
) -> usize { ) -> usize {
let mut env = Envelope::new(serial_id("bus", MAX_SERIAL), kind, op, body); let id = serial_id("bus", MAX_SERIAL);
env.attachments = attachments; let head = crate::wire::EnvelopeHead {
serde_json::to_vec(&env.to_value()) major: crate::wire::MAJOR,
minor: crate::wire::MINOR,
id: &id,
reply_to: None,
kind,
op,
};
crate::wire::encode_parts(&head, &body, &attachments)
.map(|b| b.len()) .map(|b| b.len())
// Over the limit or unencodable: the caller refuses it either way.
.unwrap_or(usize::MAX) .unwrap_or(usize::MAX)
} }

View file

@ -32,6 +32,11 @@ pub(crate) fn staging_rel(serial: u64) -> String {
format!("staging/a-{serial}") format!("staging/a-{serial}")
} }
/// Store file operations up to this size run in place on the async thread rather than on the
/// blocking pool: creating or sealing a staging file, and reading a sealed one whole. The store is
/// meant to be tmpfs, where such a copy takes microseconds and the pool hop costs more (BUS-01).
pub const INLINE_IO_BYTES: u64 = 256 * 1024;
pub(crate) fn sealed_rel(serial: u64) -> String { pub(crate) fn sealed_rel(serial: u64) -> String {
format!("sealed/a-{serial}") format!("sealed/a-{serial}")
} }

View file

@ -36,7 +36,7 @@ pub const GENERATION: u64 = 1;
pub const CONTRACT: &str = "flybus 1.0 pub const CONTRACT: &str = "flybus 1.0
frame: u32le length, 1..=65536 bytes of strict UTF-8 JSON frame: u32le length, 1..=65536 bytes of strict UTF-8 JSON
envelope: protocol major minor id replyTo kind op body attachments envelope: protocol major minor id replyTo kind op body attachments
attachment: name ref ownerId attachment: name ref ownerId [readLocation(storeId relativePath): in a router delivery only]
ref: storeId artifactId generation byteLength contentType digest ref: storeId artifactId generation byteLength contentType digest
reply: ok value | ok error{code message dispatch} reply: ok value | ok error{code message dispatch}
bus.hello: clientId clientIncarnation supportedMajors -> routerId connectionId selectedMajor selectedMinor contractDigest limits bus.hello: clientId clientIncarnation supportedMajors -> routerId connectionId selectedMajor selectedMinor contractDigest limits
@ -293,6 +293,12 @@ impl<'a> Fields<'a> {
} }
} }
/// 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.map.get(key)
}
pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> { pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> {
self.seen.insert(key); self.seen.insert(key);
match self.map.get(key) { match self.map.get(key) {
@ -472,6 +478,10 @@ pub struct Attachment {
pub name: String, pub name: String,
pub reference: ArtifactRef, pub reference: ArtifactRef,
pub owner_id: String, pub owner_id: String,
/// In a router delivery only (amendment 2026-10-01, BUS-01): the read location the
/// delivery's ownership grants, so the recipient reads the bytes without an `artifact.open`
/// round trip. A client never sends one; the router refuses an attachment that carries it.
pub read_location: Option<Location>,
} }
impl Attachment { impl Attachment {
@ -480,6 +490,9 @@ impl Attachment {
m.insert("name".into(), self.name.clone().into()); m.insert("name".into(), self.name.clone().into());
m.insert("ref".into(), self.reference.to_json()); m.insert("ref".into(), self.reference.to_json());
m.insert("ownerId".into(), self.owner_id.clone().into()); m.insert("ownerId".into(), self.owner_id.clone().into());
if let Some(location) = &self.read_location {
m.insert("readLocation".into(), location.to_json());
}
Value::Object(m) Value::Object(m)
} }
@ -488,11 +501,13 @@ impl Attachment {
let name = f.id("name")?; let name = f.id("name")?;
let reference = ArtifactRef::from_json(f.value("ref")?)?; let reference = ArtifactRef::from_json(f.value("ref")?)?;
let owner_id = f.id("ownerId")?; let owner_id = f.id("ownerId")?;
let read_location = f.optional("readLocation").map(Location::from_json).transpose()?;
f.finish()?; f.finish()?;
Ok(Attachment { Ok(Attachment {
name, name,
reference, reference,
owner_id, owner_id,
read_location,
}) })
} }
} }
@ -640,7 +655,7 @@ impl Envelope {
return err("envelope: op must be 1..=64 of [a-z.]"); return err("envelope: op must be 1..=64 of [a-z.]");
} }
let op = op.to_owned(); let op = op.to_owned();
let body = f.object("body")?.clone(); f.object("body")?;
let raw = f.array("attachments", 0, MAX_ATTACHMENTS)?; let raw = f.array("attachments", 0, MAX_ATTACHMENTS)?;
let mut attachments = Vec::with_capacity(raw.len()); let mut attachments = Vec::with_capacity(raw.len());
let mut names = HashSet::new(); let mut names = HashSet::new();
@ -652,6 +667,14 @@ impl Envelope {
attachments.push(a); attachments.push(a);
} }
f.finish()?; f.finish()?;
// The body moves out of the parsed tree rather than being copied (BUS-01).
let body = match v {
Value::Object(mut m) => match m.remove("body") {
Some(Value::Object(body)) => body,
_ => return err("envelope: body must be an object"),
},
_ => return err("envelope must be an object"),
};
Ok(Envelope { Ok(Envelope {
major, major,
minor, minor,
@ -686,7 +709,65 @@ impl Envelope {
/// Serializes, refusing anything over [`MAX_ENVELOPE_BYTES`]. /// Serializes, refusing anything over [`MAX_ENVELOPE_BYTES`].
pub fn encode(&self) -> Result<Vec<u8>, WireError> { pub fn encode(&self) -> Result<Vec<u8>, WireError> {
let bytes = serde_json::to_vec(&self.to_value()).map_err(|e| WireError(e.to_string()))?; encode_parts(
&EnvelopeHead {
major: self.major,
minor: self.minor,
id: &self.id,
reply_to: self.reply_to.as_deref(),
kind: self.kind,
op: &self.op,
},
&self.body,
&self.attachments,
)
}
}
/// An envelope's scalar fields, borrowed, for [`encode_parts`].
pub struct EnvelopeHead<'a> {
pub major: u64,
pub minor: u64,
pub id: &'a str,
pub reply_to: Option<&'a str>,
pub kind: Kind,
pub op: &'a str,
}
/// Serializes an envelope from borrowed parts -- the same bytes as [`Envelope::to_value`] in its
/// 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(
head: &EnvelopeHead<'_>,
body: &Map<String, Value>,
attachments: &[Attachment],
) -> Result<Vec<u8>, WireError> {
#[derive(serde::Serialize)]
struct Out<'a> {
protocol: &'static str,
major: u64,
minor: u64,
id: &'a str,
#[serde(rename = "replyTo")]
reply_to: Option<&'a str>,
kind: &'static str,
op: &'a str,
body: &'a Map<String, Value>,
attachments: Vec<Value>,
}
let out = Out {
protocol: PROTOCOL,
major: head.major,
minor: head.minor,
id: head.id,
reply_to: head.reply_to,
kind: head.kind.as_str(),
op: head.op,
body,
attachments: attachments.iter().map(Attachment::to_json).collect(),
};
let bytes = serde_json::to_vec(&out).map_err(|e| WireError(e.to_string()))?;
if bytes.len() > MAX_ENVELOPE_BYTES { if bytes.len() > MAX_ENVELOPE_BYTES {
return err(format!( return err(format!(
"envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}", "envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}",
@ -695,7 +776,7 @@ impl Envelope {
} }
Ok(bytes) Ok(bytes)
} }
}
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// Framing // Framing

View file

@ -768,7 +768,71 @@ async fn issued_locations_are_relative_and_contained(via: Via) {
); );
} }
/// Amendment 2026-10-01 (BUS-01): every attachment of a delivery names the read location its
/// delivery ownership grants -- the store's sealed path of that artifact -- so the recipient reads
/// it without an `artifact.open` round trip; the SDK's handle uses it.
async fn deliveries_carry_the_read_location_their_ownership_grants(via: Via) {
let e = env(via).await;
let caller = e.client("caller").await;
let mut server = e.raw_hello("server").await;
assert_eq!(
code(
&server
.call(
"service.register",
json!({"name": "agent.located", "maxQueued": 4, "maxInFlight": 4})
)
.await
),
"OK"
);
let art = sealed(&caller, b"located bytes", "application/octet-stream").await;
let _pending = caller
.call("agent.located", None, "Look", obj(json!({})), &[("in", &art)])
.await
.unwrap();
let request = within("the request", server.event()).await;
let attachment = &request.attachments[0];
let location = attachment
.read_location
.as_ref()
.expect("a delivery's attachment names where its bytes are");
assert_eq!(location.store_id, e.router.store_id());
assert_eq!(
location.relative_path,
format!("sealed/{}", attachment.reference.artifact_id)
);
assert_eq!(
std::fs::read(e.router.store_dir().join(&location.relative_path)).unwrap(),
b"located bytes"
);
// The SDK's handle on a delivered artifact reads through the same location.
let other = e.client("other").await;
other
.declare_topic("t.located", Retained::None)
.await
.unwrap();
let mut sub = caller
.subscribe("t.located", SubscriptionConfig::bounded())
.await
.unwrap();
other
.publish("t.located", obj(json!({})), &[("frame", &art_of(&other).await)])
.await
.unwrap();
let message = within("the message", sub.next()).await.unwrap();
assert_eq!(
message.artifact("frame").unwrap().read_all().await.unwrap(),
b"other bytes"
);
}
async fn art_of(client: &flybus::Client) -> flybus::Artifact {
sealed(client, b"other bytes", "application/octet-stream").await
}
both_transports!( both_transports!(
deliveries_carry_the_read_location_their_ownership_grants,
allocate_write_seal_open_roundtrip_and_mismatches, allocate_write_seal_open_roundtrip_and_mismatches,
seal_is_immutable_despite_a_stale_writable_handle, seal_is_immutable_despite_a_stale_writable_handle,
extracted_artifact_outlives_the_message_it_came_from, extracted_artifact_outlives_the_message_it_came_from,

View file

@ -413,6 +413,7 @@ async fn client_strictly_validates_hello_envelope() {
digest: None, digest: None,
}, },
owner_id: "own-1".into(), owner_id: "own-1".into(),
read_location: None,
}), }),
_ => unreachable!(), _ => unreachable!(),
} }

View file

@ -117,6 +117,11 @@ async fn malformed_frames_close_the_connection(via: Via) {
major["major"] = json!(2); major["major"] = json!(2);
let mut not_flybus = publish("msg-2"); let mut not_flybus = publish("msg-2");
not_flybus["protocol"] = json!("flybusx"); not_flybus["protocol"] = json!("flybusx");
// A read location is the router's to issue, in a delivery (BUS-01): never from a client.
let mut located = publish("msg-2");
let mut located_att = att("a");
located_att["readLocation"] = json!({"storeId": "s", "relativePath": "sealed/a-1"});
located["attachments"] = json!([located_att]);
let cases: Vec<(&str, Vec<u8>)> = vec![ let cases: Vec<(&str, Vec<u8>)> = vec![
("nested duplicate key", br#"{"protocol":"flybus","major":1,"minor":0,"id":"msg-2","replyTo":null,"kind":"command","op":"publish","body":{"topic":"t.x","payload":{"a":{"b":1,"b":2}}},"attachments":[]}"#.to_vec()), ("nested duplicate key", br#"{"protocol":"flybus","major":1,"minor":0,"id":"msg-2","replyTo":null,"kind":"command","op":"publish","body":{"topic":"t.x","payload":{"a":{"b":1,"b":2}}},"attachments":[]}"#.to_vec()),
@ -133,6 +138,7 @@ async fn malformed_frames_close_the_connection(via: Via) {
("non-null replyTo", text(reply_to).into_bytes()), ("non-null replyTo", text(reply_to).into_bytes()),
("wrong major after hello", text(major).into_bytes()), ("wrong major after hello", text(major).into_bytes()),
("wrong protocol", text(not_flybus).into_bytes()), ("wrong protocol", text(not_flybus).into_bytes()),
("a client attachment with a readLocation", text(located).into_bytes()),
]; ];
for (i, (what, bytes)) in cases.into_iter().enumerate() { for (i, (what, bytes)) in cases.into_iter().enumerate() {
let mut raw = e.raw_hello(&format!("bad-{i}")).await; let mut raw = e.raw_hello(&format!("bad-{i}")).await;