From 35d5a1f38df4c03de17a49744f972bd5169db92b Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 01:46:07 +0000 Subject: [PATCH 1/8] flybus: in-memory artifacts that never cross a router Artifact::in_memory holds an immutable buffer in the caller's address space (store id 'in-memory', no digest): it reads, clones and retains like any other handle without a router round trip, and a bus call, reply or publish refuses it as an attachment before anything is sent. Artifact::to_memory reads a sealed handle into one under the same reference. PERF-01's local lane hands these between participants of one process. --- .../crates/flybus/src/client/handles.rs | 167 +++++++++++++++--- .../flysim/crates/flybus/src/client/mod.rs | 6 +- services/flysim/crates/flybus/src/lib.rs | 2 +- 3 files changed, 144 insertions(+), 31 deletions(-) diff --git a/services/flysim/crates/flybus/src/client/handles.rs b/services/flysim/crates/flybus/src/client/handles.rs index b10674b..6442377 100644 --- a/services/flysim/crates/flybus/src/client/handles.rs +++ b/services/flysim/crates/flybus/src/client/handles.rs @@ -37,17 +37,25 @@ impl Drop for OwnerGuard { pub(crate) fn attachment_list( list: &[(&str, &Artifact)], -) -> (Vec, Vec>) { - let atts = list - .iter() - .map(|(name, a)| Attachment { +) -> Result<(Vec, Vec>), BusError> { + let mut atts = Vec::with_capacity(list.len()); + let mut keep = Vec::with_capacity(list.len()); + for (name, a) in list { + let Holder::Bus(owner) = &a.holder else { + // An in-memory artifact is not in any router's store, so no message may name it. + return Err(BusError::invalid(format!( + "attachment {name:?} is an in-memory artifact; seal a copy into the store first" + )) + .with_dispatch(Dispatch::NotDispatched)); + }; + atts.push(Attachment { name: (*name).to_owned(), reference: a.reference.as_ref().clone(), - owner_id: a.owner.id.clone(), - }) - .collect(); - let keep = list.iter().map(|(_, a)| a.owner.clone()).collect(); - (atts, keep) + owner_id: owner.id.clone(), + }); + keep.push(owner.clone()); + } + Ok((atts, keep)) } fn find( @@ -59,7 +67,7 @@ fn find( .find(|(n, _)| n == name) .map(|(_, r)| Artifact { reference: Arc::new(r.clone()), - owner: guard.clone(), + holder: Holder::Bus(guard.clone()), }) .ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}"))) } @@ -69,43 +77,129 @@ fn find( /// A read-only, cloneable handle on an immutable artifact. While any clone (or a file opened /// from it) lives, the owner it came from keeps the bytes alive. +/// +/// An artifact is either sealed in a router's store (every handle the bus hands out) or an +/// **in-memory** artifact ([`Artifact::in_memory`]): an immutable buffer in this address space +/// that no router knows about. The second kind is for participants that share one process and +/// hand each other buffers directly, without a bus message (PERF-01's in-process local lane); +/// it reads, clones and retains like any other handle, and it is refused as a bus attachment, +/// so it can never be named by a message a router would have to resolve. #[derive(Clone)] pub struct Artifact { pub(crate) reference: Arc, - pub(crate) owner: Arc, + pub(crate) holder: Holder, } +/// What keeps an artifact's bytes alive. +#[derive(Clone)] +pub(crate) enum Holder { + /// A router-side owner: a delivery or an explicit hold. + Bus(Arc), + /// The bytes themselves. + Memory(Arc<[u8]>), +} + +/// The store id every in-memory artifact reference carries. No router issues it: a router's +/// store ids are `store-`. +pub const IN_MEMORY_STORE_ID: &str = "in-memory"; + impl std::fmt::Debug for Artifact { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Artifact") .field("reference", &self.reference) - .field("owner", &self.owner.id) + .field("owner", &self.owner_id()) .finish() } } impl Artifact { + /// An immutable in-memory artifact holding `bytes`, with no digest. Nothing is copied. + pub fn in_memory(content_type: &str, bytes: impl Into>) -> Artifact { + use std::sync::atomic::{AtomicU64, Ordering}; + static SERIAL: AtomicU64 = AtomicU64::new(0); + let bytes: Arc<[u8]> = bytes.into(); + let serial = SERIAL.fetch_add(1, Ordering::Relaxed) + 1; + Artifact { + reference: Arc::new(ArtifactRef { + store_id: IN_MEMORY_STORE_ID.to_owned(), + artifact_id: format!("m-{serial}"), + generation: GENERATION, + byte_length: bytes.len() as u64, + content_type: content_type.to_owned(), + digest: None, + }), + holder: Holder::Memory(bytes), + } + } + pub fn reference(&self) -> &ArtifactRef { &self.reference } + /// The same artifact as an in-memory handle with the **same reference**: a sealed one is + /// read once, an in-memory one is returned as it is. For a caller in the owner's process + /// that must keep the bytes without holding the owner's connection (a handle is only valid + /// as an attachment on the connection that owns it). + pub async fn to_memory(&self) -> Result { + if self.is_in_memory() { + return Ok(self.clone()); + } + let bytes = self.read_all().await?; + if bytes.len() as u64 != self.reference.byte_length { + return Err(BusError::new( + ErrorCode::ArtifactMismatch, + "sealed bytes disagree with the reference's length", + )); + } + Ok(Artifact { + reference: self.reference.clone(), + holder: Holder::Memory(bytes.into()), + }) + } + + /// True for an [`Artifact::in_memory`] handle. + pub fn is_in_memory(&self) -> bool { + matches!(self.holder, Holder::Memory(_)) + } + + /// The bytes of an in-memory artifact, without a copy; `None` for a sealed one. + pub fn memory(&self) -> Option<&Arc<[u8]>> { + match &self.holder { + Holder::Memory(bytes) => Some(bytes), + Holder::Bus(_) => None, + } + } + /// The router-side owner this handle rides on: a delivery id or an explicit hold id. + /// An in-memory artifact has none and reports its store id. pub fn owner_id(&self) -> &str { - &self.owner.id + match &self.holder { + Holder::Bus(owner) => &owner.id, + Holder::Memory(_) => IN_MEMORY_STORE_ID, + } } /// Opens the sealed bytes read-only. The file keeps this handle (and so its owner) alive. pub async fn open(&self) -> Result { + let owner = match &self.holder { + Holder::Bus(owner) => owner, + Holder::Memory(bytes) => { + return Ok(ArtifactFile { + file: Backing::Memory(io::Cursor::new(bytes.clone())), + _artifact: self.clone(), + }); + } + }; let mut body = Map::new(); body.insert("ref".into(), self.reference.to_json()); - body.insert("ownerId".into(), self.owner.id.clone().into()); - let shared = &self.owner.conn.shared; + body.insert("ownerId".into(), owner.id.clone().into()); + let shared = &owner.conn.shared; let reply = shared .command( "artifact.open", body, Vec::new(), - vec![self.owner.clone()], + vec![owner.clone()], Hook::None, ) .await?; @@ -130,13 +224,16 @@ impl Artifact { )); } Ok(ArtifactFile { - file, + file: Backing::File(file), _artifact: self.clone(), }) } - /// Reads the whole artifact (on the blocking pool). + /// Reads the whole artifact (on the blocking pool; an in-memory one is copied in place). pub async fn read_all(&self) -> Result, BusError> { + if let Holder::Memory(bytes) = &self.holder { + return Ok(bytes.to_vec()); + } let mut file = self.open().await?; tokio::task::spawn_blocking(move || { let mut out = Vec::with_capacity(file.len() as usize); @@ -148,24 +245,29 @@ impl Artifact { } /// Creates an independent explicit hold, so the bytes outlive this handle's delivery. + /// An in-memory artifact's hold is another handle on the same bytes. pub async fn retain(&self) -> Result { + let owner = match &self.holder { + Holder::Bus(owner) => owner, + Holder::Memory(_) => return Ok(self.clone()), + }; let mut body = Map::new(); body.insert("ref".into(), self.reference.to_json()); - body.insert("ownerId".into(), self.owner.id.clone().into()); - let shared = &self.owner.conn.shared; + body.insert("ownerId".into(), owner.id.clone().into()); + let shared = &owner.conn.shared; let reply = shared .command( "artifact.retain", body, Vec::new(), - vec![self.owner.clone()], + vec![owner.clone()], Hook::Owner, ) .await?; match reply.extra { Extra::Owner(owner) => Ok(Artifact { reference: self.reference.clone(), - owner, + holder: Holder::Bus(owner), }), _ => Err(BusError::lost("retain reply without an owner")), } @@ -174,10 +276,15 @@ impl Artifact { /// An open, read-only sealed file. Holds its [`Artifact`]. pub struct ArtifactFile { - file: File, + file: Backing, _artifact: Artifact, } +enum Backing { + File(File), + Memory(io::Cursor>), +} + impl ArtifactFile { pub fn len(&self) -> u64 { self._artifact.reference.byte_length @@ -194,13 +301,19 @@ impl ArtifactFile { impl Read for ArtifactFile { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.file.read(buf) + match &mut self.file { + Backing::File(file) => file.read(buf), + Backing::Memory(cursor) => cursor.read(buf), + } } } impl Seek for ArtifactFile { fn seek(&mut self, pos: SeekFrom) -> io::Result { - self.file.seek(pos) + match &mut self.file { + Backing::File(file) => file.seek(pos), + Backing::Memory(cursor) => cursor.seek(pos), + } } } @@ -251,7 +364,7 @@ impl ArtifactWriter { let reference = ArtifactRef::from_json(Fields::of(&reply.value, "reply").value("ref")?)?; Ok(Artifact { reference: Arc::new(reference), - owner: self.owner.clone(), + holder: Holder::Bus(self.owner.clone()), }) } } @@ -401,7 +514,7 @@ impl Responder { outcome: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let mut body = Map::new(); body.insert("callId".into(), self.call_id.clone().into()); body.insert( diff --git a/services/flysim/crates/flybus/src/client/mod.rs b/services/flysim/crates/flybus/src/client/mod.rs index fb043f3..1ef0a80 100644 --- a/services/flysim/crates/flybus/src/client/mod.rs +++ b/services/flysim/crates/flybus/src/client/mod.rs @@ -14,7 +14,7 @@ use tokio::sync::oneshot; use handles::attachment_list; pub use handles::{ - Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder, + IN_MEMORY_STORE_ID, Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder, RpcResult, Service, Subscription, }; use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared}; @@ -361,7 +361,7 @@ impl Client { payload: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let (tx, rx) = oneshot::channel(); let (reply_tx, reply_rx) = oneshot::channel(); let shared = self.shared(); @@ -522,7 +522,7 @@ impl Client { payload: Map, attachments: &[(&str, &Artifact)], ) -> Result { - let (atts, keep) = attachment_list(attachments); + let (atts, keep) = attachment_list(attachments)?; let mut body = Map::new(); body.insert("topic".into(), topic.into()); body.insert("payload".into(), Value::Object(payload)); diff --git a/services/flysim/crates/flybus/src/lib.rs b/services/flysim/crates/flybus/src/lib.rs index fd8b4f9..fc19bc1 100644 --- a/services/flysim/crates/flybus/src/lib.rs +++ b/services/flysim/crates/flybus/src/lib.rs @@ -25,7 +25,7 @@ mod store; mod transport; pub use client::{ - Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, Message, + Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message, Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service, ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo, }; From aaf660d48e676651817e34ac51455f93013b3e2b Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 01:46:07 +0000 Subject: [PATCH 2/8] 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. --- .../crates/fly-session/src/coordinator.rs | 131 ++++- .../flysim/crates/fly-session/src/launcher.rs | 26 +- .../crates/fly-session/src/legacy_agent.rs | 64 ++- .../crates/fly-session/src/legacy_env.rs | 23 +- .../flysim/crates/fly-session/src/profile.rs | 30 +- .../flysim/crates/fly-session/src/publish.rs | 86 +++- services/flysim/crates/fly-session/src/rpc.rs | 94 +++- .../flysim/crates/fly-session/src/worker.rs | 458 +++++++++++++----- .../crates/fly-session/tests/common/mod.rs | 13 + .../crates/fly-session/tests/failures.rs | 1 + .../flysim/crates/fly-session/tests/media.rs | 36 +- .../crates/fly-session/tests/processes.rs | 1 + 12 files changed, 802 insertions(+), 161 deletions(-) diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 01d2742..e3c2ec4 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -322,6 +322,12 @@ pub struct Coordinator { /// published and never attached to an agent's sensory input. audio: BTreeMap, pending_audio: BTreeMap, + /// 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>>, + /// [`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, /// 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, /// 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>, 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 { 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 { 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 { + 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) diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index d867ede..088077c 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -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, + /// The local lane a reference carries, when the launcher offers it. + local: Option, /// The per-participant socket endpoint, kept alive for the connection's lifetime. _listener: Option, } @@ -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 { 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, 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(); diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index b6fbd37..9c0c992 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -402,9 +402,21 @@ pub fn spike_bitset(last_spike_ms: &[f64], since_ms: f64, now_ms: f64) -> Vec= 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 { + 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 = (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![ diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs index e70b996..2203a77 100644 --- a/services/flysim/crates/fly-session/src/legacy_env.rs +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -854,7 +854,7 @@ impl LegacyGameboyEnvironment { /// if there was one. async fn observation( live: &mut Live, - client: &flybus::Client, + ctx: &HandlerCtx<'_>, audio: Option>, ) -> 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); diff --git a/services/flysim/crates/fly-session/src/profile.rs b/services/flysim/crates/fly-session/src/profile.rs index 2e68b18..b9a1f71 100644 --- a/services/flysim/crates/fly-session/src/profile.rs +++ b/services/flysim/crates/fly-session/src/profile.rs @@ -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> = Mutex::new(BTreeMap::new()); +static TABLE: Mutex> = 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 diff --git a/services/flysim/crates/fly-session/src/publish.rs b/services/flysim/crates/fly-session/src/publish.rs index 8390298..7e88d26 100644 --- a/services/flysim/crates/fly-session/src/publish.rs +++ b/services/flysim/crates/fly-session/src/publish.rs @@ -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>)>, } 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, + ) -> DomainResult> { + 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 { + 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 diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index c5227d1..c3ddaaa 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -20,6 +20,10 @@ pub struct WorkerRef { pub worker_id: Id, /// The domain `incarnationId` Hello negotiated, once it has. pub domain_incarnation: Option, + /// 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, } 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, } +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 { 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 { + pub async fn finish(self) -> Result { 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, 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 { + 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 { diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e274025..c3c0ce0 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -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 { + 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) -> DomainResult { + 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>, + /// 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); + +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 { + 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>; + 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); + +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 { + 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), +} + +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 { + client: flybus::Client, + endpoint: Arc>, + cache: Arc>, + order: Arc, + 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>>, +} + +/// The local lane's hold on a shell. +struct ShellRef(Arc>); + +impl LocalDispatch for ShellRef { + fn send( + &self, + method: String, + request: SessionRpcRequest, + attachments: Vec<(String, flybus::Artifact)>, + ) -> BoxFuture<'_, Result> { + 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( client: flybus::Client, @@ -282,7 +470,30 @@ pub fn serve( 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( service_incarnation, status, cache, + local, task, client, } } -async fn run( - client: flybus::Client, - mut service: flybus::Service, - endpoint: Arc>, - cache: Arc>, -) { - // 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> = Vec::new(); - let order = Arc::new(LockOrder::default()); +/// What the bus loop answers without entering the endpoint. +struct Common { + role: Role, + capabilities: Vec, + threads: u64, + extra_ack: Option, +} + +async fn run(shell: Arc>, 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( continue; } }; - // The contract type already validated the `req-` 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( 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( } _ => {} } + shell + .admit(method, request, Incoming::Bus(incoming), Answer::Bus(responder)) + .await; + } + shell.drain().await; +} - let class = if methods.contains(&method.as_str()) { +impl Shell { + /// 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, + 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| { + 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-` 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( 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( // 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(mut f: F) -> Option( - client: flybus::Client, - endpoint: Arc>, - order: Arc, - ticket: u64, - cache: Arc>, - 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( + shell: Arc>, + 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( 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 { - match artifact.retain().await { - Ok(hold) => (name, hold), - Err(_) => (name, artifact), + 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( } } 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( } 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( 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; } } } diff --git a/services/flysim/crates/fly-session/tests/common/mod.rs b/services/flysim/crates/fly-session/tests/common/mod.rs index 92e1866..8dd2013 100644 --- a/services/flysim/crates/fly-session/tests/common/mod.rs +++ b/services/flysim/crates/fly-session/tests/common/mod.rs @@ -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, diff --git a/services/flysim/crates/fly-session/tests/failures.rs b/services/flysim/crates/fly-session/tests/failures.rs index 7de2bc1..7a2bb01 100644 --- a/services/flysim/crates/fly-session/tests/failures.rs +++ b/services/flysim/crates/fly-session/tests/failures.rs @@ -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)) diff --git a/services/flysim/crates/fly-session/tests/media.rs b/services/flysim/crates/fly-session/tests/media.rs index 220221c..69f2144 100644 --- a/services/flysim/crates/fly-session/tests/media.rs +++ b/services/flysim/crates/fly-session/tests/media.rs @@ -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"); - assert_eq!(published.view.pixels.artifact_id, last.artifact_id); + 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"); - 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" - ); + 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"); diff --git a/services/flysim/crates/fly-session/tests/processes.rs b/services/flysim/crates/fly-session/tests/processes.rs index 76f853d..7a48d20 100644 --- a/services/flysim/crates/fly-session/tests/processes.rs +++ b/services/flysim/crates/fly-session/tests/processes.rs @@ -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)) From 9aa7b92d04f64e52502a75145a7073a3e8af0499 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 01:46:07 +0000 Subject: [PATCH 3/8] fly-legacy-session: in-process sessions over the local lane; speed_ab arms LegacySession starts in-process participants with Via::Local (FLY_SESSION_LOCAL_LANE=0 keeps the bus path, a measurement knob). speed_ab takes FLY_PERF_ARMS (local, bus, process), FLY_PERF_SERVICE (the service host's per-frame reads), FLY_PERF_WORKERS (1 or 2 Tokio workers) and prints the legacy brain's own tick time beside the session's. --- .../fly-legacy-session/src/composition.rs | 17 ++++- .../crates/fly-legacy-session/src/task.rs | 12 ++++ .../fly-legacy-session/tests/speed_ab.rs | 68 +++++++++++++++++-- 3 files changed, 90 insertions(+), 7 deletions(-) diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index 9e7f94f..c331283 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -64,6 +64,14 @@ pub struct LegacyConfig { pub record: bool, } +/// `FLY_SESSION_LOCAL_LANE=0` keeps in-process participants on the bus: a measurement knob, +/// so the local lane can be compared with the bus path in one build. On by default. +pub const LOCAL_LANE_ENV: &str = "FLY_SESSION_LOCAL_LANE"; + +fn local_lane_enabled() -> bool { + std::env::var(LOCAL_LANE_ENV).map_or(true, |v| v != "0") +} + /// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds. pub fn channels_and_hold(mode: MacroMode) -> (Vec, f64) { let channels: Vec<&str> = if mode.dealt() { @@ -311,8 +319,10 @@ impl LegacySession { router, config.mode, // In-process participants reach the router in memory: no socket between two tasks - // of one process (a separate process always uses the socket). - Via::Memory, + // of one process (a separate process always uses the socket). They are called over + // the local lane: the same worker shell, no bus message and no store file per + // artifact (PERF-01, `workers-v1` amendment). + if local_lane_enabled() { Via::Local } else { Via::Memory }, &store_root, &sockets, budget, @@ -422,6 +432,9 @@ impl LegacySession { coordinator.bound_history(HISTORY); // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. coordinator.snapshot_every(SNAPSHOT_EVERY); + // Nothing in the service reads the committed-snapshot topic's admission receipt on + // the frame: the publish overlaps the next transition (PERF-01). + coordinator.defer_snapshots(std::env::var("FLY_PERF_DEFER").map_or(true, |v| v != "0")); } Ok(LegacySession { coordinator, diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs index db3f2bf..305dc84 100644 --- a/services/flysim/crates/fly-legacy-session/src/task.rs +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -600,7 +600,9 @@ impl Task for TaskFace { )); } } + let span = fly_session::profile::span("task.image"); let image = inner.image_of(new)?; + drop(span); let ms = inner.ms; let k1 = scope.step + 1; inner.evaluations += 1; @@ -608,6 +610,7 @@ impl Task for TaskFace { // `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the // location (the agent's, from the context), then the rank. + let span = fly_session::profile::span("task.sample"); let cartridge = inner.cartridge.clone(); let rewards = { let Inner { @@ -621,7 +624,11 @@ impl Task for TaskFace { }; adapter.sample(&mut reader, ms) }; + drop(span); + let span = fly_session::profile::span("task.observe"); let abandoned = inner.observe(&image, ms); + drop(span); + let span = fly_session::profile::span("task.ratchet"); let progress = inner.adapter.progress(); // `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above @@ -646,6 +653,8 @@ impl Task for TaskFace { }, ); + drop(span); + let span = fly_session::profile::span("task.outcome"); let mut outcome = AgentOutcome::default(); let mut events = Vec::new(); for (n, event) in rewards.iter().enumerate() { @@ -695,8 +704,11 @@ impl Task for TaskFace { record.rank = progress.rank; record.saved = saved; } + drop(span); + let span = fly_session::profile::span("task.contexts"); let next_contexts = inner.contexts(); let progress_value = inner.progress_value(); + drop(span); inner.current = Some((new.boundary, image)); if !recover { inner.close(); diff --git a/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs index 55b37a8..db51760 100644 --- a/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs +++ b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs @@ -114,12 +114,28 @@ impl Legacy { } } +/// The service's runtime: two Tokio workers (SERVE-01's `flysim-session`). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn session_against_legacy_interleaved() { + run(2).await; +} + +/// PERF-01: the same with one Tokio worker, the coordinator, the router and every in-process +/// participant on one thread beside the brain's sweep pool. `FLY_PERF_WORKERS` picks which of +/// the two runs (default 2). +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn session_against_legacy_interleaved_one_worker() { + run(1).await; +} + +async fn run(workers: usize) { if std::env::var_os("FLY_TASK01_BENCH").is_none() { eprintln!("skipping: FLY_TASK01_BENCH is not set"); return; } + if env_usize("FLY_PERF_WORKERS", 2) != workers { + return; + } let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), legacy_parity::fafb_dir(), @@ -134,7 +150,26 @@ async fn session_against_legacy_interleaved() { let rom = std::fs::read(&rom_path).unwrap(); let bytes = std::fs::read(&checkpoint_path).unwrap(); let checkpoint = flysim::store::decode(&bytes).unwrap(); - for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + // PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-process + // over the local lane, the default in-process path), `bus` (in-process over the bus, + // `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three. + let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned()); + // `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's + // `flysim-session`): the spike bitset of every commit and the audio chunk of every boundary. + let service = std::env::var_os("FLY_PERF_SERVICE").is_some(); + for arm in arms.split(',') { + let mode = match arm { + "local" | "bus" => ExecutionMode::InProcess, + "process" => ExecutionMode::Process, + other => panic!("unknown arm {other}"), + }; + // SAFETY: set before the session's runtime reads it; nothing else reads the variable. + unsafe { + std::env::set_var( + fly_legacy_session::composition::LOCAL_LANE_ENV, + if arm == "bus" { "0" } else { "1" }, + ); + } let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads); let root = tempfile::tempdir().unwrap(); let mut session = LegacySession::start( @@ -155,6 +190,14 @@ async fn session_against_legacy_interleaved() { session.bootstrap().await.unwrap(); session.import_flysim01(&bytes, &id("e2")).await.unwrap(); session.coordinator.disable_pacing(); + if service { + session + .coordinator + .request_commit_attachments(&[fly_session::legacy_agent::SPIKES_ATTACHMENT]); + session.coordinator.digest_views(false); + } + let audio_name = + fly_session::media::audio_attachment(fly_session::legacy_env::AUDIO_STREAM_ID); // Warm both. for _ in 0..chunk { legacy.step(); @@ -162,6 +205,10 @@ async fn session_against_legacy_interleaved() { } session.coordinator.metrics.clear(); let _ = fly_session::profile::report(); + // The legacy brain's own phase clock, to set its ticks beside the session's + // `agent.ticks` span. + legacy.agent.network.profile = true; + legacy.agent.network.reset_timings(); let (mut legacy_ms, mut session_ms) = (0.0, 0.0); let mut done = 0; while done < frames { @@ -173,24 +220,35 @@ async fn session_against_legacy_interleaved() { let at = Instant::now(); for _ in 0..chunk { session.step().await.unwrap(); + if service { + let _ = session.coordinator.take_details(); + let _ = session.coordinator.media_bytes(&audio_name).await.unwrap(); + } } session_ms += at.elapsed().as_secs_f64() * 1000.0; done += chunk; } let (l, s) = (legacy_ms / done as f64, session_ms / done as f64); eprintln!( - "{}: legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)", + "{} ({arm}{}, {workers} tokio workers): legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)", mode.label(), + if service { ", service reads" } else { "" }, 1000.0 / l, 1000.0 / s, s / l, FRAME_MS - l, FRAME_MS - s ); - for (name, count, mean) in fly_session::profile::report() { + let timings = legacy.agent.network.timings(); + eprintln!( + " legacy ticks (phase clock) mean {:>8.0} us over {done} frames", + timings.total_ns() as f64 / done as f64 / 1000.0 + ); + for (name, count, mean, max) in fly_session::profile::report_with_max() { eprintln!( - " span {name:<26} mean {:>8.0} us n {count}", - mean.as_secs_f64() * 1e6 + " span {name:<26} mean {:>8.0} us max {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6, + max.as_secs_f64() * 1e6 ); } for name in session.coordinator.metrics.names() { From fa8c9305a7308a490c31ad3d8b765acbe3925f94 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 02:15:25 +0000 Subject: [PATCH 4/8] PERF-01: spikes gathered per tick, 1 Hz session snapshots, fewer copies - flybrain-core: LifNetwork::tick_spikes, the last CPU tick's spike list (None under the GPU backend); a test proves it is exactly the neurons the tick stamped and that window unions equal the last_spike_ms scan. - legacy agent: Prepare runs its ticks one at a time and ORs each tick's list into the transition's bitset; Commit uses it instead of scanning 139,255 last-spike times (falls back to the scan when no list is kept). - legacy composition: a service session publishes its committed snapshot every 60th boundary (plus every boundary with events or boundary actions); nothing in the release subscribes, and each publication seals copies of the frame and the audio. - coordinator: a single dispatch job is called in place; worker shell moves the reply result instead of cloning it; publication promotions begin when Advance answers whatever the cadence. - profile: record() for a sample from another clock; finer spans (shell, local lane, handlers, advance parse/build, the brain's phase clock). --- .../fly-legacy-session/src/composition.rs | 13 ++-- .../crates/fly-session/src/coordinator.rs | 62 ++++++++++--------- .../crates/fly-session/src/legacy_agent.rs | 45 ++++++++++++-- .../crates/fly-session/src/legacy_env.rs | 1 + .../flysim/crates/fly-session/src/profile.rs | 14 +++++ .../flysim/crates/fly-session/src/publish.rs | 59 ------------------ services/flysim/crates/fly-session/src/rpc.rs | 6 +- .../flysim/crates/fly-session/src/worker.rs | 10 ++- .../flysim/crates/flybrain-core/src/lif.rs | 12 ++++ .../crates/flybrain-core/tests/tick_spikes.rs | 54 ++++++++++++++++ 10 files changed, 174 insertions(+), 102 deletions(-) create mode 100644 services/flysim/crates/flybrain-core/tests/tick_spikes.rs diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index a3d6a93..bc72304 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -41,8 +41,14 @@ fn grants(f: impl FnOnce(&mut Grants)) -> Grants { /// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz). const HISTORY: usize = 4096; -/// Every other boundary's snapshot: the legacy feed's `snapshot_hz` (30 Hz) at 60 Hz. -const SNAPSHOT_EVERY: u64 = 2; +/// A service session's committed-snapshot cadence on the session topic: once a second of frames +/// (every 60th boundary), plus every boundary with task events or boundary actions, which the +/// coordinator always publishes. The live presentation is the legacy feed (`docs/feed-protocol.md`, +/// 30 Hz, built by the service host from the committed boundary), not this topic, which nothing +/// in the release subscribes to; each snapshot attaches a sealed copy of the frame and the audio +/// chunk, so publishing it every other frame cost about 0.7 ms a frame on the release CPU +/// (PERF-01; was 2). +const SNAPSHOT_EVERY: u64 = 60; const COORDINATOR_CLIENT: &str = "coordinator"; const ENV_CLIENT: &str = "legacy-world"; @@ -432,9 +438,6 @@ impl LegacySession { coordinator.bound_history(HISTORY); // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. coordinator.snapshot_every(SNAPSHOT_EVERY); - // Nothing in the service reads the committed-snapshot topic's admission receipt on - // the frame: the publish overlaps the next transition (PERF-01). - coordinator.defer_snapshots(std::env::var("FLY_PERF_DEFER").map_or(true, |v| v != "0")); } Ok(LegacySession { coordinator, diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 31a8bb8..9111061 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -326,8 +326,6 @@ pub struct Coordinator { /// 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>>, - /// [`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 @@ -474,7 +472,6 @@ impl Coordinator { 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), @@ -674,14 +671,6 @@ 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); } @@ -2269,6 +2258,34 @@ impl Coordinator { }); } } + // One job has nothing to run beside it: it is called in place, not spawned. + DispatchOrder::Concurrent if jobs.len() == 1 => { + let job = jobs.into_iter().next().expect("one job"); + let started = Instant::now(); + let outcome = call_owned( + self.bus.clone(), + job.worker.clone(), + job.method, + job.scope.clone(), + job.params.clone(), + job.attachments.clone(), + job.request_id.clone(), + job.want.clone(), + deadline, + ) + .await; + out.push(JobResult { + agent_id: job.agent_id, + outcome, + scope: job.scope, + worker: job.worker, + method: job.method, + request_id: job.request_id, + params: job.params, + attachments: job.attachments, + elapsed: started.elapsed(), + }); + } DispatchOrder::Concurrent => { let mut tasks = Vec::new(); for job in jobs { @@ -2984,6 +3001,7 @@ impl Coordinator { controls: &[PortControl], ) -> Outcome { let scope = self.scope(k); + let build_span = crate::profile::span("coord.advance.build"); let params = AdvanceParams { batch_id: batch_id.clone(), controls: controls.to_vec(), @@ -2992,6 +3010,7 @@ impl Coordinator { Value::Object(m) => m, _ => Map::new(), }; + drop(build_span); let worker = self.environment.clone(); let request_id = self.serials.next(&worker.service); self.last_advance_request = Some(request_id.clone()); @@ -3112,10 +3131,12 @@ impl Coordinator { } }; + let parse_span = crate::profile::span("coord.advance.parse"); let result: StepResult = match reply.parse() { Ok(result) => result, Err(e) => return Err(self.fail_now(e, "advance")), }; + drop(parse_span); self.blame(None); let mut artifacts = reply.artifacts; self.pending_inspection = self.take_inspection(&mut artifacts); @@ -4309,25 +4330,6 @@ 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) diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 9c0c992..43a3cb8 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -489,6 +489,11 @@ pub struct LegacyAgentWorker { prepared: Option<(DomainRequestId, PreparedDecision)>, /// The brain time before the in-flight transition's ticks: the spike window's start. transition_start_ms: f64, + /// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike + /// lists during Prepare (PERF-01). It is the bitset `spike_bitset` would scan out of + /// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the + /// kernel keeps no per-tick list (the GPU backend): Commit scans as before. + tick_spikes: Option>, staged: Option, activated: BTreeSet, /// Every mutation this worker applied, reported as its progress counter. @@ -628,6 +633,7 @@ impl LegacyAgentWorker { context: None, prepared: None, transition_start_ms: 0.0, + tick_spikes: None, staged: None, activated: BTreeSet::new(), mutations: 0, @@ -1057,9 +1063,29 @@ impl LegacyAgentWorker { // 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 phase_before = agent.network.timings().total_ns(); let ticks_span = crate::profile::span("agent.ticks"); - agent.network.step(ticks); + // One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped + // are its spike list, so the transition's bitset is their union. + let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)]; + let mut listed = true; + for _ in 0..ticks { + let count = agent.network.step(1) as usize; + match agent.network.tick_spikes(count) { + Some(list) if listed => { + for &neuron in list { + bits[neuron as usize >> 3] |= 1 << (neuron & 7); + } + } + _ => listed = false, + } + } + self.tick_spikes = listed.then_some(bits); drop(ticks_span); + crate::profile::record( + "agent.ticks.phase_clock", + std::time::Duration::from_nanos(agent.network.timings().total_ns() - phase_before), + ); if agent.network.ms != brain_ticks as f64 { return Err(applied( ErrorCode::Internal, @@ -1134,7 +1160,9 @@ impl LegacyAgentWorker { "Agent.Commit must carry the step of its transition, not the new boundary", )); } + let parse_span = crate::profile::span("agent.commit.parse"); let params: CommitParams = ctx.params()?; + drop(parse_span); params .validate_against_scope(&scope) .map_err(DomainError::invalid)?; @@ -1196,7 +1224,10 @@ impl LegacyAgentWorker { self.transient.blocked_since_ms = ms; } let spikes_span = crate::profile::span("agent.spikes"); - let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms); + let spikes = match self.tick_spikes.take() { + Some(bits) => bits, + None => spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms), + }; drop(spikes_span); // 4. Retain the next context and acknowledge k+1. let digest = context.digest.clone(); @@ -1822,8 +1853,14 @@ impl WorkerEndpoint for LegacyAgentWorker { Box::pin(async move { let outcome = match ctx.method { "Agent.Initialize" => self.initialize(&ctx).await, - "Agent.Prepare" => self.prepare(&ctx).await, - "Agent.Commit" => self.commit(&ctx).await, + "Agent.Prepare" => { + let _span = crate::profile::span("agent.prepare.handler"); + self.prepare(&ctx).await + } + "Agent.Commit" => { + let _span = crate::profile::span("agent.commit.handler"); + self.commit(&ctx).await + } METHOD_AGENT_ROLLBACK => self.rollback(&ctx).await, "State.Capture" => self.state_capture(&ctx).await, "State.StageRestore" => self.state_stage_restore(&ctx).await, diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs index 2203a77..246b41f 100644 --- a/services/flysim/crates/fly-session/src/legacy_env.rs +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -1015,6 +1015,7 @@ impl LegacyGameboyEnvironment { // -- Environment.Advance ----------------------------------------------------------------- async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let _span = crate::profile::span("env.advance.handler"); let scope = ctx.scope()?.clone(); let params: AdvanceParams = ctx.params()?; let status = self.status.clone(); diff --git a/services/flysim/crates/fly-session/src/profile.rs b/services/flysim/crates/fly-session/src/profile.rs index b9a1f71..a618b57 100644 --- a/services/flysim/crates/fly-session/src/profile.rs +++ b/services/flysim/crates/fly-session/src/profile.rs @@ -53,6 +53,20 @@ impl Drop for Span { } } +/// Adds one sample measured elsewhere (a clock the caller already runs) under `name`. +pub fn record(name: &'static str, elapsed: Duration) { + if !on() { + return; + } + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO)); + entry.0 += 1; + entry.1 += elapsed; + entry.2 = entry.2.max(elapsed); +} + /// `(name, count, mean)` for every span recorded, then clears the table. pub fn report() -> Vec<(&'static str, u64, Duration)> { let mut table = TABLE diff --git a/services/flysim/crates/fly-session/src/publish.rs b/services/flysim/crates/fly-session/src/publish.rs index 7e88d26..c19e166 100644 --- a/services/flysim/crates/fly-session/src/publish.rs +++ b/services/flysim/crates/fly-session/src/publish.rs @@ -508,9 +508,6 @@ 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>)>, } impl Publisher { @@ -532,7 +529,6 @@ impl Publisher { state: Arc::new(Mutex::new(PublishedState::default())), ledger: Ledger::default(), sequence: 0, - in_flight: None, } } @@ -682,61 +678,6 @@ 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, - ) -> DomainResult> { - 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 { - 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 diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index c3ddaaa..cf38049 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -114,6 +114,7 @@ pub async fn send( .iter() .map(|(name, artifact)| ((*name).to_owned(), (*artifact).clone())) .collect(); + let _span = crate::profile::span("rpc.local.send"); let pending = lane.send(method, request, attachments).await?; return Ok(SentCall { method: method.to_owned(), @@ -152,7 +153,10 @@ impl SentCall { let mut pending = match self.pending { Pending::Bus(pending) => pending, Pending::Local(pending) => { - let reply = pending.finish().await.ok_or_else(|| { + let wait_span = crate::profile::span("rpc.local.wait"); + let reply = pending.finish().await; + drop(wait_span); + let reply = reply.ok_or_else(|| { DomainError::new( ErrorCode::BackendFailure, format!("{method}: the worker stopped before it answered"), diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index c3c0ce0..55902fa 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -666,7 +666,10 @@ impl Shell { return; }; - let body = match request.body_digest(&method) { + let digest_span = crate::profile::span("shell.digest"); + let body = request.body_digest(&method); + drop(digest_span); + let body = match body { Ok(body) => body, Err(e) => { let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone()); @@ -835,8 +838,9 @@ async fn execute( }; let _span = crate::profile::span("shell.record"); match outcome { - Ok(reply) => { - let outcome = success(&request, worker_id, incarnation_id, reply.result.clone()); + Ok(mut reply) => { + let result = std::mem::take(&mut reply.result); + let outcome = success(&request, worker_id, incarnation_id, result); // 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; an in-memory artifact is its own hold. diff --git a/services/flysim/crates/flybrain-core/src/lif.rs b/services/flysim/crates/flybrain-core/src/lif.rs index beb9496..11ebfdf 100644 --- a/services/flysim/crates/flybrain-core/src/lif.rs +++ b/services/flysim/crates/flybrain-core/src/lif.rs @@ -509,6 +509,18 @@ impl LifNetwork { } /// Run `milliseconds` ticks and return the total spike count. + /// The neurons the last CPU tick emitted, when `count` is what that one-tick + /// [`LifNetwork::step`] returned: exactly the neurons whose `last_spike_ms` it stamped, in the + /// sweep's order. `None` while the GPU backend runs the ticks, whose host copy of the list is + /// not kept per tick. A read-only view; it changes nothing a tick computes. + pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> { + #[cfg(feature = "cuda")] + if self.cuda.is_some() { + return None; + } + self.spikes.get(..count) + } + pub fn step(&mut self, milliseconds: u64) -> u64 { // The GPU backend runs the same ticks in batches and replays the host-side phases; with the // feature off this compiles to nothing and the loop below is the whole method. diff --git a/services/flysim/crates/flybrain-core/tests/tick_spikes.rs b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs new file mode 100644 index 0000000..83c01d6 --- /dev/null +++ b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs @@ -0,0 +1,54 @@ +//! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons +//! that tick stamped in `last_spike_ms`, so the union of the lists over a window is the window +//! bitset a scan of `last_spike_ms` gives. + +mod common; + +use std::collections::BTreeSet; +use std::sync::Arc; + +use common::visual_toy_dataset; +use flybrain_core::lif::{LifConfig, LifNetwork}; +use flybrain_core::plasticity::PlasticityConfig; + +#[test] +fn a_ticks_list_is_the_neurons_it_stamped_and_windows_agree_with_the_scan() { + let config = LifConfig { noise_amount: 40.0, ..LifConfig::default() }; + let mut network = + LifNetwork::new(Arc::new(visual_toy_dataset()), config, PlasticityConfig::default()) + .expect("a network"); + network.stimulate(200.0); + let neurons = network.last_spike_ms.len(); + let mut spiking_ticks = 0; + for window in 0..200 { + let since = network.ms; + let mut union = vec![0u8; neurons.div_ceil(8)]; + for _ in 0..(16 + window % 2) { + let before = network.ms; + let count = network.step(1) as usize; + let list: BTreeSet = network + .tick_spikes(count) + .expect("the CPU kernel keeps its list") + .iter() + .copied() + .collect(); + assert_eq!(list.len(), count, "a neuron spikes at most once a tick"); + let stamped: BTreeSet = (0..neurons as u32) + .filter(|&n| network.last_spike_ms[n as usize] == before) + .collect(); + assert_eq!(list, stamped); + spiking_ticks += usize::from(count > 0); + for n in list { + union[n as usize >> 3] |= 1 << (n & 7); + } + } + let mut scan = vec![0u8; neurons.div_ceil(8)]; + for (n, last) in network.last_spike_ms.iter().enumerate() { + if *last >= since { + scan[n >> 3] |= 1 << (n & 7); + } + } + assert_eq!(union, scan); + } + assert!(spiking_ticks > 0, "the fixture must spike for the test to mean anything"); +} From 9a2d7c0286675d23d1fd59ef745250e738c603b2 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 02:42:12 +0000 Subject: [PATCH 5/8] PERF-01: the local lane carries every endpoint method but Worker.*; contract amendments - worker: local_lane_carries is every method but Worker.*, so an endpoint's read-only extension (SERVE-01's Legacy.FeedStatus) no longer crosses the bus. - ipc-v1 section 1, bus-v1 section 12, step-v1 and the framework README: the in-process local lane and in-memory artifacts, dated 2026-09-30. --- docs/design/session-framework/README.md | 5 ++- docs/design/session-framework/bus-v1.md | 11 +++++++ docs/design/session-framework/ipc-v1.md | 31 +++++++++++++++++++ docs/design/session-framework/step-v1.md | 8 +++++ .../flysim/crates/fly-session/src/worker.rs | 7 +++-- 5 files changed, 58 insertions(+), 4 deletions(-) diff --git a/docs/design/session-framework/README.md b/docs/design/session-framework/README.md index f4cbc1b..5bf4b0f 100644 --- a/docs/design/session-framework/README.md +++ b/docs/design/session-framework/README.md @@ -78,7 +78,10 @@ Application / supervisor Application presentation This diagram is connectivity, not execution order. The step contract defines causal order. One router can host several independent sessions and application consumers; a deployment may choose one router per application for fault isolation. A router crash affects all its clients, -so choose that boundary deliberately. In-process mode still exercises routing and ownership. +so choose that boundary deliberately. In-process mode still exercises routing and ownership, +unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1, +amendment 2026-09-30), as the legacy composition's in-process release configuration is; process +mode always goes through the router. Defaults: coordinator per session, worker per fly, environment worker per world. Task and per-agent executors begin as coordinator-local libraries. An environment helper may own a diff --git a/docs/design/session-framework/bus-v1.md b/docs/design/session-framework/bus-v1.md index 8a545cc..5e0a3db 100644 --- a/docs/design/session-framework/bus-v1.md +++ b/docs/design/session-framework/bus-v1.md @@ -523,3 +523,14 @@ this same section forbids to reject one. longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled illustrative. + +**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client +gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in +the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no +router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into +one under the same reference. They read, clone and retain without a router, and no router ever +learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish` +before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one +process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of +the same date); section 8's ownership rules apply to every artifact a router stores, which these +never are. diff --git a/docs/design/session-framework/ipc-v1.md b/docs/design/session-framework/ipc-v1.md index fddd8ee..b42339a 100644 --- a/docs/design/session-framework/ipc-v1.md +++ b/docs/design/session-framework/ipc-v1.md @@ -17,6 +17,37 @@ ownership. This document owns Scope, model-related scalar types, worker capabili domain operation deduplication and errors. Domain request identity is independent of the bus callId: a safe retry has a new transport callId but the original domain requestId/body. +**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker +RPC is a Flybus call", for participants that share the coordinator's process. The release +container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a +frame above the brain (three round trips through the router and four or five sealed store files +a frame), against 0.7 ms for everything the legacy loop does outside its ticks. + +- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator + directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods -- + step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to + that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks. +- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through + the same shell code as a bus request: section 5's classification, canonical body digest, + result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the + endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker, + incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and + resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped + before answering is a lost connection (mutation unknown). +- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1 + section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef` + (`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3 + holds as written: every `ArtifactRef` in a payload is backed by a live handle the message + carries. An in-memory artifact never crosses a router: a bus call or a publication that needs + one carries a sealed copy (the coordinator makes it), and the snapshot names the copy. + A sealed handle a handler returns over the lane reaches the caller in memory under the same + reference. +- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached + over the bus, so process mode keeps exercising routing and ownership, and the bus path stays + the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic + transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy + parity runs in-process (lane) and process (bus). + ## 2. Common domain types ```ts diff --git a/docs/design/session-framework/step-v1.md b/docs/design/session-framework/step-v1.md index ff1de4d..a8a204a 100644 --- a/docs/design/session-framework/step-v1.md +++ b/docs/design/session-framework/step-v1.md @@ -12,6 +12,14 @@ ordering. Its frame order is this document's transaction order (legacy-gameboy-v maps it step by step), so the amendments below add capabilities to the protocol and change none of its ordering rules. +**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of +[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router: +the arrows below are then direct calls into the same worker shell, carrying the same requests and +replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that +overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the +coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the +world, the task and the commits run, and the snapshot is published before the next Prepare. + ## 1. Committed boundary At `Ready(epoch, k)`: diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index 55902fa..52bd332 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -378,10 +378,11 @@ impl LocalLane { } } -/// 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. +/// True for a method the local lane carries: every method the shell admits into the endpoint +/// (step mutations, lifecycle and capture, and an endpoint's own read-only extensions such as +/// SERVE-01's `Legacy.FeedStatus`). The common `Worker.*` methods stay on the bus. pub fn local_lane_carries(method: &str) -> bool { - matches!(classify_default(method), Some(OpClass::StepMutation | OpClass::Lifecycle)) + !method.starts_with("Worker.") } /// How the shell answers one request: over the bus, or into a local waiter. From 8618e38a5f932b7fc38eab3716823272ebae3577 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 02:55:51 +0000 Subject: [PATCH 6/8] fly-session: clippy (box the bus request), race test starts from its torn state The admission race test (TASK-01 R2-3) spawned its hammer before the first iteration set the queue up; on a loaded build box the hammer could admit into the empty initial queue, which is a legitimate admission, and fail the test. --- services/flysim/crates/fly-session/src/coordinator.rs | 8 ++++++++ services/flysim/crates/fly-session/src/worker.rs | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 9111061..6357801 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -6123,6 +6123,14 @@ mod admission_race_tests { }; let stop = AtomicBool::new(false); let torn = AtomicBool::new(false); + // The hammer must never find the queue's empty initial state (no pulse, nothing + // pending), which is a legitimate admission, not a torn commit: on a loaded box it + // can run before the first iteration below sets the state up (PERF-01 saw it once). + { + let mut state = queue.lock(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } std::thread::scope(|scope| { scope.spawn(|| { while !stop.load(Ordering::Relaxed) { diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index 52bd332..4a18bcc 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -165,7 +165,7 @@ pub struct HandlerCtx<'a> { /// 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), + Bus(Box), /// 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)>), @@ -620,7 +620,7 @@ async fn run(shell: Arc>, mut service: flybus::Servi _ => {} } shell - .admit(method, request, Incoming::Bus(incoming), Answer::Bus(responder)) + .admit(method, request, Incoming::Bus(Box::new(incoming)), Answer::Bus(responder)) .await; } shell.drain().await; From c56e04cdf8f4b76dcd7a119fb25afedb27400837 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 03:57:05 +0000 Subject: [PATCH 7/8] docs: PERF-01 in legacy-gameboy-v1 (release configuration) and the implementation guide --- .../session-framework/implementation.md | 38 +++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 25 ++++++++++++ 2 files changed, 63 insertions(+) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index f45c012..efcf767 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -441,6 +441,44 @@ B1, N1 and N3. - Against it, the legacy loop spends about 0.7 ms per frame outside the ticks. - The report `claude-task-01` has the per-phase table and what would close the rest. +### PERF-01 — The session runtime's per-frame cost (port slice) + +**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and +awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the +in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy +loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame, +in-process and process, and the compatibility string is unchanged. + +- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30). + An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`, + `launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method. + The request still goes through the shell's admission, deduplication, arrival order and + endpoint, and the reply is the same outcome. Handler media over the lane are in-memory + artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy, + no retain or open round trip. A bus call or a publication carries a sealed copy + (`rpc::promote`), begun while the task and the commits run. Process mode is untouched. + `FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also + runs over the lane. +- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare + ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits, + proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs. +- **The session topic** gets a committed snapshot every 60th boundary in a service session (and + at every boundary with events or boundary actions), not every other one. Nothing in the + release subscribes; the stream is the legacy feed. +- Small ones: a single dispatch job is called in place, the shell moves the reply result + instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling + spans for the shell, the lane, each handler and the brain's own phase clock. +- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any + other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and + work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate + (an AGENT-01 amendment) was not needed once the bitset cost nothing. +- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`; + the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the + release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms + to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame + memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache + (about 0.5 ms together) and the task's evaluation, which the legacy loop does too. + ### STATE-01 — Coherent all-participant checkpoint/recovery **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 281079c..a9a5988 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -415,6 +415,31 @@ interface LegacyGameboyComposition { for publication, traces and descriptor revisions, not a restore gate. This matches today's behaviour, where a decoder change does not refuse a checkpoint. +**Amendment, 2026-09-30 (PERF-01): the in-process release configuration.** Nothing in the +declaration, the digest or the compatibility string changes; these are execution choices of the +composition as `fly-legacy-session` builds it, recorded here because the shadow compares the +behaviour they must not change. + +- *In-process participants are called over the local lane* ([session RPCs](ipc-v1.md) section 1, + 2026-09-30): the frame, the memory image, the audio chunk and the spike bitset are in-memory + artifacts, handed over without a store file. Process mode is unchanged and still goes through + the router. `FLY_SESSION_LOCAL_LANE=0` puts an in-process session back on the bus. +- *`telemetry.spikes` is unchanged*: one bitset per transition, bit `i` set when neuron `i` + spiked in `[transition start, brain time)`, the legacy layout. The agent now builds it as the + union of the kernel's per-tick spike lists while Prepare ticks (`LifNetwork::tick_spikes`) + instead of scanning 139,255 last-spike times in Commit; the two are equal by construction and + by test, and the parity runs compare the bitset every frame. The AGENT-01 alternative -- attach + it only at the feed rate -- was not needed and was not made. +- *Committed snapshots on the session topic*: a service session publishes every 60th boundary and + every boundary with task events or boundary actions (it was every other boundary). The live + presentation is the legacy feed, which the service host builds from the committed boundary at + 30 Hz; nothing in the release subscribes to the session topic, and each publication seals a + store copy of the frame and the audio chunk. Every publication is still of a committed + boundary and still attaches the media it names (publishing-v1 section 3). +- *Nothing runs beside the brain's ticks.* On the release CPU with the sweep owning every core of + the flysim cpuset, work overlapping Prepare (a publication left in flight, for instance) slowed + the ticks by up to a third, so the coordinator finishes each boundary before the next Prepare. + ## 13. Machine-readable parts | Where | What | From e04b0c76b01fb6b889953dc38b66626de06ad58f Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 04:11:06 +0000 Subject: [PATCH 8/8] session_trace: boot parity accepts the adapter migrations v0.6.7 deploys with The live checkpoints the boot parity starts from are pokered-unique8-v7 files; since row 68 (v8) a boot takes them only with FLY_ACCEPT_ADAPTERS, as the v0.6.7 deploy sets it. The test sets the adapter's own MIGRATES_FROM when the environment names none; both runtimes read the same list. --- .../crates/fly-legacy-session/tests/session_trace.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs index 7eb09bf..cee9fc6 100644 --- a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs +++ b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs @@ -525,6 +525,18 @@ async fn run_booted( async fn fafb_boot_run_save_restore() { let Some(rom_path) = rom_path() else { return }; let Some(dataset) = fafb() else { return }; + // The live fly's checkpoints predate `pokered-unique8-v8` (row 68, v0.6.7), and a boot takes + // an older adapter's file only when the operator asks for its migration, as the v0.6.7 + // deploy does. Both runtimes read the same list, so the comparison is unchanged. + if std::env::var_os("FLY_ACCEPT_ADAPTERS").is_none() { + // SAFETY: set before any runtime or thread of this test reads the environment. + unsafe { + std::env::set_var( + "FLY_ACCEPT_ADAPTERS", + flybrain_gb::pokemon_red::MIGRATES_FROM.join(","), + ); + } + } // The rollback file (a ratchet rollback on the first boundary), and the live fly's largest // task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound // (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`).