fly-session: the in-process local lane, and the per-frame costs it leaves

- worker: one Shell per worker serves its bus loop and a LocalLane. A local
  request goes through the same admission (classification, body digest,
  result cache, arrival-order ticket, endpoint lock) and answers the same
  SessionRpcOutcome, without a bus message. Worker.* stays on the bus.
  HandlerCtx::seal keeps a local request's reply media in memory.
- rpc: a WorkerRef carrying a lane sends endpoint methods over it; sealed reply
  handles reach the caller in memory under the same reference; a bus call
  carries sealed copies of in-memory attachments (promote).
- launcher: Via::Local offers in-process participants over their lane.
- coordinator: publication attaches sealed copies of in-memory media, begun
  when Environment.Advance answers; defer_snapshots (publish without waiting
  for admission, settled at the next snapshot); digest_views and media_bytes
  as SERVE-01 has them.
- legacy env/agent: frame, memory image, audio and spike bitset sealed via
  HandlerCtx::seal; the spike bitset is built eight neurons a byte.
- profile: span maxima, enabled(); the agent runs the brain's phase clock
  when profiling.
- tests: every synthetic transport test also runs over the local lane; the
  two publication-identity checks state the sealed copy there.
This commit is contained in:
acamilo 2026-09-30 01:46:07 +00:00
parent 35d5a1f38d
commit aaf660d48e
12 changed files with 802 additions and 161 deletions

View file

