From 1bfaf923b2aac16710c4a54488d37effa336c1af Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 22:20:39 +0000 Subject: [PATCH] N5: publication at the feed's rate, in-memory transport in-process, capture spans; docs for the fix round - Coordinator::snapshot_every(n): a snapshot every n-th boundary plus every boundary with events or boundary actions; a service session publishes every other boundary, the legacy feed's 30 Hz from 60 Hz. - In-process participants reach the router in memory (a separate process still uses its socket). - Spans on the agent's and the coordinator's capture path; tests/speed.rs times the legacy frame's phases, its agent export, and a session save. - legacy-gameboy-v1: the artifact-backed ledger, the palette seed and the pending pulse (amendments of 2026-09-29). --- .../session-framework/legacy-gameboy-v1.md | 29 +++++-- .../fly-legacy-session/src/composition.rs | 9 +- .../crates/fly-legacy-session/tests/speed.rs | 84 ++++++++++++++++++- .../crates/fly-session/src/coordinator.rs | 25 +++++- .../crates/fly-session/src/legacy_agent.rs | 6 ++ 5 files changed, 145 insertions(+), 8 deletions(-) diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 8cc6e8a..281079c 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -293,12 +293,22 @@ signal. The object serves exactly one agent on one port. - *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot". - So the task holds a marker snapshot in its place, and a task ledger records `slot: bool`. A slot + So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot save is asked for exactly when the legacy capture closure runs: safe, and rank above best. -- *The palette seed.* The legacy loop seeds the palette from the brain's RNG state after boot. - `MacroMachine` never reads its generator: no macro has a random step, and flybrain-gb's macro - tests show two seeds press the same buttons. The executor therefore uses a constant, and nothing - about it crosses to the agent. +- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's + lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past + the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet, + slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A + checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's + explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable + attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate. +- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette + from the brain's RNG state after boot. A restore does the same: it seeds with the restored + agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up, + so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro + has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge: + two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future + macro that draws from the generator fails there. - *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's `Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a @@ -580,6 +590,15 @@ bridge's fulfil path and refund path both get tests in the slice that wires them fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply. After a restore the pulse is unknown and a request is refused with a retry of one frame. + *Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit + counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The + legacy `stimulate` activates the pulse the moment it admits, so this matches: + - two sugars between two commits get one admission and one `PulseActive`, as the legacy drain + gives them; + - the rate-limit slot is not spent on the refused one. + + The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the + ticks between drains; here it is undecayed until the commit reports it. - *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index b0b6d55..b93407b 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -41,6 +41,9 @@ 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; + const COORDINATOR_CLIENT: &str = "coordinator"; const ENV_CLIENT: &str = "legacy-world"; const ENV_SERVICE: &str = "env.world"; @@ -305,7 +308,9 @@ impl LegacySession { let mut launcher = Launcher::start( router, config.mode, - Via::Unix, + // 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, &store_root, &sockets, budget, @@ -413,6 +418,8 @@ impl LegacySession { } else { // A service session runs indefinitely: its in-memory history stays bounded. coordinator.bound_history(HISTORY); + // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. + coordinator.snapshot_every(SNAPSHOT_EVERY); } Ok(LegacySession { coordinator, diff --git a/services/flysim/crates/fly-legacy-session/tests/speed.rs b/services/flysim/crates/fly-legacy-session/tests/speed.rs index 65dac55..a90340b 100644 --- a/services/flysim/crates/fly-legacy-session/tests/speed.rs +++ b/services/flysim/crates/fly-legacy-session/tests/speed.rs @@ -30,6 +30,30 @@ use flysim::frame::{LegacyFrame, Parts}; use flysim::macros::macro_layer; use flysim::snapshot::MacroMode; +/// The legacy frame's phases, timed through the one hook the stream itself uses. +struct Phases { + last: Instant, + sums: std::collections::BTreeMap<&'static str, f64>, + on: bool, +} + +impl flysim::frame::FrameObserver for Phases { + fn after(&mut self, phase: flysim::frame::FramePhase, _agent: &mut NeuralAgent) { + let now = Instant::now(); + if self.on { + let name = match phase { + flysim::frame::FramePhase::Ticked => "legacy.ticks", + flysim::frame::FramePhase::Executed => "legacy.decode+execute", + flysim::frame::FramePhase::Emulated => "legacy.frame", + flysim::frame::FramePhase::Advanced => "legacy.take_frame", + flysim::frame::FramePhase::Committed => "legacy.evaluate+commit", + }; + *self.sums.entry(name).or_default() += (now - self.last).as_secs_f64() * 1000.0; + } + self.last = now; + } +} + const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; fn env_usize(name: &str, default: usize) -> usize { @@ -94,8 +118,16 @@ async fn session_against_legacy_per_frame() { let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); } let mut legacy_ms = 0.0; + let mut phases = Phases { + last: Instant::now(), + sums: Default::default(), + on: false, + }; + let mut boundary_ms = 0.0; for n in 0..warmup + frames { let started = Instant::now(); + phases.on = n >= warmup; + phases.last = started; let mut parts = Parts { agent: &mut agent, emulator: &mut emulator, @@ -103,16 +135,40 @@ async fn session_against_legacy_per_frame() { ratchet: &mut ratchet, macros: macros.as_mut(), }; - let transition = frame.transition(&mut parts, &mut ()).unwrap(); + let transition = frame.transition(&mut parts, &mut phases).unwrap(); + let at = Instant::now(); frame .boundary(&mut parts, &transition.evaluated.progress, transition.ms) .unwrap(); + if n >= warmup { + boundary_ms += at.elapsed().as_secs_f64() * 1000.0; + } if n >= warmup { legacy_ms += started.elapsed().as_secs_f64() * 1000.0; } } + // What a legacy checkpoint costs the loop: the agent's export (the writer thread encodes). + let at = Instant::now(); + for _ in 0..10 { + std::hint::black_box(agent.export_state()); + } + let export_ms = at.elapsed().as_secs_f64() * 100.0; drop(agent); let legacy_per = legacy_ms / frames as f64; + for (name, sum) in &phases.sums { + eprintln!( + " legacy {name:<24} mean {:>8.0} us", + sum * 1000.0 / frames as f64 + ); + } + eprintln!( + " legacy boundary mean {:>8.0} us", + boundary_ms * 1000.0 / frames as f64 + ); + eprintln!( + " legacy agent.export_state mean {:>8.0} us (per checkpoint)", + export_ms * 1000.0 + ); eprintln!( "legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}", (FRAME_MS / legacy_per).min(1.0) @@ -152,6 +208,32 @@ async fn session_against_legacy_per_frame() { session.step().await.unwrap(); } let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64; + if !paced { + // What a save costs the loop: the participants' State.Capture at the boundary. + let root = tempfile::tempdir().unwrap(); + session + .attach_store(&fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 2, + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }) + .unwrap(); + let at = Instant::now(); + for _ in 0..5 { + let ticket = session + .queue_save(fly_session::legacy_checkpoint::SaveKind::Hot) + .await + .unwrap(); + drop(ticket); + } + eprintln!( + " session save (capture on the loop) mean {:>8.0} us", + at.elapsed().as_secs_f64() * 1e6 / 5.0 + ); + } let factor = FRAME_MS / per; eprintln!( "session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)", diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index dcb3d6b..9ace7ce 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -381,6 +381,8 @@ pub struct Coordinator { pending_rollback: Option<(u64, EpisodeRequest)>, /// [`Coordinator::bound_history`]. history_limit: Option, + /// [`Coordinator::snapshot_every`]. + snapshot_every: u64, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -501,6 +503,7 @@ impl Coordinator { defer_rollbacks: false, pending_rollback: None, history_limit: None, + snapshot_every: 1, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -640,6 +643,15 @@ impl Coordinator { self.history_limit = Some(keep); } + /// Publishes the committed snapshot of every `n`-th boundary, and of every boundary with task + /// events or boundary actions. Presentation reads snapshots as latest values + /// (`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. + pub fn snapshot_every(&mut self, n: u64) { + self.snapshot_every = n.max(1); + } + fn trim_history(&mut self) { let Some(keep) = self.history_limit else { return }; fn trim(items: &mut Vec, keep: usize) { @@ -726,9 +738,11 @@ impl Coordinator { "capture", )); }; + let span = crate::profile::span("coord.capture.read"); let bytes = artifact.read_all().await.map_err(|e| { self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") })?; + drop(span); self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; payloads.push((worker.worker_id.clone(), bytes)); } @@ -2439,7 +2453,16 @@ impl Coordinator { slot.prepare_request = None; } self.publish_events(k + 1, &evaluation.events).await?; - self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).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 + // `snapshot_hz`, 30 Hz, from a 60 Hz loop). + if self.snapshot_every <= 1 + || (k + 1).is_multiple_of(self.snapshot_every) + || !evaluation.events.is_empty() + || !boundary_actions.is_empty() + { + self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + } // A rollback request was applied above and is not an episode end; only a terminal one // pauses the session for the episode policy. diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index a58d74f..2f4f570 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -1332,7 +1332,9 @@ impl LegacyAgentWorker { let params: CaptureParams = ctx.params()?; let previous = self.status.state(); self.status.set_state(WorkerState::Capturing); + let span = crate::profile::span("agent.capture.encode"); let bytes = self.payload(¶ms.checkpoint_id, &scope, k); + drop(span); let bytes = match bytes { Ok(bytes) => bytes, Err(e) => { @@ -1340,8 +1342,12 @@ impl LegacyAgentWorker { return Err(e); } }; + let span = crate::profile::span("agent.capture.digest"); let digest = digest_of_bytes(&bytes); + drop(span); + let span = crate::profile::span("agent.capture.seal"); let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; + drop(span); self.status.set_state(previous); let artifact = artifact?; let graph = self.graph.as_ref().expect("initialized");