Merge port/task-01 (TASK-01 round-2 fixes) into port/serve-01; hand begun captures to the writer on pause

This commit is contained in:
acamilo 2026-09-30 01:37:12 +00:00
commit 68bde25493
13 changed files with 1111 additions and 178 deletions

View file

@ -407,6 +407,40 @@ order. Where the legacy side runs in the test, the ledgers are compared after ev
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro, well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
counts and "nearer". Results: see the TASK-01 run report and the amendment below. counts and "nearer". Results: see the TASK-01 run report and the amendment below.
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
B1, N1 and N3.
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
past the 32 KiB `TypedValue` bound.
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
- The coordinator files those attachments as `task-ledger-<name>` payloads in captures and
imports.
- A bad ledger is an error, never a panic, so a boot falls to the next candidate.
- Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB).
- **N1: a sugar admitted before the next commit is an active pulse.**
- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the
seed is never read.
- **N4: saves are queued to the writer thread.**
- **N5: speed.** The profile is below. Changes:
- The world seals its three artifacts concurrently.
- Cache and caller holds are taken concurrently.
- In-process participants use the in-memory transport.
- A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded
history.
- `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside
the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state
under the lock, then encodes, digests and seals it off the lock. The coordinator's
`begin_capture` / `finish_capture` let the session step on while the payload is written.
- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`):
- The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a
few percent.
- What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a
quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit,
plus the world's and the agent's artifact seals and reads.
- 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.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.

View file

