BUS-02 review notes: recycled writers zero-filled, replays wait for the sealing reply, typed seal failures

The feed and the control API run over flybus in production, so these notes are treated as
live-path correctness.

- N3: the router empties and re-reserves a recycled writer's staging file before reissuing it,
  so no artifact sealed from it (by prefix or whole) carries the previous artifact's bytes;
  ArtifactWriter::seal's doc now holds for every writer. contractDigest text says so.
- N2: a sealing reply is sent with the worker's result cache held, so a duplicate replays the
  sealed artifacts instead of attaching the still-unsealed writer.
- N1: a refused sealing reply is answered as the handler's own seal failure was before BUS-02
  (BACKEND_FAILURE, mutation applied), cached the same way, worker marked failed, and logged.
- N5: a failed staging rename unlinks the writer's own staging file.
- N4: recycle without a sealing attachment is refused even when false; one writer named by two
  attachments is refused as INVALID_ENVELOPE; the SDK checks writers on rpc.call and publish
  replies too.
- N6: the store-directory cache is per client connection; bus-v1 notes the residual case.
- N7: the fly-edge stall test waits for the feed topic; SERVE-01 parity accepts a refused
  /stimulate drained one frame late (retryAfterMs one frame apart, nothing else).
- tests: the review's adversarial lifecycle suite (sealing_lifecycle.rs); recycled-writer content,
  rename failure and recycle edges (sealing.rs); replay-vs-sealing and typed refusal in the worker
  shell; smaller-after-larger artifacts through fly-edge and fly-control-edge.
This commit is contained in:
acamilo 2026-10-02 10:14:23 +00:00
parent 29b51ff336
commit 6a92a1902b
19 changed files with 977 additions and 92 deletions

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.
@ -588,7 +592,12 @@ critical path, for answers the router could give as it admits the reply.
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.
writing into the recycled staging file reaches only the staging inode. A reissued writer is a
fresh allocation in content as well: the router empties the staging file and reserves it again
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.

View file

