session: the live composition's participants on the router (BUS-01)

FLY_SESSION_TRANSPORT=bus (flysim-session --transport bus) runs the
agent and the world as socket clients of the session's router, one
process each by default (FLY_SESSION_MODE=thread and in-process too);
local, the PERF-01 lane, stays the default. Results, traces, checkpoints
and the compatibility string are the same in every arm (SessionArm:
local, bus/in-process, bus/thread, bus/process; FLY_PARITY_ARMS picks
them for the parity suites).

- process-mode placement: the service splits its cpuset as PERF-02 does
  and hands each process its CPUs (--host-cpus, --sweep-cpus;
  Launcher::place_process; pool::apply_placement); FLY_SESSION_AUX_CPUS
  moves the service and the world
- the launcher's own clients in memory in thread and process modes
- participants on a one-worker runtime; long handlers under
  block_in_place, which fixes a process-mode boot that failed when
  Agent.Initialize outlived the 2 s probe on a loaded box
- writers allocated ahead (WriterPool); a worker's own seals cached by
  clone, not a second hold
- over the bus the agent's Commit attaches its feed status, which the
  host reads instead of calling Legacy.FeedStatus at every publish
- fly-shadow --mode / FLY_SHADOW_MODE names the topology, forwarded to a
  remote box; the verdict records candidate.transport; fly-shadow check
  --require-arm

legacy-gameboy-v1 section 12 and 18 carry the dated amendments.
This commit is contained in:
acamilo 2026-10-02 00:09:41 +00:00
parent 8b6d69e13c
commit b2fd148f52
22 changed files with 1012 additions and 111 deletions

View file