@ -322,6 +322,12 @@ pub struct Coordinator {
/// published and never attached to an agent's sensory input.
audio: BTreeMap<String, flybus::Artifact>,
pending_audio: BTreeMap<String, flybus::Artifact>,
/// Sealed copies of in-memory media being made for this boundary's publication, by the
/// in-memory artifact's id (PERF-01): begun as soon as `Environment.Advance` answers, so the
/// store round trips overlap the task's evaluation and the commits.
promoting: BTreeMap<String, tokio::task::JoinHandle<DomainResult<flybus::Artifact>>>,
/// [`Coordinator::defer_snapshots`].
defer_snapshots: bool,
/// One chunk sequence per declared audio stream, for this epoch.
timelines: AudioTimelines,
/// The attachment names this session's native media travels under. The composition
@ -367,6 +373,9 @@ pub struct Coordinator {
commit_attachments: Vec<String>,
/// Record [`StepDetails`] for every transition (a parity run).
record_details: bool,
/// Digest every view into the step details (on with them by default; a service that reads
/// the details only for the commit attachments turns it off).
digest_views: bool,
last_details: Option<StepDetails>,
/// Audience admissions: queued by the edge, cut into the next Prepare.
admissions: AdmissionQueue,
@ -464,6 +473,8 @@ impl Coordinator {
pending_views: BTreeMap::new(),
audio: BTreeMap::new(),
pending_audio: BTreeMap::new(),
promoting: BTreeMap::new(),
defer_snapshots: false,
timelines: AudioTimelines::default(),
media_names: vec![
media::view_attachment(crate::environment::VIEW_ID),
@ -495,6 +506,7 @@ impl Coordinator {
environment_capabilities: Vec::new(),
commit_attachments: Vec::new(),
record_details: false,
digest_views: true,
last_details: None,
admissions: AdmissionQueue::default(),
in_flight_admissions: Vec::new(),
@ -594,6 +606,20 @@ impl Coordinator {
.collect()
}
/// The bytes of one media handle this committed boundary holds, by attachment name (the
/// view or an audio chunk), or `None` when the boundary holds no such handle. (The same
/// method as SERVE-01's service host reads the step's audio with.)
pub async fn media_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, String> {
let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else {
return Ok(None);
};
artifact
.read_all()
.await
.map(Some)
.map_err(|e| format!("reading {name}: {}", e.message))
}
/// Where each declared audio stream's next chunk may start.
pub fn audio_positions(&self) -> BTreeMap<String, u64> {
self.timelines.positions()
@ -648,6 +674,14 @@ impl Coordinator {
/// (`publishing-v1`), and the legacy feed publishes at `snapshot_hz` (30 Hz) from its 60 Hz
/// loop, so a live composition need not pay a publication on every frame. 1 (every boundary)
/// by default.
/// Publishes committed snapshots without waiting for the router's admission (PERF-01): the
/// bus publish runs beside the next transition and its outcome is settled at the next
/// snapshot, in order, so a session fault still fails the epoch, one publication later.
/// Off by default; the legacy composition's service configuration turns it on.
pub fn defer_snapshots(&mut self, on: bool) {
self.defer_snapshots = on;
}
pub fn snapshot_every(&mut self, n: u64) {
self.snapshot_every = n.max(1);
}
@ -833,6 +867,13 @@ impl Coordinator {
self.record_details = on;
}
/// Whether recorded step details carry each view's SHA-256 (`StepDetails::view_digests`):
/// on by default; SERVE-01's service host reads the details for the commit attachments only
/// and turns it off, which saves hashing every frame.
pub fn digest_views(&mut self, on: bool) {
self.digest_views = on;
}
/// The details of the last completed transition, when they are recorded.
pub fn take_details(&mut self) -> Option<StepDetails> {
self.last_details.take()
@ -2320,6 +2361,9 @@ impl Coordinator {
let span = crate::profile::span("coord.advance");
let step_result = self.advance(k, &batch_id, &controls).await?;
drop(span);
if self.snapshot_every <= 1 || (k + 1).is_multiple_of(self.snapshot_every) {
self.begin_promotions();
}
let span = crate::profile::span("coord.observe");
// ---- Phase C: observe and evaluate the task once
@ -2452,7 +2496,7 @@ impl Coordinator {
self.admissions.set_remaining(agent_id, result.telemetry.stimulus_remaining_ms);
}
let view_digests = if self.record_details {
let view_digests = if self.record_details && self.digest_views {
self.view_digests(&step_result.observation).await?
} else {
Vec::new()
@ -2521,6 +2565,7 @@ impl Coordinator {
slot.prepared = None;
slot.prepare_request = None;
}
let publish_span = crate::profile::span("coord.publish");
self.publish_events(k + 1, &evaluation.events).await?;
// Every boundary with events or boundary actions is published; otherwise every
// `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at
@ -2532,6 +2577,7 @@ impl Coordinator {
{
self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?;
}
drop(publish_span);
// A rollback request was applied above and is not an episode end; only a terminal one
// pauses the session for the episode policy.
@ -2571,6 +2617,41 @@ impl Coordinator {
Ok(reports)
}
/// Starts sealing a bus copy of every in-memory medium the boundary just produced, for its
/// publication ([`Coordinator::publication_handle`]).
fn begin_promotions(&mut self) {
for (_, stale) in std::mem::take(&mut self.promoting) {
stale.abort();
}
for artifact in self.pending_views.values().chain(self.pending_audio.values()) {
if artifact.is_in_memory() {
let (bus, artifact) = (self.bus.clone(), artifact.clone());
let id = artifact.reference().artifact_id.clone();
self.promoting.insert(
id,
tokio::spawn(async move { crate::rpc::promote(&bus, &artifact).await }),
);
}
}
}
/// The handle a publication attaches for `artifact`: the handle itself when it is sealed in
/// the router's store, else the sealed copy begun at the Advance, or one made now.
async fn publication_handle(
&mut self,
artifact: &flybus::Artifact,
) -> DomainResult<flybus::Artifact> {
if !artifact.is_in_memory() {
return Ok(artifact.clone());
}
match self.promoting.remove(&artifact.reference().artifact_id) {
Some(task) => task.await.map_err(|e| {
DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None)
})?,
None => crate::rpc::promote(&self.bus, artifact).await,
}
}
fn batch_id(&self, k: u64) -> Id {
parse_id(&format!("batch-{}-{k}", self.epoch)).expect("epoch and step make an Id")
}
@ -3323,7 +3404,7 @@ impl Coordinator {
}
// Step 5: every reply in hand. The session is at Ready(e', k).
let view_digests = if self.record_details {
let view_digests = if self.record_details && self.digest_views {
let mut out = Vec::new();
for view in &restored.sensory_views {
let name = media::view_attachment(&view.view_id);
@ -4116,6 +4197,33 @@ impl Coordinator {
}
}
}
// In-memory media (the local lane) cross the router as sealed copies: the snapshot names
// the copies it attaches (the PERF-01 amendment).
let mut snapshot = snapshot;
for (_, artifact) in attachments.iter_mut() {
if !artifact.is_in_memory() {
continue;
}
let copy = match self.publication_handle(artifact).await {
Ok(copy) => copy,
Err(e) => return Err(self.fail_now(e, "publish")),
};
let (old, new) = (artifact.reference().clone(), copy.reference().clone());
for view in &mut snapshot.views {
if view.pixels == old {
view.pixels = new.clone();
}
}
for chunk in &mut snapshot.audio {
if chunk.samples == old {
chunk.samples = new.clone();
}
}
*artifact = copy;
}
for (_, unused) in std::mem::take(&mut self.promoting) {
unused.abort();
}
if self.injections.substituted_published_handle && self.injections.at_step + 1 == boundary {
// The same attachment name and the same bytes, a different object. Only the
// artifact identity sees it, which is why the check compares that and not names.
@ -4159,6 +4267,25 @@ impl Coordinator {
});
}
let positions = self.timelines.positions();
if self.defer_snapshots {
// The previous snapshot's outcome is settled here; this one's at the next.
let previous = match self
.publisher
.publish_snapshot_deferred(&descriptor, &snapshot, &attachments, &positions)
.await
{
Ok(previous) => previous,
Err(e) => return Err(self.fail_now(e, "publish")),
};
self.audit.push(format!("publish:{boundary}"));
if let Some(outcome) = previous {
let outcome = self.settle(outcome, "publish")?;
if outcome.is_accepted() {
self.stats.publications += 1;
}
}
return Ok(());
}
let outcome = match self
.publisher
.publish_snapshot(&descriptor, &snapshot, &attachments, &positions)

View file

@ -42,6 +42,10 @@ use crate::worker::{StatusCell, WorkerHandle, serve};
pub enum Via {
Memory,
Unix,
/// In memory, and every in-process participant is also offered over its local lane
/// ([`crate::worker::LocalLane`], PERF-01): its endpoint methods are called without a bus
/// message. A thread or a separate process still reaches the router over its socket.
Local,
}
/// Where a participant runs.
@ -340,6 +344,8 @@ pub struct LaunchedWorker {
pub peak_rss_kib: u64,
body: Body,
status: Option<StatusCell>,
/// The local lane a reference carries, when the launcher offers it.
local: Option<crate::worker::LocalLane>,
/// The per-participant socket endpoint, kept alive for the connection's lifetime.
_listener: Option<UnixListenerHandle>,
}
@ -354,6 +360,7 @@ impl LaunchedWorker {
&self.identity.worker_id,
);
r.domain_incarnation = Some(self.domain_incarnation.clone());
r.local = self.local.clone();
r
}
@ -419,7 +426,7 @@ impl Endpoints {
/// A connection this process owns, over the configured transport.
async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> {
let transport = match self.via {
Via::Memory => self.router.connect_in_memory_as(client_id),
Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id),
Via::Unix => {
let path = self.socket_path(client_id);
let listener = self.listen(&path, client_id).await?;
@ -471,6 +478,8 @@ pub struct Launcher {
supervisor: Client,
workers: BTreeMap<Id, LaunchedWorker>,
serial: u64,
/// Whether an in-process participant's reference carries its local lane (PERF-01).
local_lane: bool,
}
/// The bus client id the supervisor connects under.
@ -534,9 +543,18 @@ impl Launcher {
supervisor,
workers: BTreeMap::new(),
serial: 0,
local_lane: mode == ExecutionMode::InProcess && via == Via::Local,
})
}
/// Offers every in-process participant launched from now on over the local lane
/// ([`crate::worker::LocalLane`]): its [`LaunchedWorker::worker_ref`] carries the lane, so a
/// coordinator in this process calls its endpoint methods without the bus. A thread or a
/// separate process has no lane and is always reached over the bus.
pub fn use_local_lane(&mut self, on: bool) {
self.local_lane = on;
}
pub fn mode(&self) -> ExecutionMode {
self.mode
}
@ -742,6 +760,10 @@ impl Launcher {
Body::Process(Some(child)) => Some(child.id()),
_ => None,
};
let local = match &body {
Body::Task(Some(handle)) if self.local_lane => Some(handle.local.clone()),
_ => None,
};
// The registration is discovered, not assumed: the launcher says hello with the
// identity it configured, and the reply is what the coordinator later pins.
let identified = self.identify(identity).await;
@ -756,6 +778,7 @@ impl Launcher {
peak_rss_kib: 0,
body,
status,
local: None,
_listener: listener,
};
terminate(&mut dying);
@ -770,6 +793,7 @@ impl Launcher {
peak_rss_kib: 0,
body,
status,
local,
_listener: listener,
};
worker.refresh_rss();

View file

@ -402,9 +402,21 @@ pub fn spike_bitset(last_spike_ms: &[f64], since_ms: f64, now_ms: f64) -> Vec<u8
if now_ms <= since_ms {
return bytes;
}
for (index, last) in last_spike_ms.iter().enumerate() {
if *last >= since_ms {
bytes[index >> 3] |= 1 << (index & 7);
// Eight neurons per byte, branch-free, so the compiler vectorises the comparison (PERF-01:
// 139,255 neurons a frame). The same `last >= since` test as the bit-at-a-time loop.
let chunks = last_spike_ms.chunks_exact(8);
let tail = chunks.remainder();
for (byte, chunk) in bytes.iter_mut().zip(chunks) {
let mut bits = 0u8;
for (bit, last) in chunk.iter().enumerate() {
bits |= u8::from(*last >= since_ms) << bit;
}
*byte = bits;
}
if !tail.is_empty() {
let at = last_spike_ms.len() / 8;
for (bit, last) in tail.iter().enumerate() {
bytes[at] |= u8::from(*last >= since_ms) << bit;
}
}
bytes
@ -1042,6 +1054,9 @@ impl LegacyAgentWorker {
let brain_ticks = accumulator.brain_ticks();
let remainder = accumulator.remainder();
self.transition_start_ms = agent.network.ms;
// Profiling runs the brain's own phase clock too, as a measured legacy loop does, so
// the two brains carry the same instrumentation (PERF-01).
agent.network.profile = crate::profile::enabled();
let ticks_span = crate::profile::span("agent.ticks");
agent.network.step(ticks);
drop(ticks_span);
@ -1196,7 +1211,8 @@ impl LegacyAgentWorker {
telemetry: self.telemetry(),
};
let _seal_span = crate::profile::span("agent.seal_spikes");
let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
let artifact = ctx
.seal(SPIKES_CONTENT_TYPE, spikes)
.await
.map_err(|e| applied(e.code, e.message))?;
self.status.set_state(WorkerState::Ready);
@ -1862,6 +1878,46 @@ mod tests {
);
}
#[test]
fn the_bytewise_spike_bitset_is_the_bit_at_a_time_one() {
// PERF-01 replaced the per-neuron loop; every length and window agrees with it,
// including NaN (never >=) and infinities.
fn reference(last: &[f64], since: f64, now: f64) -> Vec<u8> {
let mut bytes = vec![0u8; last.len().div_ceil(8)];
if now <= since {
return bytes;
}
for (index, value) in last.iter().enumerate() {
if *value >= since {
bytes[index >> 3] |= 1 << (index & 7);
}
}
bytes
}
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for len in 0..40usize {
for _ in 0..20 {
let last: Vec<f64> = (0..len)
.map(|_| match next() % 10 {
0 => f64::NAN,
1 => f64::NEG_INFINITY,
2 => -1_000_000.0,
n => (n * 3) as f64,
})
.collect();
let since = (next() % 30) as f64;
let now = since + (next() % 3) as f64;
assert_eq!(spike_bitset(&last, since, now), reference(&last, since, now));
}
}
}
#[test]
fn the_macro_in_a_decision_is_the_first_bound_channel_held() {
let active = vec![

View file

@ -854,7 +854,7 @@ impl LegacyGameboyEnvironment {
/// if there was one.
async fn observation(
live: &mut Live,
client: &flybus::Client,
ctx: &HandlerCtx<'_>,
audio: Option<Vec<u8>>,
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
let image = {
@ -868,16 +868,15 @@ impl LegacyGameboyEnvironment {
}
let audio_f32 = audio.as_deref().map(audio_f32le);
// The three artifacts are independent: they are sealed concurrently, so the boundary
// waits for the router's round trips once rather than three times.
// waits for the router's round trips once rather than three times. Over the local lane
// each is an in-memory artifact owning its bytes (`HandlerCtx::seal`).
let seal_span = crate::profile::span("env.seal");
let (frame, memory, samples) = tokio::join!(
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer),
media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image),
ctx.seal(FRAME_CONTENT_TYPE, live.framebuffer.to_vec()),
ctx.seal(MEMORY_CONTENT_TYPE, image),
async {
match &audio_f32 {
Some(bytes) => media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), bytes)
.await
.map(Some),
match audio_f32 {
Some(bytes) => ctx.seal(AUDIO_CONTENT_TYPE, bytes).await.map(Some),
None => Ok(None),
}
}
@ -998,7 +997,7 @@ impl LegacyGameboyEnvironment {
audio_discontinuity: false,
};
let (observation, attachments) =
LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?;
LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?;
self.live = Some(live);
// The world is stopped when O[0] goes out and cannot free-run while the brain warms up.
self.status.set_state(WorkerState::Ready);
@ -1074,7 +1073,7 @@ impl LegacyGameboyEnvironment {
status.progress(1);
let (observation, attachments) =
LegacyGameboyEnvironment::observation(live, ctx.client, Some(audio)).await?;
LegacyGameboyEnvironment::observation(live, ctx, Some(audio)).await?;
let result = StepResult {
batch_id: params.batch_id,
applied_from_step: applied_from,
@ -1170,7 +1169,7 @@ impl LegacyGameboyEnvironment {
live.batches.clear();
live.audio_discontinuity = true;
let (observation, attachments) =
LegacyGameboyEnvironment::observation(live, ctx.client, None).await?;
LegacyGameboyEnvironment::observation(live, ctx, None).await?;
status.set_state(WorkerState::Ready);
status.set_scope(Some(scope.clone()));
status.progress(1);
@ -1435,7 +1434,7 @@ impl LegacyGameboyEnvironment {
audio_discontinuity: true,
};
let (observation, attachments) =
LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?;
LegacyGameboyEnvironment::observation(&mut live, ctx, None).await?;
self.live = Some(live);
self.activated.insert(token);
self.status.set_state(WorkerState::Ready);

View file

@ -11,7 +11,12 @@ use std::sync::atomic::{AtomicU8, Ordering};
use std::time::{Duration, Instant};
static STATE: AtomicU8 = AtomicU8::new(0); // 0 unknown, 1 off, 2 on
static TABLE: Mutex<BTreeMap<&'static str, (u64, Duration)>> = Mutex::new(BTreeMap::new());
static TABLE: Mutex<BTreeMap<&'static str, (u64, Duration, Duration)>> = Mutex::new(BTreeMap::new());
/// Whether profiling is on for this process (`FLY_SESSION_PROFILE`).
pub fn enabled() -> bool {
on()
}
fn on() -> bool {
match STATE.load(Ordering::Relaxed) {
@ -39,9 +44,11 @@ impl Drop for Span {
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = table.entry(name).or_insert((0, Duration::ZERO));
let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO));
let elapsed = started.elapsed();
entry.0 += 1;
entry.1 += started.elapsed();
entry.1 += elapsed;
entry.2 = entry.2.max(elapsed);
}
}
}
@ -53,7 +60,22 @@ pub fn report() -> Vec<(&'static str, u64, Duration)> {
.unwrap_or_else(std::sync::PoisonError::into_inner);
let out = table
.iter()
.map(|(name, (count, total))| (*name, *count, *total / (*count).max(1) as u32))
.map(|(name, (count, total, _))| (*name, *count, *total / (*count).max(1) as u32))
.collect();
table.clear();
out
}
/// As [`report`], with each span's longest single sample: `(name, count, mean, max)`.
pub fn report_with_max() -> Vec<(&'static str, u64, Duration, Duration)> {
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let out = table
.iter()
.map(|(name, (count, total, max))| {
(*name, *count, *total / (*count).max(1) as u32, *max)
})
.collect();
table.clear();
out

View file

@ -508,6 +508,9 @@ pub struct Publisher {
state: SharedState,
ledger: Ledger,
sequence: u64,
/// The snapshot publish still waiting for the router's admission, when snapshots are
/// published without waiting ([`Publisher::publish_snapshot_deferred`], PERF-01).
in_flight: Option<(String, tokio::task::JoinHandle<Result<flybus::PublishReceipt, flybus::BusError>>)>,
}
impl Publisher {
@ -529,6 +532,7 @@ impl Publisher {
state: Arc::new(Mutex::new(PublishedState::default())),
ledger: Ledger::default(),
sequence: 0,
in_flight: None,
}
}
@ -635,8 +639,31 @@ impl Publisher {
.map(|(name, artifact)| (name.clone(), artifact.reference().clone()))
.collect();
check_publication(descriptor, snapshot, &named, audio_next_sample)?;
let refs: Vec<(&str, &flybus::Artifact)> =
attachments.iter().map(|(n, a)| (n.as_str(), a)).collect();
// An in-memory artifact (the in-process local lane) is in no router's store, so the
// published message carries a sealed copy of it and names that copy: the coherence
// check above ran against the handles the agents were given.
let mut published = std::borrow::Cow::Borrowed(snapshot);
let mut sealed = Vec::with_capacity(attachments.len());
for (name, artifact) in attachments {
let copy = crate::rpc::promote(&self.bus, artifact).await?;
if copy.reference() != artifact.reference() {
let (old, new) = (artifact.reference(), copy.reference());
let snapshot = published.to_mut();
for view in &mut snapshot.views {
if &view.pixels == old {
view.pixels = new.clone();
}
}
for chunk in &mut snapshot.audio {
if &chunk.samples == old {
chunk.samples = new.clone();
}
}
}
sealed.push((name.as_str(), copy));
}
let refs: Vec<(&str, &flybus::Artifact)> = sealed.iter().map(|(n, a)| (*n, a)).collect();
let snapshot = published.as_ref();
let topic = self.snapshot_topic.topic.clone();
let outcome = PublicationOutcome::from_bus(
&topic,
@ -655,6 +682,61 @@ impl Publisher {
Ok(outcome)
}
/// As [`Publisher::publish_snapshot`], without waiting for the router: the value is checked,
/// numbered and recorded now, and the bus publish runs beside the next transition. Returns
/// the outcome of the **previous** deferred snapshot, settled first, so snapshots reach the
/// topic in order and a fault is still reported, one publication later (PERF-01).
pub async fn publish_snapshot_deferred(
&mut self,
descriptor: &SessionDescriptor,
snapshot: &CommittedSnapshot,
attachments: &[(String, flybus::Artifact)],
audio_next_sample: &BTreeMap<String, u64>,
) -> DomainResult<Option<PublicationOutcome>> {
let previous = self.settle_in_flight().await;
let named: Vec<(String, ArtifactRef)> = attachments
.iter()
.map(|(name, artifact)| (name.clone(), artifact.reference().clone()))
.collect();
check_publication(descriptor, snapshot, &named, audio_next_sample)?;
let mut sealed = Vec::with_capacity(attachments.len());
for (name, artifact) in attachments {
if artifact.is_in_memory() {
return Err(DomainError::invalid(format!(
"attachment {name} is in memory; the coordinator attaches sealed copies"
)));
}
sealed.push((name.clone(), artifact.clone()));
}
let topic = self.snapshot_topic.topic.clone();
let (bus, payload, publish_topic) =
(self.bus.clone(), object(snapshot.to_json()), topic.clone());
self.in_flight = Some((
topic,
tokio::spawn(async move {
let refs: Vec<(&str, &flybus::Artifact)> =
sealed.iter().map(|(n, a)| (n.as_str(), a)).collect();
bus.publish(&publish_topic, payload, &refs).await
}),
));
self.sequence += 1;
lock(&self.state).latest = Some(snapshot.clone());
Ok(previous)
}
/// Waits for the deferred snapshot publish still in flight, records its outcome and
/// returns it; `None` when there is none.
pub async fn settle_in_flight(&mut self) -> Option<PublicationOutcome> {
let (topic, task) = self.in_flight.take()?;
let result = match task.await {
Ok(result) => result,
Err(e) => Err(flybus::BusError::new(flybus::ErrorCode::RouterLost, e.to_string())),
};
let outcome = PublicationOutcome::from_bus(&topic, result);
self.ledger.record(&outcome);
Some(outcome)
}
/// Offers this boundary's events to the bounded batch and publishes what it holds.
///
/// An empty batch publishes nothing and is not an outcome. A refused batch is held for the

View file

@ -20,6 +20,10 @@ pub struct WorkerRef {
pub worker_id: Id,
/// The domain `incarnationId` Hello negotiated, once it has.
pub domain_incarnation: Option<Id>,
/// The worker's shell in this process, when the launcher offers it (PERF-01): endpoint
/// methods then go over the local lane instead of the bus. Same shell, same admission,
/// same outcomes; no router in between.
pub local: Option<crate::worker::LocalLane>,
}
impl WorkerRef {
@ -29,6 +33,7 @@ impl WorkerRef {
bus_incarnation: bus_incarnation.to_owned(),
worker_id: worker_id.clone(),
domain_incarnation: None,
local: None,
}
}
}
@ -79,11 +84,16 @@ pub async fn call(
/// sent after it to the same worker is dispatched after it.
pub struct SentCall {
method: String,
pending: flybus::PendingCall,
pending: Pending,
request_id: DomainRequestId,
want_artifacts: Vec<String>,
}
enum Pending {
Bus(flybus::PendingCall),
Local(crate::worker::LocalPending),
}
/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits).
#[allow(clippy::too_many_arguments)]
pub async fn send(
@ -97,6 +107,26 @@ pub async fn send(
want_artifacts: &[String],
) -> Result<SentCall, DomainError> {
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
if let Some(lane) = &target.local
&& crate::worker::local_lane_carries(method)
{
let attachments = attachments
.iter()
.map(|(name, artifact)| ((*name).to_owned(), (*artifact).clone()))
.collect();
let pending = lane.send(method, request, attachments).await?;
return Ok(SentCall {
method: method.to_owned(),
pending: Pending::Local(pending),
request_id,
want_artifacts: want_artifacts.to_vec(),
});
}
// An in-memory artifact is in no router's store: a bus call carries a sealed copy of it.
let promoted = promote_all(bus, attachments).await?;
let attachments: Vec<(&str, &flybus::Artifact)> =
promoted.iter().map(|(n, a)| (n.as_str(), a)).collect();
let attachments = attachments.as_slice();
let pending = bus
.call(
&target.service,
@ -109,7 +139,7 @@ pub async fn send(
.map_err(|e| bus_error(method, &e))?;
Ok(SentCall {
method: method.to_owned(),
pending,
pending: Pending::Bus(pending),
request_id,
want_artifacts: want_artifacts.to_vec(),
})
@ -117,9 +147,39 @@ pub async fn send(
impl SentCall {
/// Waits for the terminal reply.
pub async fn finish(mut self) -> Result<DomainReply, DomainError> {
pub async fn finish(self) -> Result<DomainReply, DomainError> {
let method = self.method.as_str();
let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?;
let mut pending = match self.pending {
Pending::Bus(pending) => pending,
Pending::Local(pending) => {
let reply = pending.finish().await.ok_or_else(|| {
DomainError::new(
ErrorCode::BackendFailure,
format!("{method}: the worker stopped before it answered"),
MutationCertainty::Unknown,
)
})?;
// The handles are the worker's own (in memory, or sealed holds its cache
// keeps too); only the wanted ones are kept, as the bus path extracts.
// A sealed handle is only valid as an attachment on the worker's own
// connection, so a sealed reply artifact (a handler that sealed through the
// bus) reaches the caller in memory, under the same reference.
let mut artifacts = BTreeMap::new();
for (name, artifact) in reply.artifacts {
if !self.want_artifacts.contains(&name) {
continue;
}
let artifact = artifact.to_memory().await.map_err(|e| bus_error(method, &e))?;
artifacts.insert(name, artifact);
}
return Ok(DomainReply {
outcome: reply.outcome,
request_id: self.request_id,
artifacts,
});
}
};
let result = pending.result().await.map_err(|e| bus_error(method, &e))?;
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
// An independent explicit hold on each wanted attachment, so the handle outlives this
@ -152,6 +212,32 @@ impl SentCall {
}
}
/// Every attachment as a bus artifact: sealed handles as they are, in-memory ones as a sealed
/// copy in the caller's store.
pub async fn promote_all(
bus: &flybus::Client,
attachments: &[(&str, &flybus::Artifact)],
) -> Result<Vec<(String, flybus::Artifact)>, DomainError> {
let mut out = Vec::with_capacity(attachments.len());
for (name, artifact) in attachments {
out.push(((*name).to_owned(), promote(bus, artifact).await?));
}
Ok(out)
}
/// One artifact as a bus artifact ([`promote_all`]).
pub async fn promote(
bus: &flybus::Client,
artifact: &flybus::Artifact,
) -> Result<flybus::Artifact, DomainError> {
match artifact.memory() {
None => Ok(artifact.clone()),
Some(bytes) => {
crate::media::seal_copy(bus, artifact.reference().content_type.clone(), bytes).await
}
}
}
/// Maps a bus failure onto a domain error, preserving how certain the mutation is.
fn bus_error(method: &str, e: &flybus::BusError) -> DomainError {
let mutation = match e.dispatch {

View file

@ -159,7 +159,29 @@ pub struct HandlerCtx<'a> {
pub method: &'a str,
pub request: &'a SessionRpcRequest,
pub client: &'a flybus::Client,
pub incoming: &'a flybus::Request,
pub incoming: &'a Incoming,
}
/// How a domain request reached the shell, and so where its attachments are.
pub enum Incoming {
/// A bus request delivery: the attachments are the delivery's.
Bus(flybus::Request),
/// The in-process local lane ([`LocalLane`]): the caller's own handles, in memory or
/// sealed, handed over without a bus message.
Local(Vec<(String, flybus::Artifact)>),
}
impl Incoming {
fn artifact(&self, name: &str) -> Result<flybus::Artifact, String> {
match self {
Incoming::Bus(request) => request.artifact(name).map_err(|e| e.message),
Incoming::Local(list) => list
.iter()
.find(|(n, _)| n == name)
.map(|(_, a)| a.clone())
.ok_or_else(|| format!("no attachment named {name:?}")),
}
}
}
impl HandlerCtx<'_> {
@ -185,10 +207,25 @@ impl HandlerCtx<'_> {
self.incoming.artifact(name).map_err(|e| {
DomainError::before(
ErrorCode::BufferInvalid,
format!("attachment {name:?} is missing or unowned: {}", e.message),
format!("attachment {name:?} is missing or unowned: {e}"),
)
})
}
/// True when the request came over the in-process local lane.
pub fn is_local(&self) -> bool {
matches!(self.incoming, Incoming::Local(_))
}
/// One immutable reply artifact holding `bytes`. Over the local lane it is an in-memory
/// artifact that owns `bytes` (no copy, no store file, no router round trip); over the bus
/// it is allocated, written and sealed in the router's store as before.
pub async fn seal(&self, content_type: &str, bytes: Vec<u8>) -> DomainResult<flybus::Artifact> {
if self.is_local() {
return Ok(flybus::Artifact::in_memory(content_type, bytes));
}
crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await
}
}
/// A handler's boxed future, so the endpoint trait stays dyn-compatible.
@ -231,6 +268,8 @@ pub struct WorkerHandle {
pub service_incarnation: String,
pub status: StatusCell,
pub cache: Arc<tokio::sync::Mutex<ResultCache>>,
/// The same shell, reachable without the bus by a caller in this process.
pub local: LocalLane,
task: tokio::task::JoinHandle<()>,
client: flybus::Client,
}
@ -248,6 +287,7 @@ impl WorkerHandle {
/// Stops serving and closes the worker's bus connection, which drops its registration and
/// every owner it held. A later reply from it can attach to nothing.
pub async fn stop(self) {
self.local.close();
self.task.abort();
let _ = self.task.await;
self.client.close().await;
@ -257,6 +297,7 @@ impl WorkerHandle {
/// dropped, which this does. For a supervisor's `Drop`, where there is no runtime to wait
/// on.
pub fn abort(self) {
self.local.close();
self.task.abort();
}
@ -266,10 +307,157 @@ impl WorkerHandle {
/// the process's exit are the same event rather than two racing ones.
pub async fn join(self) {
let _ = self.task.await;
self.local.close();
self.client.close().await;
}
}
// -------------------------------------------------------------------------------------------
// The in-process local lane (PERF-01)
/// A terminal domain reply delivered over the local lane, with the artifacts it attaches.
pub struct LocalReply {
pub outcome: SessionRpcOutcome,
pub artifacts: Vec<(String, flybus::Artifact)>,
}
/// A request admitted by the local lane and not yet answered. Like an admitted bus call, it is
/// in the worker's order already: a request sent after it to the same worker runs after it.
pub struct LocalPending(tokio::sync::oneshot::Receiver<LocalReply>);
impl LocalPending {
/// Waits for the terminal reply. `None` when the worker stopped before answering, which
/// the caller treats exactly as a bus call whose connection was lost.
pub async fn finish(self) -> Option<LocalReply> {
self.0.await.ok()
}
}
/// What the local lane dispatches into: one worker's shell, the same one its bus loop uses.
trait LocalDispatch: Send + Sync {
fn send(
&self,
method: String,
request: SessionRpcRequest,
attachments: Vec<(String, flybus::Artifact)>,
) -> BoxFuture<'_, Result<LocalPending, DomainError>>;
fn close(&self);
}
/// A handle on a worker's shell for a caller in the same process (`workers-v1` PERF-01
/// amendment). A request sent this way goes through exactly the admission a bus request goes
/// through -- deduplication and the operation key, the result cache, the arrival-order lock and
/// the endpoint -- and returns the same `SessionRpcOutcome`; only the transport differs: no bus
/// message, no router, and reply artifacts the handler may keep in memory
/// ([`HandlerCtx::seal`]). The common `Worker.*` methods are not served here: they stay on the
/// bus, where the supervisor asks them.
#[derive(Clone)]
pub struct LocalLane(Arc<dyn LocalDispatch>);
impl std::fmt::Debug for LocalLane {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("LocalLane")
}
}
impl LocalLane {
/// Admits one domain request in this worker's order and returns without waiting for it
/// to execute. Refuses what the bus loop would answer without entering the endpoint's
/// order (the common methods) with UNSUPPORTED, before any mutation.
pub async fn send(
&self,
method: &str,
request: SessionRpcRequest,
attachments: Vec<(String, flybus::Artifact)>,
) -> Result<LocalPending, DomainError> {
self.0.send(method.to_owned(), request, attachments).await
}
fn close(&self) {
self.0.close();
}
}
/// True for a method the local lane carries: every method the shell admits through its
/// result cache into the endpoint. `Worker.*` stays on the bus.
pub fn local_lane_carries(method: &str) -> bool {
matches!(classify_default(method), Some(OpClass::StepMutation | OpClass::Lifecycle))
}
/// How the shell answers one request: over the bus, or into a local waiter.
enum Answer {
Bus(flybus::Responder),
Local(tokio::sync::oneshot::Sender<LocalReply>),
}
impl Answer {
async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) {
match self {
Answer::Bus(responder) => {
let list: Vec<(&str, &flybus::Artifact)> =
artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
let _ = responder.reply(outcome.to_outcome(), &list).await;
}
Answer::Local(tx) => {
let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() });
}
}
}
}
/// Everything fixed about one worker's shell, shared by its bus loop and its local lane.
struct Shell<E> {
client: flybus::Client,
endpoint: Arc<tokio::sync::Mutex<E>>,
cache: Arc<tokio::sync::Mutex<ResultCache>>,
order: Arc<LockOrder>,
status: StatusCell,
worker_id: Id,
incarnation_id: Id,
session_id: Id,
methods: Vec<&'static str>,
/// Admission is one request at a time across both lanes, so tickets follow arrival.
admission: tokio::sync::Mutex<()>,
closed: std::sync::atomic::AtomicBool,
/// The admitted mutations' tasks, awaited when the shell stops.
running: Mutex<Vec<tokio::task::JoinHandle<()>>>,
}
/// The local lane's hold on a shell.
struct ShellRef<E>(Arc<Shell<E>>);
impl<E: WorkerEndpoint> LocalDispatch for ShellRef<E> {
fn send(
&self,
method: String,
request: SessionRpcRequest,
attachments: Vec<(String, flybus::Artifact)>,
) -> BoxFuture<'_, Result<LocalPending, DomainError>> {
let shell = &self.0;
Box::pin(async move {
if shell.closed.load(std::sync::atomic::Ordering::SeqCst) {
return Err(DomainError::before(
ErrorCode::IdentityMismatch,
format!("{method}: the worker {} has stopped", shell.worker_id),
));
}
if !local_lane_carries(&method) {
return Err(DomainError::before(
ErrorCode::Unsupported,
format!("{method} is not carried by the local lane"),
));
}
let (tx, rx) = tokio::sync::oneshot::channel();
shell.admit(method, request, Incoming::Local(attachments), Answer::Local(tx)).await;
Ok(LocalPending(rx))
})
}
fn close(&self) {
self.0.closed.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
/// Registers `service_name` and serves `endpoint` on it until the service ends or Shutdown.
pub fn serve<E: WorkerEndpoint>(
client: flybus::Client,
@ -282,7 +470,30 @@ pub fn serve<E: WorkerEndpoint>(
let service_name = service.name().to_owned();
let service_incarnation = service.incarnation().to_owned();
let cache = Arc::new(tokio::sync::Mutex::new(ResultCache::new()));
let task = tokio::spawn(run(client.clone(), service, Arc::new(tokio::sync::Mutex::new(endpoint)), cache.clone()));
// Identity and capabilities are fixed for the endpoint's lifetime, so the shell reads them
// once and never takes the endpoint mutex to answer Hello or Status.
let common = Common {
role: endpoint.role(),
capabilities: endpoint.capabilities(),
threads: endpoint.worker_threads(),
extra_ack: endpoint.acknowledge_extra_id(),
};
let shell = Arc::new(Shell {
client: client.clone(),
session_id: endpoint.session_id(),
methods: endpoint.methods(),
endpoint: Arc::new(tokio::sync::Mutex::new(endpoint)),
cache: cache.clone(),
order: Arc::new(LockOrder::default()),
status: status.clone(),
worker_id: worker_id.clone(),
incarnation_id: incarnation_id.clone(),
admission: tokio::sync::Mutex::new(()),
closed: std::sync::atomic::AtomicBool::new(false),
running: Mutex::new(Vec::new()),
});
let local = LocalLane(Arc::new(ShellRef(shell.clone())));
let task = tokio::spawn(run(shell, service, common));
WorkerHandle {
worker_id,
incarnation_id,
@ -290,36 +501,25 @@ pub fn serve<E: WorkerEndpoint>(
service_incarnation,
status,
cache,
local,
task,
client,
}
}
async fn run<E: WorkerEndpoint>(
client: flybus::Client,
mut service: flybus::Service,
endpoint: Arc<tokio::sync::Mutex<E>>,
cache: Arc<tokio::sync::Mutex<ResultCache>>,
) {
// Identity and capabilities are fixed for the endpoint's lifetime, so the shell reads them
// once and never takes the endpoint mutex to answer Hello or Status.
#[allow(clippy::type_complexity)]
let (worker_id, incarnation_id, session_id, role, capabilities, status, methods, threads, extra_ack) = {
let e = endpoint.lock().await;
(
e.worker_id(),
e.incarnation_id(),
e.session_id(),
e.role(),
e.capabilities(),
e.status_cell(),
e.methods(),
e.worker_threads(),
e.acknowledge_extra_id(),
)
};
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
let order = Arc::new(LockOrder::default());
/// What the bus loop answers without entering the endpoint.
struct Common {
role: Role,
capabilities: Vec<Id>,
threads: u64,
extra_ack: Option<Id>,
}
async fn run<E: WorkerEndpoint>(shell: Arc<Shell<E>>, mut service: flybus::Service, common: Common) {
let Common { role, capabilities, threads, extra_ack } = common;
let (worker_id, incarnation_id, session_id) =
(shell.worker_id.clone(), shell.incarnation_id.clone(), shell.session_id.clone());
let (status, cache) = (shell.status.clone(), shell.cache.clone());
while let Some(incoming) = service.next().await {
let method = incoming.method().to_owned();
let responder = incoming.responder();
@ -340,8 +540,6 @@ async fn run<E: WorkerEndpoint>(
continue;
}
};
// The contract type already validated the `req-<U64>` form when it read the envelope.
let serial = request.request_id.clone();
// The common methods never enter the endpoint mutex, so they answer during a mutation.
match method.as_str() {
@ -397,7 +595,12 @@ async fn run<E: WorkerEndpoint>(
let value = result.to_json();
let outcome =
success(&request, &worker_id, &incarnation_id, object(value));
// The local lane stops with the bus loop: nothing is admitted after a
// Shutdown on either.
shell.closed.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
// Admitted mutations still finish and answer.
shell.drain().await;
return;
}
Err(e) => {
@ -415,36 +618,60 @@ async fn run<E: WorkerEndpoint>(
}
_ => {}
}
shell
.admit(method, request, Incoming::Bus(incoming), Answer::Bus(responder))
.await;
}
shell.drain().await;
}
let class = if methods.contains(&method.as_str()) {
impl<E: WorkerEndpoint> Shell<E> {
/// Waits until every admitted mutation has answered.
async fn drain(&self) {
let running = std::mem::take(&mut *self.running.lock().expect("never poisoned"));
for task in running {
let _ = task.await;
}
}
/// Classification, deduplication and the arrival-order ticket for one endpoint request,
/// then its execution in a task of its own. Both lanes come here, one request at a time.
async fn admit(
self: &Arc<Self>,
method: String,
request: SessionRpcRequest,
incoming: Incoming,
answer: Answer,
) {
let (worker_id, incarnation_id) = (&self.worker_id, &self.incarnation_id);
let refuse = |e: DomainError, scope: Option<Scope>| {
failure(&request.request_id, worker_id, incarnation_id, scope, e)
};
// One admission at a time across both lanes: the ticket order is the arrival order.
let _admission = self.admission.lock().await;
let _span = crate::profile::span("shell.admit");
// The contract type already validated the `req-<U64>` form when it read the envelope.
let serial = request.request_id.clone();
let class = if self.methods.contains(&method.as_str()) {
classify_default(&method)
} else {
None
};
let Some(class) = class else {
let outcome = failure(
&request.request_id,
&worker_id,
&incarnation_id,
request.scope.clone(),
let outcome = refuse(
DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")),
request.scope.clone(),
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
answer.send(outcome, &[]).await;
return;
};
let body = match request.body_digest(&method) {
Ok(body) => body,
Err(e) => {
let outcome = failure(
&request.request_id,
&worker_id,
&incarnation_id,
request.scope.clone(),
DomainError::invalid(format!("{method}: {e}")),
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone());
answer.send(outcome, &[]).await;
return;
}
};
let key = match (class, &request.scope) {
@ -456,18 +683,12 @@ async fn run<E: WorkerEndpoint>(
worker_id: worker_id.clone(),
},
(OpClass::StepMutation, None) => {
let outcome = failure(
&request.request_id,
&worker_id,
&incarnation_id,
None,
DomainError::invalid(format!("{method} requires a scope")),
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None);
answer.send(outcome, &[]).await;
return;
}
_ => OperationKey {
session_id: session_id.clone(),
session_id: self.session_id.clone(),
epoch: id("lifecycle"),
step: 0,
method: method.clone(),
@ -479,55 +700,37 @@ async fn run<E: WorkerEndpoint>(
// is dereferenced, because a duplicate may arrive after its input delivery was
// consumed and needs only the cached result.
let admission = {
let mut c = cache.lock().await;
let mut c = self.cache.lock().await;
c.admit(class, &key, serial.clone(), &body)
};
match admission {
Admission::Replay(reply) => {
let _ = responder.reply(reply.outcome.to_outcome(), &reply.attachments()).await;
continue;
answer.send(reply.outcome.clone(), &reply.artifacts).await;
return;
}
Admission::Refuse(e) => {
let outcome = failure(
&request.request_id,
&worker_id,
&incarnation_id,
request.scope.clone(),
e,
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
continue;
let outcome = refuse(e, request.scope.clone());
answer.send(outcome, &[]).await;
return;
}
Admission::Execute => {}
}
status.set_active(Some(request.request_id.clone()));
self.status.set_active(Some(request.request_id.clone()));
// The mutation runs in its own task so the shell keeps reading. That is what lets an
// exact duplicate arriving mid-execution be refused with IN_PROGRESS while the
// original bus call still completes normally. The endpoint mutex, not this loop,
// original call still completes normally. The endpoint mutex, not this loop,
// enforces one mutation at a time.
running.retain(|task| !task.is_finished());
let ticket = order.issue();
running.push(tokio::spawn(execute(
client.clone(),
endpoint.clone(),
order.clone(),
let ticket = self.order.issue();
let task = tokio::spawn(execute(
self.clone(),
ticket,
cache.clone(),
status.clone(),
worker_id.clone(),
incarnation_id.clone(),
class,
key,
serial,
body,
method,
request,
incoming,
)));
}
for task in running {
let _ = task.await;
Admitted { class, key, serial, body, method, request, incoming },
answer,
));
let mut running = self.running.lock().expect("never poisoned");
running.retain(|task| !task.is_finished());
running.push(task);
}
}
@ -591,34 +794,36 @@ async fn futures_poll_once<F: std::future::Future + Unpin>(mut f: F) -> Option<F
.await
}
/// Runs one admitted mutation, records its reply and answers the bus call.
#[allow(clippy::too_many_arguments)]
async fn execute<E: WorkerEndpoint>(
client: flybus::Client,
endpoint: Arc<tokio::sync::Mutex<E>>,
order: Arc<LockOrder>,
ticket: u64,
cache: Arc<tokio::sync::Mutex<ResultCache>>,
status: StatusCell,
worker_id: Id,
incarnation_id: Id,
/// One admitted request, as `execute` needs it.
struct Admitted {
class: OpClass,
key: OperationKey,
serial: DomainRequestId,
body: Digest,
method: String,
request: SessionRpcRequest,
incoming: flybus::Request,
incoming: Incoming,
}
/// Runs one admitted mutation, records its reply and answers the call.
async fn execute<E: WorkerEndpoint>(
shell: Arc<Shell<E>>,
ticket: u64,
admitted: Admitted,
answer: Answer,
) {
let responder = incoming.responder();
let Admitted { class, key, serial, body, method, request, incoming } = admitted;
let (worker_id, incarnation_id, status, cache) =
(&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache);
let outcome = {
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
// never held across a bus round trip taken by anything else.
let mut e = order.lock_in_turn(ticket, &endpoint).await;
let mut e = shell.order.lock_in_turn(ticket, &shell.endpoint).await;
let _span = crate::profile::span("shell.handle");
let ctx = HandlerCtx {
method: &method,
request: &request,
client: &client,
client: &shell.client,
incoming: &incoming,
};
e.handle(ctx).await
@ -628,30 +833,35 @@ async fn execute<E: WorkerEndpoint>(
Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await,
other => other,
};
let _span = crate::profile::span("shell.record");
match outcome {
Ok(reply) => {
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
let outcome = success(&request, worker_id, incarnation_id, reply.result.clone());
// The cache owns its own hold on every artifact, so a replay survives the first
// caller consuming its delivery. The holds are independent router round trips, so
// they are taken concurrently.
// they are taken concurrently; an in-memory artifact is its own hold.
let retains: Vec<_> = reply
.artifacts
.iter()
.map(|(name, artifact)| {
let (name, artifact) = (name.clone(), artifact.clone());
tokio::spawn(async move {
async move {
if artifact.is_in_memory() {
return (name, artifact);
}
let task = tokio::spawn(async move {
match artifact.retain().await {
Ok(hold) => (name, hold),
Err(_) => (name, artifact),
}
})
});
task.await.expect("a retain task never panics")
}
})
.collect();
let mut holds = Vec::with_capacity(retains.len());
for retain in retains {
if let Ok(pair) = retain.await {
holds.push(pair);
}
holds.push(retain.await);
}
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
{
@ -663,9 +873,7 @@ async fn execute<E: WorkerEndpoint>(
}
}
status.set_completed(request.request_id.clone());
let attachments: Vec<(&str, &flybus::Artifact)> =
reply.artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect();
let _ = responder.reply(outcome.to_outcome(), &attachments).await;
answer.send(outcome, &reply.artifacts).await;
}
Err(e) => {
if e.mutation == MutationCertainty::None {
@ -675,8 +883,8 @@ async fn execute<E: WorkerEndpoint>(
} else {
let cached = CachedReply::new(failure_outcome(
&request.request_id,
&worker_id,
&incarnation_id,
worker_id,
incarnation_id,
request.scope.clone(),
e.clone(),
));
@ -691,12 +899,12 @@ async fn execute<E: WorkerEndpoint>(
status.set_active(None);
let outcome = failure(
&request.request_id,
&worker_id,
&incarnation_id,
worker_id,
incarnation_id,
request.scope.clone(),
e,
);
let _ = responder.reply(outcome.to_outcome(), &[]).await;
answer.send(outcome, &[]).await;
}
}
}

View file

@ -29,6 +29,15 @@ macro_rules! both_transports {
}
)*
}
// PERF-01: in memory, in-process participants over their local lane.
mod local_lane {
$(
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn $name() {
super::$name($crate::common::via_local()).await
}
)*
}
};
}
@ -40,6 +49,10 @@ pub fn via_unix() -> Via {
Via::Unix
}
pub fn via_local() -> Via {
Via::Local
}
/// A started session plus the temporary directory its store lives in.
pub struct Fixture {
pub dir: tempfile::TempDir,

View file

@ -282,6 +282,7 @@ async fn a_reply_from_another_incarnation_is_rejected(via: Via) {
bus_incarnation: restarted.service_incarnation.clone(),
worker_id: fly_b(),
domain_incarnation: old.domain_incarnation.clone(),
local: None,
};
assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone()));
let err = within("status", f.harness.coordinator.status(&stale))

View file

@ -136,7 +136,21 @@ async fn one_shared_image_reaches_both_agents_through_owned_attachments(via: Via
"one snapshot carries the whole multi-agent session"
);
let last = a.last().expect("an entry per boundary");
if via == Via::Local {
// Over the local lane the agents' handle is in memory, in no router's store, so
// publication carries a sealed copy of the same bytes (the PERF-01 amendment).
assert_ne!(published.view.pixels.artifact_id, last.artifact_id);
let held = f
.harness
.coordinator
.media_bytes(&fly_session::media::view_attachment(&published.view.view_id))
.await
.unwrap()
.expect("the boundary's frame");
assert_eq!(published.artifact.read_all().await.unwrap(), held, "the same bytes");
} else {
assert_eq!(published.view.pixels.artifact_id, last.artifact_id);
}
assert_eq!(published.view.produced_step, last.produced_step);
let bytes = published.artifact.read_all().await.expect("the published frame");
assert_eq!(bytes.len() as u64, VIEW_WIDTH * VIEW_HEIGHT * 4);
@ -395,12 +409,20 @@ async fn one_audio_chunk_per_boundary_with_an_exact_sample_budget(via: Via) {
let published = frame_at(&mut spectator, STEPS).await;
let (published_chunk, artifact) = published.audio.first().expect("the published chunk");
if via == Via::Local {
// A sealed copy of the in-memory chunk (the PERF-01 amendment): same bytes, same
// position, another artifact.
assert_eq!(published_chunk.first_sample, chunk.first_sample);
assert_eq!(published_chunk.samples.byte_length, chunk.samples.byte_length);
assert_ne!(artifact.reference().artifact_id, chunk.samples.artifact_id);
} else {
assert_eq!(published_chunk.samples, chunk.samples);
assert_eq!(
artifact.reference().artifact_id,
chunk.samples.artifact_id,
"the same owned handle is published, not a copy"
);
}
let bytes = artifact.read_all().await.expect("the published chunk");
assert_eq!(bytes.len() as u64, per_step * CHANNELS * 4);
require_finite_samples(&bytes).expect("native samples are finite f32");

View file

@ -905,6 +905,7 @@ async fn an_old_worker_reply_after_a_restart_is_rejected_on_stale_epoch_or_incar
bus_incarnation: restarted.service_incarnation.clone(),
worker_id: fly_b(),
domain_incarnation: old.domain_incarnation.clone(),
local: None,
};
assert_ne!(old.domain_incarnation, Some(restarted.incarnation_id.clone()));
let err = within("status", f.harness.coordinator.status(&stale))