@ -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 - *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". 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. 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. - *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's
`MacroMachine` never reads its generator: no macro has a random step, and flybrain-gb's macro lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past
tests show two seeds press the same buttons. The executor therefore uses a constant, and nothing the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet,
about it crosses to the agent. 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 - *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 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 `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 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. 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. 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 - *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 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 answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside

View file

@ -75,31 +75,34 @@ impl LegacyAdmission {
/// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is /// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is
/// queued for the next Prepare; the result is its interaction id and the clamped duration. /// queued for the next Prepare; the result is its interaction id and the clamped duration.
pub fn sugar(&mut self, now_ms: u64, duration_ms: Option<f64>) -> Result<(Id, f64), Refusal> { pub fn sugar(&mut self, now_ms: u64, duration_ms: Option<f64>) -> Result<(Id, f64), Refusal> {
let Some(remaining) = self.queue.stimulus_remaining_ms(&self.agent_id) else { // Read the pulse, decide and queue under one lock, so a commit cannot land between the
// reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by
// a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs:
// a second request before the next commit is refused (`PulseActive`), not admitted
// into a pulse that would take the max and add nothing (review N1).
let agent_id = self.agent_id.clone();
let interaction_id = self.next_id("sugar");
let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms);
let admission = self.queue.admit_with(&agent_id, |remaining, pending| {
let Some(remaining) = remaining else {
return Err(Refusal::PulseActive { return Err(Refusal::PulseActive {
retry_after_ms: UNKNOWN_PULSE_RETRY_MS, retry_after_ms: UNKNOWN_PULSE_RETRY_MS,
}); });
}; };
// A sugar admitted and not yet reported on by a commit is an active pulse, as it is in limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?;
// the legacy loop the moment `stimulate` runs: a second request before the next commit let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms);
// is refused (`PulseActive`), not admitted into a pulse that would take the max and add Ok(Admission::Stimulus {
// nothing (TASK-01 review N1). agent_id: agent_id.clone(),
let pending = self
.queue
.pending_stimulus_ms(&self.agent_id)
.unwrap_or(0.0);
self.limiter.admit(now_ms, remaining.max(pending))?;
let duration = duration_ms
.unwrap_or(self.default_ms)
.clamp(1.0, self.max_ms)
.min(self.max_ms);
let interaction_id = self.next_id("sugar");
self.queue.admit(Admission::Stimulus {
agent_id: self.agent_id.clone(),
interaction_id: interaction_id.clone(), interaction_id: interaction_id.clone(),
kind_id: id(STIMULUS_REWARD_PULSE), kind_id: id(STIMULUS_REWARD_PULSE),
duration_ms: duration, duration_ms: duration,
})
}); });
if admission.is_err() {
// A refusal spends no id.
self.serial -= 1;
}
let Admission::Stimulus { duration_ms: duration, .. } = admission?;
Ok((interaction_id, duration)) Ok((interaction_id, duration))
} }

View file

@ -27,7 +27,7 @@ use flysim::snapshot::MacroMode;
use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
use fly_session::legacy_checkpoint::{ use fly_session::legacy_checkpoint::{
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
SaveReport, SaveTicket, now_wall_ms, SaveReport, SaveTicket, TaskHalf, now_wall_ms,
}; };
use flysim::store::Checkpoint; use flysim::store::Checkpoint;
use std::time::Instant; use std::time::Instant;
@ -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). /// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
const HISTORY: usize = 4096; 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 COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world"; const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world"; const ENV_SERVICE: &str = "env.world";
@ -93,6 +96,8 @@ pub struct LegacySession {
saves: u64, saves: u64,
/// Saves on the writer thread whose outcome has not been collected. /// Saves on the writer thread whose outcome has not been collected.
pending_saves: Vec<SaveTicket>, pending_saves: Vec<SaveTicket>,
/// Captures sent and not yet collected ([`LegacySession::begin_save`]).
pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>,
/// The feed event log's watermark the saves record: the restored file's, carried over (the /// The feed event log's watermark the saves record: the restored file's, carried over (the
/// session runtime has no feed event log of its own before EDGE-01). /// session runtime has no feed event log of its own before EDGE-01).
last_event_id: u64, last_event_id: u64,
@ -318,7 +323,9 @@ impl LegacySession {
let mut launcher = Launcher::start( let mut launcher = Launcher::start(
router, router,
config.mode, 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, &store_root,
&sockets, &sockets,
budget, budget,
@ -426,6 +433,8 @@ impl LegacySession {
} else { } else {
// A service session runs indefinitely: its in-memory history stays bounded. // A service session runs indefinitely: its in-memory history stays bounded.
coordinator.bound_history(HISTORY); 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 { Ok(LegacySession {
coordinator, coordinator,
@ -439,6 +448,7 @@ impl LegacySession {
checkpointer: None, checkpointer: None,
saves: 0, saves: 0,
pending_saves: Vec::new(), pending_saves: Vec::new(),
pending_captures: Vec::new(),
last_event_id: 0, last_event_id: 0,
}) })
} }
@ -593,15 +603,43 @@ impl LegacySession {
/// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The /// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The
/// outcome is collected by [`LegacySession::completed_saves`]. /// outcome is collected by [`LegacySession::completed_saves`].
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> { pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
self.begin_save(kind).await?;
let mut tickets = self.finish_captures().await?;
let last = tickets
.pop()
.ok_or_else(|| "no save was begun".to_owned())?;
self.pending_saves.extend(tickets);
Ok(last)
}
/// Begins one save of the committed boundary: every participant's `State.Capture` is sent
/// (each takes its state now) and the task's half is taken now; the session may step on
/// while the agent encodes and seals its payload off its lock
/// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`]
/// hands it to the writer.
pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> {
self.saves += 1; self.saves += 1;
let capture = self
.coordinator
.begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?)
.await
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
let (task, _slot_filled) = self.task.task_half();
self.pending_captures.push((capture, kind, task));
Ok(())
}
/// Collects every begun capture, in order, and queues it to the checkpointer's writer.
pub async fn finish_captures(&mut self) -> Result<Vec<SaveTicket>, String> {
let mut tickets = Vec::new();
for (capture, kind, task) in std::mem::take(&mut self.pending_captures) {
let (boundary, world, agents) = self let (boundary, world, agents) = self
.coordinator .coordinator
.capture_payloads(&parse_id(&format!("legacy-save-{}", self.saves))?) .finish_capture(capture)
.await .await
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents) let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents)
.map_err(|_| "the legacy composition has exactly one agent".to_owned())?; .map_err(|_| "the legacy composition has exactly one agent".to_owned())?;
let (task, _slot_filled) = self.task.task_half();
let capture = LegacyCapture { let capture = LegacyCapture {
boundary, boundary,
agent_payload: agent, agent_payload: agent,
@ -610,32 +648,49 @@ impl LegacySession {
}; };
let last_event_id = self.last_event_id; let last_event_id = self.last_event_id;
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
checkpointer.save(kind, capture, last_event_id, now_wall_ms()) tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?);
}
Ok(tickets)
} }
/// The saves queued so far that have committed (or failed), without waiting; with `wait`, /// The saves queued so far that have committed (or failed), without waiting; with `wait`,
/// every queued save's outcome. A failed save is an error: the caller decides. /// every queued save's outcome. Every outcome is reported, a failed save as its own `Err`
pub async fn completed_saves(&mut self, wait: bool) -> Result<Vec<SaveReport>, String> { /// beside the others (TASK-01 review R2-2): the caller decides.
pub async fn completed_saves(&mut self, wait: bool) -> Vec<Result<SaveReport, String>> {
let mut done = Vec::new(); let mut done = Vec::new();
let mut still = Vec::new(); let mut still = Vec::new();
for mut ticket in std::mem::take(&mut self.pending_saves) { for mut ticket in std::mem::take(&mut self.pending_saves) {
let outcome = if wait { let stopped = || Err("the checkpoint writer stopped".to_owned());
Some((&mut ticket.reply).await.map_err(|_| ())) if wait {
done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped()));
} else { } else {
match ticket.reply.try_recv() { match ticket.reply.try_recv() {
Ok(result) => Some(Ok(result)), Ok(result) => done.push(result),
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None, Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket),
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => Some(Err(())), Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()),
} }
};
match outcome {
None => still.push(ticket),
Some(Ok(result)) => done.push(result?),
Some(Err(())) => return Err("the checkpoint writer stopped".to_owned()),
} }
} }
self.pending_saves = still; self.pending_saves = still;
Ok(done) done
}
/// Hands every begun capture to the writer now and reports what was queued. `advance` does
/// this after the next step so the agent's sealing overlaps it; a step that fails does it
/// before returning the error, and a caller that pauses (or is about to stop stepping) calls
/// this so a save begun at the last boundary reaches the writer as the legacy loop's
/// immediate hand-off would have (TASK-01 review R2-1).
pub async fn flush_captures(&mut self) -> Result<Vec<SaveQueued>, String> {
let mut saves = Vec::new();
for ticket in self.finish_captures().await? {
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
}
Ok(saves)
} }
/// One transition and what the legacy loop does at the boundary it reaches, in the declared /// One transition and what the legacy loop does at the boundary it reaches, in the declared
@ -643,12 +698,23 @@ impl LegacySession {
/// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save
/// after it, then the interval saves (`checkpoint_if_due`). /// after it, then the interval saves (`checkpoint_if_due`).
pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> { pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> {
let report = self let report = match self.coordinator.step().await {
.coordinator Ok(report) => report,
.step() Err(e) => {
.await // The legacy writer already has the saves of the earlier boundaries: hand the
.map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?; // begun captures over before reporting the failure (TASK-01 review R2-1).
let mut saves = Vec::new(); let flushed = self.flush_captures().await.err();
let mut message =
format!("step ({} at {}): {}", e.detail, e.phase, e.error.message);
if let Some(flush) = flushed {
message.push_str(&format!("; and the pending saves: {flush}"));
}
return Err(message);
}
};
// The captures begun at the last boundary: the agent sealed its payload while this
// transition's Prepare ticked.
let saves = self.flush_captures().await?;
if self.checkpointer.is_some() { if self.checkpointer.is_some() {
let rank = self.task.rank(); let rank = self.task.rank();
let ms = self.task.brain_ms(); let ms = self.task.brain_ms();
@ -658,13 +724,7 @@ impl LegacySession {
.expect("attached") .expect("attached")
.observe_rank(rank, ms); .observe_rank(rank, ms);
if let Some(RankChange::Climbed(rank)) = change { if let Some(RankChange::Climbed(rank)) = change {
let ticket = self.queue_save(SaveKind::Milestone(rank)).await?; self.begin_save(SaveKind::Milestone(rank)).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
} }
let rolled_back = self let rolled_back = self
@ -679,13 +739,7 @@ impl LegacySession {
})?; })?;
if self.checkpointer.is_some() { if self.checkpointer.is_some() {
if rolled_back { if rolled_back {
let ticket = self.queue_save(SaveKind::Durable).await?; self.begin_save(SaveKind::Durable).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
let due = self let due = self
.checkpointer .checkpointer
@ -693,13 +747,7 @@ impl LegacySession {
.expect("attached") .expect("attached")
.due(Instant::now()); .due(Instant::now());
if let Some(kind) = due { if let Some(kind) = due {
let ticket = self.queue_save(kind).await?; self.begin_save(kind).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
} }
Ok(( Ok((
@ -723,11 +771,16 @@ impl LegacySession {
if self.checkpointer.is_none() { if self.checkpointer.is_none() {
return Ok(None); return Ok(None);
} }
self.flush_captures().await?;
let report = self.save(SaveKind::Durable).await?; let report = self.save(SaveKind::Durable).await?;
self.completed_saves(true).await?; let outcomes = self.completed_saves(true).await;
if let Some(checkpointer) = self.checkpointer.as_mut() { if let Some(checkpointer) = self.checkpointer.as_mut() {
checkpointer.close(); checkpointer.close();
} }
// Every queued save has been waited for; the first failure is the shutdown's.
for outcome in outcomes {
outcome?;
}
Ok(Some(report)) Ok(Some(report))
} }

View file

@ -937,6 +937,13 @@ impl SessionHost {
if self.status != FeedStatus::Paused { if self.status != FeedStatus::Paused {
self.status = FeedStatus::Paused; self.status = FeedStatus::Paused;
self.emit(NewEvent::new(FeedEventKind::System, "Paused by the operator")); self.emit(NewEvent::new(FeedEventKind::System, "Paused by the operator"));
// A pause must never hold a begun save (TASK-01 review R2-1). This host
// saves through `queue_save`, which hands its capture over at once, so
// there is normally nothing to flush; a begun capture would reach the
// writer here rather than sit until the next step.
if let Err(error) = self.session.flush_captures().await {
tracing::error!(%error, "could not hand over the pending captures on pause");
}
if let Err(error) = self.checkpoint(SaveKind::Durable, None).await { if let Err(error) = self.checkpoint(SaveKind::Durable, None).await {
tracing::error!(%error, "could not checkpoint on pause"); tracing::error!(%error, "could not checkpoint on pause");
} }

View file

@ -0,0 +1,126 @@
//! TASK-01 round-2 review notes R2-1 and R2-2 on the session's save hand-off. The toy raw
//! composition from power-on (`FLY_ROM`; a build without it skips):
//!
//! - R2-1: a save begun at boundary k reaches the writer even when the step after it fails, and
//! `flush_captures` hands it over while the loop idles (a pause), as the legacy loop's writer
//! thread has it from the boundary on.
//! - R2-2: `completed_saves` reports every queued save's outcome, a failed one beside the rest.
use std::path::PathBuf;
use fly_legacy_session::composition::{
LegacyConfig, LegacySession, StoreConfig,
};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_checkpoint::SaveKind;
use fly_session::legacy_parity;
use fly_session::types::id;
use flysim::snapshot::MacroMode;
async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)> {
let Some(rom_path) = std::env::var_os("FLY_ROM").map(PathBuf::from) else {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
return None;
};
let config = LegacyConfig {
mode: ExecutionMode::InProcess,
rom_path,
dataset_dir: legacy_parity::toy::dir(),
profile: LegacyProfileKind::Toy,
macro_mode: MacroMode::Raw,
agent_id: id("fly"),
agent_threads: 1,
record: true,
};
let mut session = LegacySession::start(&root.join("run"), config)
.await
.expect("the session starts");
session.bootstrap().await.expect("Ready(0)");
let store = StoreConfig {
hot_dir: root.join("hot"),
durable_dir: root.join("durable"),
keep_generations: 4,
// Saves only when asked.
hot_seconds: 1e9,
checkpoint_seconds: 1e9,
speed: 1.0,
};
session.attach_store(&store).expect("the store attaches");
Some((session, store))
}
/// One step, then the interval save it began (the first boundary is due for a durable one)
/// written and collected, so a test starts with nothing queued.
async fn warm_up(session: &mut LegacySession) {
session.advance().await.expect("a step");
session.flush_captures().await.expect("the flush");
for outcome in session.completed_saves(true).await {
outcome.expect("the first save");
}
}
fn files_in(dir: &std::path::Path) -> usize {
std::fs::read_dir(dir)
.map(|entries| entries.filter_map(Result::ok).count())
.unwrap_or(0)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_begun_save_reaches_the_writer_when_the_next_step_fails() {
let root = tempfile::tempdir().expect("tmp");
let Some((mut session, _)) = session(root.path()).await else { return };
warm_up(&mut session).await;
for _ in 0..2 {
session.advance().await.expect("a step");
}
session.begin_save(SaveKind::Hot).await.expect("a capture begins");
// The next transition fails at its commit.
session.coordinator.injections.at_step = 3;
session.coordinator.injections.undeclared_stimulus = true;
let error = session.advance().await.err().expect("the step fails");
assert!(error.starts_with("step ("), "{error}");
let outcomes = session.completed_saves(true).await;
assert_eq!(outcomes.len(), 1, "the save begun before the failed step was written");
let report = outcomes.into_iter().next().unwrap().expect("and it committed");
assert!(!report.durable);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_pause_flushes_the_begun_save() {
let root = tempfile::tempdir().expect("tmp");
let Some((mut session, store)) = session(root.path()).await else { return };
warm_up(&mut session).await;
session.begin_save(SaveKind::Hot).await.expect("a capture begins");
let before = files_in(&store.hot_dir);
let queued = session.flush_captures().await.expect("the flush");
assert_eq!(queued.len(), 1);
let outcomes = session.completed_saves(true).await;
assert_eq!(outcomes.len(), 1);
assert!(outcomes[0].is_ok());
assert!(files_in(&store.hot_dir) > before, "the hot generation is on disk");
assert!(
session.flush_captures().await.expect("a second flush").is_empty(),
"nothing is held twice"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn every_save_outcome_is_reported_after_a_failure() {
let root = tempfile::tempdir().expect("tmp");
let Some((mut session, store)) = session(root.path()).await else { return };
warm_up(&mut session).await;
// The store's hot directory goes away under the writer: every save after it fails. The
// first failure must not hide the outcomes behind it.
std::fs::remove_dir_all(&store.hot_dir).expect("remove hot");
std::fs::write(&store.hot_dir, b"not a directory").expect("block hot");
let mut expected = 0;
for _ in 0..3 {
session.begin_save(SaveKind::Hot).await.expect("begin");
session.flush_captures().await.expect("flush");
expected += 1;
}
let outcomes = session.completed_saves(true).await;
assert_eq!(outcomes.len(), expected, "one outcome per queued save: {outcomes:?}");
assert!(outcomes.iter().all(Result::is_err), "the writes failed: {outcomes:?}");
}

View file

@ -753,6 +753,9 @@ async fn fafb_reward_segments() {
"FLY_DOOR_CHECKPOINT", "FLY_DOOR_CHECKPOINT",
"FLY_CATCH_CHECKPOINT", "FLY_CATCH_CHECKPOINT",
"FLY_ENGAGE_CHECKPOINT", "FLY_ENGAGE_CHECKPOINT",
// The live fly's largest task ledgers (42 and 46 KB, TASK-01 review B1).
"FLY_ROW64_CHECKPOINT",
"FLY_ROW65_YARD_CHECKPOINT",
] ]
.iter() .iter()
.filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p)))) .filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p))))

View file

@ -30,6 +30,30 @@ use flysim::frame::{LegacyFrame, Parts};
use flysim::macros::macro_layer; use flysim::macros::macro_layer;
use flysim::snapshot::MacroMode; 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; const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
fn env_usize(name: &str, default: usize) -> usize { 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 _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
} }
let mut legacy_ms = 0.0; 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 { for n in 0..warmup + frames {
let started = Instant::now(); let started = Instant::now();
phases.on = n >= warmup;
phases.last = started;
let mut parts = Parts { let mut parts = Parts {
agent: &mut agent, agent: &mut agent,
emulator: &mut emulator, emulator: &mut emulator,
@ -103,16 +135,40 @@ async fn session_against_legacy_per_frame() {
ratchet: &mut ratchet, ratchet: &mut ratchet,
macros: macros.as_mut(), 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 frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms) .boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.unwrap(); .unwrap();
if n >= warmup {
boundary_ms += at.elapsed().as_secs_f64() * 1000.0;
}
if n >= warmup { if n >= warmup {
legacy_ms += started.elapsed().as_secs_f64() * 1000.0; 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); drop(agent);
let legacy_per = legacy_ms / frames as f64; 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!( eprintln!(
"legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}", "legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}",
(FRAME_MS / legacy_per).min(1.0) (FRAME_MS / legacy_per).min(1.0)
@ -152,6 +208,32 @@ async fn session_against_legacy_per_frame() {
session.step().await.unwrap(); session.step().await.unwrap();
} }
let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64; 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; let factor = FRAME_MS / per;
eprintln!( eprintln!(
"session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)", "session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)",

View file

@ -0,0 +1,207 @@
//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, measured
//! A/B-interleaved on one box so both see the same load: chunks of `FLY_TASK01_AB_CHUNK` frames
//! of the legacy loop (`LegacyFrame`, the service's frame, trace off) alternate with chunks of the
//! session (agent, world and task under the coordinator, service configuration: no details,
//! bounded history, snapshots at 30 Hz), both from the same checkpoint with the same sweep threads.
//! A shared box's load then shifts both arms alike, and the ratio is the comparison.
//!
//! `FLY_TASK01_BENCH=1` plus rom-env and `data/fafb-v783`. Reported per execution mode: mean
//! ms/frame of each arm, the ratio, the fps each sustains unpaced, and the headroom at 1x (one
//! Game Boy frame is 16.74 ms).
use std::sync::Arc;
use std::time::Instant;
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use fly_session::types::id;
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::lif::SweepPlan;
use flybrain_gb::GameAdapter;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::Ratchet;
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
use flysim::config::Config;
use flysim::frame::{LegacyFrame, Parts};
use flysim::macros::{MacroLayer, macro_layer};
use flysim::snapshot::MacroMode;
const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
fn env_usize(name: &str, default: usize) -> usize {
std::env::var(name)
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(default)
}
struct Legacy {
emulator: Emulator,
adapter: PokemonRedReward,
ratchet: Ratchet,
agent: NeuralAgent,
frame: LegacyFrame,
macros: Option<MacroLayer>,
}
impl Legacy {
fn new(
rom: &[u8],
dataset: &std::path::Path,
checkpoint: &flysim::store::Checkpoint,
threads: usize,
) -> Legacy {
let data = Arc::new(load_brain_dataset_from_dir(dataset).unwrap());
let mut emulator =
Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap();
let mut adapter = PokemonRedReward::new();
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_owned();
config.macros.mode = MacroMode::Macros;
let (channels, hold_ms) = channels_and_hold(MacroMode::Macros);
let channels: Vec<&str> = channels.iter().map(String::as_str).collect();
let mut agent_config =
AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
agent_config.warmup_ms = config.loop_.warmup_ms;
let mut agent = NeuralAgent::new(data, agent_config).unwrap();
if threads > 1 {
agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap());
}
let mut frame = LegacyFrame::new();
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
checkpoint,
)
.unwrap();
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
}
Legacy {
emulator,
adapter,
ratchet,
agent,
frame,
macros,
}
}
fn step(&mut self) {
let mut parts = Parts {
agent: &mut self.agent,
emulator: &mut self.emulator,
adapter: &mut self.adapter,
ratchet: &mut self.ratchet,
macros: self.macros.as_mut(),
};
let transition = self.frame.transition(&mut parts, &mut ()).unwrap();
self.frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.unwrap();
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_against_legacy_interleaved() {
if std::env::var_os("FLY_TASK01_BENCH").is_none() {
eprintln!("skipping: FLY_TASK01_BENCH is not set");
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(),
std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from),
) else {
eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing");
return;
};
let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1800);
let chunk = env_usize("FLY_TASK01_AB_CHUNK", 60);
let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3);
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] {
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
let root = tempfile::tempdir().unwrap();
let mut session = LegacySession::start(
root.path(),
LegacyConfig {
mode,
rom_path: rom_path.clone(),
dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production,
macro_mode: MacroMode::Macros,
agent_id: id("fly"),
agent_threads: threads.max(1),
record: false,
},
)
.await
.unwrap();
session.bootstrap().await.unwrap();
session.import_flysim01(&bytes, &id("e2")).await.unwrap();
session.coordinator.disable_pacing();
// Warm both.
for _ in 0..chunk {
legacy.step();
session.step().await.unwrap();
}
session.coordinator.metrics.clear();
let _ = fly_session::profile::report();
let (mut legacy_ms, mut session_ms) = (0.0, 0.0);
let mut done = 0;
while done < frames {
let at = Instant::now();
for _ in 0..chunk {
legacy.step();
}
legacy_ms += at.elapsed().as_secs_f64() * 1000.0;
let at = Instant::now();
for _ in 0..chunk {
session.step().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)",
mode.label(),
1000.0 / l,
1000.0 / s,
s / l,
FRAME_MS - l,
FRAME_MS - s
);
for (name, count, mean) in fly_session::profile::report() {
eprintln!(
" span {name:<26} mean {:>8.0} us n {count}",
mean.as_secs_f64() * 1e6
);
}
for name in session.coordinator.metrics.names() {
let p = session.coordinator.metrics.percentiles(&name).unwrap();
eprintln!(
" {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}",
p.p50_us(),
p.p95_us(),
session.coordinator.metrics.count(&name)
);
}
session.stop().await;
}
}

View file

@ -384,6 +384,8 @@ pub struct Coordinator {
pending_rollback: Option<(u64, EpisodeRequest)>, pending_rollback: Option<(u64, EpisodeRequest)>,
/// [`Coordinator::bound_history`]. /// [`Coordinator::bound_history`].
history_limit: Option<usize>, history_limit: Option<usize>,
/// [`Coordinator::snapshot_every`].
snapshot_every: u64,
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
stats: Stats, stats: Stats,
/// The ordered actions this session took, for the ordering assertions. /// The ordered actions this session took, for the ordering assertions.
@ -505,6 +507,7 @@ impl Coordinator {
defer_rollbacks: false, defer_rollbacks: false,
pending_rollback: None, pending_rollback: None,
history_limit: None, history_limit: None,
snapshot_every: 1,
lifecycle_acks: Vec::new(), lifecycle_acks: Vec::new(),
stats: Stats::default(), stats: Stats::default(),
audit: Vec::new(), audit: Vec::new(),
@ -714,6 +717,15 @@ impl Coordinator {
self.history_limit = Some(keep); 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) { fn trim_history(&mut self) {
let Some(keep) = self.history_limit else { return }; let Some(keep) = self.history_limit else { return };
fn trim<T>(items: &mut Vec<T>, keep: usize) { fn trim<T>(items: &mut Vec<T>, keep: usize) {
@ -771,6 +783,19 @@ impl Coordinator {
&mut self, &mut self,
checkpoint_id: &Id, checkpoint_id: &Id,
) -> Outcome<(u64, Vec<u8>, Vec<(Id, Vec<u8>)>)> { ) -> Outcome<(u64, Vec<u8>, Vec<(Id, Vec<u8>)>)> {
let pending = self.begin_capture(checkpoint_id).await?;
self.finish_capture(pending).await
}
/// Sends every participant's `State.Capture` for the committed boundary and returns without
/// waiting for the replies: the capture off the loop (TASK-01 review N5).
///
/// Each participant takes its state at the boundary when it handles the request, which it
/// does before any request sent after it (a worker takes its lock in arrival order), and a
/// participant that encodes off its lock (the legacy agent) answers the next Prepare while it
/// seals the payload. The session may step on; [`Coordinator::finish_capture`] collects the
/// payloads, in the order sent, whenever the host is ready for them.
pub async fn begin_capture(&mut self, checkpoint_id: &Id) -> Outcome<PendingCapture> {
let origin = self.phases.phase(); let origin = self.phases.phase();
let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary()) let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary())
else { else {
@ -789,24 +814,67 @@ impl Coordinator {
participants.extend(self.agents.iter().map(|slot| slot.worker.clone())); participants.extend(self.agents.iter().map(|slot| slot.worker.clone()));
let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json()); let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json());
let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()];
let mut payloads = Vec::new(); let scope = self.scope(boundary);
let mut calls = Vec::new();
for worker in participants { for worker in participants {
let reply = self let request_id = self.serials.next(&worker.service);
.call(&worker, "State.Capture", Some(self.scope(boundary)), params.clone(), &[], &want) let sent = crate::rpc::send(
.await?; &self.bus,
&worker,
"State.Capture",
Some(scope.clone()),
params.clone(),
&[],
request_id,
&want,
)
.await;
match sent {
Ok(sent) => calls.push((worker, sent)),
Err(e) => {
self.blame(Some(worker.worker_id.clone()));
return Err(self.fail_now(e, "capture"));
}
}
}
self.transition(origin)?;
Ok(PendingCapture { checkpoint_id: checkpoint_id.clone(), boundary, scope, calls })
}
/// Collects a capture begun with [`Coordinator::begin_capture`]: the world's payload and
/// every agent's, read and released.
pub async fn finish_capture(
&mut self,
pending: PendingCapture,
) -> Outcome<(u64, Vec<u8>, Vec<(Id, Vec<u8>)>)> {
let PendingCapture { checkpoint_id, boundary, scope, calls } = pending;
let mut payloads = Vec::new();
for (worker, sent) in calls {
let reply = match sent.finish().await {
Ok(reply) => reply,
Err(e) => {
self.blame(Some(worker.worker_id.clone()));
return Err(self.fail_now(e, "capture"));
}
};
self.check_reply(&worker, &reply, &Some(scope.clone()), "State.Capture")?;
if let Err(e) = reply.result() {
return Err(self.fail_now(e, "capture"));
}
let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else { let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else {
return Err(self.fail_now( return Err(self.fail_now(
DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"),
"capture", "capture",
)); ));
}; };
let span = crate::profile::span("coord.capture.read");
let bytes = artifact.read_all().await.map_err(|e| { let bytes = artifact.read_all().await.map_err(|e| {
self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") 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?; self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?;
payloads.push((worker.worker_id.clone(), bytes)); payloads.push((worker.worker_id.clone(), bytes));
} }
self.transition(origin)?;
let world = payloads.remove(0).1; let world = payloads.remove(0).1;
self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}")); self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}"));
Ok((boundary, world, payloads)) Ok((boundary, world, payloads))
@ -1575,6 +1643,19 @@ struct AdmissionState {
ended: Vec<(Admission, AdmissionEnd)>, ended: Vec<(Admission, AdmissionEnd)>,
} }
impl AdmissionState {
fn set_remaining(&mut self, agent_id: &Id, remaining: Option<f64>) {
match remaining {
Some(ms) => {
self.remaining.insert(agent_id.clone(), ms);
}
None => {
self.remaining.remove(agent_id);
}
}
}
}
/// The edge's handle on admission: queue what the composition's rules admitted, read the last /// The edge's handle on admission: queue what the composition's rules admitted, read the last
/// commit's stimulus pulse, collect the outcomes. Clone it freely; every clone is the same queue. /// commit's stimulus pulse, collect the outcomes. Clone it freely; every clone is the same queue.
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@ -1632,6 +1713,11 @@ impl AdmissionQueue {
} }
fn end(&self, admissions: Vec<Admission>, end: AdmissionEnd) { fn end(&self, admissions: Vec<Admission>, end: AdmissionEnd) {
self.commit(admissions, end, &[]);
}
/// Ends the admissions and records the commit's pulses under one lock.
fn commit(&self, admissions: Vec<Admission>, end: AdmissionEnd, pulses: &[(Id, Option<f64>)]) {
let mut state = self.lock(); let mut state = self.lock();
for admission in admissions { for admission in admissions {
state state
@ -1639,18 +1725,38 @@ impl AdmissionQueue {
.retain(|a| a.interaction_id() != admission.interaction_id()); .retain(|a| a.interaction_id() != admission.interaction_id());
state.ended.push((admission, end.clone())); state.ended.push((admission, end.clone()));
} }
for (agent_id, remaining) in pulses {
state.set_remaining(agent_id, *remaining);
}
}
/// Decides and queues one admission under the lock every commit takes: `decide` gets the
/// agent's last reported pulse and the longest pending one, and returns the admission to
/// queue (or a refusal). No commit can interleave between the reads and the push, which is
/// the single-threaded legacy loop's answer (TASK-01 review R2-3).
pub fn admit_with<E>(
&self,
agent_id: &Id,
decide: impl FnOnce(Option<f64>, Option<f64>) -> Result<Admission, E>,
) -> Result<Admission, E> {
let mut state = self.lock();
let remaining = state.remaining.get(agent_id).copied();
let pending = state
.queued
.iter()
.chain(state.in_flight.iter())
.filter(|a| a.agent_id() == agent_id)
.map(|a| match a {
Admission::Stimulus { duration_ms, .. } => *duration_ms,
})
.reduce(f64::max);
let admission = decide(remaining, pending)?;
state.queued.push(admission.clone());
Ok(admission)
} }
fn set_remaining(&self, agent_id: &Id, remaining: Option<f64>) { fn set_remaining(&self, agent_id: &Id, remaining: Option<f64>) {
let mut state = self.lock(); self.lock().set_remaining(agent_id, remaining);
match remaining {
Some(ms) => {
state.remaining.insert(agent_id.clone(), ms);
}
None => {
state.remaining.remove(agent_id);
}
}
} }
fn forget_remaining(&self) { fn forget_remaining(&self) {
@ -1691,6 +1797,21 @@ pub struct RollbackDetails {
pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>, pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>,
} }
/// A capture sent to every participant and not yet collected ([`Coordinator::begin_capture`]).
pub struct PendingCapture {
checkpoint_id: Id,
boundary: u64,
scope: Scope,
calls: Vec<(WorkerRef, crate::rpc::SentCall)>,
}
impl PendingCapture {
/// The committed boundary the capture is of.
pub fn boundary(&self) -> u64 {
self.boundary
}
}
/// A checkpoint of another format, assembled by an importer in each participant's own capture /// A checkpoint of another format, assembled by an importer in each participant's own capture
/// format, to install as a session's start ([`Coordinator::import`]). /// format, to install as a session's start ([`Coordinator::import`]).
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -2445,10 +2566,14 @@ impl Coordinator {
self.stats.advances += 1; self.stats.advances += 1;
// The admissions this transition carried are applied: its Prepare committed. // The admissions this transition carried are applied: its Prepare committed.
let applied = std::mem::take(&mut self.in_flight_admissions); let applied = std::mem::take(&mut self.in_flight_admissions);
self.admissions.end(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }); // One lock for the end of the in-flight admissions and the new pulse: an edge thread
for (agent_id, result) in &commits { // never sees the admission gone and the old pulse still standing (TASK-01 review R2-3).
self.admissions.set_remaining(agent_id, result.telemetry.stimulus_remaining_ms); let pulses: Vec<(Id, Option<f64>)> = commits
} .iter()
.map(|(agent_id, result)| (agent_id.clone(), result.telemetry.stimulus_remaining_ms))
.collect();
self.admissions
.commit(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }, &pulses);
let view_digests = if self.record_details && self.digest_views { let view_digests = if self.record_details && self.digest_views {
self.view_digests(&step_result.observation).await? self.view_digests(&step_result.observation).await?
@ -2521,7 +2646,16 @@ impl Coordinator {
} }
let publishing = Instant::now(); let publishing = Instant::now();
self.publish_events(k + 1, &evaluation.events).await?; 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
// `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?; self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?;
}
self.metrics.record("publish", publishing.elapsed()); self.metrics.record("publish", publishing.elapsed());
// A rollback request was applied above and is not an episode end; only a terminal one // A rollback request was applied above and is not an episode end; only a terminal one
@ -5921,3 +6055,71 @@ impl Coordinator {
}) })
} }
} }
#[cfg(test)]
mod admission_race_tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
/// TASK-01 review R2-3: a sugar arriving while a commit ends the in-flight admission and
/// reports the pulse must never see "no pending admission" beside the old, over pulse. The
/// only state the hammer accepts in is exactly that torn one; the commit under test is
/// atomic, so it is never seen.
#[test]
fn no_sugar_is_admitted_between_a_commit_ending_and_its_pulse() {
let queue = AdmissionQueue::default();
let agent = id("fly");
let in_flight = Admission::Stimulus {
agent_id: agent.clone(),
interaction_id: id("sugar-1"),
kind_id: id("reward-pulse"),
duration_ms: 400.0,
};
let stop = AtomicBool::new(false);
let torn = AtomicBool::new(false);
std::thread::scope(|scope| {
scope.spawn(|| {
while !stop.load(Ordering::Relaxed) {
let admitted = queue.admit_with(&agent, |remaining, pending| {
if remaining.unwrap_or(0.0).max(pending.unwrap_or(0.0)) > 0.0 {
Err(())
} else {
Ok(Admission::Stimulus {
agent_id: agent.clone(),
interaction_id: id("sugar-x"),
kind_id: id("reward-pulse"),
duration_ms: 1.0,
})
}
});
if admitted.is_ok() {
torn.store(true, Ordering::Relaxed);
return;
}
}
});
for _ in 0..200_000 {
if torn.load(Ordering::Relaxed) {
break;
}
// The state after a cut: the sugar is in flight and the last pulse is over.
{
let mut state = queue.lock();
state.queued.clear();
state.in_flight = vec![in_flight.clone()];
state.set_remaining(&agent, Some(0.0));
}
queue.commit(
vec![in_flight.clone()],
AdmissionEnd::Applied { boundary: 1 },
&[(agent.clone(), Some(400.0))],
);
}
stop.store(true, Ordering::Relaxed);
});
assert!(
!torn.load(Ordering::Relaxed),
"a sugar was admitted into a live pulse in the commit's window"
);
}
}

View file

@ -325,6 +325,43 @@ pub fn encode_payload(
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
} }
/// A capture's inputs, copied at the boundary so the encoding can run off the endpoint's lock.
struct CaptureSnapshot {
state: AgentState,
agent_id: Id,
checkpoint_id: Id,
scope: Scope,
committed_step: u64,
profile: AssetRef,
seed: i32,
reinforcements: u64,
macro_channels: Vec<String>,
accumulator: TickAccumulator,
context: TypedValue,
}
impl CaptureSnapshot {
fn encode(&self) -> DomainResult<Vec<u8>> {
encode_payload(
&self.state,
&PayloadIdentity {
agent_id: &self.agent_id,
checkpoint_id: &self.checkpoint_id,
source_scope: &self.scope,
committed_step: self.committed_step,
profile: &self.profile,
seed: self.seed,
reinforcements: self.reinforcements,
macro_channels: &self.macro_channels,
},
&self.accumulator,
&self.context,
None,
)
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
}
}
/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). /// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`).
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> { pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
let parts = decode_envelope(bytes, PAYLOAD_MAGIC) let parts = decode_envelope(bytes, PAYLOAD_MAGIC)
@ -1375,7 +1412,8 @@ impl LegacyAgentWorker {
/// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session` /// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session`
/// manifest member with the accumulator, the context and the identities. The readout /// manifest member with the accumulator, the context and the identities. The readout
/// transient is not in it (`legacy-transient-reset`). /// transient is not in it (`legacy-transient-reset`).
fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<Vec<u8>> { /// Everything a capture payload is encoded from, copied out of the live agent.
fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<CaptureSnapshot> {
let agent = self.agent.as_ref().expect("initialized"); let agent = self.agent.as_ref().expect("initialized");
let accumulator = self.accumulator.as_ref().expect("initialized"); let accumulator = self.accumulator.as_ref().expect("initialized");
let context = self.context.as_ref().expect("initialized"); let context = self.context.as_ref().expect("initialized");
@ -1383,23 +1421,19 @@ impl LegacyAgentWorker {
// The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
encode_payload( Ok(CaptureSnapshot {
&state, state,
&PayloadIdentity { agent_id: self.config.agent_id.clone(),
agent_id: &self.config.agent_id, checkpoint_id: checkpoint_id.clone(),
checkpoint_id, scope: scope.clone(),
source_scope: scope,
committed_step: k, committed_step: k,
profile: &self.profile.asset, profile: self.profile.asset.clone(),
seed: self.seed, seed: self.seed,
reinforcements: self.reinforcements, reinforcements: self.reinforcements,
macro_channels: &self.config.macro_channels, macro_channels: self.config.macro_channels.clone(),
}, accumulator: accumulator.clone(),
accumulator, context: context.typed.clone(),
&context.typed, })
None,
)
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
} }
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> { async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
@ -1425,36 +1459,50 @@ impl LegacyAgentWorker {
)); ));
} }
let params: CaptureParams = ctx.params()?; let params: CaptureParams = ctx.params()?;
let previous = self.status.state(); // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's
self.status.set_state(WorkerState::Capturing); // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
let bytes = self.payload(&params.checkpoint_id, &scope, k); // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next
let bytes = match bytes { // Prepare does not wait for them (TASK-01 review N5).
Ok(bytes) => bytes, let snapshot = {
Err(e) => { let _span = crate::profile::span("agent.capture.snapshot");
self.status.set_state(previous); self.snapshot(&params.checkpoint_id, &scope, k)?
return Err(e);
}
}; };
let digest = digest_of_bytes(&bytes);
let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await;
self.status.set_state(previous);
let artifact = artifact?;
let graph = self.graph.as_ref().expect("initialized"); let graph = self.graph.as_ref().expect("initialized");
let result = CaptureResult { let compatibility = compatibility_digest(
checkpoint_id: params.checkpoint_id,
boundary: k,
compatibility_digest: compatibility_digest(
&self.config.agent_id, &self.config.agent_id,
&self.profile.asset, &self.profile.asset,
graph, graph,
self.seed, self.seed,
), );
let client = ctx.client.clone();
Ok(HandlerReply::deferred(Box::pin(async move {
let bytes = tokio::task::spawn_blocking(move || {
let _span = crate::profile::span("agent.capture.encode");
let bytes = snapshot.encode()?;
let digest = {
let _span = crate::profile::span("agent.capture.digest");
digest_of_bytes(&bytes)
};
Ok::<_, DomainError>((bytes, digest))
})
.await
.map_err(|e| DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None))?;
let (bytes, digest) = bytes?;
let artifact = {
let _span = crate::profile::span("agent.capture.seal");
crate::state::seal_payload(&client, &bytes, &digest).await?
};
let result = CaptureResult {
checkpoint_id: params.checkpoint_id,
boundary: k,
compatibility_digest: compatibility,
payload: artifact.reference().clone(), payload: artifact.reference().clone(),
}; };
Ok(HandlerReply::with_artifacts( Ok(HandlerReply::with_artifacts(
object(result.to_json()), object(result.to_json()),
vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)],
)) ))
})))
} }
async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> { async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {

View file

@ -69,8 +69,35 @@ pub async fn call(
request_id: DomainRequestId, request_id: DomainRequestId,
want_artifacts: &[String], want_artifacts: &[String],
) -> Result<DomainReply, DomainError> { ) -> Result<DomainReply, DomainError> {
send(bus, target, method, scope, params, attachments, request_id, want_artifacts)
.await?
.finish()
.await
}
/// A domain call that has been sent and not yet answered: the bus has it in order, so a call
/// sent after it to the same worker is dispatched after it.
pub struct SentCall {
method: String,
pending: flybus::PendingCall,
request_id: DomainRequestId,
want_artifacts: Vec<String>,
}
/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits).
#[allow(clippy::too_many_arguments)]
pub async fn send(
bus: &flybus::Client,
target: &WorkerRef,
method: &str,
scope: Option<Scope>,
params: Map<String, Value>,
attachments: &[(&str, &flybus::Artifact)],
request_id: DomainRequestId,
want_artifacts: &[String],
) -> Result<SentCall, DomainError> {
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) }; let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
let mut pending = bus let pending = bus
.call( .call(
&target.service, &target.service,
Some(&target.bus_incarnation), Some(&target.bus_incarnation),
@ -80,26 +107,49 @@ pub async fn call(
) )
.await .await
.map_err(|e| bus_error(method, &e))?; .map_err(|e| bus_error(method, &e))?;
let result = pending.result().await.map_err(|e| bus_error(method, &e))?; Ok(SentCall {
method: method.to_owned(),
pending,
request_id,
want_artifacts: want_artifacts.to_vec(),
})
}
impl SentCall {
/// Waits for the terminal reply.
pub async fn finish(mut self) -> Result<DomainReply, DomainError> {
let method = self.method.as_str();
let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?;
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
let mut artifacts = BTreeMap::new(); // An independent explicit hold on each wanted attachment, so the handle outlives this
for name in want_artifacts { // delivery and can be forwarded to several Commit calls and to publication. The holds
if let Ok(artifact) = result.artifact(name) { // are independent router round trips, so they are taken concurrently.
// An independent explicit hold, so the handle outlives this delivery and can be let wanted: Vec<(String, flybus::Artifact)> = self
// forwarded to several Commit calls and to publication. .want_artifacts
.iter()
.filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a)))
.collect();
let retains: Vec<_> = wanted
.into_iter()
.map(|(name, artifact)| {
tokio::spawn(async move {
match artifact.retain().await { match artifact.retain().await {
Ok(hold) => { Ok(hold) => (name, hold),
artifacts.insert(name.clone(), hold); Err(_) => (name, artifact),
}
Err(_) => {
artifacts.insert(name.clone(), artifact);
}
} }
})
})
.collect();
let mut artifacts = BTreeMap::new();
for retain in retains {
if let Ok((name, artifact)) = retain.await {
artifacts.insert(name, artifact);
} }
} }
drop(result); drop(result);
Ok(DomainReply { outcome, request_id, artifacts }) Ok(DomainReply { outcome, request_id: self.request_id, artifacts })
}
} }
/// Maps a bus failure onto a domain error, preserving how certain the mutation is. /// Maps a bus failure onto a domain error, preserving how certain the mutation is.

