diff --git a/docs/design/session-framework/bus-conformance.md b/docs/design/session-framework/bus-conformance.md index 83e2114..2ec491b 100644 --- a/docs/design/session-framework/bus-conformance.md +++ b/docs/design/session-framework/bus-conformance.md @@ -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` | | 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) | -| 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 | | `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) | @@ -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) | | 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 | `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) | | 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` | diff --git a/docs/design/session-framework/bus-v1.md b/docs/design/session-framework/bus-v1.md index 5e0a3db..2ed8cfb 100644 --- a/docs/design/session-framework/bus-v1.md +++ b/docs/design/session-framework/bus-v1.md @@ -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 the same date); section 8's ownership rules apply to every artifact a router stores, which these 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. diff --git a/services/flysim/crates/flybus/README.md b/services/flysim/crates/flybus/README.md index 003fbe4..b8e7825 100644 --- a/services/flysim/crates/flybus/README.md +++ b/services/flysim/crates/flybus/README.md @@ -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. - 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 the allocated length fail. Unwritten bytes read as zeros. - 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 calls; dispatched calls can still be answered while a `Request` or `Responder` retains reply 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 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` with dispatch `dispatched`: `CALL_GONE` while the route remains live, or `NO_SERVICE` after 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 diff --git a/services/flysim/crates/flybus/src/client/handles.rs b/services/flysim/crates/flybus/src/client/handles.rs index 6442377..3329393 100644 --- a/services/flysim/crates/flybus/src/client/handles.rs +++ b/services/flysim/crates/flybus/src/client/handles.rs @@ -52,22 +52,29 @@ pub(crate) fn attachment_list( name: (*name).to_owned(), reference: a.reference.as_ref().clone(), owner_id: owner.id.clone(), + read_location: None, }); keep.push(owner.clone()); } Ok((atts, keep)) } -fn find( - list: &[(String, ArtifactRef)], - guard: &Arc, - name: &str, -) -> Result { +/// One attachment of a delivery, with the read location the router issued for it (bus-v1 +/// section 12 amendment 2026-10-01; `None` from a router that issues none). +#[derive(Clone, Debug)] +pub(crate) struct Delivered { + pub name: String, + pub reference: ArtifactRef, + pub location: Option>, +} + +fn find(list: &[Delivered], guard: &Arc, name: &str) -> Result { list.iter() - .find(|(n, _)| n == name) - .map(|(_, r)| Artifact { - reference: Arc::new(r.clone()), + .find(|d| d.name == name) + .map(|d| Artifact { + reference: Arc::new(d.reference.clone()), holder: Holder::Bus(guard.clone()), + location: d.location.clone(), }) .ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}"))) } @@ -88,6 +95,9 @@ fn find( pub struct Artifact { pub(crate) reference: Arc, 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>, } /// What keeps an artifact's bytes alive. @@ -129,6 +139,7 @@ impl Artifact { digest: None, }), holder: Holder::Memory(bytes), + location: None, } } @@ -154,6 +165,7 @@ impl Artifact { Ok(Artifact { reference: self.reference.clone(), holder: Holder::Memory(bytes.into()), + location: None, }) } @@ -162,6 +174,14 @@ impl Artifact { 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. pub fn memory(&self) -> Option<&Arc<[u8]>> { match &self.holder { @@ -190,20 +210,28 @@ impl Artifact { }); } }; - let mut body = Map::new(); - body.insert("ref".into(), self.reference.to_json()); - body.insert("ownerId".into(), owner.id.clone().into()); let shared = &owner.conn.shared; - let reply = shared - .command( - "artifact.open", - body, - Vec::new(), - vec![owner.clone()], - Hook::None, - ) - .await?; - let loc = Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)?; + // 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(); + body.insert("ref".into(), self.reference.to_json()); + body.insert("ownerId".into(), owner.id.clone().into()); + let reply = shared + .command( + "artifact.open", + body, + Vec::new(), + vec![owner.clone()], + Hook::None, + ) + .await?; + Location::from_json(Fields::of(&reply.value, "reply").value("readLocation")?)? + } + }; if loc.store_id != self.reference.store_id { return Err(BusError::new( 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, BusError> { if let Holder::Memory(bytes) = &self.holder { return Ok(bytes.to_vec()); } 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 || { let mut out = Vec::with_capacity(file.len() as usize); file.read_to_end(&mut out).map(|_| out) @@ -268,6 +305,7 @@ impl Artifact { Extra::Owner(owner) => Ok(Artifact { reference: self.reference.clone(), holder: Holder::Bus(owner), + location: self.location.clone(), }), _ => Err(BusError::lost("retain reply without an owner")), } @@ -365,6 +403,7 @@ impl ArtifactWriter { Ok(Artifact { reference: Arc::new(reference), holder: Holder::Bus(self.owner.clone()), + location: None, }) } } @@ -405,7 +444,7 @@ pub struct Message { pub(crate) topic_sequence: u64, pub(crate) replaced: u64, pub(crate) payload: Map, - pub(crate) attachments: Vec<(String, ArtifactRef)>, + pub(crate) attachments: Vec, } impl Message { @@ -432,7 +471,7 @@ impl Message { &self.payload } pub fn attachment_names(&self) -> impl Iterator { - 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. pub fn artifact(&self, name: &str) -> Result { @@ -451,7 +490,7 @@ pub struct Request { pub(crate) service_incarnation: String, pub(crate) method: String, pub(crate) payload: Map, - pub(crate) attachments: Vec<(String, ArtifactRef)>, + pub(crate) attachments: Vec, } impl Request { @@ -554,7 +593,7 @@ pub struct RpcResult { pub(crate) responder: Identity, pub(crate) service_incarnation: String, pub(crate) outcome: Map, - pub(crate) attachments: Vec<(String, ArtifactRef)>, + pub(crate) attachments: Vec, } impl RpcResult { diff --git a/services/flysim/crates/flybus/src/client/reactor.rs b/services/flysim/crates/flybus/src/client/reactor.rs index abdf9fa..c9ef972 100644 --- a/services/flysim/crates/flybus/src/client/reactor.rs +++ b/services/flysim/crates/flybus/src/client/reactor.rs @@ -20,7 +20,8 @@ use tokio::sync::{Notify, mpsc, oneshot, watch}; use super::SessionInfo; 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::transport::Transport; @@ -388,9 +389,16 @@ fn next_outgoing(shared: &Shared) -> Next { }; st.next_msg += 1; let n = st.next_msg; - let mut env = Envelope::new(serial_id("msg", n), Kind::Command, cmd.op, cmd.body.clone()); - env.attachments = cmd.attachments.clone(); - match env.encode() { + let id = serial_id("msg", n); + let head = crate::wire::EnvelopeHead { + 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) => { st.pending.insert( n, @@ -786,7 +794,7 @@ fn complete( Ok(()) } -fn attachments(env: &Envelope, delivery_id: &str) -> Result, WireError> { +fn attachments(env: &Envelope, delivery_id: &str) -> Result, WireError> { env.attachments .iter() .map(|a| { @@ -795,7 +803,20 @@ fn attachments(env: &Envelope, delivery_id: &str) -> Result( 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"; match inner.with_state(|s| s.handle(c, env)) { Outcome::Done => {} Outcome::Close => return, Outcome::Allocate(job) => { 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)) .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)); } + 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) => { let inner = inner.clone(); tokio::spawn(async move { diff --git a/services/flysim/crates/flybus/src/router/state.rs b/services/flysim/crates/flybus/src/router/state.rs index 33380d0..2542d8b 100644 --- a/services/flysim/crates/flybus/src/router/state.rs +++ b/services/flysim/crates/flybus/src/router/state.rs @@ -442,12 +442,21 @@ fn dedup(serials: Vec) -> Vec { 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 { list.iter() .map(|(name, r)| Attachment { name: name.clone(), reference: r.clone(), 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() } @@ -458,10 +467,18 @@ fn frame_len( body: Map, attachments: Vec, ) -> usize { - let mut env = Envelope::new(serial_id("bus", MAX_SERIAL), kind, op, body); - env.attachments = attachments; - serde_json::to_vec(&env.to_value()) + let id = serial_id("bus", MAX_SERIAL); + let head = crate::wire::EnvelopeHead { + 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()) + // Over the limit or unencodable: the caller refuses it either way. .unwrap_or(usize::MAX) } diff --git a/services/flysim/crates/flybus/src/store.rs b/services/flysim/crates/flybus/src/store.rs index 4964ac6..ed975e3 100644 --- a/services/flysim/crates/flybus/src/store.rs +++ b/services/flysim/crates/flybus/src/store.rs @@ -32,6 +32,11 @@ pub(crate) fn staging_rel(serial: u64) -> String { 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 { format!("sealed/a-{serial}") } diff --git a/services/flysim/crates/flybus/src/wire.rs b/services/flysim/crates/flybus/src/wire.rs index 3e2e1bb..6486b74 100644 --- a/services/flysim/crates/flybus/src/wire.rs +++ b/services/flysim/crates/flybus/src/wire.rs @@ -36,7 +36,7 @@ pub const GENERATION: u64 = 1; 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 +attachment: name ref ownerId [readLocation(storeId relativePath): in a router delivery only] 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 @@ -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> { self.seen.insert(key); match self.map.get(key) { @@ -472,6 +478,10 @@ pub struct Attachment { pub name: String, pub reference: ArtifactRef, 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, } impl Attachment { @@ -480,6 +490,9 @@ impl Attachment { m.insert("name".into(), self.name.clone().into()); m.insert("ref".into(), self.reference.to_json()); 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) } @@ -488,11 +501,13 @@ impl Attachment { let name = f.id("name")?; let reference = ArtifactRef::from_json(f.value("ref")?)?; let owner_id = f.id("ownerId")?; + let read_location = f.optional("readLocation").map(Location::from_json).transpose()?; f.finish()?; Ok(Attachment { name, reference, owner_id, + read_location, }) } } @@ -640,7 +655,7 @@ impl Envelope { return err("envelope: op must be 1..=64 of [a-z.]"); } let op = op.to_owned(); - let body = f.object("body")?.clone(); + f.object("body")?; let raw = f.array("attachments", 0, MAX_ATTACHMENTS)?; let mut attachments = Vec::with_capacity(raw.len()); let mut names = HashSet::new(); @@ -652,6 +667,14 @@ impl Envelope { attachments.push(a); } 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 { major, minor, @@ -686,17 +709,75 @@ impl Envelope { /// Serializes, refusing anything over [`MAX_ENVELOPE_BYTES`]. pub fn encode(&self) -> Result, WireError> { - let bytes = serde_json::to_vec(&self.to_value()).map_err(|e| WireError(e.to_string()))?; - if bytes.len() > MAX_ENVELOPE_BYTES { - return err(format!( - "envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}", - bytes.len() - )); - } - Ok(bytes) + 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, + attachments: &[Attachment], +) -> Result, 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, + attachments: Vec, + } + 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 { + return err(format!( + "envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}", + bytes.len() + )); + } + Ok(bytes) +} + + // --------------------------------------------------------------------------------------------- // Framing diff --git a/services/flysim/crates/flybus/tests/conformance_artifacts.rs b/services/flysim/crates/flybus/tests/conformance_artifacts.rs index 2eb874b..2417e3e 100644 --- a/services/flysim/crates/flybus/tests/conformance_artifacts.rs +++ b/services/flysim/crates/flybus/tests/conformance_artifacts.rs @@ -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!( + deliveries_carry_the_read_location_their_ownership_grants, allocate_write_seal_open_roundtrip_and_mismatches, seal_is_immutable_despite_a_stale_writable_handle, extracted_artifact_outlives_the_message_it_came_from, diff --git a/services/flysim/crates/flybus/tests/sol_review_races.rs b/services/flysim/crates/flybus/tests/sol_review_races.rs index 793df64..308804f 100644 --- a/services/flysim/crates/flybus/tests/sol_review_races.rs +++ b/services/flysim/crates/flybus/tests/sol_review_races.rs @@ -413,6 +413,7 @@ async fn client_strictly_validates_hello_envelope() { digest: None, }, owner_id: "own-1".into(), + read_location: None, }), _ => unreachable!(), } diff --git a/services/flysim/crates/flybus/tests/wire.rs b/services/flysim/crates/flybus/tests/wire.rs index 0b74ede..dbd8d00 100644 --- a/services/flysim/crates/flybus/tests/wire.rs +++ b/services/flysim/crates/flybus/tests/wire.rs @@ -117,6 +117,11 @@ async fn malformed_frames_close_the_connection(via: Via) { major["major"] = json!(2); let mut not_flybus = publish("msg-2"); 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)> = 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()), ("wrong major after hello", text(major).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() { let mut raw = e.raw_hello(&format!("bad-{i}")).await;