@ -571,6 +571,20 @@ section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched
`/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 emptied
and reserved again when the router reissues it, 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)

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
let mut subscription = loop {
match client
.subscribe(
feedbus::TOPIC,
SubscriptionConfig::latest().in_flight(2).replay(true),
)
.await
.unwrap();
{
Ok(subscription) => break subscription,
Err(error)
if error.code == flybus::ErrorCode::NoTopic && Instant::now() < deadline =>
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
Err(error) => panic!("subscribe: {error:?}"),
}
};
hoards.push(tokio::spawn(async move {
let mut kept = Vec::new();
while let Some(message) = subscription.next().await {

View file

@ -492,6 +492,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(),
@ -539,6 +559,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

@ -519,6 +519,17 @@ 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 {
/// 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).
@ -527,23 +538,23 @@ impl Answer {
outcome: SessionRpcOutcome,
artifacts: &[(String, flybus::Artifact)],
unsealed: Vec<flybus::Unsealed>,
) -> Vec<flybus::ArtifactWriter> {
) -> Sent {
match self {
Answer::Bus(responder) => {
let list: Vec<(&str, &flybus::Artifact)> =
artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
if unsealed.is_empty() {
let _ = responder.reply(outcome.to_outcome(), &list).await;
return Vec::new();
return Sent::Done(Vec::new());
}
match responder.reply_sealing(outcome.to_outcome(), &list, unsealed, true).await {
Ok(sealed) => sealed.writers,
Err(_) => Vec::new(),
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() });
Vec::new()
Sent::Done(Vec::new())
}
}
}
@ -1039,20 +1050,83 @@ 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");
let unsealed = std::mem::take(&mut *unsealed.lock().expect("never poisoned"));
let recycled = answer.send(outcome, &reply.artifacts, unsealed).await;
let sent = answer.send(outcome, &reply.artifacts, unsealed).await;
drop(reply_span);
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).
@ -1264,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

@ -192,7 +192,9 @@ let kept = frame.retain().await?; // an independent explicit hold
`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 handle is valid once the reply is admitted. The router accepts sealing attachments on
The router empties 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
@ -344,7 +346,7 @@ before admission are `not-dispatched`. A command in flight when the connection i
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 as a new writer, listed in the reply value's `writers`. A refused sealing send
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.
@ -411,7 +413,12 @@ socket, through the same router code:
- `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.
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

@ -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
@ -410,8 +410,10 @@ impl ArtifactWriter {
}
}
/// 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.
/// 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
}
@ -593,7 +595,9 @@ impl Unsealed {
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.
/// With `recycle`, a fresh writer of the same allocation for each artifact sealed. Its
/// staging file is the sealed artifact's, emptied: it reads as zeros, as a new
/// allocation does.
pub writers: Vec<ArtifactWriter>,
}
@ -689,7 +693,7 @@ impl Responder {
else {
continue;
};
let path = resolve(&shared.store_root, &location.store_id, &location)?;
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 {

View file

@ -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 {

View file

@ -127,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,
@ -157,6 +159,7 @@ impl Shared {
Shared {
info,
store_root,
dirs: crate::store::DirCache::default(),
state: Mutex::new(ClientState {
closed: None,
shutting_down: false,
@ -628,6 +631,7 @@ 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")?;
@ -661,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")?;
@ -1093,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

@ -335,23 +335,40 @@ async fn read_loop<R: AsyncRead + Unpin>(
// 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 and
// renamed for the artifact it becomes; otherwise it goes with the copy.
// its commands stay in order. A recycled writer's staging file is kept,
// renamed for the artifact it becomes and reset to zeros, 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, Option<u64>)> =
job.seals.iter().map(|s| (s.serial, s.len, s.recycle)).collect();
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, recycle)| {
.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() => i
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
.rename(&crate::store::staging_rel(serial), &crate::store::staging_rel(next))
.map_err(crate::store::SealFailure::Io),
.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(&crate::store::staging_rel(serial));
i.store.remove(&staging);
r
}
}

View file

@ -1316,9 +1316,11 @@ impl State {
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 => false,
Some(Value::Bool(b)) => b,
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();
@ -1336,7 +1338,13 @@ impl State {
// Another artifact under a writer's owner id: check_owned refuses it later.
continue;
}
if sealing || found.iter().any(|(s, _, _)| *s == artifact) {
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];
@ -1359,11 +1367,12 @@ content type, a null digest and at most the allocated length",
found.push((artifact, owner, r.byte_length));
}
if found.is_empty() {
if recycle {
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");

View file

@ -108,27 +108,27 @@ 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,
/// reserved (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. Truncating frees those blocks, and the
/// reservation that follows is the one `create_staging` makes.
pub(crate) fn reset_staging(&self, serial: u64, len: u64) -> io::Result<()> {
let file = OpenOptions::new()
.write(true)
.custom_flags(libc::O_NOFOLLOW)
.open(self.path(&staging_rel(serial)))?;
file.set_len(0)?;
reserve(&file, 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.
@ -201,6 +201,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) {
@ -344,7 +361,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,
@ -374,19 +396,20 @@ pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result<Pat
_ => return Err(refuse("parent, root or current-directory component")),
}
}
// The directory part (`sealed`, `staging`) is resolved once per store directory and cached
// (BUS-02): canonicalizing the whole path is a readlink per component, twice, on every open
// 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 = canonical_dir(&root.join(&loc.store_id), None)
let base = dirs
.canonical(&root.join(&loc.store_id), None)
.map_err(|e| refuse(&format!("store directory: {e}")))?;
let parent = match dir {
None => base.clone(),
Some(dir) => canonical_dir(&root.join(&loc.store_id), Some(dir)).map_err(|e| match e.kind() {
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()),
})?,
@ -405,33 +428,35 @@ pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result<Pat
}
}
/// `store.join(dir).canonicalize()`, cached per process: a store's directories are made by its
/// router when the store is created and never move.
fn canonical_dir(store: &Path, dir: Option<&str>) -> io::Result<PathBuf> {
use std::collections::HashMap;
use std::sync::Mutex;
static CACHE: Mutex<Option<HashMap<PathBuf, PathBuf>>> = Mutex::new(None);
/// 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) = CACHE
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.and_then(|m| m.get(&key).cloned())
{
return Ok(hit);
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 cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
let map = cache.get_or_insert_with(HashMap::new);
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> {
OpenOptions::new()
@ -466,7 +491,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",
@ -477,7 +502,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:?}"
);
}
@ -486,7 +511,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

@ -38,7 +38,7 @@ 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; the reply value then carries writers[name artifactId generation ownerId writeLocation], each sealed writer's staging allocation reissued
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

View file

@ -140,7 +140,148 @@ async fn a_refused_sealing_send_releases_its_writers(via: Via) {
.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,
);