View file

@ -113,24 +113,39 @@ impl StatusCell {
} }
} }
/// The rest of a reply a handler finishes outside the endpoint's lock.
pub type DeferredReply =
std::pin::Pin<Box<dyn std::future::Future<Output = DomainResult<HandlerReply>> + Send>>;
/// What a handler produced: a domain `result` object and the artifacts it attaches. /// What a handler produced: a domain `result` object and the artifacts it attaches.
pub struct HandlerReply { pub struct HandlerReply {
pub result: Map<String, Value>, pub result: Map<String, Value>,
pub artifacts: Vec<(String, flybus::Artifact)>, pub artifacts: Vec<(String, flybus::Artifact)>,
/// True when a failure left the endpoint mutated; the shell reports it as such. /// True when a failure left the endpoint mutated; the shell reports it as such.
pub mutated: bool, pub mutated: bool,
/// When set, the reply is this future's: the handler took what it needs from the endpoint
/// (a state snapshot at the committed boundary) and the rest -- encoding, digesting and
/// sealing a capture payload -- runs after the endpoint's lock is released, so the next
/// mutation (the next `Agent.Prepare`) does not wait for it. The bus call is answered
/// when it completes, and cached like any other reply.
pub deferred: Option<DeferredReply>,
} }
impl HandlerReply { impl HandlerReply {
pub fn new(result: Map<String, Value>) -> HandlerReply { pub fn new(result: Map<String, Value>) -> HandlerReply {
HandlerReply { result, artifacts: Vec::new(), mutated: true } HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None }
} }
pub fn with_artifacts( pub fn with_artifacts(
result: Map<String, Value>, result: Map<String, Value>,
artifacts: Vec<(String, flybus::Artifact)>, artifacts: Vec<(String, flybus::Artifact)>,
) -> HandlerReply { ) -> HandlerReply {
HandlerReply { result, artifacts, mutated: true } HandlerReply { result, artifacts, mutated: true, deferred: None }
}
/// A reply finished by `rest` outside the endpoint's lock ([`HandlerReply::deferred`]).
pub fn deferred(rest: DeferredReply) -> HandlerReply {
HandlerReply { result: Map::new(), artifacts: Vec::new(), mutated: true, deferred: Some(rest) }
} }
/// The canonical JSON of one method result. /// The canonical JSON of one method result.
@ -304,6 +319,7 @@ async fn run<E: WorkerEndpoint>(
) )
}; };
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new(); let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
let order = Arc::new(LockOrder::default());
while let Some(incoming) = service.next().await { while let Some(incoming) = service.next().await {
let method = incoming.method().to_owned(); let method = incoming.method().to_owned();
let responder = incoming.responder(); let responder = incoming.responder();
@ -491,9 +507,12 @@ async fn run<E: WorkerEndpoint>(
// original bus call still completes normally. The endpoint mutex, not this loop, // original bus call still completes normally. The endpoint mutex, not this loop,
// enforces one mutation at a time. // enforces one mutation at a time.
running.retain(|task| !task.is_finished()); running.retain(|task| !task.is_finished());
let ticket = order.issue();
running.push(tokio::spawn(execute( running.push(tokio::spawn(execute(
client.clone(), client.clone(),
endpoint.clone(), endpoint.clone(),
order.clone(),
ticket,
cache.clone(), cache.clone(),
status.clone(), status.clone(),
worker_id.clone(), worker_id.clone(),
@ -512,11 +531,73 @@ async fn run<E: WorkerEndpoint>(
} }
} }
/// Admitted mutations take the endpoint's lock in the order they arrived.
///
/// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in
/// spawn order: without this, a `State.Capture` followed on the wire by the next
/// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken
/// in arrival order, and the lock taken only on the ticket's turn keep the wire's order.
#[derive(Default)]
struct LockOrder {
issued: std::sync::atomic::AtomicU64,
turn: std::sync::atomic::AtomicU64,
changed: tokio::sync::Notify,
}
impl LockOrder {
fn issue(&self) -> u64 {
self.issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}
async fn lock_in_turn<'a, E>(
&self,
ticket: u64,
endpoint: &'a tokio::sync::Mutex<E>,
) -> tokio::sync::MutexGuard<'a, E> {
loop {
let changed = self.changed.notified();
if self.turn.load(std::sync::atomic::Ordering::SeqCst) == ticket {
break;
}
changed.await;
}
// Queue on the lock first, then hand the turn on: the next ticket queues behind this
// one on the (fair) mutex.
let lock = endpoint.lock();
tokio::pin!(lock);
let guard = match futures_poll_once(lock.as_mut()).await {
Some(guard) => guard,
None => {
self.advance();
return lock.await;
}
};
self.advance();
guard
}
fn advance(&self) {
self.turn.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.changed.notify_waiters();
}
}
/// Polls a future once: its output if it is ready, else `None` with the future registered.
async fn futures_poll_once<F: std::future::Future + Unpin>(mut f: F) -> Option<F::Output> {
std::future::poll_fn(|cx| match std::pin::Pin::new(&mut f).poll(cx) {
std::task::Poll::Ready(v) => std::task::Poll::Ready(Some(v)),
std::task::Poll::Pending => std::task::Poll::Ready(None),
})
.await
}
/// Runs one admitted mutation, records its reply and answers the bus call. /// Runs one admitted mutation, records its reply and answers the bus call.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
async fn execute<E: WorkerEndpoint>( async fn execute<E: WorkerEndpoint>(
client: flybus::Client, client: flybus::Client,
endpoint: Arc<tokio::sync::Mutex<E>>, endpoint: Arc<tokio::sync::Mutex<E>>,
order: Arc<LockOrder>,
ticket: u64,
cache: Arc<tokio::sync::Mutex<ResultCache>>, cache: Arc<tokio::sync::Mutex<ResultCache>>,
status: StatusCell, status: StatusCell,
worker_id: Id, worker_id: Id,
@ -533,7 +614,7 @@ async fn execute<E: WorkerEndpoint>(
let outcome = { let outcome = {
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // 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. // never held across a bus round trip taken by anything else.
let mut e = endpoint.lock().await; let mut e = order.lock_in_turn(ticket, &endpoint).await;
let ctx = HandlerCtx { let ctx = HandlerCtx {
method: &method, method: &method,
request: &request, request: &request,
@ -542,16 +623,34 @@ async fn execute<E: WorkerEndpoint>(
}; };
e.handle(ctx).await e.handle(ctx).await
}; };
// A deferred reply finishes here, with the endpoint's lock released.
let outcome = match outcome {
Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await,
other => other,
};
match outcome { match outcome {
Ok(reply) => { Ok(reply) => {
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone()); let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
let mut holds = Vec::with_capacity(reply.artifacts.len()); // The cache owns its own hold on every artifact, so a replay survives the first
for (name, artifact) in &reply.artifacts { // caller consuming its delivery. The holds are independent router round trips, so
// The cache owns its own hold, so a replay survives the first caller // they are taken concurrently.
// consuming its delivery. let retains: Vec<_> = reply
.artifacts
.iter()
.map(|(name, artifact)| {
let (name, artifact) = (name.clone(), artifact.clone());
tokio::spawn(async move {
match artifact.retain().await { match artifact.retain().await {
Ok(hold) => holds.push((name.clone(), hold)), Ok(hold) => (name, hold),
Err(_) => holds.push((name.clone(), artifact.clone())), Err(_) => (name, artifact),
}
})
})
.collect();
let mut holds = Vec::with_capacity(retains.len());
for retain in retains {
if let Ok(pair) = retain.await {
holds.push(pair);
} }
} }
let cached = CachedReply::with_artifacts(outcome.clone(), holds); let cached = CachedReply::with_artifacts(outcome.clone(), holds);