session: pin the sweep workers one per cpu in flysim-session (PERF-02)

CUT-01's speed probation fell back at a median realtime factor of 0.959.
With exactly as many cpus as sweep threads, the session's host threads
(dispatching tokio worker, coordinator, listeners) sleep and wake around
every transition, the sweep workers park and wake with them, and the
scheduler often stacks two workers on one cpu: the session's ticks ran
about 35% slower than the legacy loop's on the same frames (equal with a
spare cpu).

flybrain_core::pool::place_workers gives each spawned sweep worker a cpu
of its own and confines every other thread to the rest of the cpuset;
flysim-session calls it before spawning anything (in-process and thread
modes; FLY_SESSION_PIN=0 turns it off). Placement chooses cpus only, so
no result, trace or checkpoint changes; the legacy loop, process mode and
the shadow binary never call it. The compatibility string is unchanged.

On the release cpu model, 4 cpus, 4 threads, same frames: session 16.16
-> 12.98 ms/frame (legacy 10.53). The service's profile line prints the
measurement spans and the brain's phase split when FLY_SESSION_PROFILE is
set. Docs: legacy-gameboy-v1 section 12 amendment, implementation entry.
This commit is contained in:
acamilo 2026-10-01 12:16:59 +00:00
parent 390d118460
commit 8fa98b0b03
8 changed files with 366 additions and 2 deletions

View file

@ -479,6 +479,22 @@ in-process and process, and the compatibility string is unchanged.
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.
### PERF-02 — The session's ticks on the release cpuset (port slice)
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. The legacy loop and process mode are
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
workers against the sequential kernel on the real connectome. The service's periodic profile
line also prints the measurement spans (and the brain's phase split) when
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no

View file

@ -440,6 +440,22 @@ behaviour they must not change.
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.
**Amendment, 2026-10-01 (PERF-02): thread placement in the service.** Again nothing in the
declaration, the digest or the compatibility string changes, and no result can: placement chooses
the CPU a thread runs on, never what an index of a parallel phase computes.
- `flysim-session` (in-process and thread modes), before it spawns any thread, gives each of the
`RAYON_NUM_THREADS - 1` spawned sweep workers one CPU of the unit's cpuset to itself and confines
every other thread -- the dispatching runtime worker, the coordinator, the listeners, the
checkpoint writer -- to the rest (the first CPU, plus any beyond the sweep's). Process mode and
the legacy loop are unchanged. `FLY_SESSION_PIN=0` keeps every thread floating, as before.
- Why: the session's host threads sleep and wake around every transition, so the sweep workers
park and wake every transition too, and the scheduler often woke two of them onto one CPU while
a host thread held another: each parallel phase of that transition then took two shares' time.
On the release CPU model with a four-CPU cpuset the session's ticks ran 35% slower than the
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost
what the legacy loop's do.
## 13. Machine-readable parts
| Where | What |

View file

@ -491,6 +491,7 @@ dependencies = [
"cudarc",
"flate2",
"indexmap",
"libc",
"libm",
"ryu-js",
"serde",

View file

@ -70,6 +70,10 @@ pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE";
/// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only).
pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE";
/// `0` keeps every thread floating over the cpuset; anything else, or unset, places them
/// ([`place_threads`]).
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
/// How the service composes its session, beyond flysim's own [`Config`].
#[derive(Clone, Debug)]
pub struct ServiceOptions {
@ -187,11 +191,44 @@ pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored");
}
}
place_threads(&config, &options);
flysim::serve(config, move |shared, snapshots, commands, notifier| {
run_host(shared, snapshots, commands, notifier, &options)
})
}
/// PERF-02: one CPU of its own for each spawned sweep worker, the rest of the cpuset for every
/// other thread (the dispatching tokio worker, the coordinator, the listeners, the checkpoint
/// writer), before any of them is spawned. The legacy loop's four busy threads keep their CPUs by
/// themselves; the session's host threads sleep and wake around every transition, and without
/// this the sweep workers' wake-ups often land two on one CPU (`flybrain_core::pool::
/// place_workers`). In-process and thread modes only: a worker process would inherit the host's
/// mask without the plan. Placement changes no result, trace or checkpoint.
fn place_threads(config: &Config, options: &ServiceOptions) {
if std::env::var(SESSION_PIN_ENV).ok().as_deref() == Some("0") {
tracing::info!("{SESSION_PIN_ENV}=0: the threads float over the cpuset");
return;
}
if !matches!(
options.mode,
ExecutionMode::InProcess | ExecutionMode::Thread
) {
return;
}
let workers = config.loop_.threads;
match flybrain_core::pool::place_workers(workers) {
Some(placement) => tracing::info!(
sweep_workers = ?placement.workers,
host = ?placement.host,
"sweep workers pinned one per cpu; every other thread on the host cpus"
),
None => tracing::info!(
workers,
"threads not placed (fewer cpus than sweep threads, or no pool): they float"
),
}
}
/// The runtime [`flysim::serve`] runs: boot a [`SessionHost`] on a session runtime of its own,
/// report ready, run it until a shutdown, stop every worker. Also what a test runs in place of
/// the listeners, as the legacy side runs `Sim::boot` and `Sim::run`.
@ -859,6 +896,19 @@ impl SessionHost {
realtime_factor = self.realtime.factor(),
"session profile (count x p50/p95/max ms):{line}"
);
// The measurement spans (`fly_session::profile`, on only when the process started with
// its switch set): mean per call, so a profile run can see where a frame goes.
if fly_session::profile::enabled() {
let mut spans = String::new();
for (name, count, mean, max) in fly_session::profile::report_with_max() {
spans.push_str(&format!(
" {name}={count}x{:.3}/{:.1}",
mean.as_secs_f64() * 1e3,
max.as_secs_f64() * 1e3
));
}
tracing::info!("session spans (count x mean/max ms):{spans}");
}
}
/// `Sim::recovered`: the ticker, the metric, the `recovering` status and a durable save.

