Merge port/perf-01 (PERF-01) into v0.7.0 release candidate

This commit is contained in:
acamilo 2026-09-30 10:05:07 +00:00
commit 7f5f5d0e5d
27 changed files with 1254 additions and 208 deletions

View file

@ -78,7 +78,10 @@ Application / supervisor Application presentation
This diagram is connectivity, not execution order. The step contract defines causal order.
One router can host several independent sessions and application consumers; a deployment may
choose one router per application for fault isolation. A router crash affects all its clients,
so choose that boundary deliberately. In-process mode still exercises routing and ownership.
so choose that boundary deliberately. In-process mode still exercises routing and ownership,
unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1,
amendment 2026-09-30), as the legacy composition's in-process release configuration is; process
mode always goes through the router.
Defaults: coordinator per session, worker per fly, environment worker per world. Task and
per-agent executors begin as coordinator-local libraries. An environment helper may own a

View file

@ -523,3 +523,14 @@ this same section forbids to reject one.
longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because
section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled
illustrative.
**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client
gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in
the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no
router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into
one under the same reference. They read, clone and retain without a router, and no router ever
learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish`
before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
the same date); section 8's ownership rules apply to every artifact a router stores, which these
never are.

View file

@ -441,6 +441,44 @@ B1, N1 and N3.
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
- The report `claude-task-01` has the per-phase table and what would close the rest.
### PERF-01 — The session runtime's per-frame cost (port slice)
**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and
awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the
in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy
loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame,
in-process and process, and the compatibility string is unchanged.
- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30).
An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`,
`launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method.
The request still goes through the shell's admission, deduplication, arrival order and
endpoint, and the reply is the same outcome. Handler media over the lane are in-memory
artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy,
no retain or open round trip. A bus call or a publication carries a sealed copy
(`rpc::promote`), begun while the task and the commits run. Process mode is untouched.
`FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also
runs over the lane.
- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare
ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits,
proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs.
- **The session topic** gets a committed snapshot every 60th boundary in a service session (and
at every boundary with events or boundary actions), not every other one. Nothing in the
release subscribes; the stream is the legacy feed.
- Small ones: a single dispatch job is called in place, the shell moves the reply result
instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling
spans for the shell, the lane, each handler and the brain's own phase clock.
- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any
other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and
work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate
(an AGENT-01 amendment) was not needed once the bitset cost nothing.
- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`;
the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the
release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms
to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.

View file

@ -17,6 +17,37 @@ ownership. This document owns Scope, model-related scalar types, worker capabili
domain operation deduplication and errors. Domain request identity is independent of the bus
callId: a safe retry has a new transport callId but the original domain requestId/body.
**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker
RPC is a Flybus call", for participants that share the coordinator's process. The release
container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a
frame above the brain (three round trips through the router and four or five sealed store files
a frame), against 0.7 ms for everything the legacy loop does outside its ticks.
- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator
directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods --
step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to
that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks.
- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through
the same shell code as a bus request: section 5's classification, canonical body digest,
result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the
endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker,
incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and
resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped
before answering is a lost connection (mutation unknown).
- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1
section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef`
(`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3
holds as written: every `ArtifactRef` in a payload is backed by a live handle the message
carries. An in-memory artifact never crosses a router: a bus call or a publication that needs
one carries a sealed copy (the coordinator makes it), and the snapshot names the copy.
A sealed handle a handler returns over the lane reaches the caller in memory under the same
reference.
- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached
over the bus, so process mode keeps exercising routing and ownership, and the bus path stays
the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic
transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy
parity runs in-process (lane) and process (bus).
## 2. Common domain types
```ts

View file

@ -415,6 +415,31 @@ interface LegacyGameboyComposition {
for publication, traces and descriptor revisions, not a restore gate. This matches today's
behaviour, where a decoder change does not refuse a checkpoint.
**Amendment, 2026-09-30 (PERF-01): the in-process release configuration.** Nothing in the
declaration, the digest or the compatibility string changes; these are execution choices of the
composition as `fly-legacy-session` builds it, recorded here because the shadow compares the
behaviour they must not change.
- *In-process participants are called over the local lane* ([session RPCs](ipc-v1.md) section 1,
2026-09-30): the frame, the memory image, the audio chunk and the spike bitset are in-memory
artifacts, handed over without a store file. Process mode is unchanged and still goes through
the router. `FLY_SESSION_LOCAL_LANE=0` puts an in-process session back on the bus.
- *`telemetry.spikes` is unchanged*: one bitset per transition, bit `i` set when neuron `i`
spiked in `[transition start, brain time)`, the legacy layout. The agent now builds it as the
union of the kernel's per-tick spike lists while Prepare ticks (`LifNetwork::tick_spikes`)
instead of scanning 139,255 last-spike times in Commit; the two are equal by construction and
by test, and the parity runs compare the bitset every frame. The AGENT-01 alternative -- attach
it only at the feed rate -- was not needed and was not made.
- *Committed snapshots on the session topic*: a service session publishes every 60th boundary and
every boundary with task events or boundary actions (it was every other boundary). The live
presentation is the legacy feed, which the service host builds from the committed boundary at
30 Hz; nothing in the release subscribes to the session topic, and each publication seals a
store copy of the frame and the audio chunk. Every publication is still of a committed
boundary and still attaches the media it names (publishing-v1 section 3).
- *Nothing runs beside the brain's ticks.* On the release CPU with the sweep owning every core of
the flysim cpuset, work overlapping Prepare (a publication left in flight, for instance) slowed
the ticks by up to a third, so the coordinator finishes each boundary before the next Prepare.
## 13. Machine-readable parts
| Where | What |

View file

@ -12,6 +12,14 @@ ordering. Its frame order is this document's transaction order (legacy-gameboy-v
maps it step by step), so the amendments below add capabilities to the protocol and change
none of its ordering rules.
**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of
[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router:
the arrows below are then direct calls into the same worker shell, carrying the same requests and
replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that
overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the
coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the
world, the task and the commits run, and the snapshot is published before the next Prepare.
## 1. Committed boundary
At `Ready(epoch, k)`:

View file

@ -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";
@ -64,6 +70,14 @@ pub struct LegacyConfig {
pub record: bool,
}
/// `FLY_SESSION_LOCAL_LANE=0` keeps in-process participants on the bus: a measurement knob,
/// so the local lane can be compared with the bus path in one build. On by default.
pub const LOCAL_LANE_ENV: &str = "FLY_SESSION_LOCAL_LANE";
fn local_lane_enabled() -> bool {
std::env::var(LOCAL_LANE_ENV).map_or(true, |v| v != "0")
}
/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds.
pub fn channels_and_hold(mode: MacroMode) -> (Vec<String>, f64) {
let channels: Vec<&str> = if mode.dealt() {
@ -311,8 +325,10 @@ impl LegacySession {
router,
config.mode,
// In-process participants reach the router in memory: no socket between two tasks
// of one process (a separate process always uses the socket).
Via::Memory,
// of one process (a separate process always uses the socket). They are called over
// the local lane: the same worker shell, no bus message and no store file per
// artifact (PERF-01, `workers-v1` amendment).
if local_lane_enabled() { Via::Local } else { Via::Memory },
&store_root,
&sockets,
budget,

View file

@ -600,7 +600,9 @@ impl Task for TaskFace {
));
}
}
let span = fly_session::profile::span("task.image");
let image = inner.image_of(new)?;
drop(span);
let ms = inner.ms;
let k1 = scope.step + 1;
inner.evaluations += 1;
@ -608,6 +610,7 @@ impl Task for TaskFace {
// `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the
// location (the agent's, from the context), then the rank.
let span = fly_session::profile::span("task.sample");
let cartridge = inner.cartridge.clone();
let rewards = {
let Inner {
@ -621,7 +624,11 @@ impl Task for TaskFace {
};
adapter.sample(&mut reader, ms)
};
drop(span);
let span = fly_session::profile::span("task.observe");
let abandoned = inner.observe(&image, ms);
drop(span);
let span = fly_session::profile::span("task.ratchet");
let progress = inner.adapter.progress();
// `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above
@ -646,6 +653,8 @@ impl Task for TaskFace {
},
);
drop(span);
let span = fly_session::profile::span("task.outcome");
let mut outcome = AgentOutcome::default();
let mut events = Vec::new();
for (n, event) in rewards.iter().enumerate() {
@ -695,8 +704,11 @@ impl Task for TaskFace {
record.rank = progress.rank;
record.saved = saved;
}
drop(span);
let span = fly_session::profile::span("task.contexts");
let next_contexts = inner.contexts();
let progress_value = inner.progress_value();
drop(span);
inner.current = Some((new.boundary, image));
if !recover {
inner.close();

View file

@ -525,6 +525,18 @@ async fn run_booted(
async fn fafb_boot_run_save_restore() {
let Some(rom_path) = rom_path() else { return };
let Some(dataset) = fafb() else { return };
// The live fly's checkpoints predate `pokered-unique8-v8` (row 68, v0.6.7), and a boot takes
// an older adapter's file only when the operator asks for its migration, as the v0.6.7
// deploy does. Both runtimes read the same list, so the comparison is unchanged.
if std::env::var_os("FLY_ACCEPT_ADAPTERS").is_none() {
// SAFETY: set before any runtime or thread of this test reads the environment.
unsafe {
std::env::set_var(
"FLY_ACCEPT_ADAPTERS",
flybrain_gb::pokemon_red::MIGRATES_FROM.join(","),
);
}
}
// The rollback file (a ratchet rollback on the first boundary), and the live fly's largest
// task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound
// (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`).

View file

@ -114,12 +114,28 @@ impl Legacy {
}
}
/// The service's runtime: two Tokio workers (SERVE-01's `flysim-session`).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_against_legacy_interleaved() {
run(2).await;
}
/// PERF-01: the same with one Tokio worker, the coordinator, the router and every in-process
/// participant on one thread beside the brain's sweep pool. `FLY_PERF_WORKERS` picks which of
/// the two runs (default 2).
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn session_against_legacy_interleaved_one_worker() {
run(1).await;
}
async fn run(workers: usize) {
if std::env::var_os("FLY_TASK01_BENCH").is_none() {
eprintln!("skipping: FLY_TASK01_BENCH is not set");
return;
}
if env_usize("FLY_PERF_WORKERS", 2) != workers {
return;
}
let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = (
std::env::var_os("FLY_ROM").map(std::path::PathBuf::from),
legacy_parity::fafb_dir(),
@ -134,7 +150,26 @@ async fn session_against_legacy_interleaved() {
let rom = std::fs::read(&rom_path).unwrap();
let bytes = std::fs::read(&checkpoint_path).unwrap();
let checkpoint = flysim::store::decode(&bytes).unwrap();
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] {
// PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-process
// over the local lane, the default in-process path), `bus` (in-process over the bus,
// `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three.
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned());
// `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's
// `flysim-session`): the spike bitset of every commit and the audio chunk of every boundary.
let service = std::env::var_os("FLY_PERF_SERVICE").is_some();
for arm in arms.split(',') {
let mode = match arm {
"local" | "bus" => ExecutionMode::InProcess,
"process" => ExecutionMode::Process,
other => panic!("unknown arm {other}"),
};
// SAFETY: set before the session's runtime reads it; nothing else reads the variable.
unsafe {
std::env::set_var(
fly_legacy_session::composition::LOCAL_LANE_ENV,
if arm == "bus" { "0" } else { "1" },
);
}
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
let root = tempfile::tempdir().unwrap();
let mut session = LegacySession::start(
@ -155,6 +190,14 @@ async fn session_against_legacy_interleaved() {
session.bootstrap().await.unwrap();
session.import_flysim01(&bytes, &id("e2")).await.unwrap();
session.coordinator.disable_pacing();
if service {
session
.coordinator
.request_commit_attachments(&[fly_session::legacy_agent::SPIKES_ATTACHMENT]);
session.coordinator.digest_views(false);
}
let audio_name =
fly_session::media::audio_attachment(fly_session::legacy_env::AUDIO_STREAM_ID);
// Warm both.
for _ in 0..chunk {
legacy.step();
@ -162,6 +205,10 @@ async fn session_against_legacy_interleaved() {
}
session.coordinator.metrics.clear();
let _ = fly_session::profile::report();
// The legacy brain's own phase clock, to set its ticks beside the session's
// `agent.ticks` span.
legacy.agent.network.profile = true;
legacy.agent.network.reset_timings();
let (mut legacy_ms, mut session_ms) = (0.0, 0.0);
let mut done = 0;
while done < frames {
@ -173,24 +220,35 @@ async fn session_against_legacy_interleaved() {
let at = Instant::now();
for _ in 0..chunk {
session.step().await.unwrap();
if service {
let _ = session.coordinator.take_details();
let _ = session.coordinator.media_bytes(&audio_name).await.unwrap();
}
}
session_ms += at.elapsed().as_secs_f64() * 1000.0;
done += chunk;
}
let (l, s) = (legacy_ms / done as f64, session_ms / done as f64);
eprintln!(
"{}: legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)",
"{} ({arm}{}, {workers} tokio workers): legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)",
mode.label(),
if service { ", service reads" } else { "" },
1000.0 / l,
1000.0 / s,
s / l,
FRAME_MS - l,
FRAME_MS - s
);
for (name, count, mean) in fly_session::profile::report() {
let timings = legacy.agent.network.timings();
eprintln!(
" legacy ticks (phase clock) mean {:>8.0} us over {done} frames",
timings.total_ns() as f64 / done as f64 / 1000.0
);
for (name, count, mean, max) in fly_session::profile::report_with_max() {
eprintln!(
" span {name:<26} mean {:>8.0} us n {count}",
mean.as_secs_f64() * 1e6
" span {name:<26} mean {:>8.0} us max {:>8.0} us n {count}",
mean.as_secs_f64() * 1e6,
max.as_secs_f64() * 1e6
);
}
for name in session.coordinator.metrics.names() {

View file

@ -322,6 +322,10 @@ pub struct Coordinator {
/// published and never attached to an agent's sensory input.
audio: BTreeMap<String, flybus::Artifact>,
pending_audio: BTreeMap<String, flybus::Artifact>,
/// Sealed copies of in-memory media being made for this boundary's publication, by the
/// in-memory artifact's id (PERF-01): begun as soon as `Environment.Advance` answers, so the
/// store round trips overlap the task's evaluation and the commits.
promoting: BTreeMap<String, tokio::task::JoinHandle<DomainResult<flybus::Artifact>>>,
/// One chunk sequence per declared audio stream, for this epoch.
timelines: AudioTimelines,
/// The attachment names this session's native media travels under. The composition
@ -367,6 +371,9 @@ pub struct Coordinator {
commit_attachments: Vec<String>,
/// Record [`StepDetails`] for every transition (a parity run).
record_details: bool,
/// Digest every view into the step details (on with them by default; a service that reads
/// the details only for the commit attachments turns it off).
digest_views: bool,
last_details: Option<StepDetails>,
/// Audience admissions: queued by the edge, cut into the next Prepare.
admissions: AdmissionQueue,
@ -464,6 +471,7 @@ impl Coordinator {
pending_views: BTreeMap::new(),
audio: BTreeMap::new(),
pending_audio: BTreeMap::new(),
promoting: BTreeMap::new(),
timelines: AudioTimelines::default(),
media_names: vec![
media::view_attachment(crate::environment::VIEW_ID),
@ -495,6 +503,7 @@ impl Coordinator {
environment_capabilities: Vec::new(),
commit_attachments: Vec::new(),
record_details: false,
digest_views: true,
last_details: None,
admissions: AdmissionQueue::default(),
in_flight_admissions: Vec::new(),
@ -594,6 +603,20 @@ impl Coordinator {
.collect()
}
/// The bytes of one media handle this committed boundary holds, by attachment name (the
/// view or an audio chunk), or `None` when the boundary holds no such handle. (The same
/// method as SERVE-01's service host reads the step's audio with.)
pub async fn media_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, String> {
let Some(artifact) = self.views.get(name).or_else(|| self.audio.get(name)) else {
return Ok(None);
};
artifact
.read_all()
.await
.map(Some)
.map_err(|e| format!("reading {name}: {}", e.message))
}
/// Where each declared audio stream's next chunk may start.
pub fn audio_positions(&self) -> BTreeMap<String, u64> {
self.timelines.positions()
@ -833,6 +856,13 @@ impl Coordinator {
self.record_details = on;
}
/// Whether recorded step details carry each view's SHA-256 (`StepDetails::view_digests`):
/// on by default; SERVE-01's service host reads the details for the commit attachments only
/// and turns it off, which saves hashing every frame.
pub fn digest_views(&mut self, on: bool) {
self.digest_views = on;
}
/// The details of the last completed transition, when they are recorded.
pub fn take_details(&mut self) -> Option<StepDetails> {
self.last_details.take()
@ -2228,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 {
@ -2358,6 +2416,9 @@ impl Coordinator {
let span = crate::profile::span("coord.advance");
let step_result = self.advance(k, &batch_id, &controls).await?;
drop(span);
if self.snapshot_every <= 1 || (k + 1).is_multiple_of(self.snapshot_every) {
self.begin_promotions();
}
let span = crate::profile::span("coord.observe");
// ---- Phase C: observe and evaluate the task once
@ -2494,7 +2555,7 @@ impl Coordinator {
self.admissions
.commit(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }, &pulses);
let view_digests = if self.record_details {
let view_digests = if self.record_details && self.digest_views {
self.view_digests(&step_result.observation).await?
} else {
Vec::new()
@ -2563,6 +2624,7 @@ impl Coordinator {
slot.prepared = None;
slot.prepare_request = None;
}
let publish_span = crate::profile::span("coord.publish");
self.publish_events(k + 1, &evaluation.events).await?;
// Every boundary with events or boundary actions is published; otherwise every
// `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at
@ -2574,6 +2636,7 @@ impl Coordinator {
{
self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?;
}
drop(publish_span);
// A rollback request was applied above and is not an episode end; only a terminal one
// pauses the session for the episode policy.
@ -2613,6 +2676,41 @@ impl Coordinator {
Ok(reports)
}
/// Starts sealing a bus copy of every in-memory medium the boundary just produced, for its
/// publication ([`Coordinator::publication_handle`]).
fn begin_promotions(&mut self) {
for (_, stale) in std::mem::take(&mut self.promoting) {
stale.abort();
}
for artifact in self.pending_views.values().chain(self.pending_audio.values()) {
if artifact.is_in_memory() {
let (bus, artifact) = (self.bus.clone(), artifact.clone());
let id = artifact.reference().artifact_id.clone();
self.promoting.insert(
id,
tokio::spawn(async move { crate::rpc::promote(&bus, &artifact).await }),
);
}
}
}
/// The handle a publication attaches for `artifact`: the handle itself when it is sealed in
/// the router's store, else the sealed copy begun at the Advance, or one made now.
async fn publication_handle(
&mut self,
artifact: &flybus::Artifact,
) -> DomainResult<flybus::Artifact> {
if !artifact.is_in_memory() {
return Ok(artifact.clone());
}
match self.promoting.remove(&artifact.reference().artifact_id) {
Some(task) => task.await.map_err(|e| {
DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None)
})?,
None => crate::rpc::promote(&self.bus, artifact).await,
}
}
fn batch_id(&self, k: u64) -> Id {
parse_id(&format!("batch-{}-{k}", self.epoch)).expect("epoch and step make an Id")
}
@ -2903,6 +3001,7 @@ impl Coordinator {
controls: &[PortControl],
) -> Outcome<StepResult> {
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(),
@ -2911,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());
@ -3031,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);
@ -3365,7 +3467,7 @@ impl Coordinator {
}
// Step 5: every reply in hand. The session is at Ready(e', k).
let view_digests = if self.record_details {
let view_digests = if self.record_details && self.digest_views {
let mut out = Vec::new();
for view in &restored.sensory_views {
let name = media::view_attachment(&view.view_id);
@ -4158,6 +4260,33 @@ impl Coordinator {
}
}
}
// In-memory media (the local lane) cross the router as sealed copies: the snapshot names
// the copies it attaches (the PERF-01 amendment).
let mut snapshot = snapshot;
for (_, artifact) in attachments.iter_mut() {
if !artifact.is_in_memory() {
continue;
}
let copy = match self.publication_handle(artifact).await {
Ok(copy) => copy,
Err(e) => return Err(self.fail_now(e, "publish")),
};
let (old, new) = (artifact.reference().clone(), copy.reference().clone());
for view in &mut snapshot.views {
if view.pixels == old {
view.pixels = new.clone();
}
}
for chunk in &mut snapshot.audio {
if chunk.samples == old {
chunk.samples = new.clone();
}
}
*artifact = copy;
}
for (_, unused) in std::mem::take(&mut self.promoting) {
unused.abort();
}
if self.injections.substituted_published_handle && self.injections.at_step + 1 == boundary {
// The same attachment name and the same bytes, a different object. Only the
// artifact identity sees it, which is why the check compares that and not names.
@ -5994,6 +6123,14 @@ mod admission_race_tests {
};
let stop = AtomicBool::new(false);
let torn = AtomicBool::new(false);
// The hammer must never find the queue's empty initial state (no pulse, nothing
// pending), which is a legitimate admission, not a torn commit: on a loaded box it
// can run before the first iteration below sets the state up (PERF-01 saw it once).
{
let mut state = queue.lock();
state.in_flight = vec![in_flight.clone()];
state.set_remaining(&agent, Some(0.0));
}
std::thread::scope(|scope| {
scope.spawn(|| {
while !stop.load(Ordering::Relaxed) {

View file

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

View file

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

View file

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

View file

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

View file

@ -635,8 +635,31 @@ impl Publisher {
.map(|(name, artifact)| (name.clone(), artifact.reference().clone()))
.collect();
check_publication(descriptor, snapshot, &named, audio_next_sample)?;
let refs: Vec<(&str, &flybus::Artifact)> =
attachments.iter().map(|(n, a)| (n.as_str(), a)).collect();
// An in-memory artifact (the in-process local lane) is in no router's store, so the
// published message carries a sealed copy of it and names that copy: the coherence
// check above ran against the handles the agents were given.
let mut published = std::borrow::Cow::Borrowed(snapshot);
let mut sealed = Vec::with_capacity(attachments.len());
for (name, artifact) in attachments {
let copy = crate::rpc::promote(&self.bus, artifact).await?;
if copy.reference() != artifact.reference() {
let (old, new) = (artifact.reference(), copy.reference());
let snapshot = published.to_mut();
for view in &mut snapshot.views {
if &view.pixels == old {
view.pixels = new.clone();
}
}
for chunk in &mut snapshot.audio {
if &chunk.samples == old {
chunk.samples = new.clone();
}
}
}
sealed.push((name.as_str(), copy));
}
let refs: Vec<(&str, &flybus::Artifact)> = sealed.iter().map(|(n, a)| (*n, a)).collect();
let snapshot = published.as_ref();
let topic = self.snapshot_topic.topic.clone();
let outcome = PublicationOutcome::from_bus(
&topic,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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.

View file

@ -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<u32> = 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<u32> = (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");
}

View file

@ -37,17 +37,25 @@ impl Drop for OwnerGuard {
pub(crate) fn attachment_list(
list: &[(&str, &Artifact)],
) -> (Vec<Attachment>, Vec<Arc<OwnerGuard>>) {
let atts = list
.iter()
.map(|(name, a)| Attachment {
) -> Result<(Vec<Attachment>, Vec<Arc<OwnerGuard>>), BusError> {
let mut atts = Vec::with_capacity(list.len());
let mut keep = Vec::with_capacity(list.len());
for (name, a) in list {
let Holder::Bus(owner) = &a.holder else {
// An in-memory artifact is not in any router's store, so no message may name it.
return Err(BusError::invalid(format!(
"attachment {name:?} is an in-memory artifact; seal a copy into the store first"
))
.with_dispatch(Dispatch::NotDispatched));
};
atts.push(Attachment {
name: (*name).to_owned(),
reference: a.reference.as_ref().clone(),
owner_id: a.owner.id.clone(),
})
.collect();
let keep = list.iter().map(|(_, a)| a.owner.clone()).collect();
(atts, keep)
owner_id: owner.id.clone(),
});
keep.push(owner.clone());
}
Ok((atts, keep))
}
fn find(
@ -59,7 +67,7 @@ fn find(
.find(|(n, _)| n == name)
.map(|(_, r)| Artifact {
reference: Arc::new(r.clone()),
owner: guard.clone(),
holder: Holder::Bus(guard.clone()),
})
.ok_or_else(|| BusError::invalid(format!("no attachment named {name:?}")))
}
@ -69,43 +77,129 @@ fn find(
/// A read-only, cloneable handle on an immutable artifact. While any clone (or a file opened
/// from it) lives, the owner it came from keeps the bytes alive.
///
/// An artifact is either sealed in a router's store (every handle the bus hands out) or an
/// **in-memory** artifact ([`Artifact::in_memory`]): an immutable buffer in this address space
/// that no router knows about. The second kind is for participants that share one process and
/// hand each other buffers directly, without a bus message (PERF-01's in-process local lane);
/// it reads, clones and retains like any other handle, and it is refused as a bus attachment,
/// so it can never be named by a message a router would have to resolve.
#[derive(Clone)]
pub struct Artifact {
pub(crate) reference: Arc<ArtifactRef>,
pub(crate) owner: Arc<OwnerGuard>,
pub(crate) holder: Holder,
}
/// What keeps an artifact's bytes alive.
#[derive(Clone)]
pub(crate) enum Holder {
/// A router-side owner: a delivery or an explicit hold.
Bus(Arc<OwnerGuard>),
/// The bytes themselves.
Memory(Arc<[u8]>),
}
/// The store id every in-memory artifact reference carries. No router issues it: a router's
/// store ids are `store-<tag>`.
pub const IN_MEMORY_STORE_ID: &str = "in-memory";
impl std::fmt::Debug for Artifact {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Artifact")
.field("reference", &self.reference)
.field("owner", &self.owner.id)
.field("owner", &self.owner_id())
.finish()
}
}
impl Artifact {
/// An immutable in-memory artifact holding `bytes`, with no digest. Nothing is copied.
pub fn in_memory(content_type: &str, bytes: impl Into<Arc<[u8]>>) -> Artifact {
use std::sync::atomic::{AtomicU64, Ordering};
static SERIAL: AtomicU64 = AtomicU64::new(0);
let bytes: Arc<[u8]> = bytes.into();
let serial = SERIAL.fetch_add(1, Ordering::Relaxed) + 1;
Artifact {
reference: Arc::new(ArtifactRef {
store_id: IN_MEMORY_STORE_ID.to_owned(),
artifact_id: format!("m-{serial}"),
generation: GENERATION,
byte_length: bytes.len() as u64,
content_type: content_type.to_owned(),
digest: None,
}),
holder: Holder::Memory(bytes),
}
}
pub fn reference(&self) -> &ArtifactRef {
&self.reference
}
/// The same artifact as an in-memory handle with the **same reference**: a sealed one is
/// read once, an in-memory one is returned as it is. For a caller in the owner's process
/// that must keep the bytes without holding the owner's connection (a handle is only valid
/// as an attachment on the connection that owns it).
pub async fn to_memory(&self) -> Result<Artifact, BusError> {
if self.is_in_memory() {
return Ok(self.clone());
}
let bytes = self.read_all().await?;
if bytes.len() as u64 != self.reference.byte_length {
return Err(BusError::new(
ErrorCode::ArtifactMismatch,
"sealed bytes disagree with the reference's length",
));
}
Ok(Artifact {
reference: self.reference.clone(),
holder: Holder::Memory(bytes.into()),
})
}
/// True for an [`Artifact::in_memory`] handle.
pub fn is_in_memory(&self) -> bool {
matches!(self.holder, Holder::Memory(_))
}
/// The bytes of an in-memory artifact, without a copy; `None` for a sealed one.
pub fn memory(&self) -> Option<&Arc<[u8]>> {
match &self.holder {
Holder::Memory(bytes) => Some(bytes),
Holder::Bus(_) => None,
}
}
/// The router-side owner this handle rides on: a delivery id or an explicit hold id.
/// An in-memory artifact has none and reports its store id.
pub fn owner_id(&self) -> &str {
&self.owner.id
match &self.holder {
Holder::Bus(owner) => &owner.id,
Holder::Memory(_) => IN_MEMORY_STORE_ID,
}
}
/// Opens the sealed bytes read-only. The file keeps this handle (and so its owner) alive.
pub async fn open(&self) -> Result<ArtifactFile, BusError> {
let owner = match &self.holder {
Holder::Bus(owner) => owner,
Holder::Memory(bytes) => {
return Ok(ArtifactFile {
file: Backing::Memory(io::Cursor::new(bytes.clone())),
_artifact: self.clone(),
});
}
};
let mut body = Map::new();
body.insert("ref".into(), self.reference.to_json());
body.insert("ownerId".into(), self.owner.id.clone().into());
let shared = &self.owner.conn.shared;
body.insert("ownerId".into(), owner.id.clone().into());
let shared = &owner.conn.shared;
let reply = shared
.command(
"artifact.open",
body,
Vec::new(),
vec![self.owner.clone()],
vec![owner.clone()],
Hook::None,
)
.await?;
@ -130,13 +224,16 @@ impl Artifact {
));
}
Ok(ArtifactFile {
file,
file: Backing::File(file),
_artifact: self.clone(),
})
}
/// Reads the whole artifact (on the blocking pool).
/// Reads the whole artifact (on the blocking pool; an in-memory one is copied in place).
pub async fn read_all(&self) -> Result<Vec<u8>, BusError> {
if let Holder::Memory(bytes) = &self.holder {
return Ok(bytes.to_vec());
}
let mut file = self.open().await?;
tokio::task::spawn_blocking(move || {
let mut out = Vec::with_capacity(file.len() as usize);
@ -148,24 +245,29 @@ impl Artifact {
}
/// Creates an independent explicit hold, so the bytes outlive this handle's delivery.
/// An in-memory artifact's hold is another handle on the same bytes.
pub async fn retain(&self) -> Result<Artifact, BusError> {
let owner = match &self.holder {
Holder::Bus(owner) => owner,
Holder::Memory(_) => return Ok(self.clone()),
};
let mut body = Map::new();
body.insert("ref".into(), self.reference.to_json());
body.insert("ownerId".into(), self.owner.id.clone().into());
let shared = &self.owner.conn.shared;
body.insert("ownerId".into(), owner.id.clone().into());
let shared = &owner.conn.shared;
let reply = shared
.command(
"artifact.retain",
body,
Vec::new(),
vec![self.owner.clone()],
vec![owner.clone()],
Hook::Owner,
)
.await?;
match reply.extra {
Extra::Owner(owner) => Ok(Artifact {
reference: self.reference.clone(),
owner,
holder: Holder::Bus(owner),
}),
_ => Err(BusError::lost("retain reply without an owner")),
}
@ -174,10 +276,15 @@ impl Artifact {
/// An open, read-only sealed file. Holds its [`Artifact`].
pub struct ArtifactFile {
file: File,
file: Backing,
_artifact: Artifact,
}
enum Backing {
File(File),
Memory(io::Cursor<Arc<[u8]>>),
}
impl ArtifactFile {
pub fn len(&self) -> u64 {
self._artifact.reference.byte_length
@ -194,13 +301,19 @@ impl ArtifactFile {
impl Read for ArtifactFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file.read(buf)
match &mut self.file {
Backing::File(file) => file.read(buf),
Backing::Memory(cursor) => cursor.read(buf),
}
}
}
impl Seek for ArtifactFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.file.seek(pos)
match &mut self.file {
Backing::File(file) => file.seek(pos),
Backing::Memory(cursor) => cursor.seek(pos),
}
}
}
@ -251,7 +364,7 @@ impl ArtifactWriter {
let reference = ArtifactRef::from_json(Fields::of(&reply.value, "reply").value("ref")?)?;
Ok(Artifact {
reference: Arc::new(reference),
owner: self.owner.clone(),
holder: Holder::Bus(self.owner.clone()),
})
}
}
@ -401,7 +514,7 @@ impl Responder {
outcome: Map<String, Value>,
attachments: &[(&str, &Artifact)],
) -> Result<bool, BusError> {
let (atts, keep) = attachment_list(attachments);
let (atts, keep) = attachment_list(attachments)?;
let mut body = Map::new();
body.insert("callId".into(), self.call_id.clone().into());
body.insert(

View file

@ -14,7 +14,7 @@ use tokio::sync::oneshot;
use handles::attachment_list;
pub use handles::{
Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder,
IN_MEMORY_STORE_ID, Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder,
RpcResult, Service, Subscription,
};
use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared};
@ -361,7 +361,7 @@ impl Client {
payload: Map<String, Value>,
attachments: &[(&str, &Artifact)],
) -> Result<PendingCall, BusError> {
let (atts, keep) = attachment_list(attachments);
let (atts, keep) = attachment_list(attachments)?;
let (tx, rx) = oneshot::channel();
let (reply_tx, reply_rx) = oneshot::channel();
let shared = self.shared();
@ -522,7 +522,7 @@ impl Client {
payload: Map<String, Value>,
attachments: &[(&str, &Artifact)],
) -> Result<PublishReceipt, BusError> {
let (atts, keep) = attachment_list(attachments);
let (atts, keep) = attachment_list(attachments)?;
let mut body = Map::new();
body.insert("topic".into(), topic.into());
body.insert("payload".into(), Value::Object(payload));

View file

@ -25,7 +25,7 @@ mod store;
mod transport;
pub use client::{
Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, Message,
Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message,
Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service,
ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo,
};