@ -456,6 +456,79 @@ the CPU a thread runs on, never what an index of a parallel phase computes.
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost 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. what the legacy loop's do.
**Amendment, 2026-10-01 (BUS-01): the composition on the router.** The operator's direction of
2026-10-01: run the live session's participants over the flybus router on Unix sockets, one
emulator and one fly today, because multiplayer and more flies follow. Nothing in the declaration,
the digest or the compatibility string changes, and no result can: the bus carries the same
domain calls, in the same order, to the same endpoints as the local lane. Traces, checkpoints and
the FAFB parity runs are identical in every arm (`local`, `bus/thread`, `bus/process`;
`fly_legacy_session::composition::SessionArm`).
*Selecting it.* `FLY_SESSION_TRANSPORT=bus` (or `flysim-session --transport bus`) puts every
participant on the router's sockets; `FLY_SESSION_MODE` then defaults to `process`, and `thread` and
`in-process` are also allowed (`in-process` on the bus is every participant a socket client from
the coordinator's own runtime). `local`, the default, is the PERF-01 lane and stays the release
configuration until a cutover onto the bus. `local` with a thread or a process is refused: those
have no lane. On the container, `fly-runtime session --bus` (`session-bus`) writes
`Environment=FLY_SESSION_TRANSPORT=bus` into the runtime drop-in, and `session --local` takes it out.
*The topology (process mode, the bus default).*
| Process | Runs | Bus client | Reached by |
| --- | --- | --- | --- |
| `flysim-session` (the unit's main process) | the router (one per session), the launcher's supervisor, the coordinator with the `pokered-macros-v1` task and executor, the service host (feed, control API, metrics, checkpoint writer, sugar journal) | `coordinator`, `launcher` | in memory: they live with the router |
| `fly-session legacy-agent` (child) | AGENT-01: the brain, its readout and its sweep pool | `legacy-fly`, registers `agent.fly` | `<session dir>/attempt-N/sockets/legacy-fly-<n>.sock`, launcher-bound |
| `fly-session legacy-environment` (child) | ENV-01: binjgb, the slot, the memory image | `legacy-world`, then `legacy-world-r2` for the restore's replacement world; registers `env.world` | `.../sockets/legacy-world[-r2]-<n>.sock`, launcher-bound |
- *Policy* (closed, `composition.rs`): the coordinator may call `agent.*` and `env.*` and owns
`session.*` (publish, topics, its query service); the supervisor may call `agent.*` and `env.*`
and register nothing; each participant may register exactly its own service and call nothing.
An identity is bound by the launcher before Hello, so a process cannot answer as another.
- *Media* stay artifacts in the router's store (`<session dir>/attempt-N/store`, tmpfs, `fly`
0700): the 92,160-byte frame, the 65,536-byte memory image, the audio chunk (about 6.4 KB a frame
of `f32le`) and the 17,407-byte spike bitset every transition, and the captures (MBs, every hot
save). Inline is not an option: bus-v1 section 8.1 forbids binary in a body, and the image alone
would not fit the 64 KiB envelope once encoded. A delivery names each attachment's read location
(bus-v1 section 12, 2026-10-01), so a read is a local file read; a worker seals into writers it
allocated after the previous step (`worker::WriterPool`). Over the bus the agent's Commit also
attaches its feed status (`legacy.feed-status`, the `Legacy.FeedStatus` result's bytes as of the
committed boundary), which the service host reads instead of making that call at every publish;
a rollback after the Commit makes it ask again.
- *One unit, restarted as a whole.* The session cannot survive the loss of a participant: its
state is split across them and is recovered only as a group (STATE-01), and the store's last save
is that group. So the children belong to `flysim.service` (the launcher spawns them; systemd's
default `KillMode=control-group` reaps them with the unit), a dead participant fails the step
within `ipc-v1` section 6's ten seconds, `flysim-session` exits, and `Restart=always` starts the
whole session again from the store -- what a crash of the in-process session does today. A
child also exits when its router connection closes. The router lives in the coordinator's
process for the same reason: its loss is the session's. One unit keeps `fly-runtime`'s one
drop-in switch, the `OnFailure=` fallback to legacy (three starts in ten minutes), the speed
probation, the watchdog and the unstick rule's restart unchanged; separate units would need
`BindsTo=` chains and three start limits for no recovery a group restore does not already give.
- *CPUs.* The unit's cpuset is unchanged (on the release container `flysim.slice`'s four CPUs).
The service splits it as PERF-02 does and hands the split out: the agent process pins its spawned
sweep workers one per CPU and keeps its other threads (its dispatcher is sweep worker 0) on the
remaining CPU (`fly-session ... --sweep-cpus 3,5,7 --host-cpus 1`); the service process and the
world process run on that same host CPU. The transaction is serial -- nothing overlaps Prepare
(PERF-01) -- so they take turns on it rather than contend. `FLY_SESSION_AUX_CPUS` moves the
service and the world elsewhere in the unit's cpuset; it was measured and does not pay
(implementation guide, BUS-01). `FLY_SESSION_PIN=0` floats everything, as before.
- *Each participant process has one async worker, and a long handler gives it up*
(`tokio::task::block_in_place` for `*.Initialize`, `State.*`, `Agent.Rollback`): the agent's
warm-up runs for seconds, and a Tokio worker blocked that long stranded the shell's own bus loop,
so `ipc-v1` section 6's resolution of a slow `Agent.Initialize` failed ("never resolved") and a
session could not boot on a loaded box. A step's handlers (milliseconds) run in place, so a bus
request crosses no thread inside a participant. The local lane is unchanged.
*N agents and M environments are configuration.* Nothing above assumes one of each: the
launcher starts any number of `LegacyAgentLaunch` and environment launches, each with its own
client id, service name and socket; the policy grants are per client; placements are per worker
id (`Launcher::place_process`), so each agent process pins its own sweep to its own CPUs; the
coordinator calls agents concurrently and assembles one batch over every declared port; the router
has no notion of a fly. What is one-of-each today is this composition (`LegacyConfig`, one
`PokeredTask`, `FLYSIM01`'s one agent and one world) and the service's CPU split (one agent's
plan), which a multi-agent composition replaces rather than extends.
## 13. Machine-readable parts ## 13. Machine-readable parts
| Where | What | | Where | What |
@ -944,3 +1017,24 @@ verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`. unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's - *The guard* stays on the container and guards the live fly as before; it now watches the relay's
cost, which is a few file reads and one ssh stream. cost, which is a few file reads and one ssh stream.
**Amendment, 2026-10-01 (BUS-01): a shadow of the bus topology.** A cutover onto the bus is a
cutover into another topology, so it needs a shadow that ran it. `fly-shadow --mode` (and
`FLY_SHADOW_MODE`) names the topology as `SessionArm` does: `local` (the default, the in-process
lane; `in-process` is the same), `bus/thread`, `bus/process` (`bus`, `process`), `bus/in-process`.
`fly-shadow-run start --bus` sets `FLY_SHADOW_MODE=bus/process` in a drop-in of
`flyshadow.service` (`mode.conf`); in remote mode the relay forwards it with the rest of the live
composition's settings (it is in `FORWARDED_ENV`), so the box's shadow -- the same release, which
ships `fly-session` beside `fly-shadow` -- starts its agent and its world as child processes on its
own router's sockets. Its placement is the box's: the shadow places no thread. The verdict records
the topology (`candidate.executionMode`, and `candidate.transport`, new), and
`fly-shadow check --require-arm bus/process` (`fly-shadow-run check --bus`) refuses a verdict that
did not run it; a verdict from before this amendment, with no `transport`, counts as `local` when
it ran in process. The comparison, the window and every other rule of this section are unchanged.
The shadow follows the trace only the legacy loop writes (`FLY_TRACE_DIR`); the session runtime
ignores it. So the live fly runs the legacy runtime for the shadow's window, as it did for CUT-01:
`fly-shadow-run start` refuses while `flysim.service` runs the session runtime. The procedure for a
switch onto the bus is: `fly-runtime legacy`; `fly-shadow-run start --bus`; three hours of zero
divergence; `fly-shadow-run check --bus && fly-runtime session --bus` (the probation then judges
the bus topology). Shadowing the session runtime from its own trace is not built.

View file

@ -18,7 +18,7 @@
//! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` | //! | `--out DIR` | `$FLY_SHADOW_DIR`: `verdict.json`, `divergence.json` |
//! | `--spool DIR` | `<out>/spool` | //! | `--spool DIR` | `<out>/spool` |
//! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores | //! | `--work DIR` | `$FLY_SHADOW_WORK`, else `<out>/work`: sockets and artifact stores |
//! | `--mode in-process\|thread\|process` | `in-process` | //! | `--mode local\|bus/in-process\|bus/thread\|bus/process` | `$FLY_SHADOW_MODE`, else `local` (in-process over the local lane); `in-process`, `thread`, `process` and `bus` are accepted (BUS-01) |
//! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads | //! | `--threads N` | `$FLY_SHADOW_THREADS`, else 2: the shadow agent's sweep threads |
//! | `--required-brain-seconds S` | 10800 | //! | `--required-brain-seconds S` | 10800 |
//! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) | //! | `--lag-guard-margin S` | 0.05 s/s; the shadow pauses 60 s while the live `fly_lag_seconds` grows faster than `fly-shadow-run`'s baseline rate (`<out>/baseline.json`) plus this margin (the baseline's own margin wins), and stops pausing for 10 minutes when a pause did not help (0 disables) |
@ -46,7 +46,9 @@
//! and writes nothing outside DIR; N bounds the mirrored saves (3072). //! and writes nothing outside DIR; N bounds the mirrored saves (3072).
//! //!
//! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING] //! `check --verdict FILE [--current DIR] [--binary NAME] [--compatibility STRING]
//! [--max-age-seconds N]`: the cutover rule of `fly_legacy_session::shadow::verdict`. `--current` //! [--max-age-seconds N] [--require-arm ARM]`: the cutover rule of
//! `fly_legacy_session::shadow::verdict`, and with `--require-arm` (BUS-01: `bus/process`, ...) also
//! that the shadow ran that topology. `--current`
//! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for //! is the release link CUT-01 switches into (default `/opt/fly/current`): the verdict must be for
//! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the //! the directory it resolves to, with every shadowed binary unchanged there. `--binary` is the
//! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`, //! file name of the session-runtime binary CUT-01 switches to (default `flysim-session`,
@ -160,6 +162,8 @@ fn main() {
.unwrap_or_else(|| "flysim-session".to_owned()); .unwrap_or_else(|| "flysim-session".to_owned());
let compatibility = args.value("--compatibility"); let compatibility = args.value("--compatibility");
let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300); let max_age: i64 = args.parsed("--max-age-seconds").unwrap_or(300);
// BUS-01: the topology the cutover goes into, which the shadow must have run.
let require_arm = args.value("--require-arm");
args.done(); args.done();
let compatibility = compatibility.unwrap_or_else(|| { let compatibility = compatibility.unwrap_or_else(|| {
let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e)); let config = flysim::config::Config::load(None).unwrap_or_else(|e| die(e));
@ -179,7 +183,12 @@ fn main() {
dir: &dir_text, dir: &dir_text,
binaries: &binaries, binaries: &binaries,
}; };
match verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age) { let allowed = verdict::allows_cutover(&value, &binary, &release, &compatibility, now, max_age)
.and_then(|()| match &require_arm {
Some(arm) => verdict::ran_arm(&value, arm),
None => Ok(()),
});
match allowed {
Ok(()) => println!("cutover allowed: {}", value["reason"]), Ok(()) => println!("cutover allowed: {}", value["reason"]),
Err(reason) => { Err(reason) => {
println!("cutover refused: {reason}"); println!("cutover refused: {reason}");
@ -212,12 +221,18 @@ fn run(mut args: Args) {
.map(PathBuf::from) .map(PathBuf::from)
.or_else(|| env_path("FLY_SHADOW_WORK")) .or_else(|| env_path("FLY_SHADOW_WORK"))
.unwrap_or_else(|| out_dir.join("work")); .unwrap_or_else(|| out_dir.join("work"));
let mode = match args.value("--mode").as_deref() { // BUS-01: `--mode` (else `FLY_SHADOW_MODE`, which the remote relay forwards to the box) names
None | Some("in-process") => ExecutionMode::InProcess, // the topology: `local` (= `in-process`, the default), `bus/in-process`, `bus/thread`,
Some("thread") => ExecutionMode::Thread, // `bus/process` (= `bus`, = `process`), `thread`.
Some("process") => ExecutionMode::Process, let arm = args
Some(other) => die(format!("--mode {other:?}")), .value("--mode")
}; .or_else(|| std::env::var("FLY_SHADOW_MODE").ok().filter(|v| !v.is_empty()))
.map(|value| {
fly_legacy_session::composition::SessionArm::parse(&value)
.unwrap_or_else(|e| die(format!("--mode / FLY_SHADOW_MODE: {e}")))
})
.unwrap_or(fly_legacy_session::composition::SessionArm::LOCAL);
let mode: ExecutionMode = arm.mode;
let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| { let agent_threads: usize = args.parsed("--threads").unwrap_or_else(|| {
std::env::var("FLY_SHADOW_THREADS") std::env::var("FLY_SHADOW_THREADS")
.ok() .ok()
@ -292,6 +307,7 @@ fn run(mut args: Args) {
macro_mode: config.macros.mode, macro_mode: config.macros.mode,
speed: config.loop_.speed, speed: config.loop_.speed,
mode, mode,
transport: arm.transport,
agent_threads, agent_threads,
required_brain_seconds: required, required_brain_seconds: required,
all_files, all_files,
@ -309,7 +325,8 @@ fn run(mut args: Args) {
run_id_file, run_id_file,
}; };
eprintln!( eprintln!(
"fly-shadow: {} mode, {} threads, following {} (stores {} and {}, read only)", "fly-shadow: {} ({} mode), {} threads, following {} (stores {} and {}, read only)",
arm.label(),
mode.label(), mode.label(),
agent_threads, agent_threads,
shadow_config.trace_dir.display(), shadow_config.trace_dir.display(),

View file

@ -7,10 +7,11 @@
//! //!
//! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or //! It reads exactly `flysim`'s configuration (`/etc/fly/fly.env` through the unit, or
//! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat //! `--config flysim.toml`), writes the same checkpoint stores, event log, sugar journal and chat
//! sidecar, and serves the same feed, control API and metrics. Three variables are its own: //! sidecar, and serves the same feed, control API and metrics. These variables are its own:
//! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`), //! `FLY_SESSION_DIR` (the session's router store and sockets, default `/run/fly/session`),
//! `FLY_SESSION_MODE` (`in-process`, `thread` or `process`) and `FLY_SESSION_PROFILE` //! `FLY_SESSION_TRANSPORT` (`local`, the default, or `bus`; `--transport`), `FLY_SESSION_MODE`
//! (`production`, or `toy` for tests). //! (`in-process`, `thread` or `process`; `process` by default on the bus), `FLY_SESSION_PIN`,
//! `FLY_SESSION_AUX_CPUS` and `FLY_SESSION_PROFILE` (`production`, or `toy` for tests).
//! //!
//! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's //! The one-shot flags are `flysim`'s: `--check-config`, `--print-compatibility` (the session's
//! own string, which must equal `flysim`'s), `--print-state-compatibility` and //! own string, which must equal `flysim`'s), `--print-state-compatibility` and
@ -48,6 +49,12 @@ struct Args {
/// service stopped; `flysim --reset-to-milestone`, the same store). /// service stopped; `flysim --reset-to-milestone`, the same store).
#[arg(long, value_name = "RANK")] #[arg(long, value_name = "RANK")]
reset_to_milestone: Option<u32>, reset_to_milestone: Option<u32>,
/// `local` (in-process over the local lane) or `bus` (every participant a socket client of
/// the session's router, one process each unless `FLY_SESSION_MODE` says otherwise).
/// Overrides `FLY_SESSION_TRANSPORT`.
#[arg(long, value_name = "local|bus")]
transport: Option<String>,
} }
fn main() -> Result<()> { fn main() -> Result<()> {
@ -55,7 +62,8 @@ fn main() -> Result<()> {
init_tracing(); init_tracing();
let config = Config::load(args.config.as_deref())?; let config = Config::load(args.config.as_deref())?;
let options = fly_legacy_session::service::ServiceOptions::from_env()?; let options =
fly_legacy_session::service::ServiceOptions::from_env_with(args.transport.as_deref())?;
tracing::info!(config = ?config, options = ?options, "resolved configuration"); tracing::info!(config = ?config, options = ?options, "resolved configuration");
if args.check_config { if args.check_config {
println!("{}", toml::to_string_pretty(&config)?); println!("{}", toml::to_string_pretty(&config)?);

View file

@ -14,8 +14,8 @@ use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy; use fly_session::fly_session_types::gameboy;
use fly_session::launcher::{ use fly_session::launcher::{
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, ProcessCpus,
ThreadBudget, Via, SUPERVISOR_CLIENT, ThreadBudget, Via,
}; };
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT}; use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
use fly_session::legacy_env::BackendConfig; use fly_session::legacy_env::BackendConfig;
@ -54,12 +54,152 @@ const COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world"; const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world"; const ENV_SERVICE: &str = "env.world";
const ENV_WORKER: &str = "world"; const ENV_WORKER: &str = "world";
/// The environment's worker id, which [`LegacyConfig::placements`] names it by.
pub const WORLD_WORKER: &str = ENV_WORKER;
const AGENT_CLIENT: &str = "legacy-fly"; const AGENT_CLIENT: &str = "legacy-fly";
/// How the session's participants reach each other (BUS-01).
///
/// - `Local`: in-process participants are called over the local lane (PERF-01): no bus message
/// and no store file per call. Only [`ExecutionMode::InProcess`] has a lane.
/// - `Bus`: every participant is a client of the session's router over a Unix-domain socket,
/// launcher-bound to its identity, with its artifacts in the router's store: the topology that
/// takes more flies and more worlds by configuration. In-process, thread and process modes all
/// run it; thread and process modes have no other transport.
///
/// Neither changes a result, a trace or a checkpoint: the transport carries the same domain calls
/// to the same endpoints (`legacy-gameboy-v1` section 12, amendment 2026-10-01 BUS-01).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Transport {
#[default]
Local,
Bus,
}
impl Transport {
pub fn label(&self) -> &'static str {
match self {
Transport::Local => "local",
Transport::Bus => "bus",
}
}
/// `local` or `bus`.
pub fn parse(value: &str) -> Result<Transport, String> {
match value {
"local" => Ok(Transport::Local),
"bus" => Ok(Transport::Bus),
other => Err(format!("transport {other:?}: local or bus")),
}
}
/// The launcher transport for a mode: the lane only in process and only when asked for (and
/// not turned off by `FLY_SESSION_LOCAL_LANE=0`, which keeps an in-memory bus); Unix sockets
/// for the bus, and always for a thread or a process.
pub fn via(&self, mode: ExecutionMode) -> Via {
match (self, mode) {
(Transport::Local, ExecutionMode::InProcess) if local_lane_enabled() => Via::Local,
(Transport::Local, ExecutionMode::InProcess) => Via::Memory,
_ => Via::Unix,
}
}
}
/// One way to run the composition: where the participants run and how they are reached.
/// `local` (in-process over the lane, the release default until the bus cutover), `bus/in-process`,
/// `bus/thread` and `bus/process`. Parity runs and measurements name them this way
/// (`FLY_PARITY_ARMS`, `FLY_PERF_ARMS`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SessionArm {
pub mode: ExecutionMode,
pub transport: Transport,
}
impl SessionArm {
pub const LOCAL: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Local,
};
pub const BUS_IN_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::InProcess,
transport: Transport::Bus,
};
pub const BUS_THREAD: SessionArm = SessionArm {
mode: ExecutionMode::Thread,
transport: Transport::Bus,
};
pub const BUS_PROCESS: SessionArm = SessionArm {
mode: ExecutionMode::Process,
transport: Transport::Bus,
};
pub fn label(&self) -> String {
match self.transport {
Transport::Local => "local".to_owned(),
Transport::Bus => format!("bus/{}", self.mode.label()),
}
}
/// `local`, `bus` (= `bus/process`), `bus/in-process`, `bus/thread`, `bus/process`; also the
/// bare mode names `in-process` (= local), `thread` and `process` (= the bus).
pub fn parse(value: &str) -> Result<SessionArm, String> {
Ok(match value.trim() {
"local" | "in-process" => SessionArm::LOCAL,
"bus/in-process" => SessionArm::BUS_IN_PROCESS,
"bus/thread" | "thread" => SessionArm::BUS_THREAD,
"bus" | "bus/process" | "process" => SessionArm::BUS_PROCESS,
other => {
return Err(format!(
"{other:?}: local, bus/in-process, bus/thread or bus/process"
));
}
})
}
/// The arms a parity run compares with the legacy loop: `FLY_PARITY_ARMS` (a list of
/// [`SessionArm::parse`] names), else `local`, `bus/thread` and `bus/process`. Process mode
/// needs the workspace's `fly-session` binary; a build without it skips that arm and says so.
pub fn parity_arms() -> Vec<SessionArm> {
let arms = match std::env::var("FLY_PARITY_ARMS") {
Ok(list) if !list.trim().is_empty() => SessionArm::parse_list(&list)
.unwrap_or_else(|e| panic!("FLY_PARITY_ARMS: {e}")),
_ => vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS],
};
let program = fly_session::launcher::default_worker_program();
arms.into_iter()
.filter(|arm| {
let runnable = arm.mode != ExecutionMode::Process || program.is_file();
if !runnable {
eprintln!(
"{} skipped: no worker program at {}",
arm.label(),
program.display()
);
}
runnable
})
.collect()
}
/// A comma-separated list of [`SessionArm::parse`] names.
pub fn parse_list(value: &str) -> Result<Vec<SessionArm>, String> {
value
.split(',')
.filter(|part| !part.trim().is_empty())
.map(SessionArm::parse)
.collect()
}
}
/// How one legacy session is composed. /// How one legacy session is composed.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct LegacyConfig { pub struct LegacyConfig {
pub mode: ExecutionMode, pub mode: ExecutionMode,
/// The transport in-process participants use; thread and process modes always use the bus.
pub transport: Transport,
/// Process mode: where each participant process's threads run, by worker id (the agent's
/// id, [`WORLD_WORKER`]). Empty: they float (BUS-01).
pub placements: BTreeMap<Id, ProcessCpus>,
pub rom_path: PathBuf, pub rom_path: PathBuf,
pub dataset_dir: PathBuf, pub dataset_dir: PathBuf,
pub profile: LegacyProfileKind, pub profile: LegacyProfileKind,
@ -337,11 +477,11 @@ impl LegacySession {
let mut launcher = Launcher::start( let mut launcher = Launcher::start(
router, router,
config.mode, config.mode,
// In-process participants reach the router in memory: no socket between two tasks // `Transport::Local`: in-process participants are called over the local lane: the same
// of one process (a separate process always uses the socket). They are called over // worker shell, no bus message and no store file per artifact (PERF-01, `workers-v1`
// the local lane: the same worker shell, no bus message and no store file per // amendment). `Transport::Bus`: every participant is a socket client of the router,
// artifact (PERF-01, `workers-v1` amendment). // whatever its mode (BUS-01); a thread or a separate process always is.
if local_lane_enabled() { Via::Local } else { Via::Memory }, config.transport.via(config.mode),
&store_root, &store_root,
&sockets, &sockets,
budget, budget,
@ -349,6 +489,9 @@ impl LegacySession {
.await .await
.map_err(|e| format!("launcher: {}", e.message))?; .map_err(|e| format!("launcher: {}", e.message))?;
for (worker, cpus) in &config.placements {
launcher.place_process(worker, cpus.clone());
}
let mut backend = BackendConfig::legacy(&rom_digest); let mut backend = BackendConfig::legacy(&rom_digest);
backend.slots = vec![id(crate::task::SLOT)]; backend.slots = vec![id(crate::task::SLOT)];
launcher launcher

View file

@ -35,8 +35,10 @@ use serde_json::Value;
use tokio::sync::{mpsc, oneshot, watch}; use tokio::sync::{mpsc, oneshot, watch};
use fly_session::fly_session_types::gameboy; use fly_session::fly_session_types::gameboy;
use fly_session::launcher::ExecutionMode; use fly_session::launcher::{ExecutionMode, ProcessCpus};
use fly_session::legacy_agent::{LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT}; use fly_session::legacy_agent::{
FEED_STATUS_ATTACHMENT, LegacyProfileKind, METHOD_FEED_STATUS, SPIKES_ATTACHMENT,
};
use fly_session::legacy_checkpoint::{RankChange, SaveKind, SaveReport, SaveTicket}; use fly_session::legacy_checkpoint::{RankChange, SaveKind, SaveReport, SaveTicket};
use fly_session::types::*; use fly_session::types::*;
use flybrain_gb::adapter::GameAdapter; use flybrain_gb::adapter::GameAdapter;
@ -56,9 +58,14 @@ use flysim::snapshot::{
PROTOCOL, RewardKind, Snapshot, f32_bytes, finite, PROTOCOL, RewardKind, Snapshot, f32_bytes, finite,
}; };
use crate::composition::{Boot, LegacyConfig, LegacySession, StoreConfig, boot_unsaved}; use crate::composition::{
Boot, LegacyConfig, LegacySession, StoreConfig, Transport, boot_unsaved,
};
use crate::task::GAME; use crate::task::GAME;
/// The service's one agent.
const AGENT_ID: &str = "fly";
/// The runtime name the sugar journal's boot header records. /// The runtime name the sugar journal's boot header records.
pub const RUNTIME: &str = "fly-session"; pub const RUNTIME: &str = "fly-session";
@ -67,30 +74,83 @@ pub const SESSION_DIR_ENV: &str = "FLY_SESSION_DIR";
pub const DEFAULT_SESSION_DIR: &str = "/run/fly/session"; pub const DEFAULT_SESSION_DIR: &str = "/run/fly/session";
/// `in-process` (the default), `thread` or `process` (`fly-session`'s launcher modes). /// `in-process` (the default), `thread` or `process` (`fly-session`'s launcher modes).
pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE"; pub const SESSION_MODE_ENV: &str = "FLY_SESSION_MODE";
/// `local` (the default: in-process over the local lane) or `bus` (every participant a socket
/// client of the session's router; the mode defaults to `process`). BUS-01.
pub const SESSION_TRANSPORT_ENV: &str = "FLY_SESSION_TRANSPORT";
/// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only). /// `production` (the default, `gameboy-legacy-fafb-v783-v1`) or `toy` (tests only).
pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE"; pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE";
/// `0` keeps every thread floating over the cpuset; anything else, or unset, places them /// `0` keeps every thread floating over the cpuset; anything else, or unset, places them
/// ([`place_threads`]). /// ([`place_threads`]).
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN"; pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
/// Process mode: a CPU list for the service process (router, coordinator, listeners, checkpoint
/// writer) and the environment process, instead of the sweep's host CPU (BUS-01). It must lie in
/// the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs).
pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS";
/// How the service composes its session, beyond flysim's own [`Config`]. /// How the service composes its session, beyond flysim's own [`Config`].
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ServiceOptions { pub struct ServiceOptions {
pub mode: ExecutionMode, pub mode: ExecutionMode,
pub transport: Transport,
pub profile: LegacyProfileKind, pub profile: LegacyProfileKind,
pub session_dir: PathBuf, pub session_dir: PathBuf,
/// Process mode: each participant process's CPUs, by worker id ([`place_threads`]).
pub placements: std::collections::BTreeMap<Id, ProcessCpus>,
}
/// The mode and transport from their two settings: `FLY_SESSION_TRANSPORT` (or `--transport`)
/// and `FLY_SESSION_MODE`. Unset, the transport follows the mode (thread and process modes have
/// only the bus) and the mode follows the transport (`bus` runs one process per participant).
/// `local` with a thread or a process is refused: those have no local lane.
pub fn mode_and_transport(
mode: Option<&str>,
transport: Option<&str>,
) -> Result<(ExecutionMode, Transport)> {
let mode = match mode.filter(|v| !v.is_empty()) {
None => None,
Some("in-process") => Some(ExecutionMode::InProcess),
Some("thread") => Some(ExecutionMode::Thread),
Some("process") => Some(ExecutionMode::Process),
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"),
};
let transport = match transport.filter(|v| !v.is_empty()) {
None => None,
Some(value) => {
Some(Transport::parse(value).map_err(|e| anyhow!("{SESSION_TRANSPORT_ENV}: {e}"))?)
}
};
Ok(match (mode, transport) {
(None, None) | (None, Some(Transport::Local)) => {
(ExecutionMode::InProcess, Transport::Local)
}
(None, Some(Transport::Bus)) => (ExecutionMode::Process, Transport::Bus),
(Some(ExecutionMode::InProcess), transport) => {
(ExecutionMode::InProcess, transport.unwrap_or(Transport::Local))
}
(Some(mode), None | Some(Transport::Bus)) => (mode, Transport::Bus),
(Some(mode), Some(Transport::Local)) => bail!(
"{SESSION_MODE_ENV}={} has no local lane: its participants reach the router over \
sockets ({SESSION_TRANSPORT_ENV}=bus, or unset)",
mode.label()
),
})
} }
impl ServiceOptions { impl ServiceOptions {
/// From `FLY_SESSION_MODE`, `FLY_SESSION_PROFILE` and `FLY_SESSION_DIR`. /// From `FLY_SESSION_MODE`, `FLY_SESSION_TRANSPORT`, `FLY_SESSION_PROFILE` and
/// `FLY_SESSION_DIR`.
pub fn from_env() -> Result<ServiceOptions> { pub fn from_env() -> Result<ServiceOptions> {
let mode = match std::env::var(SESSION_MODE_ENV).ok().as_deref() { Self::from_env_with(None)
None | Some("") | Some("in-process") => ExecutionMode::InProcess, }
Some("thread") => ExecutionMode::Thread,
Some("process") => ExecutionMode::Process, /// [`ServiceOptions::from_env`], with `--transport` in place of `FLY_SESSION_TRANSPORT`.
Some(other) => bail!("{SESSION_MODE_ENV}={other}: in-process, thread or process"), pub fn from_env_with(transport: Option<&str>) -> Result<ServiceOptions> {
}; let env_transport = std::env::var(SESSION_TRANSPORT_ENV).ok();
let (mode, transport) = mode_and_transport(
std::env::var(SESSION_MODE_ENV).ok().as_deref(),
transport.or(env_transport.as_deref()),
)?;
let profile = match std::env::var(SESSION_PROFILE_ENV).ok().as_deref() { let profile = match std::env::var(SESSION_PROFILE_ENV).ok().as_deref() {
None | Some("") | Some("production") => LegacyProfileKind::Production, None | Some("") | Some("production") => LegacyProfileKind::Production,
Some("toy") => LegacyProfileKind::Toy, Some("toy") => LegacyProfileKind::Toy,
@ -101,8 +161,10 @@ impl ServiceOptions {
.unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR)); .unwrap_or_else(|| PathBuf::from(DEFAULT_SESSION_DIR));
Ok(ServiceOptions { Ok(ServiceOptions {
mode, mode,
transport,
profile, profile,
session_dir, session_dir,
placements: Default::default(),
}) })
} }
} }
@ -134,11 +196,13 @@ pub fn legacy_config(config: &Config, options: &ServiceOptions) -> Result<Legacy
} }
Ok(LegacyConfig { Ok(LegacyConfig {
mode: options.mode, mode: options.mode,
transport: options.transport,
placements: options.placements.clone(),
rom_path: config.paths.rom.clone(), rom_path: config.paths.rom.clone(),
dataset_dir: config.paths.dataset.clone(), dataset_dir: config.paths.dataset.clone(),
profile: options.profile, profile: options.profile,
macro_mode: config.macros.mode, macro_mode: config.macros.mode,
agent_id: id("fly"), agent_id: id(AGENT_ID),
agent_threads: config.loop_.threads.max(1), agent_threads: config.loop_.threads.max(1),
record: false, record: false,
}) })
@ -179,7 +243,7 @@ pub fn service_config(mut config: Config) -> Config {
} }
/// Run the service until a signal or a fatal error: [`flysim::serve`] around a [`SessionHost`]. /// Run the service until a signal or a fatal error: [`flysim::serve`] around a [`SessionHost`].
pub fn run(config: Config, options: ServiceOptions) -> Result<()> { pub fn run(config: Config, mut options: ServiceOptions) -> Result<()> {
let config = service_config(config); let config = service_config(config);
// Refuse a configuration the session cannot run before any listener is bound. // Refuse a configuration the session cannot run before any listener is bound.
legacy_config(&config, &options)?; legacy_config(&config, &options)?;
@ -191,7 +255,19 @@ pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored"); tracing::warn!("{variable} is set, but {what} is a legacy-loop tool; ignored");
} }
} }
place_threads(&config, &options); place_threads(&config, &mut options);
tracing::info!(
transport = options.transport.label(),
mode = options.mode.label(),
"session participants: {}",
match (options.transport, options.mode) {
(Transport::Local, _) => "in process, over the local lane",
(Transport::Bus, ExecutionMode::InProcess) => "in process, socket clients of the router",
(Transport::Bus, ExecutionMode::Thread) => "on threads, socket clients of the router",
(Transport::Bus, ExecutionMode::Process) =>
"one process each, socket clients of the router",
}
);
flysim::serve(config, move |shared, snapshots, commands, notifier| { flysim::serve(config, move |shared, snapshots, commands, notifier| {
run_host(shared, snapshots, commands, notifier, &options) run_host(shared, snapshots, commands, notifier, &options)
}) })
@ -202,20 +278,79 @@ pub fn run(config: Config, options: ServiceOptions) -> Result<()> {
/// writer), before any of them is spawned. The legacy loop's four busy threads keep their CPUs by /// 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 /// 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:: /// 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 /// place_workers`). Placement changes no result, trace or checkpoint.
/// mask without the plan. Placement changes no result, trace or checkpoint. ///
fn place_threads(config: &Config, options: &ServiceOptions) { /// In-process and thread modes place this process's own threads. Process mode (BUS-01) makes the
/// same split of this process's cpuset and hands it out: the agent process gets the sweep CPUs
/// and the host CPU (`--sweep-cpus`, `--host-cpus`), and this process -- the router, the
/// coordinator, the listeners -- and the environment process run on the host CPU too, or on
/// `FLY_SESSION_AUX_CPUS` when it is set. The transaction is serial (nothing overlaps Prepare,
/// PERF-01), so they share that CPU with the agent's dispatcher without contending.
fn place_threads(config: &Config, options: &mut ServiceOptions) {
if std::env::var(SESSION_PIN_ENV).ok().as_deref() == Some("0") { if std::env::var(SESSION_PIN_ENV).ok().as_deref() == Some("0") {
tracing::info!("{SESSION_PIN_ENV}=0: the threads float over the cpuset"); tracing::info!("{SESSION_PIN_ENV}=0: the threads float over the cpuset");
return; return;
} }
if !matches!( let workers = config.loop_.threads;
options.mode, if options.mode == ExecutionMode::Process {
ExecutionMode::InProcess | ExecutionMode::Thread let plan = flybrain_core::pool::allowed_cpus()
) { .and_then(|allowed| flybrain_core::pool::split_cpus(&allowed, workers));
let Some(plan) = plan else {
tracing::info!(
workers,
"threads not placed (fewer cpus than sweep threads): every process floats"
);
return;
};
let aux = match std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) {
None => plan.host.clone(),
Some(value) => match flybrain_core::pool::parse_cpu_list(&value) {
Some(cpus) => cpus,
None => {
tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored");
plan.host.clone()
}
},
};
let aux = if flybrain_core::pool::confine_current(&aux) {
aux
} else {
tracing::warn!(?aux, "could not confine the service to these cpus; using the host cpus");
if !flybrain_core::pool::confine_current(&plan.host) {
tracing::warn!("could not confine the service at all: every process floats");
return;
}
plan.host.clone()
};
// The agent's own host threads (its dispatcher is sweep worker 0) keep the plan's host
// cpus, less any the service and the world were moved onto.
let agent_host: Vec<usize> = plan.host.iter().copied().filter(|c| !aux.contains(c)).collect();
options.placements.insert(
id(AGENT_ID),
ProcessCpus {
host: if agent_host.is_empty() { plan.host.clone() } else { agent_host },
sweep: plan.workers.clone(),
},
);
options.placements.insert(
id(crate::composition::WORLD_WORKER),
ProcessCpus {
host: aux.clone(),
sweep: Vec::new(),
},
);
tracing::info!(
sweep_workers = ?plan.workers,
agent_host = ?plan.host,
service_and_world = ?aux,
"process mode: the agent's sweep workers pinned one per cpu; the service, the router \
and the world on the rest"
);
return; return;
} }
let workers = config.loop_.threads; if std::env::var_os(SESSION_AUX_CPUS_ENV).is_some() {
tracing::warn!("{SESSION_AUX_CPUS_ENV} is for process mode; ignored");
}
match flybrain_core::pool::place_workers(workers) { match flybrain_core::pool::place_workers(workers) {
Some(placement) => tracing::info!( Some(placement) => tracing::info!(
sweep_workers = ?placement.workers, sweep_workers = ?placement.workers,
@ -402,6 +537,12 @@ pub struct SessionHost {
spikes: Vec<u8>, spikes: Vec<u8>,
/// The agent's feed status as last read, for a publish whose read failed. /// The agent's feed status as last read, for a publish whose read failed.
last_feed: AgentFeed, last_feed: AgentFeed,
/// Over the bus (BUS-01): the feed status the last Commit attached, as of the committed
/// boundary; the next publish uses it instead of calling `Legacy.FeedStatus`. Cleared by a
/// rollback, which changes the agent after its Commit.
committed_feed: Option<Value>,
/// Whether the agent attaches its feed status to every Commit (the bus transport).
feed_on_commit: bool,
semantic_rewards: bool, semantic_rewards: bool,
next_profile: Instant, next_profile: Instant,
@ -522,6 +663,8 @@ impl SessionHost {
dc_blocker: DcBlocker::default(), dc_blocker: DcBlocker::default(),
spikes: Vec::new(), spikes: Vec::new(),
last_feed: AgentFeed::default(), last_feed: AgentFeed::default(),
committed_feed: None,
feed_on_commit: options.transport == Transport::Bus,
semantic_rewards, semantic_rewards,
next_profile: now + PROFILE_PERIOD, next_profile: now + PROFILE_PERIOD,
shared, shared,
@ -532,9 +675,15 @@ impl SessionHost {
// The service reads every transition's commit (the spike bitset) and paces itself by // The service reads every transition's commit (the spike bitset) and paces itself by
// flysim's `Pacer`, as the legacy loop does. // flysim's `Pacer`, as the legacy loop does.
host.session.coordinator.disable_pacing(); host.session.coordinator.disable_pacing();
host.session if host.feed_on_commit {
.coordinator host.session
.request_commit_attachments(&[SPIKES_ATTACHMENT]); .coordinator
.request_commit_attachments(&[SPIKES_ATTACHMENT, FEED_STATUS_ATTACHMENT]);
} else {
host.session
.coordinator
.request_commit_attachments(&[SPIKES_ATTACHMENT]);
}
host.session.coordinator.digest_views(false); host.session.coordinator.digest_views(false);
let origin = match &boot { let origin = match &boot {
@ -659,6 +808,7 @@ impl SessionHost {
let mut next_watchdog = Instant::now(); let mut next_watchdog = Instant::now();
loop { loop {
let iteration = Instant::now();
self.shared.beat(); self.shared.beat();
if let Some(period) = watchdog_period { if let Some(period) = watchdog_period {
let now = Instant::now(); let now = Instant::now();
@ -739,6 +889,9 @@ impl SessionHost {
"the simulation is behind real time; no frames are being skipped" "the simulation is behind real time; no frames are being skipped"
); );
} }
// The frame's compute time, before the pacing sleep (`fly_frame_work_*`), as the
// legacy loop records it.
self.shared.metrics.frame_work.record(iteration.elapsed());
let sleep = pacer.next_sleep(Instant::now()); let sleep = pacer.next_sleep(Instant::now());
if !sleep.is_zero() { if !sleep.is_zero() {
tokio::time::sleep(sleep).await; tokio::time::sleep(sleep).await;
@ -787,6 +940,9 @@ impl SessionHost {
self.remaining_ms = remaining; self.remaining_ms = remaining;
} }
for (agent, name, bytes) in &details.commit_attachments { for (agent, name, bytes) in &details.commit_attachments {
if *agent == self.agent_id && name == FEED_STATUS_ATTACHMENT {
self.committed_feed = serde_json::from_slice(bytes).ok();
}
if *agent == self.agent_id && name == SPIKES_ATTACHMENT { if *agent == self.agent_id && name == SPIKES_ATTACHMENT {
if self.spikes.len() < bytes.len() { if self.spikes.len() < bytes.len() {
self.spikes.resize(bytes.len(), 0); self.spikes.resize(bytes.len(), 0);
@ -860,6 +1016,8 @@ impl SessionHost {
.await .await
.map_err(|e| anyhow!("rollback ({} at {}): {}", e.detail, e.phase, e.error.message))?; .map_err(|e| anyhow!("rollback ({} at {}): {}", e.detail, e.phase, e.error.message))?;
if rolled_back { if rolled_back {
// The rollback changed the agent after its Commit: the next publish asks again.
self.committed_feed = None;
let feed = self.session.task.take_feed(); let feed = self.session.task.take_feed();
let (game_over, events) = feed.rollback.unwrap_or_default(); let (game_over, events) = feed.rollback.unwrap_or_default();
self.recovered(game_over, &events).await; self.recovered(game_over, &events).await;
@ -1277,7 +1435,11 @@ impl SessionHost {
/// `Sim::publish`: one snapshot of the committed boundary. `with_attachments` is false while /// `Sim::publish`: one snapshot of the committed boundary. `with_attachments` is false while
/// not running, which is the protocol's header-only idle cadence. /// not running, which is the protocol's header-only idle cadence.
async fn publish(&mut self, with_attachments: bool) { async fn publish(&mut self, with_attachments: bool) {
match self.read_feed().await { let feed = match self.committed_feed.take() {
Some(value) => AgentFeed::parse(&value),
None => self.read_feed().await,
};
match feed {
Ok(feed) => self.last_feed = feed, Ok(feed) => self.last_feed = feed,
Err(error) => tracing::warn!(%error, "the agent's feed status: publishing the last one"), Err(error) => tracing::warn!(%error, "the agent's feed status: publishing the last one"),
} }
@ -1383,6 +1545,53 @@ impl SessionHost {
mod tests { mod tests {
use super::*; use super::*;
/// BUS-01: the transport and the mode, from their two settings.
#[test]
fn the_transport_and_the_mode_follow_each_other() {
use crate::composition::SessionArm;
let pick = |mode, transport| mode_and_transport(mode, transport).ok();
let local = (ExecutionMode::InProcess, Transport::Local);
assert_eq!(pick(None, None), Some(local));
assert_eq!(pick(Some(""), Some("")), Some(local));
assert_eq!(pick(None, Some("local")), Some(local));
assert_eq!(pick(Some("in-process"), None), Some(local));
assert_eq!(pick(None, Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
assert_eq!(
pick(Some("in-process"), Some("bus")),
Some((ExecutionMode::InProcess, Transport::Bus))
);
// A thread or a process has only the bus, whether or not the transport says so.
assert_eq!(pick(Some("thread"), None), Some((ExecutionMode::Thread, Transport::Bus)));
assert_eq!(pick(Some("process"), Some("bus")), Some((ExecutionMode::Process, Transport::Bus)));
assert_eq!(pick(Some("process"), Some("local")), None);
assert_eq!(pick(Some("thread"), Some("local")), None);
assert_eq!(pick(Some("fork"), None), None);
assert_eq!(pick(None, Some("udp")), None);
// The arms the parity runs and the shadow name parse to the same pairs.
for (name, arm) in [
("local", SessionArm::LOCAL),
("in-process", SessionArm::LOCAL),
("bus", SessionArm::BUS_PROCESS),
("process", SessionArm::BUS_PROCESS),
("bus/process", SessionArm::BUS_PROCESS),
("bus/thread", SessionArm::BUS_THREAD),
("thread", SessionArm::BUS_THREAD),
("bus/in-process", SessionArm::BUS_IN_PROCESS),
] {
assert_eq!(SessionArm::parse(name), Ok(arm), "{name}");
}
assert_eq!(SessionArm::BUS_PROCESS.label(), "bus/process");
assert_eq!(SessionArm::LOCAL.label(), "local");
assert!(SessionArm::parse("bus/fork").is_err());
assert_eq!(
SessionArm::parse_list("local, bus/thread,,bus").unwrap(),
vec![SessionArm::LOCAL, SessionArm::BUS_THREAD, SessionArm::BUS_PROCESS]
);
// The launcher transport each arm runs on.
assert_eq!(Transport::Bus.via(ExecutionMode::InProcess), fly_session::Via::Unix);
assert_eq!(Transport::Local.via(ExecutionMode::Process), fly_session::Via::Unix);
}
/// The environment's native audio through the f32 DC blocker is the legacy loop's u8 audio /// The environment's native audio through the f32 DC blocker is the legacy loop's u8 audio
/// through its own, bit for bit, across chunk boundaries. /// through its own, bit for bit, across chunk boundaries.
#[test] #[test]

View file

@ -51,7 +51,7 @@ use fly_session::types::{id, parse_id};
use flysim::snapshot::MacroMode; use flysim::snapshot::MacroMode;
use crate::admission::LegacyAdmission; use crate::admission::LegacyAdmission;
use crate::composition::{LegacyConfig, LegacySession}; use crate::composition::{LegacyConfig, LegacySession, Transport};
use crate::trace::{self, Agreement, Difference}; use crate::trace::{self, Agreement, Difference};
use checkpoint::ShadowCapture; use checkpoint::ShadowCapture;
use follow::Follower; use follow::Follower;
@ -87,6 +87,9 @@ pub struct ShadowConfig {
pub macro_mode: MacroMode, pub macro_mode: MacroMode,
pub speed: f64, pub speed: f64,
pub mode: ExecutionMode, pub mode: ExecutionMode,
/// How the shadow session's participants reach each other (BUS-01): the local lane, or the
/// router's sockets.
pub transport: Transport,
pub agent_threads: usize, pub agent_threads: usize,
pub required_brain_seconds: f64, pub required_brain_seconds: f64,
/// Follow every trace file present at start, oldest first (a rehearsal), rather than only the /// Follow every trace file present at start, oldest first (a rehearsal), rather than only the
@ -457,6 +460,9 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
} }
let session_config = LegacyConfig { let session_config = LegacyConfig {
mode: config.mode, mode: config.mode,
transport: config.transport,
// The shadow places nothing: its box gives it cores of its own.
placements: Default::default(),
rom_path: config.rom_path.clone(), rom_path: config.rom_path.clone(),
dataset_dir: config.dataset_dir.clone(), dataset_dir: config.dataset_dir.clone(),
profile: config.profile, profile: config.profile,
@ -517,6 +523,7 @@ pub async fn run(config: ShadowConfig, stop: StopFlag) -> Result<(Ended, Verdict
release: config.release.clone(), release: config.release.clone(),
compatibility: compatibility.clone(), compatibility: compatibility.clone(),
execution_mode: config.mode.label().to_owned(), execution_mode: config.mode.label().to_owned(),
transport: config.transport.label().to_owned(),
agent_threads: config.agent_threads, agent_threads: config.agent_threads,
required_brain_seconds: config.required_brain_seconds, required_brain_seconds: config.required_brain_seconds,
agreement: Agreement::default(), agreement: Agreement::default(),

View file

@ -57,7 +57,9 @@ pub const TRACE_CHUNK: u64 = 4 << 20;
/// The live configuration the relay forwards to the box, so the remote shadow runs the live /// The live configuration the relay forwards to the box, so the remote shadow runs the live
/// service's composition (game, macro mode, accepted adapters, pins): exactly these names, and /// service's composition (game, macro mode, accepted adapters, pins): exactly these names, and
/// nothing that is a path or a secret. The box's own env file supplies the paths. /// nothing that is a path or a secret. The box's own env file supplies the paths.
pub const FORWARDED_ENV: [&str; 14] = [ pub const FORWARDED_ENV: [&str; 15] = [
// BUS-01: the topology the box's shadow runs (`fly-shadow-run start --bus`).
"FLY_SHADOW_MODE",
"FLY_GAME", "FLY_GAME",
"FLYSIM_LOOP_GAME", "FLYSIM_LOOP_GAME",
"FLY_MACRO_MODE", "FLY_MACRO_MODE",

View file

@ -229,6 +229,8 @@ pub struct Verdict {
pub release: String, pub release: String,
pub compatibility: String, pub compatibility: String,
pub execution_mode: String, pub execution_mode: String,
/// `local` or `bus` (BUS-01): with `execution_mode`, the topology the shadow ran.
pub transport: String,
pub agent_threads: usize, pub agent_threads: usize,
pub required_brain_seconds: f64, pub required_brain_seconds: f64,
pub agreement: Agreement, pub agreement: Agreement,
@ -324,6 +326,7 @@ impl Verdict {
"compatibility": self.compatibility, "compatibility": self.compatibility,
"compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()), "compatibilitySha256": crate::shadow::sha256_hex(self.compatibility.as_bytes()),
"executionMode": self.execution_mode, "executionMode": self.execution_mode,
"transport": self.transport,
"agentThreads": self.agent_threads, "agentThreads": self.agent_threads,
}, },
"required": {"brainSeconds": self.required_brain_seconds}, "required": {"brainSeconds": self.required_brain_seconds},
@ -424,6 +427,36 @@ pub struct Release<'a> {
pub binaries: &'a std::collections::BTreeMap<String, String>, pub binaries: &'a std::collections::BTreeMap<String, String>,
} }
/// The topology a verdict's shadow ran, named as [`crate::composition::SessionArm::label`] names
/// it: `local`, `bus/in-process`, `bus/thread` or `bus/process`. A verdict from before BUS-01 has
/// no `transport`: its in-process shadow ran the local lane, a thread or a process the bus.
pub fn shadowed_arm(verdict: &Value) -> String {
let candidate = &verdict["candidate"];
let mode = candidate["executionMode"].as_str().unwrap_or("in-process");
let transport = match candidate["transport"].as_str() {
Some(transport) => transport,
None if mode == "in-process" => "local",
None => "bus",
};
if transport == "local" {
"local".to_owned()
} else {
format!("{transport}/{mode}")
}
}
/// `fly-shadow check --require-arm`: the cutover is into a topology, so the shadow must have run
/// that one (BUS-01). `required` is a [`crate::composition::SessionArm`] name.
pub fn ran_arm(verdict: &Value, required: &str) -> Result<(), String> {
let required = crate::composition::SessionArm::parse(required)?.label();
let ran = shadowed_arm(verdict);
if ran == required {
Ok(())
} else {
Err(format!("the shadow ran {ran}, not {required}"))
}
}
/// How far ahead of the clock a verdict's `updatedAt` may be before it is refused. /// How far ahead of the clock a verdict's `updatedAt` may be before it is refused.
const MAX_CLOCK_SKEW_S: i64 = 60; const MAX_CLOCK_SKEW_S: i64 = 60;
@ -571,6 +604,7 @@ mod tests {
release: "/opt/fly/releases/test".to_owned(), release: "/opt/fly/releases/test".to_owned(),
compatibility: "c".to_owned(), compatibility: "c".to_owned(),
execution_mode: "in-process".to_owned(), execution_mode: "in-process".to_owned(),
transport: "local".to_owned(),
agent_threads: 2, agent_threads: 2,
required_brain_seconds: 10_800.0, required_brain_seconds: 10_800.0,
agreement: Agreement::default(), agreement: Agreement::default(),
@ -607,6 +641,7 @@ mod tests {
release: String::new(), release: String::new(),
compatibility: String::new(), compatibility: String::new(),
execution_mode: String::new(), execution_mode: String::new(),
transport: String::new(),
agent_threads: 1, agent_threads: 1,
required_brain_seconds: 10_800.0, required_brain_seconds: 10_800.0,
agreement: Agreement::default(), agreement: Agreement::default(),
@ -633,6 +668,27 @@ mod tests {
} }
} }
#[test]
fn the_arm_a_verdict_ran_is_checked_by_name() {
// BUS-01: a cutover onto the bus needs a shadow that ran the bus.
let mut v = verdict(Status::Pass, 10_800_000.0);
assert_eq!(shadowed_arm(&v), "local");
assert!(ran_arm(&v, "local").is_ok());
assert!(ran_arm(&v, "bus/process").is_err());
v["candidate"]["executionMode"] = json!("process");
v["candidate"]["transport"] = json!("bus");
assert_eq!(shadowed_arm(&v), "bus/process");
assert!(ran_arm(&v, "bus").is_ok());
assert!(ran_arm(&v, "process").is_ok());
assert!(ran_arm(&v, "bus/thread").is_err());
assert!(ran_arm(&v, "nonsense").is_err());
// A verdict from before BUS-01: no transport.
v["candidate"].as_object_mut().expect("an object").remove("transport");
assert_eq!(shadowed_arm(&v), "bus/process");
v["candidate"]["executionMode"] = json!("in-process");
assert_eq!(shadowed_arm(&v), "local");
}
#[test] #[test]
fn a_stop_ends_the_window() { fn a_stop_ends_the_window() {
// B2: brain time compared before a coverage gap never counts toward a pass. // B2: brain time compared before a coverage gap never counts toward a pass.

View file

@ -25,6 +25,8 @@ async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)>
}; };
let config = LegacyConfig { let config = LegacyConfig {
mode: ExecutionMode::InProcess, mode: ExecutionMode::InProcess,
transport: Default::default(),
placements: Default::default(),
rom_path, rom_path,
dataset_dir: legacy_parity::toy::dir(), dataset_dir: legacy_parity::toy::dir(),
profile: LegacyProfileKind::Toy, profile: LegacyProfileKind::Toy,

View file

@ -29,8 +29,8 @@ use std::time::{Duration, Instant};
use axum::body::Body; use axum::body::Body;
use axum::http::{Method, Request}; use axum::http::{Method, Request};
use fly_legacy_session::composition::SessionArm;
use fly_legacy_session::service::{ServiceOptions, run_host}; use fly_legacy_session::service::{ServiceOptions, run_host};
use fly_session::launcher::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind; use fly_session::legacy_agent::LegacyProfileKind;
use flysim::AppState; use flysim::AppState;
use flysim::config::Config; use flysim::config::Config;
@ -69,14 +69,14 @@ fn sha(bytes: &[u8]) -> String {
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Runtime { enum Runtime {
Legacy, Legacy,
Session(ExecutionMode), Session(SessionArm),
} }
impl Runtime { impl Runtime {
fn label(&self) -> String { fn label(&self) -> String {
match self { match self {
Runtime::Legacy => "legacy".to_owned(), Runtime::Legacy => "legacy".to_owned(),
Runtime::Session(mode) => format!("session ({})", mode.label()), Runtime::Session(arm) => format!("session ({})", arm.label()),
} }
} }
} }
@ -245,11 +245,13 @@ fn record(
let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?; let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?;
sim.run(&notifier) sim.run(&notifier)
} }
Runtime::Session(mode) => { Runtime::Session(arm) => {
let options = ServiceOptions { let options = ServiceOptions {
mode, mode: arm.mode,
transport: arm.transport,
profile, profile,
session_dir, session_dir,
placements: Default::default(),
}; };
run_host(loop_shared, snapshots_tx, command_rx, &notifier, &options) run_host(loop_shared, snapshots_tx, command_rx, &notifier, &options)
} }
@ -580,15 +582,8 @@ fn seed(from: &Path, to: &Path) {
} }
} }
fn modes() -> Vec<ExecutionMode> { fn modes() -> Vec<SessionArm> {
let mut modes = vec![ExecutionMode::InProcess]; SessionArm::parity_arms()
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!("process mode skipped: no worker program at {}", program.display());
}
modes
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]

View file

@ -31,11 +31,12 @@ use std::sync::Arc;
use serde_json::Value; use serde_json::Value;
use fly_legacy_session::admission::LegacyAdmission; use fly_legacy_session::admission::LegacyAdmission;
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; use fly_legacy_session::composition::{
LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_legacy_session::driver::{DecisionDriver, RotationDriver}; use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
use fly_legacy_session::task::ledgers_of; use fly_legacy_session::task::ledgers_of;
use fly_legacy_session::trace::{self, Agreement}; use fly_legacy_session::trace::{self, Agreement};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind; use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity; use fly_session::legacy_parity;
use fly_session::types::id; use fly_session::types::id;
@ -81,18 +82,8 @@ fn env_usize(name: &str, default: usize) -> usize {
.unwrap_or(default) .unwrap_or(default)
} }
fn modes() -> Vec<ExecutionMode> { fn modes() -> Vec<SessionArm> {
let mut modes = vec![ExecutionMode::InProcess]; SessionArm::parity_arms()
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!(
"process mode skipped: no worker program at {}",
program.display()
);
}
modes
} }
/// What each frame admits at its top, in admission order, and whether the rotation driver hands /// What each frame admits at its top, in admission order, and whether the rotation driver hands
@ -230,7 +221,7 @@ fn run_legacy(
/// The same run on the session framework. /// The same run on the session framework.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
async fn run_session( async fn run_session(
mode: ExecutionMode, mode: SessionArm,
rom_path: &Path, rom_path: &Path,
dataset_dir: &Path, dataset_dir: &Path,
profile: LegacyProfileKind, profile: LegacyProfileKind,
@ -241,7 +232,9 @@ async fn run_session(
) -> Run { ) -> Run {
let root = tempfile::tempdir().expect("tmp"); let root = tempfile::tempdir().expect("tmp");
let config = LegacyConfig { let config = LegacyConfig {
mode, mode: mode.mode,
transport: mode.transport,
placements: Default::default(),
rom_path: rom_path.to_owned(), rom_path: rom_path.to_owned(),
dataset_dir: dataset_dir.to_owned(), dataset_dir: dataset_dir.to_owned(),
profile, profile,
@ -599,8 +592,10 @@ async fn fafb_boot_run_save_restore() {
flysim::store::Store::new(&store.durable_dir, store.keep_generations) flysim::store::Store::new(&store.durable_dir, store.keep_generations)
.commit(generation, &original, None) .commit(generation, &original, None)
.expect("the seeded store"); .expect("the seeded store");
let config = |mode| LegacyConfig { let config = |mode: SessionArm| LegacyConfig {
mode, mode: mode.mode,
transport: mode.transport,
placements: Default::default(),
rom_path: rom_path.clone(), rom_path: rom_path.clone(),
dataset_dir: dataset.clone(), dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production, profile: LegacyProfileKind::Production,

View file

@ -203,6 +203,7 @@ fn config(
macro_mode: MacroMode::Raw, macro_mode: MacroMode::Raw,
speed: 0.0, speed: 0.0,
mode: ExecutionMode::InProcess, mode: ExecutionMode::InProcess,
transport: Default::default(),
agent_threads: 1, agent_threads: 1,
required_brain_seconds: 30.0, required_brain_seconds: 30.0,
all_files: true, all_files: true,

View file

@ -182,6 +182,7 @@ fn box_shadow(rom: &Path, root: &Path) -> ShadowConfig {
// The live service's loop.speed (real time), which its saves record. // The live service's loop.speed (real time), which its saves record.
speed: 1.0, speed: 1.0,
mode: ExecutionMode::InProcess, mode: ExecutionMode::InProcess,
transport: Default::default(),
agent_threads: 1, agent_threads: 1,
required_brain_seconds: 20.0, required_brain_seconds: 20.0,
all_files: false, all_files: false,

View file

@ -12,8 +12,9 @@
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; use fly_legacy_session::composition::{
use fly_session::ExecutionMode; LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_session::legacy_agent::LegacyProfileKind; use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity; use fly_session::legacy_parity;
use fly_session::types::id; use fly_session::types::id;
@ -175,13 +176,16 @@ async fn session_against_legacy_per_frame() {
); );
// ---- The session, unpaced then paced, in each mode. // ---- The session, unpaced then paced, in each mode.
for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { for arm in [SessionArm::LOCAL, SessionArm::BUS_PROCESS] {
let mode = arm.mode;
for paced in [false, true] { for paced in [false, true] {
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
let mut session = LegacySession::start( let mut session = LegacySession::start(
root.path(), root.path(),
LegacyConfig { LegacyConfig {
mode, mode,
transport: arm.transport,
placements: Default::default(),
rom_path: rom_path.clone(), rom_path: rom_path.clone(),
dataset_dir: dataset.clone(), dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production, profile: LegacyProfileKind::Production,

View file

@ -12,8 +12,9 @@
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; use fly_legacy_session::composition::{
use fly_session::ExecutionMode; LegacyConfig, LegacySession, SessionArm, channels_and_hold,
};
use fly_session::legacy_agent::LegacyProfileKind; use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity; use fly_session::legacy_parity;
use fly_session::types::id; use fly_session::types::id;
@ -151,23 +152,24 @@ async fn run(workers: usize) {
let bytes = std::fs::read(&checkpoint_path).unwrap(); let bytes = std::fs::read(&checkpoint_path).unwrap();
let checkpoint = flysim::store::decode(&bytes).unwrap(); let checkpoint = flysim::store::decode(&bytes).unwrap();
// PERF-01: `FLY_PERF_ARMS` picks the session arms, comma-separated: `local` (in-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, // over the local lane, the default in-process path), `memory` (in-process over the bus in
// `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path) and `process`. Default: all three. // memory, `FLY_SESSION_LOCAL_LANE=0`, the TASK-01 path), and the BUS-01 socket arms
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,bus,process".to_owned()); // `bus/in-process`, `bus/thread`, `bus/process` (`process`). Default: local, memory, process.
let arms = std::env::var("FLY_PERF_ARMS").unwrap_or_else(|_| "local,memory,process".to_owned());
// `FLY_PERF_SERVICE=1` adds the service host's per-frame reads (SERVE-01's // `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. // `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(); let service = std::env::var_os("FLY_PERF_SERVICE").is_some();
for arm in arms.split(',') { for arm in arms.split(',') {
let mode = match arm { let parsed = match arm {
"local" | "bus" => ExecutionMode::InProcess, "memory" => SessionArm::LOCAL,
"process" => ExecutionMode::Process, other => SessionArm::parse(other).unwrap_or_else(|e| panic!("FLY_PERF_ARMS: {e}")),
other => panic!("unknown arm {other}"),
}; };
let mode = parsed.mode;
// SAFETY: set before the session's runtime reads it; nothing else reads the variable. // SAFETY: set before the session's runtime reads it; nothing else reads the variable.
unsafe { unsafe {
std::env::set_var( std::env::set_var(
fly_legacy_session::composition::LOCAL_LANE_ENV, fly_legacy_session::composition::LOCAL_LANE_ENV,
if arm == "bus" { "0" } else { "1" }, if arm == "memory" { "0" } else { "1" },
); );
} }
let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads); let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads);
@ -176,6 +178,8 @@ async fn run(workers: usize) {
root.path(), root.path(),
LegacyConfig { LegacyConfig {
mode, mode,
transport: parsed.transport,
placements: Default::default(),
rom_path: rom_path.clone(), rom_path: rom_path.clone(),
dataset_dir: dataset.clone(), dataset_dir: dataset.clone(),
profile: LegacyProfileKind::Production, profile: LegacyProfileKind::Production,

View file

@ -95,6 +95,26 @@ fly-session legacy-environment ... --worker ID --port p1 --rom PATH --rom-digest
fly-session measure --steps 300 --agents 1,2,4 fly-session measure --steps 300 --agents 1,2,4
``` ```
BUS-01 (the live composition on the router) added four things here:
- **Placement per process.** `Launcher::place_process(worker_id, ProcessCpus { host, sweep })`
hands a separate process its CPUs as `--host-cpus` and `--sweep-cpus`; the worker applies them
(`flybrain_core::pool::apply_placement`) before it starts a thread, so an agent process pins its
own sweep and every agent can have its own CPUs.
- **The launcher's own clients in memory.** In thread and process modes the supervisor's and the
coordinator's connections are in memory (they live with the router); the participants' are the
sockets.
- **One async worker per participant, and long handlers give it up.** A thread or process
participant runs on a multi-thread runtime with one worker, so a bus request crosses no thread
inside it; a handler that can run for seconds (`*.Initialize`, `State.*`, `Agent.Rollback`) runs
under `tokio::task::block_in_place`, so the shell keeps reading -- and answers `Worker.Status`
and an exact duplicate's `IN_PROGRESS` -- while the legacy agent warms up. The local lane is
unchanged.
- **Writers allocated ahead** (`worker::WriterPool`): after each bus reply the shell allocates a
staging writer for each of the last few reply-artifact shapes it sealed, so the next step's seal
is one round trip instead of two. Reply artifacts the worker holds itself (its own seals) are
cached by clone, not by a second `retain`.
## What it implements ## What it implements
- **The transaction, in order.** Prepare all agents concurrently; run each task-local executor - **The transaction, in order.** Prepare all agents concurrently; run each task-local executor

View file

@ -42,6 +42,8 @@ fly-session <command> [options]
Worker options (agent and environment): Worker options (agent and environment):
--socket PATH the launcher's endpoint for this participant --socket PATH the launcher's endpoint for this participant
--host-cpus LIST the CPUs every thread of this process runs on (optional)
--sweep-cpus LIST an agent's sweep workers, one CPU each (optional, with --host-cpus)
--store-root PATH the router's artifact store root --store-root PATH the router's artifact store root
--client-id ID the configured bus client identity --client-id ID the configured bus client identity
--service NAME the one service name this worker registers --service NAME the one service name this worker registers
@ -212,6 +214,7 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
} }
let session_id = options.id(flags::SESSION)?; let session_id = options.id(flags::SESSION)?;
let incarnation_id = options.id(flags::INCARNATION)?; let incarnation_id = options.id(flags::INCARNATION)?;
place(options)?;
let what = match role { let what = match role {
"agent" => Started::Agent(AgentLaunch { "agent" => Started::Agent(AgentLaunch {
session_id, session_id,
@ -291,8 +294,28 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
service: service.clone(), service: service.clone(),
}), }),
}; };
let runtime = tokio::runtime::Builder::new_multi_thread() if crate::profile::enabled() {
.worker_threads(threads) // A worker process keeps its own span table (`FLY_SESSION_PROFILE`): printed once a
// minute on stderr, the service's journal, beside the coordinator's profile line.
let who = client_id.clone();
std::thread::spawn(move || {
loop {
std::thread::sleep(std::time::Duration::from_secs(60));
let line: Vec<String> = crate::profile::report_with_max()
.into_iter()
.map(|(name, count, mean, max)| {
format!(
"{name}={count}x{:.3}/{:.1}",
mean.as_secs_f64() * 1e3,
max.as_secs_f64() * 1e3
)
})
.collect();
eprintln!("worker profile {who} (count x mean/max ms): {}", line.join(" "));
}
});
}
let runtime = crate::launcher::participant_runtime(threads)
.enable_all() .enable_all()
.build() .build()
.map_err(|e| format!("runtime: {e}"))?; .map_err(|e| format!("runtime: {e}"))?;
@ -305,6 +328,42 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
}) })
} }
/// `--host-cpus` and `--sweep-cpus` (BUS-01): the placement the launcher made for this process,
/// applied before any thread starts, so every thread inherits the host set and every sweep pool
/// pins its workers. Without `--host-cpus` the process floats over what it inherited.
fn place(options: &Options) -> Result<(), String> {
let list = |flag: &str| -> Result<Option<Vec<usize>>, String> {
options
.optional(flag)
.map(|value| {
flybrain_core::pool::parse_cpu_list(value)
.ok_or_else(|| format!("--{flag}: {value:?} is not a cpu list"))
})
.transpose()
};
let (host, sweep) = (list(flags::HOST_CPUS)?, list(flags::SWEEP_CPUS)?);
let Some(host) = host else {
if sweep.is_some() {
return Err(format!("--{} needs --{}", flags::SWEEP_CPUS, flags::HOST_CPUS));
}
return Ok(());
};
let placement = flybrain_core::pool::Placement {
workers: sweep.unwrap_or_default(),
host,
};
// Best effort, as in the service: a refused placement leaves the process floating.
if flybrain_core::pool::apply_placement(&placement) {
eprintln!(
"placed: sweep workers {:?}, every other thread on {:?}",
placement.workers, placement.host
);
} else {
eprintln!("placement {placement:?} refused; the threads float");
}
Ok(())
}
fn parse_channels(value: &str) -> Result<Vec<String>, String> { fn parse_channels(value: &str) -> Result<Vec<String>, String> {
value value
.split(',') .split(',')

View file

@ -411,6 +411,10 @@ pub enum ReapOutcome {
struct Endpoints { struct Endpoints {
router: Router, router: Router,
via: Via, via: Via,
/// How this process's own clients -- the supervisor and the coordinator, which live with the
/// router -- reach it: in memory when the participants are a thread or a process away (their
/// sockets are the ones that cross a boundary; BUS-01), else the participants' transport.
own: Via,
store_root: PathBuf, store_root: PathBuf,
sockets: PathBuf, sockets: PathBuf,
next_socket: AtomicU64, next_socket: AtomicU64,
@ -423,9 +427,18 @@ impl Endpoints {
self.sockets.join(format!("{client_id}-{n}.sock")) self.sockets.join(format!("{client_id}-{n}.sock"))
} }
/// A connection this process owns, over the configured transport. /// A connection this process owns: the supervisor's and the coordinator's.
async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> { async fn connect(&self, client_id: &str) -> Result<Client, flybus::BusError> {
let transport = match self.via { self.connect_via(self.own, client_id).await
}
/// A connection for an in-process participant, over the participants' transport.
async fn connect_participant(&self, client_id: &str) -> Result<Client, flybus::BusError> {
self.connect_via(self.via, client_id).await
}
async fn connect_via(&self, via: Via, client_id: &str) -> Result<Client, flybus::BusError> {
let transport = match via {
Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id), Via::Memory | Via::Local => self.router.connect_in_memory_as(client_id),
Via::Unix => { Via::Unix => {
let path = self.socket_path(client_id); let path = self.socket_path(client_id);
@ -480,6 +493,30 @@ pub struct Launcher {
serial: u64, serial: u64,
/// Whether an in-process participant's reference carries its local lane (PERF-01). /// Whether an in-process participant's reference carries its local lane (PERF-01).
local_lane: bool, local_lane: bool,
/// Where each separate-process participant's threads run, by worker id (BUS-01).
placements: BTreeMap<Id, ProcessCpus>,
}
/// Where a separate-process participant's threads run (BUS-01): `host` for every thread of the
/// process, and for an agent `sweep`, one CPU per spawned sweep worker (`flybrain_core::pool::
/// Placement`). Given to the worker as `--host-cpus` and `--sweep-cpus`; the worker applies it
/// before it starts a thread. Placement chooses a CPU, never a result.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessCpus {
pub host: Vec<usize>,
pub sweep: Vec<usize>,
}
/// The runtime a thread or process participant serves on (BUS-01): one async worker, so a bus
/// request crosses no thread inside the participant -- each crossing was a wake-up on the
/// participant's shared CPU, about a millisecond a transition in all -- and multi-thread rather
/// than current-thread, so a handler that runs for seconds (a warm-up, a restore, a capture) can
/// hand that worker over (`tokio::task::block_in_place`) and the shell keeps answering status and
/// duplicates meanwhile. The thread allocation (`threads`) is the agent's sweep, not this runtime's.
pub fn participant_runtime(_threads: usize) -> tokio::runtime::Builder {
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.worker_threads(1);
builder
} }
/// The bus client id the supervisor connects under. /// The bus client id the supervisor connects under.
@ -528,6 +565,10 @@ impl Launcher {
let endpoints = Endpoints { let endpoints = Endpoints {
router, router,
via: mode.transport(via), via: mode.transport(via),
own: match mode {
ExecutionMode::InProcess => via,
ExecutionMode::Thread | ExecutionMode::Process => Via::Memory,
},
store_root: store_root.into(), store_root: store_root.into(),
sockets, sockets,
next_socket: AtomicU64::new(0), next_socket: AtomicU64::new(0),
@ -544,9 +585,16 @@ impl Launcher {
workers: BTreeMap::new(), workers: BTreeMap::new(),
serial: 0, serial: 0,
local_lane: mode == ExecutionMode::InProcess && via == Via::Local, local_lane: mode == ExecutionMode::InProcess && via == Via::Local,
placements: BTreeMap::new(),
}) })
} }
/// Places the separate process of `worker_id` (launched from now on) on `cpus`. Process mode
/// only; the other modes share this process's placement.
pub fn place_process(&mut self, worker_id: &Id, cpus: ProcessCpus) {
self.placements.insert(worker_id.clone(), cpus);
}
/// Offers every in-process participant launched from now on over the local lane /// 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 /// ([`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 /// coordinator in this process calls its endpoint methods without the bus. A thread or a
@ -807,7 +855,7 @@ impl Launcher {
) -> Result<(WorkerHandle, StatusCell), DomainError> { ) -> Result<(WorkerHandle, StatusCell), DomainError> {
let client = self let client = self
.endpoints .endpoints
.connect(&identity.client_id) .connect_participant(&identity.client_id)
.await .await
.map_err(|e| launch_error(&identity.worker_id, &e))?; .map_err(|e| launch_error(&identity.worker_id, &e))?;
let service = register_with_retry(&client, &identity.service, self.health.boot) let service = register_with_retry(&client, &identity.service, self.health.boot)
@ -862,10 +910,7 @@ impl Launcher {
let join = std::thread::Builder::new() let join = std::thread::Builder::new()
.name(format!("fly-session-{}", identity.worker_id)) .name(format!("fly-session-{}", identity.worker_id))
.spawn(move || { .spawn(move || {
let runtime = tokio::runtime::Builder::new_multi_thread() let runtime = participant_runtime(threads).enable_all().build();
.worker_threads(threads)
.enable_all()
.build();
let runtime = match runtime { let runtime = match runtime {
Ok(runtime) => runtime, Ok(runtime) => runtime,
Err(e) => { Err(e) => {
@ -953,6 +998,18 @@ impl Launcher {
for (flag, value) in what.arguments() { for (flag, value) in what.arguments() {
command.arg(flag).arg(value); command.arg(flag).arg(value);
} }
if let Some(cpus) = self.placements.get(&identity.worker_id) {
if !cpus.host.is_empty() {
command
.arg(format!("--{}", flags::HOST_CPUS))
.arg(flybrain_core::pool::format_cpu_list(&cpus.host));
}
if !cpus.sweep.is_empty() {
command
.arg(format!("--{}", flags::SWEEP_CPUS))
.arg(flybrain_core::pool::format_cpu_list(&cpus.sweep));
}
}
command.stdin(std::process::Stdio::null()); command.stdin(std::process::Stdio::null());
let child = command.spawn().map_err(|e| { let child = command.spawn().map_err(|e| {
DomainError::new( DomainError::new(
@ -1411,6 +1468,10 @@ pub(crate) mod flags {
pub const WORKER_THREADS: &str = "worker-threads"; pub const WORKER_THREADS: &str = "worker-threads";
pub const MODES: &str = "modes"; pub const MODES: &str = "modes";
/// BUS-01: the CPUs of the worker's threads, and an agent's sweep workers.
pub const HOST_CPUS: &str = "host-cpus";
pub const SWEEP_CPUS: &str = "sweep-cpus";
/// What every launched worker is given. /// What every launched worker is given.
pub const COMMON: &[&str] = &[ pub const COMMON: &[&str] = &[
SOCKET, SOCKET,
@ -1420,6 +1481,8 @@ pub(crate) mod flags {
THREADS, THREADS,
SESSION, SESSION,
INCARNATION, INCARNATION,
HOST_CPUS,
SWEEP_CPUS,
]; ];
/// What only an agent is given. /// What only an agent is given.
pub const AGENT_ONLY: &[&str] = &[ pub const AGENT_ONLY: &[&str] = &[

View file

@ -95,6 +95,14 @@ pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset";
/// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is /// declared extension of this one worker, not a `workers-v1` method: it changes nothing, is
/// answered in any phase once initialized, and is not in any trace. /// answered in any phase once initialized, and is not in any trace.
pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus"; pub const METHOD_FEED_STATUS: &str = "Legacy.FeedStatus";
/// BUS-01: the same feed status, as of the boundary the Commit commits, attached to a Commit reply
/// that reaches the agent over the bus (`application/json`, the [`METHOD_FEED_STATUS`] result's
/// bytes). The service host reads it instead of calling [`METHOD_FEED_STATUS`] after the step, which
/// over the bus is a round trip of its own; the bytes are the ones that call would return, since
/// nothing changes the agent between its Commit and the host's publish. Over the local lane, where
/// the call costs nothing, the reply does not carry it.
pub const FEED_STATUS_ATTACHMENT: &str = "legacy.feed-status";
pub const FEED_STATUS_CONTENT_TYPE: &str = "application/json";
pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1"; pub const FEED_STATUS_CAPABILITY: &str = "legacy-feed-status-v1";
/// The one stimulus kind the profile supports. /// The one stimulus kind the profile supports.
@ -1358,16 +1366,32 @@ impl LegacyAgentWorker {
telemetry: self.telemetry(), telemetry: self.telemetry(),
}; };
let _seal_span = crate::profile::span("agent.seal_spikes"); let _seal_span = crate::profile::span("agent.seal_spikes");
let artifact = ctx // Over the bus the feed status rides along, sealed beside the spikes (one round trip for
.seal(SPIKES_CONTENT_TYPE, spikes) // both): the service host's publish then needs no call of its own.
.await let feed = match (ctx.is_local(), self.agent.as_ref()) {
.map_err(|e| applied(e.code, e.message))?; (false, Some(agent)) => Some(
serde_json::to_vec(&feed_status_of(agent)).expect("a JSON value serializes"),
),
_ => None,
};
let (artifact, feed) = tokio::join!(ctx.seal(SPIKES_CONTENT_TYPE, spikes), async {
match feed {
Some(bytes) => ctx.seal(FEED_STATUS_CONTENT_TYPE, bytes).await.map(Some),
None => Ok(None),
}
});
let artifact = artifact.map_err(|e| applied(e.code, e.message))?;
let feed = feed.map_err(|e| applied(e.code, e.message))?;
self.status.set_state(WorkerState::Ready); self.status.set_state(WorkerState::Ready);
self.status self.status
.set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1))); .set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1)));
let mut attachments = vec![(SPIKES_ATTACHMENT.to_owned(), artifact)];
if let Some(feed) = feed {
attachments.push((FEED_STATUS_ATTACHMENT.to_owned(), feed));
}
Ok(HandlerReply::with_artifacts( Ok(HandlerReply::with_artifacts(
object(result.to_json()), object(result.to_json()),
vec![(SPIKES_ATTACHMENT.to_owned(), artifact)], attachments,
)) ))
} }

View file

@ -50,7 +50,7 @@ pub fn audio_attachment(stream_id: &str) -> String {
format!("audio.{stream_id}") format!("audio.{stream_id}")
} }
fn store_error(what: &str, message: &str) -> DomainError { pub(crate) fn store_error(what: &str, message: &str) -> DomainError {
DomainError::new( DomainError::new(
ErrorCode::BackendFailure, ErrorCode::BackendFailure,
format!("{what}: {message}"), format!("{what}: {message}"),

View file

@ -160,6 +160,78 @@ pub struct HandlerCtx<'a> {
pub request: &'a SessionRpcRequest, pub request: &'a SessionRpcRequest,
pub client: &'a flybus::Client, pub client: &'a flybus::Client,
pub incoming: &'a Incoming, pub incoming: &'a Incoming,
/// Staging writers allocated ahead for the reply artifacts this worker seals every step.
pub(crate) writers: &'a WriterPool,
}
/// Staging writers allocated ahead of need (BUS-01). A bus worker seals the same shapes of reply
/// artifact every step -- the environment a 92,160-byte frame, a 65,536-byte memory image and an
/// audio chunk of one of two lengths, the agent a 17,407-byte spike bitset -- and allocating one
/// is a router round trip on the step's critical path. The pool remembers the last few
/// `(content type, length)` shapes [`HandlerCtx::seal`] asked for and, after each reply, allocates
/// a writer for every remembered shape that has none, off the critical path. A seal that finds a
/// ready writer of its exact shape writes and seals it; one that does not allocates as before. A
/// writer is an artifact like any other: unsealed, it is released when dropped, and the bytes it
/// seals are the bytes written, so nothing a caller sees depends on the pool.
#[derive(Default)]
pub struct WriterPool {
state: Mutex<PoolState>,
}
#[derive(Default)]
struct PoolState {
/// The most recent distinct shapes, newest last.
recent: Vec<(String, u64)>,
ready: Vec<((String, u64), flybus::ArtifactWriter)>,
allocating: Vec<(String, u64)>,
}
/// Shapes the pool keeps writers for: an environment's three reply artifacts, with the audio
/// chunk's two lengths, and an agent's one.
const POOL_SHAPES: usize = 4;
impl WriterPool {
fn take(&self, content_type: &str, len: u64) -> Option<flybus::ArtifactWriter> {
let mut st = self.state.lock().expect("never poisoned");
let shape = (content_type.to_owned(), len);
if let Some(at) = st.recent.iter().position(|s| *s == shape) {
st.recent.remove(at);
} else if st.recent.len() >= POOL_SHAPES {
let gone = st.recent.remove(0);
st.ready.retain(|(s, _)| *s != gone);
}
st.recent.push(shape.clone());
let at = st.ready.iter().position(|(s, _)| *s == shape)?;
Some(st.ready.swap_remove(at).1)
}
/// Allocates, in the background, a writer for every remembered shape that has none.
fn refill(self: &Arc<Self>, client: &flybus::Client) {
let wanted: Vec<(String, u64)> = {
let mut st = self.state.lock().expect("never poisoned");
let wanted: Vec<_> = st
.recent
.iter()
.filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s))
.cloned()
.collect();
st.allocating.extend(wanted.iter().cloned());
wanted
};
for shape in wanted {
let (pool, client) = (self.clone(), client.clone());
tokio::spawn(async move {
let writer = client.artifacts().allocate(shape.1, &shape.0).await;
let mut st = pool.state.lock().expect("never poisoned");
st.allocating.retain(|s| *s != shape);
if let Ok(writer) = writer
&& st.recent.contains(&shape)
{
st.ready.push((shape, writer));
}
});
}
}
} }
/// How a domain request reached the shell, and so where its attachments are. /// How a domain request reached the shell, and so where its attachments are.
@ -224,7 +296,20 @@ impl HandlerCtx<'_> {
if self.is_local() { if self.is_local() {
return Ok(flybus::Artifact::in_memory(content_type, bytes)); return Ok(flybus::Artifact::in_memory(content_type, bytes));
} }
crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await // A writer allocated ahead for this shape saves the allocation's round trip ([`WriterPool`]).
let Some(mut writer) = self.writers.take(content_type, bytes.len() as u64) else {
let _span = crate::profile::span("shell.seal.allocated");
return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await;
};
let _span = crate::profile::span("shell.seal.pooled");
use std::io::Write as _;
writer
.write_all(&bytes)
.map_err(|e| crate::media::store_error("write", &e.to_string()))?;
writer
.seal()
.await
.map_err(|e| crate::media::store_error("seal", &e.message))
} }
} }
@ -422,6 +507,8 @@ struct Shell<E> {
closed: std::sync::atomic::AtomicBool, closed: std::sync::atomic::AtomicBool,
/// The admitted mutations' tasks, awaited when the shell stops. /// The admitted mutations' tasks, awaited when the shell stops.
running: Mutex<Vec<tokio::task::JoinHandle<()>>>, running: Mutex<Vec<tokio::task::JoinHandle<()>>>,
/// Reply writers allocated ahead (BUS-01).
writers: Arc<WriterPool>,
} }
/// The local lane's hold on a shell. /// The local lane's hold on a shell.
@ -492,6 +579,7 @@ pub fn serve<E: WorkerEndpoint>(
admission: tokio::sync::Mutex::new(()), admission: tokio::sync::Mutex::new(()),
closed: std::sync::atomic::AtomicBool::new(false), closed: std::sync::atomic::AtomicBool::new(false),
running: Mutex::new(Vec::new()), running: Mutex::new(Vec::new()),
writers: Arc::default(),
}); });
let local = LocalLane(Arc::new(ShellRef(shell.clone()))); let local = LocalLane(Arc::new(ShellRef(shell.clone())));
let task = tokio::spawn(run(shell, service, common)); let task = tokio::spawn(run(shell, service, common));
@ -829,8 +917,24 @@ async fn execute<E: WorkerEndpoint>(
request: &request, request: &request,
client: &shell.client, client: &shell.client,
incoming: &incoming, incoming: &incoming,
writers: &shell.writers,
}; };
e.handle(ctx).await if matches!(incoming, Incoming::Bus(_)) && long_method(&method) && blocking_allowed() {
// A long bus request's handler runs with this worker thread handed over to blocking
// work (BUS-01): the legacy agent's warm-up is seconds of synchronous computation, and
// a Tokio worker blocked that long strands the tasks queued on it -- the shell's own
// bus loop and its connection's reader among them -- so a duplicate arriving
// mid-execution could not be answered IN_PROGRESS and `ipc-v1` section 6's resolution
// of a slow Initialize ran out ("never resolved"). `block_in_place` moves those tasks
// to another thread first. A step's handlers (milliseconds) run in place: the hand-over
// is a thread wake-up of its own. The local lane's caller awaits the handler on its own
// task and is unchanged.
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(e.handle(ctx))
})
} else {
e.handle(ctx).await
}
}; };
// A deferred reply finishes here, with the endpoint's lock released. // A deferred reply finishes here, with the endpoint's lock released.
let outcome = match outcome { let outcome = match outcome {
@ -851,7 +955,12 @@ async fn execute<E: WorkerEndpoint>(
.map(|(name, artifact)| { .map(|(name, artifact)| {
let (name, artifact) = (name.clone(), artifact.clone()); let (name, artifact) = (name.clone(), artifact.clone());
async move { async move {
if artifact.is_in_memory() { // An in-memory artifact is its own hold, and so is a sealed one this
// worker holds explicitly (its own seal): a clone keeps it as long as the
// cache needs it, without another router round trip (BUS-01). Only a
// delivery's handle -- a forwarded request attachment -- needs a hold of
// its own, so the delivery can be consumed.
if artifact.is_in_memory() || artifact.is_hold() {
return (name, artifact); return (name, artifact);
} }
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
@ -868,6 +977,7 @@ async fn execute<E: WorkerEndpoint>(
for retain in retains { for retain in retains {
holds.push(retain.await); holds.push(retain.await);
} }
let cache_span = crate::profile::span("shell.record.cache");
let cached = CachedReply::with_artifacts(outcome.clone(), holds); let cached = CachedReply::with_artifacts(outcome.clone(), holds);
{ {
let mut c = cache.lock().await; let mut c = cache.lock().await;
@ -878,7 +988,15 @@ async fn execute<E: WorkerEndpoint>(
} }
} }
status.set_completed(request.request_id.clone()); status.set_completed(request.request_id.clone());
drop(cache_span);
let reply_span = crate::profile::span("shell.reply");
answer.send(outcome, &reply.artifacts).await; answer.send(outcome, &reply.artifacts).await;
drop(reply_span);
// The next step's writers, allocated while the caller goes on (bus requests only:
// the lane seals nothing into the store).
if matches!(incoming, Incoming::Bus(_)) {
shell.writers.refill(&shell.client);
}
} }
Err(e) => { Err(e) => {
if e.mutation == MutationCertainty::None { if e.mutation == MutationCertainty::None {
@ -914,6 +1032,20 @@ async fn execute<E: WorkerEndpoint>(
} }
} }
/// The methods whose handlers can run for seconds: the warm-ups, the restores and the captures.
/// A step's methods (Prepare, Advance, Commit: milliseconds) are not among them; neither are the
/// read-only extensions.
fn long_method(method: &str) -> bool {
method.ends_with(".Initialize") || method.starts_with("State.") || method == "Agent.Rollback"
}
/// Whether this thread is a worker of a multi-thread Tokio runtime, where
/// [`tokio::task::block_in_place`] is allowed.
fn blocking_allowed() -> bool {
tokio::runtime::Handle::try_current()
.is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread)
}
/// The retention class of every method name the contracts define. /// The retention class of every method name the contracts define.
fn classify_default(method: &str) -> Option<OpClass> { fn classify_default(method: &str) -> Option<OpClass> {
match method { match method {

View file

@ -296,6 +296,61 @@ pub fn place_workers(workers: usize) -> Option<Placement> {
Some(placement) Some(placement)
} }
/// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its
/// placement by the launcher, which split the service's cpuset, instead of splitting its own mask.
/// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and
/// pins worker `i` of every pool created afterwards to `placement.workers[i - 1]`. False, and
/// nothing changed, when the kernel refuses the host set, when a placement is already recorded,
/// or off Linux. Placement decides only the CPU: no result depends on it.
pub fn apply_placement(placement: &Placement) -> bool {
if WORKER_CPUS.get().is_some() || placement.host.is_empty() {
return false;
}
if !affinity::set_current(&placement.host) {
return false;
}
WORKER_CPUS.set(placement.workers.clone()).is_ok()
}
/// The CPUs the calling thread may run on (`sched_getaffinity`); `None` off Linux.
pub fn allowed_cpus() -> Option<Vec<usize>> {
affinity::allowed()
}
/// Confines the calling thread, and every thread it spawns afterwards, to `cpus`; false (and
/// unchanged) if the kernel refuses or off Linux.
pub fn confine_current(cpus: &[usize]) -> bool {
affinity::set_current(cpus)
}
/// A CPU list as `taskset` and cpusets write it: `1,3,5-7`.
pub fn parse_cpu_list(value: &str) -> Option<Vec<usize>> {
let mut cpus = Vec::new();
for part in value.split(',').map(str::trim).filter(|p| !p.is_empty()) {
match part.split_once('-') {
Some((a, b)) => {
let (a, b): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?);
if a > b {
return None;
}
cpus.extend(a..=b);
}
None => cpus.push(part.parse().ok()?),
}
}
cpus.sort_unstable();
cpus.dedup();
(!cpus.is_empty()).then_some(cpus)
}
/// The inverse of [`parse_cpu_list`], without ranges: `1,3,5`.
pub fn format_cpu_list(cpus: &[usize]) -> String {
cpus.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join(",")
}
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
mod affinity { mod affinity {
/// The CPUs the calling thread may run on. /// The CPUs the calling thread may run on.
@ -467,6 +522,16 @@ mod tests {
assert_eq!(ran.load(Ordering::Relaxed), 8); assert_eq!(ran.load(Ordering::Relaxed), 8);
} }
#[test]
fn cpu_lists_parse_as_taskset_writes_them() {
assert_eq!(parse_cpu_list("1,3,5,7"), Some(vec![1, 3, 5, 7]));
assert_eq!(parse_cpu_list("9-11, 1 ,10"), Some(vec![1, 9, 10, 11]));
assert_eq!(parse_cpu_list(""), None);
assert_eq!(parse_cpu_list("3-1"), None);
assert_eq!(parse_cpu_list("x"), None);
assert_eq!(format_cpu_list(&[1, 3, 5]), "1,3,5");
}
#[test] #[test]
fn the_split_gives_each_worker_a_cpu_and_the_host_the_rest() { fn the_split_gives_each_worker_a_cpu_and_the_host_the_rest() {
// The release's flysim cpuset, four whole cores, four sweep threads. // The release's flysim cpuset, four whole cores, four sweep threads.