View file

@ -1159,6 +1159,7 @@ impl LegacyAgentWorker {
// the two brains carry the same instrumentation (PERF-01).
agent.network.profile = crate::profile::enabled();
let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.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.
@ -1181,6 +1182,26 @@ impl LegacyAgentWorker {
"agent.ticks.phase_clock",
std::time::Duration::from_nanos(agent.network.timings().total_ns() - phase_before),
);
if crate::profile::enabled() {
let now = agent.network.timings();
for (name, after, before) in [
("agent.ticks.drive", now.drive_ns, phases_before.drive_ns),
("agent.ticks.sweep", now.sweep_ns, phases_before.sweep_ns),
(
"agent.ticks.observe",
now.observe_ns,
phases_before.observe_ns,
),
(
"agent.ticks.propagate",
now.propagate_ns,
phases_before.propagate_ns,
),
("agent.ticks.rates", now.rates_ns, phases_before.rates_ns),
] {
crate::profile::record(name, std::time::Duration::from_nanos(after - before));
}
}
if agent.network.ms != brain_ticks as f64 {
return Err(applied(
ErrorCode::Internal,

View file

@ -23,6 +23,10 @@ serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
# sched_getaffinity / sched_setaffinity for the opt-in worker placement (pool::place_workers).
libc = "0.2"
[dev-dependencies]
base64.workspace = true

View file

@ -19,7 +19,7 @@ use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::panic::AssertUnwindSafe;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::thread::JoinHandle;
/// `spin_loop` iterations before a worker starts yielding. Roughly a microsecond.
@ -29,6 +29,11 @@ const YIELDS: u32 = 256;
type Job = dyn Fn(usize) + Sync;
/// The CPUs the workers of every pool created after [`place_workers`] are pinned to: worker `i`
/// (`1..workers`) runs on `WORKER_CPUS[i - 1]`. Unset -- the default, and always for the legacy
/// loop -- the workers float over the process's CPUs as they always have.
static WORKER_CPUS: OnceLock<Vec<usize>> = OnceLock::new();
struct Shared {
/// Bumped once per dispatch. A worker runs when this differs from what it last saw.
generation: AtomicUsize,
@ -84,13 +89,22 @@ impl WorkerPool {
signal: Condvar::new(),
workers,
});
// A placement covers a pool of at most its own size; a larger pool floats entirely.
let pinned = WORKER_CPUS.get().filter(|cpus| cpus.len() >= workers - 1);
let mut threads = Vec::with_capacity(workers - 1);
for index in 1..workers {
let shared = Arc::clone(&shared);
let cpu = pinned.map(|cpus| cpus[index - 1]);
threads.push(
std::thread::Builder::new()
.name(format!("{name}-{index}"))
.spawn(move || worker_loop(&shared, index))?,
.spawn(move || {
if let Some(cpu) = cpu {
// Best effort: a refused pin leaves the worker floating, as before.
let _ = affinity::set_current(&[cpu]);
}
worker_loop(&shared, index)
})?,
);
}
Ok(Self { shared, threads })
@ -226,6 +240,107 @@ fn worker_loop(shared: &Shared, index: usize) {
}
}
/// Where [`place_workers`] put the process's threads.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Placement {
/// One CPU per spawned worker, in worker order (worker 0 is the dispatching thread).
pub workers: Vec<usize>,
/// The CPUs every other thread of the process runs on, the dispatcher included.
pub host: Vec<usize>,
}
/// Splits `allowed` for a pool of `workers`: one CPU of its own for each of the `workers - 1`
/// spawned workers, and the rest -- at least one CPU -- for everything else, the dispatching
/// thread (worker 0) included. `None` when there are not `workers` distinct CPUs to split.
pub fn split_cpus(allowed: &[usize], workers: usize) -> Option<Placement> {
let mut cpus = allowed.to_vec();
cpus.sort_unstable();
cpus.dedup();
if workers < 2 || cpus.len() < workers {
return None;
}
let mut host = vec![cpus[0]];
host.extend_from_slice(&cpus[workers..]);
Some(Placement {
workers: cpus[1..workers].to_vec(),
host,
})
}
/// Opt-in thread placement for a host whose threads share the sweep's CPUs (PERF-02).
///
/// A pool's workers spin between the phases of a tick and park between ticks that are
/// milliseconds apart. A host that does milliseconds of work on other threads between two
/// `step` calls (the session runtime's environment, task and commit, its async runtime, its
/// listeners) makes the workers park and wake every transition, and the scheduler, placing each
/// wake-up on whatever CPU looks free that instant, often stacks two workers on one CPU while
/// another runs host threads: every parallel phase of that transition then takes the time of two
/// shares. Measured on the release CPU model with a 4-CPU cpuset and 4 sweep threads: the
/// session's ticks 35% slower than the legacy loop's, the same ticks as legacy with a spare CPU.
///
/// This confines the calling thread -- and so every thread it spawns afterwards -- to
/// [`Placement::host`], and pins worker `i` of every pool created afterwards to
/// `Placement::workers[i - 1]`. Call it once, early, before the process spawns any thread.
/// `None` (and nothing changed) when there are fewer allowed CPUs than `workers`, when it was
/// already called, or off Linux. Placement decides only which CPU a thread runs on: no result
/// depends on it.
pub fn place_workers(workers: usize) -> Option<Placement> {
if WORKER_CPUS.get().is_some() {
return None;
}
let placement = split_cpus(&affinity::allowed()?, workers)?;
if !affinity::set_current(&placement.host) {
return None;
}
WORKER_CPUS.set(placement.workers.clone()).ok()?;
Some(placement)
}
#[cfg(target_os = "linux")]
mod affinity {
/// The CPUs the calling thread may run on.
pub fn allowed() -> Option<Vec<usize>> {
// SAFETY: a zeroed cpu_set_t is a valid empty set, and sched_getaffinity writes at most
// the size it is given.
unsafe {
let mut set: libc::cpu_set_t = std::mem::zeroed();
if libc::sched_getaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mut set) != 0 {
return None;
}
let cpus: Vec<usize> = (0..libc::CPU_SETSIZE as usize)
.filter(|&cpu| libc::CPU_ISSET(cpu, &set))
.collect();
(!cpus.is_empty()).then_some(cpus)
}
}
/// Confines the calling thread to `cpus`; false (and unchanged) if the kernel refuses.
pub fn set_current(cpus: &[usize]) -> bool {
if cpus.is_empty() || cpus.iter().any(|&cpu| cpu >= libc::CPU_SETSIZE as usize) {
return false;
}
// SAFETY: as above; every index is below CPU_SETSIZE.
unsafe {
let mut set: libc::cpu_set_t = std::mem::zeroed();
for &cpu in cpus {
libc::CPU_SET(cpu, &mut set);
}
libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set) == 0
}
}
}
#[cfg(not(target_os = "linux"))]
mod affinity {
pub fn allowed() -> Option<Vec<usize>> {
None
}
pub fn set_current(_cpus: &[usize]) -> bool {
false
}
}
/// A mutable slice that workers may split between themselves.
///
/// The kernel's parallel phases write disjoint contiguous ranges of the same array. The borrow
@ -351,4 +466,43 @@ mod tests {
});
assert_eq!(ran.load(Ordering::Relaxed), 8);
}
#[test]
fn the_split_gives_each_worker_a_cpu_and_the_host_the_rest() {
// The release's flysim cpuset, four whole cores, four sweep threads.
assert_eq!(
split_cpus(&[7, 3, 1, 5], 4),
Some(Placement {
workers: vec![3, 5, 7],
host: vec![1],
})
);
// A spare CPU goes to the host.
assert_eq!(
split_cpus(&[1, 3, 5, 7, 9], 4),
Some(Placement {
workers: vec![3, 5, 7],
host: vec![1, 9],
})
);
// Too few CPUs (a stale cpuset), or no pool at all: nothing is placed.
assert_eq!(split_cpus(&[1, 3], 3), None);
assert_eq!(split_cpus(&[1, 1, 3], 3), None);
assert_eq!(split_cpus(&[1, 3, 5, 7], 1), None);
}
#[cfg(target_os = "linux")]
#[test]
fn a_pinned_thread_reports_its_cpu() {
// On a thread of its own, so the test runner's threads keep their mask.
std::thread::spawn(|| {
let allowed = affinity::allowed().expect("the allowed cpus");
let cpu = *allowed.last().expect("at least one cpu");
assert!(affinity::set_current(&[cpu]));
assert_eq!(affinity::allowed(), Some(vec![cpu]));
assert!(!affinity::set_current(&[]));
})
.join()
.expect("the pinning thread");
}
}

