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"); +}