View file

@ -0,0 +1,102 @@
//! PERF-02: pinned sweep workers compute what floating ones do.
//!
//! `pool::place_workers` confines the calling thread to the host CPUs and pins every worker of the
//! pools created afterwards to a CPU of its own. It is process-wide and once only, so this file
//! is its own test binary with a single test. On the committed `data/fafb-v783` it runs a pinned
//! 4-worker network against the sequential one, spikes and full exported state (plastic traces
//! included), and checks the workers really run where the placement says.
//!
//! Skips with a message when the dataset is absent or the process has fewer than four CPUs.
mod common;
use std::sync::Arc;
use common::{frame_pool, real_dataset_dir};
use flybrain_core::dataset::load_brain_dataset_from_dir;
use flybrain_core::lif::{LifConfig, LifNetwork, SweepPlan};
use flybrain_core::plasticity::PlasticityConfig;
use flybrain_core::pool::{WorkerPool, place_workers};
#[test]
fn a_pinned_pool_reproduces_the_sequential_run() {
let Some(dir) = real_dataset_dir() else {
eprintln!("skipped: data/fafb-v783/meta.json is absent in this worktree");
return;
};
// The placement must come before any pool exists.
let Some(placement) = place_workers(4) else {
eprintln!("skipped: fewer than four cpus to place four workers on");
return;
};
let data = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset must load"));
let frames = frame_pool(1, 99, 160, 144);
let run = |sweep: SweepPlan| {
let mut network = LifNetwork::new(
Arc::clone(&data),
LifConfig::default(),
PlasticityConfig::default(),
)
.expect("a default network");
network.set_sweep_plan(sweep);
network.set_visual_frame(&frames[0], 160, 144);
let mut spikes = Vec::new();
for _ in 0..60 {
spikes.push(network.step(1));
}
network.stimulate(120.0);
for _ in 0..60 {
spikes.push(network.step(1));
}
let ms = network.ms;
network.plasticity.reinforce(1.0, ms);
// A gap of milliseconds between steps, as a host's transition work makes, so the workers
// park and wake on their pinned cpus as they do in the service.
std::thread::sleep(std::time::Duration::from_millis(20));
for _ in 0..40 {
spikes.push(network.step(1));
}
(spikes, network.export_state())
};
let reference = run(SweepPlan::sequential());
assert!(reference.0.iter().sum::<u64>() > 0);
#[cfg(target_os = "linux")]
{
// The spawned workers run on the placement's cpus, one each. A worker pins itself as it
// starts, so the check follows a dispatch, which every worker has run.
let pool = WorkerPool::new(4, "flysim-sweep").expect("a pool");
pool.broadcast(&|_| {});
let mut seen = Vec::new();
for task in std::fs::read_dir("/proc/self/task").expect("the task list") {
let task = task.expect("a task").path();
let comm = std::fs::read_to_string(task.join("comm")).unwrap_or_default();
if !comm.starts_with("flysim-sweep-") {
continue;
}
let status = std::fs::read_to_string(task.join("status")).expect("the task status");
let list = status
.lines()
.find_map(|line| line.strip_prefix("Cpus_allowed_list:"))
.expect("Cpus_allowed_list")
.trim()
.to_owned();
seen.push(list);
}
seen.sort();
let mut want: Vec<String> = placement.workers.iter().map(usize::to_string).collect();
want.sort();
assert_eq!(
seen, want,
"the sweep workers are not on the placement's cpus"
);
}
let got = run(SweepPlan::with_threads(4).expect("a pool"));
assert_eq!(
got.0, reference.0,
"spike counts differ with pinned workers"
);
assert_eq!(got.1, reference.1, "state differs with pinned workers");
}