Compare commits

..

5 commits

Author SHA1 Message Date
acamilo
49bb69e5da docs: v0.7.5 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 15:58:22 +00:00
acamilo
2c1b51695a Merge port/perf-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE-WITH-NOTES; R1-R3 addressed): the session pins its sweep workers, and the sim's cpus are its own 2026-10-01 15:58:22 +00:00
acamilo
ac7be4a204 infra: fly-cpu-confine also confines /.lxc, check ignores its own chain (PERF-02 review R1-R3)
apply/release/status now cover the cgroup pct exec lands in (/.lxc, only when
it already exists, warn-only when unwritable). check no longer counts its own
process or its parents. Runbook: rollback via an older 05-deploy needs
fly-cpu-confine release; the exact post-first-deploy status/check commands.
2026-10-01 15:57:46 +00:00
acamilo
ab537d1045 infra: the sim's cpus are exclusive to the sim (PERF-02 review N1)
A pinned sweep worker cannot leave its cpu, so any sustained cpu-bound process allowed there
collapsed the session runtime to 0.14x real time. flysim and flysim-session now run in
flysim.slice (AllowedCPUs = the sim's set) and bin/fly-cpu-confine, run by their ExecStartPre,
confines system.slice, user.slice and init.scope to the other cpus. It refuses while a sim unit
still sits outside the slice (shrinking system.slice under it would make it float). Without a
partition the deploy writes FLY_SESSION_PIN=0. fly-recap and fly-retention run at SCHED_IDLE.
The drop-in plan is one function (cpuset_dropin_plan) shared by the deploy and lint; lint covers the
plan, the units, the deploy wiring and fly-cpu-confine against a stub systemctl and a fake /proc.
Runbook and README updated.
2026-10-01 15:01:47 +00:00
acamilo
8fa98b0b03 session: pin the sweep workers one per cpu in flysim-session (PERF-02)
CUT-01's speed probation fell back at a median realtime factor of 0.959.
With exactly as many cpus as sweep threads, the session's host threads
(dispatching tokio worker, coordinator, listeners) sleep and wake around
every transition, the sweep workers park and wake with them, and the
scheduler often stacks two workers on one cpu: the session's ticks ran
about 35% slower than the legacy loop's on the same frames (equal with a
spare cpu).

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

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

View file

@ -479,6 +479,22 @@ in-process and process, and the compatibility string is unchanged.
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too. (about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
### PERF-02 — The session's ticks on the release cpuset (port slice)
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. Pinning is only safe in a cpuset that is the sim's alone (a pinned worker cannot leave a CPU that something else hogs: 0.14x real time): the deploy makes it so with `flysim.slice` and `fly-cpu-confine` and writes `FLY_SESSION_PIN=0` when it cannot (`infra/docs/runbook.md`). The legacy loop and process mode are
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
workers against the sequential kernel on the real connectome. The service's periodic profile
line also prints the measurement spans (and the brain's phase split) when
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
### SHADOW-01 — The session runtime beside the live fly (port slice) ### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no **2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no

View file

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

View file

@ -1002,3 +1002,12 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge
computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before, computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before,
Oddish caught after. Review: APPROVE. Oddish caught after. Review: APPROVE.
- 2026-10-01 (v0.7.5, port slice PERF-02): the first cutover (v0.7.3, after a 3 h shadow with zero
divergence) failed its speed probation at a median 0.959x real time and fell back to legacy on
its own. Cause: with exactly as many CPUs as sweep threads, the session's other threads woke each
frame and the scheduler often stacked two sweep threads on one CPU. flysim-session now pins each
sweep worker to its own CPU and its other threads to the remaining one (16.2 to 13.0 ms a frame on
a build box of the release CPU; legacy 10.5), and the sim gets its own slice: every other unit,
user session and `pct exec` shell is confined off its CPUs (a hog there collapsed a pinned
session). Results, traces and the compatibility string are unchanged. Reviews: two rounds,
APPROVE-WITH-NOTES; notes addressed.

View file

@ -182,12 +182,16 @@ NEED_RELOAD=0
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}" RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}" ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
DEPLOY_CPUS="" DEPLOY_CPUS=""
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to
# flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
PARTITION_ACTIVE=0
if [ -n "${CPUSET:-}" ]; then if [ -n "${CPUSET:-}" ]; then
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \ deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)" "/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \ read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
PARTITION_ACTIVE=1
log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim" log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim"
else else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \ log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -428,7 +432,7 @@ fi
# 2. systemd units # 2. systemd units
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging systemd units" log "05-deploy: converging systemd units"
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.slice "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
[ -f "$f" ] || continue [ -f "$f" ] || continue
name="$(basename "$f")" name="$(basename "$f")"
changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)" changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)"
@ -559,6 +563,17 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# refuses anything but "raw" for a game with no macros, reads the retired # refuses anything but "raw" for a game with no macros, reads the retired
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised # "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
# value outright. # value outright.
# PERF-02: flysim-session pins its sweep workers one per cpu of the cpuset it finds. That is only
# safe when the cpuset is the sim's alone: with the partition in force (section 3b) it is, and
# bin/fly-cpu-confine keeps every other process off it. Without it (no CPUSET, or a conf that does
# not match) the unit sees the container's whole cpuset, where a pinned worker would sit on a cpu
# anything can hog (measured 0.14x real time), so pinning is turned off: the threads float. The
# runtime reads the exact value 0 as off.
if [ "$PARTITION_ACTIVE" -eq 1 ]; then
echo "FLY_SESSION_PIN=1"
else
echo "FLY_SESSION_PIN=0"
fi
echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}" echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the # Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as # bus"). "direct" is the default and is flysim binding :7400 itself, as
@ -703,8 +718,8 @@ if [ -n "${CPUSET:-}" ]; then
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \ "Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
"leaves cpuset.cpus.effective empty and the unit unstartable." "leaves cpuset.cpus.effective empty and the unit unstartable."
else else
read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
log "05-deploy: cpuset partition — flysim=$sim_cpus, xvfb/flystage/flystage-web/pulse/mediamtx/flyedge=$page_cpus, flycast=$encoder_cpus" log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
tmp_dropin="$(mktemp)" tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day # flyedge is off by default, but its drop-in is written with the rest so that the day
# it is enabled it serves the page from the page's CPUs, never from flysim's. # it is enabled it serves the page from the page's CPUs, never from flysim's.
@ -713,31 +728,41 @@ if [ -n "${CPUSET:-}" ]; then
# flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not # flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
# flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder # flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
# leave idle and never a cycle of the live fly's. # leave idle and never a cycle of the live fly's.
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session flyshadow; do # flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
case "$u" in # its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
flysim|flysim-session) cpus="$sim_cpus" ;; # using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
flycast) cpus="$encoder_cpus" ;; # everything else. See that script's header for the cgroup semantics and the ordering rule.
flyshadow) cpus="${page_cpus},${encoder_cpus}" ;; # A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
*) cpus="$page_cpus" ;; mapfile -t plan_lines <<< "$plan"
esac for plan_line in "${plan_lines[@]}"; do
{ read -r u cpus <<< "$plan_line"
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit." case "$u" in *=) continue ;; esac
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4." cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
echo "[Service]" ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
echo "AllowedCPUs=${cpus}" changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
} > "$tmp_dropin"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.service.d"
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.service.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then if [ "$changed" = changed ]; then
NEED_RELOAD=1 NEED_RELOAD=1
log "05-deploy: ${u}.service.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload" log "05-deploy: ${u}.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
fi fi
done done
{
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
echo "$plan" | awk '$1 ~ /=$/ {print $1 $2}'
} > "$tmp_dropin"
changed="$(converge_file "$CTID" "$tmp_dropin" /etc/fly/cpuset.env 0644 root:root)"
[ "$changed" = changed ] && log "05-deploy: /etc/fly/cpuset.env changed — fly-cpu-confine applies it when flysim next (re)starts, by which time it runs in flysim.slice"
rm -f "$tmp_dropin" rm -f "$tmp_dropin"
fi fi
else else
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)" log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
fi fi
# No partition in force: nothing may stay confined by an earlier one, and the session runtime must
# not pin (fly.env above says FLY_SESSION_PIN=0). A confinement already applied lasts until the next
# boot or `fly-cpu-confine release`.
if [ "$PARTITION_ACTIVE" -ne 1 ]; then
ct_exec "$CTID" -- rm -f /etc/fly/cpuset.env
log "05-deploy: no cpuset partition: /etc/fly/cpuset.env removed, FLY_SESSION_PIN=0 in fly.env (sweep workers float); run \`fly-cpu-confine release\` if an earlier partition is still applied"
fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not # 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not
@ -745,7 +770,7 @@ fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /opt/fly/bin" log "05-deploy: converging bin/ helpers to /opt/fly/bin"
ct_exec "$CTID" -- mkdir -p /opt/fly/bin ct_exec "$CTID" -- mkdir -p /opt/fly/bin
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
done done

View file

@ -267,6 +267,12 @@ refuses to write the drop-ins until the conf actually carries
`CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves `CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves
`cpuset.cpus.effective` empty and the unit unstartable. `cpuset.cpus.effective` empty and the unit unstartable.
The sim's CPUs are also kept exclusive to it (PERF-02 review N1, `infra/docs/runbook.md` "The sim's
CPUs are exclusive to the sim"): the sim units run in `flysim.slice`, and `bin/fly-cpu-confine`
confines `system.slice`, `user.slice`, `init.scope` and `/.lxc` (`pct exec`) to the other CPUs when the sim starts.
Without a partition (`CPUSET` unset) none of this applies and the deploy turns the session
runtime's worker pinning off (`FLY_SESSION_PIN=0`).
`CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local `CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local
socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md` socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md`
section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three

188
infra/bin/fly-cpu-confine Executable file
View file

@ -0,0 +1,188 @@
#!/usr/bin/env bash
# infra/bin/fly-cpu-confine — keep every process that is not the sim off the sim's CPUs.
#
# Usage (INSIDE the container, as root):
# fly-cpu-confine apply confine system.slice, user.slice, init.scope and /.lxc (where `pct exec`
# lands) to the non-sim CPUs
# fly-cpu-confine release undo `apply` (all of them go back to the container's whole cpuset)
# fly-cpu-confine status what each of them is confined to, and where the sim runs
# fly-cpu-confine check list every process that is not in flysim.slice but may run on a
# sim CPU (exit 1 if there is one); this command's own process and its
# parents (the shell it was started from) are noted, not failed
#
# Why. The session runtime pins its sweep workers one per CPU (PERF-02). A pinned worker cannot
# leave its CPU, so any sustained CPU-bound process that may run there stalls every barrier:
# measured 0.14x real time with a plain busy loop (0.68x at nice 19; SCHED_IDLE is harmless).
# Priorities do not fix that; keeping the sim's CPUs to the sim does.
#
# How (cgroup v2). flysim.service and flysim-session.service run in flysim.slice, which has
# AllowedCPUs= the sim's CPUs (a drop-in written by 05-deploy.sh). Its siblings under the root
# cgroup are system.slice (every other service, cron, apt, sshd), user.slice (every login
# session) and init.scope (PID 1 and what it forks). `apply` sets AllowedCPUs= the NON-sim CPUs
# on those three, so nothing that systemd places anywhere else can reach a sim CPU. A child's
# cpuset is bounded by its parent's, so the sim must never sit under a slice that excludes its
# CPUs: that is why it has a slice of its own and is not left in system.slice.
#
# The CPU lists come from ${CPUSET_ENV} (written by 05-deploy.sh, from the same cpuset_partition
# call as the AllowedCPUs= drop-ins). No file means no partition: nothing is confined.
#
# `apply` is runtime-only (systemctl set-property --runtime) and is run by flysim.service and
# flysim-session.service's ExecStartPre, so it is re-applied after every boot and every restart
# and can never run while the sim still sits in system.slice: shrinking system.slice under a
# sim that has not been restarted into flysim.slice would silently make it float over the page
# CPUs. `apply` refuses (exit 3, nothing changed) if a sim unit is outside flysim.slice.
#
# `pct exec` / `pct enter` (lxc-attach) put their processes in the cgroup `/.lxc` (or `/.lxc-N`),
# a sibling of system.slice that systemd does not manage. It is written directly
# (cpuset.cpus), only if it already exists (a cgroup lxc owns is never created here), and a
# failure is a warning, never an error: it must not stop the sim from starting. If it cannot be
# written, `check` lists what is running there; run long operator jobs with
# `systemd-run --scope --slice=system.slice -- <cmd>` (or `... -- bash`).
set -euo pipefail
: "${CPUSET_ENV:=/etc/fly/cpuset.env}"
: "${SYSTEMCTL:=systemctl}"
: "${PROC_ROOT:=/proc}"
: "${CGROUP_ROOT:=/sys/fs/cgroup}"
: "${SIM_SLICE:=flysim.slice}"
: "${SIM_UNITS:=flysim.service flysim-session.service}"
CONFINED_UNITS="system.slice user.slice init.scope"
# existing lxc attach cgroups (/.lxc, /.lxc-N) that have a cpuset
lxc_cgroups() {
local d
for d in "$CGROUP_ROOT"/.lxc "$CGROUP_ROOT"/.lxc-*; do
[ -d "$d" ] && [ -e "$d/cpuset.cpus" ] && echo "$d"
done
return 0
}
# set_lxc CPUS — write CPUS into every lxc attach cgroup; warn, never fail.
set_lxc() {
local d
for d in $(lxc_cgroups); do
if ! echo "$1" > "$d/cpuset.cpus" 2>/dev/null; then
log "WARNING: cannot write ${d}/cpuset.cpus; processes started with pct exec stay unconfined (run long jobs with systemd-run --scope --slice=system.slice)"
fi
done
return 0
}
log() { echo "fly-cpu-confine: $*" >&2; }
# read_env — set SIM_CPUS and OTHER_CPUS from ${CPUSET_ENV}, or return 1 when there is no partition.
# Parsed as KEY=VALUE lines, never sourced.
read_env() {
SIM_CPUS="" OTHER_CPUS=""
[ -r "$CPUSET_ENV" ] || return 1
local k v
while IFS='=' read -r k v; do
case "$k" in
FLY_SIM_CPUS) SIM_CPUS="$v" ;;
FLY_OTHER_CPUS) OTHER_CPUS="$v" ;;
esac
done < "$CPUSET_ENV"
[ -n "$SIM_CPUS" ] && [ -n "$OTHER_CPUS" ]
}
# expand LIST — one cpu number per line for a list such as 1,3,5-7.
expand() {
echo "$1" | tr ',' '\n' | awk -F- 'NF==1 && $1 != "" {print $1} NF==2 {for (i=$1;i<=$2;i++) print i}'
}
sim_outside_slice() {
local u cg
for u in $SIM_UNITS; do
cg="$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
[ -n "$cg" ] || continue
case "$cg" in
"/${SIM_SLICE}/"*) ;;
*) echo "$u ($cg)"; return 0 ;;
esac
done
return 1
}
cmd="${1:-}"
case "$cmd" in
apply)
if ! read_env; then
log "no partition configured (${CPUSET_ENV} missing or empty): nothing confined"
exit 0
fi
if out="$(sim_outside_slice)"; then
log "REFUSING to confine: $out runs outside ${SIM_SLICE}; restart it first (it would float over the page cpus otherwise)"
exit 3
fi
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${OTHER_CPUS}"
done
set_lxc "$OTHER_CPUS"
log "system.slice, user.slice, init.scope and /.lxc confined to ${OTHER_CPUS}; ${SIM_SLICE} keeps ${SIM_CPUS}"
;;
release)
# Not `AllowedCPUs=` (empty): systemd leaves the cgroup's cpuset.cpus at its last value while
# the cpuset controller stays enabled for some other unit (here flysim.slice), so the slices
# would stay confined. Set the container's whole cpuset explicitly.
all_cpus="$(cat "${CGROUP_ROOT}/cpuset.cpus.effective" 2>/dev/null || true)"
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${all_cpus}"
done
set_lxc "$all_cpus"
log "system.slice, user.slice, init.scope and /.lxc released to the container's whole cpuset (${all_cpus:-unknown})"
;;
status)
for u in $CONFINED_UNITS $SIM_SLICE; do
echo "$u AllowedCPUs=$("$SYSTEMCTL" show -p AllowedCPUs --value "$u" 2>/dev/null || true)"
done
for d in $(lxc_cgroups); do
echo "${d#"$CGROUP_ROOT"} cpuset.cpus=$(cat "$d/cpuset.cpus" 2>/dev/null || true)"
done
for u in $SIM_UNITS; do
echo "$u ControlGroup=$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
done
;;
check)
if ! read_env; then
log "no partition configured: nothing to check"
exit 0
fi
sim="$(expand "$SIM_CPUS" | sort -n | tr '\n' ' ')"
bad=0
# this process and its parents (the pct exec shell chain) are not a CPU hog
self=" "
p="${SELF_PID:-$$}"
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#self}" -lt 400 ]; do
self="$self$p "
p="$(sed -n 's/^PPid:[[:space:]]*//p' "$PROC_ROOT/$p/status" 2>/dev/null || true)"
done
for d in "$PROC_ROOT"/[0-9]*; do
pid="${d##*/}"
[ -r "$d/status" ] || continue
cg="$(sed -n 's/^0:://p' "$d/cgroup" 2>/dev/null || true)"
case "$cg" in "/${SIM_SLICE}/"* | "/${SIM_SLICE}") continue ;; esac
# kernel threads have no cgroup of their own in this sense and are not a CPU hog
if [ -z "$(readlink "$d/exe" 2>/dev/null || true)" ]; then continue; fi
allowed="$(sed -n 's/^Cpus_allowed_list:[[:space:]]*//p' "$d/status")"
[ -n "$allowed" ] || continue
hit=""
for c in $(expand "$allowed"); do
for s in $sim; do [ "$c" = "$s" ] && hit="$hit$c,"; done
done
if [ -n "$hit" ]; then
case "$self" in *" $pid "*)
log "note: ${pid} ($(cat "$d/comm" 2>/dev/null)) is this check's own process chain in ${cg:-?} and may run on sim cpu ${hit%,}; not counted"
continue ;;
esac
echo "process $pid ($(cat "$d/comm" 2>/dev/null)) in ${cg:-?} may run on sim cpu ${hit%,}"
bad=1
fi
done
[ "$bad" -eq 0 ] && log "ok: only ${SIM_SLICE} can run on ${SIM_CPUS}"
exit "$bad"
;;
*)
sed -n '2,11p' "$0" >&2
exit 2
;;
esac

View file

@ -850,6 +850,78 @@ not a constant, and live in the operator's infra repo
ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh` ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh`
checks it against both the current shape and the earlier, narrower one. checks it against both the current shape and the earlier, narrower one.
### The sim's CPUs are exclusive to the sim (PERF-02 review N1)
The session runtime pins its sweep workers one per CPU. A pinned worker cannot leave its CPU, so
any sustained CPU-bound process that is allowed on a worker's CPU stalls every barrier: measured
**0.14x real time** with a plain busy loop (0.68x at nice 19; `SCHED_IDLE` was harmless; the
floating, unpinned runtimes held 0.86-0.94x under the same hog). Priorities cannot fix that, so
the partition above is completed by making the sim's CPUs exclusive:
- `flysim.service` and `flysim-session.service` run in **`flysim.slice`** (`units/flysim.slice`),
whose `AllowedCPUs=` is the sim's set (`flysim.slice.d/cpuset.conf`, written by `05-deploy.sh` from
`lib/common.sh`'s `cpuset_dropin_plan`, the same call that writes every other drop-in).
- `bin/fly-cpu-confine apply` sets `AllowedCPUs=` the **non-sim** CPUs on `system.slice` (every
other service, cron, apt, sshd), `user.slice` (every login session) and `init.scope`, and writes
the same list to `/sys/fs/cgroup/.lxc/cpuset.cpus` (where `pct exec` / `pct enter` processes land,
see below). It runs as
both sim units' `ExecStartPre` (root, failure never blocks the start), so it is re-applied after
every boot and every restart. The lists come from `/etc/fly/cpuset.env`, which the deploy writes.
- The slice is named without a dash on purpose: systemd nests `a-b.slice` under `a.slice`, and a
child's cpuset is bounded by its parent's (cgroup v2: effective cpus = own cpus intersected with
the parent's, and the parent's when that is empty). `flysim.slice` sits beside `system.slice`
under the root slice, so nothing above it excludes its CPUs.
- **Ordering rule.** Shrinking `system.slice` under a flysim that still sits in `system.slice` (a
unit started before this change, not yet restarted) would leave its own `AllowedCPUs=` outside the
parent's set and silently make it float over the page CPUs. So `apply` refuses (exit 3, nothing
changed) while a sim unit's cgroup is not under `/flysim.slice/`. A deploy therefore changes
nothing on a running sim; the confinement starts with the next `flysim` (re)start, which is the
first moment it is safe. `fly-cpu-confine status` shows the result.
- `fly-recap` and `fly-retention` also run at `CPUSchedulingPolicy=idle`, which the review measured
harmless beside the pinned workers (defence in depth for the batch jobs).
- **No partition, no pinning.** With `CPUSET` unset (or the container conf not matching it) there
is no confinement, so `05-deploy.sh` writes `FLY_SESSION_PIN=0` to `/etc/fly/fly.env` and the
session runtime's threads float, as before PERF-02. With the partition in force it writes
`FLY_SESSION_PIN=1`. (The runtime treats exactly `0` as off.)
- **`pct exec` / `pct enter`:** `lxc-attach` puts its processes in the cgroup `/.lxc` (or
`/.lxc-N`), a sibling of `system.slice` that systemd does not manage. `apply` writes the non-sim
list into the `cpuset.cpus` of every such cgroup that already exists (it never creates one; lxc
owns it). Where that file is not writable it logs a warning and carries on: `apply` never fails
the sim's start. In that case run long operator jobs through
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`. A `.lxc-N` created
after `apply` is not covered until the next sim start. `fly-cpu-confine check` lists every
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one); its own
process and the shell chain it was started from are printed as a note and not counted, so it
exits 0 on a healthy container when run through `pct exec`.
- **After the first deploy (once):** restart the sim so the confinement is applied, then read it.
`apply` is refused while flysim still runs outside `flysim.slice`, so nothing changes until then.
```
pct exec <ctid> -- systemctl restart flysim.service
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine status # system.slice, user.slice, init.scope and /.lxc = the non-sim cpus; flysim.slice = the sim's; flysim ControlGroup under /flysim.slice/
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine check # exit 0: "ok: only flysim.slice can reach ..."
pct exec <ctid> -- systemctl show -p AllowedCPUs flycast.service xvfb.service # still the drop-in values
```
Then watch the probation RTF. A `check` that names a process is a hog to move or stop.
- **If lag grows on the session runtime**: `fly-cpu-confine check`, then `top -H` for a stray hog on
the sim's CPUs. `FLY_SESSION_PIN=0` (a drop-in) restores floating.
- `fly-cpu-confine release` undoes the runtime confinement (until the next sim start); it sets
`system.slice`, `user.slice`, `init.scope` and `/.lxc` back to the container's whole cpuset
explicitly, because systemd keeps the old mask for an empty `AllowedCPUs=` while the cpuset
controller stays on for another unit. (Tested in `tests/lint.sh` against a fake cgroup tree.)
- **Rollback by re-running an older infra tree's `05-deploy.sh`** (rather than the symlink flip in
"Roll back a release", which is fine): an infra tree older than this change has no
`Slice=flysim.slice`, so flysim restarts into `system.slice`, which is still confined to the
non-sim CPUs. Its `AllowedCPUs=` then does not intersect that set and it floats over the page and
encoder CPUs while the sim's own CPUs sit idle (the slow shape again, not a black stream). After
such a rollback run `pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine release` (or reboot), then
restart flysim.
Verified on a real-systemd box (4 CPUs, the sim as a unit in `flysim.slice` on 3 of them, 3 sweep
threads, paced at 0.55x): confined or not, with no hog the session holds 0.55; five busy loops (three
as system services, two from a user shell) unconfined sit on the sim's CPUs and the session drops to
0.37; confined by the unit's own `ExecStartPre`, every loop samples on CPU 0 only, the sim's threads
keep their CPUs and the session holds 0.54-0.55.
### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition ### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition
`FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into `FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into

View file

@ -189,6 +189,44 @@ cpuset_partition() {
echo "$sim_cpus $page_cpus $encoder_cpus" echo "$sim_cpus $page_cpus $encoder_cpus"
} }
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] — print one "UNIT-NAME CPUS" line for every
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service,
# flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine:
#
# flysim.slice the sim's CPUs (flysim.service and flysim-session.service run in it);
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
# slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge the page CPUs;
# flycast the encoder CPUs;
# flyshadow page + encoder (never the sim's);
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
# of CPUSET that is not the sim's, in CPUSET order.
#
# One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
# cpuset_partition does.
cpuset_dropin_plan() {
local cpuset="$1" rayon="$2" encoder="${3:-2}" sim page enc u
read -r sim page enc <<< "$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
echo "flysim.slice $sim"
for u in flysim flysim-session; do echo "${u}.service $sim"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge; do echo "${u}.service $page"; done
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $sim"
echo "FLY_OTHER_CPUS= ${page},${enc}"
}
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to
# /etc/systemd/system/UNIT-NAME.d/cpuset.conf ([Slice] for a .slice, [Service] otherwise).
cpuset_dropin_text() {
local unit="$1" cpus="$2" label="$3" section="Service"
case "$unit" in *.slice) section="Slice" ;; esac
echo "# generated by infra/05-deploy.sh from CPUSET in ${label} — do not hand-edit."
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[${section}]"
echo "AllowedCPUs=${cpus}"
}
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# operator-box guard # operator-box guard
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -147,7 +147,7 @@ check_exec_path() {
# stripping a leading '-' (systemd's "failure is ok" marker) and any # stripping a leading '-' (systemd's "failure is ok" marker) and any
# /bin/sh -c '...' wrapper (checked as a shell built-in, always ok). # /bin/sh -c '...' wrapper (checked as a shell built-in, always ok).
local cmd local cmd
cmd="$(echo "$line" | sed -E 's/^Exec(Start|StartPre|StartPost)=//' | sed -E 's/^-//' | awk '{print $1}')" cmd="$(echo "$line" | sed -E 's/^Exec(Start|StartPre|StartPost)=//' | sed -E 's/^[-+@!:]+//' | awk '{print $1}')"
[ -z "$cmd" ] && return 0 [ -z "$cmd" ] && return 0
case "$cmd" in case "$cmd" in
@ -824,11 +824,9 @@ grep -qF '[ -n "$from" ] || die "--from is required' "$SETUP" \
grep -qF 'restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\"' "$INFRA_DIR/box/fly-shadow-remote-setup" \ grep -qF 'restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\"' "$INFRA_DIR/box/fly-shadow-remote-setup" \
&& pass "fly-shadow-remote-setup limits the relay key to the ingest (restrict, forced command)" \ && pass "fly-shadow-remote-setup limits the relay key to the ingest (restrict, forced command)" \
|| fail "fly-shadow-remote-setup must write restrict,command=\"/opt/fly/current/fly-shadow ingest --root \$ROOT\"" || fail "fly-shadow-remote-setup must write restrict,command=\"/opt/fly/current/fly-shadow ingest --root \$ROOT\""
if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then grep -qF 'echo "flyshadow.service ${page},${enc}"' "$INFRA_DIR/lib/common.sh" \
pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs" && pass "cpuset_dropin_plan keeps flyshadow.service off flysim's CPUs (page + encoder; checked disjoint in section 3c2)" \
else || fail "cpuset_dropin_plan must give flyshadow.service the page and encoder CPUs, never flysim's"
fail "05-deploy.sh must give flyshadow.service the page and encoder CPUs, never flysim's"
fi
if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \ if grep -qF 'FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")"' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then && grep -qF 'echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"' "$INFRA_DIR/05-deploy.sh"; then
pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value" pass "05-deploy.sh validates FLY_FEED_VIA and writes the normalized value"
@ -844,11 +842,7 @@ if [ "$fv_out" = "empty=direct direct=direct DIRECT=direct bus=bus Bus=bus BUS=b
else else
fail "feed_via_normalize: got '$fv_out'" fail "feed_via_normalize: got '$fv_out'"
fi fi
if grep -qE '^[[:space:]]*for u in flysim .*\bflyedge\b.*; do$' "$INFRA_DIR/05-deploy.sh"; then # (the cpuset drop-ins for flyedge.service and flysim-session.service are checked from the plan, section 3c2)
pass "05-deploy.sh writes a cpuset drop-in for flyedge.service"
else
fail "05-deploy.sh cpuset loop must include flyedge (the page's CPUs, never flysim's)"
fi
if grep -qE '^Environment=FLY_FEED_VIA' "$INFRA_DIR/units/flysim.service"; then if grep -qE '^Environment=FLY_FEED_VIA' "$INFRA_DIR/units/flysim.service"; then
fail "flysim.service pins FLY_FEED_VIA; it belongs to fly.env so a box can be switched by deploy" fail "flysim.service pins FLY_FEED_VIA; it belongs to fly.env so a box can be switched by deploy"
else else
@ -917,9 +911,6 @@ grep -qE '^d /run/fly/session +0700 fly +fly' "$INFRA_DIR/config/fly-tmpfiles.co
grep -qE 'for name in .*\bfly-runtime\b.*; do$' "$INFRA_DIR/05-deploy.sh" \ grep -qE 'for name in .*\bfly-runtime\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh installs fly-runtime" \ && pass "05-deploy.sh installs fly-runtime" \
|| fail "05-deploy.sh must converge bin/fly-runtime to /opt/fly/bin" || fail "05-deploy.sh must converge bin/fly-runtime to /opt/fly/bin"
grep -qE '^[[:space:]]*for u in flysim .*\bflysim-session\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes flysim-session.service's cpuset drop-in" \
|| fail "05-deploy.sh cpuset loop must include flysim-session (flysim's cores)"
grep -qF 'flysim.service.d/10-runtime.conf' "$INFRA_DIR/05-deploy.sh" \ grep -qF 'flysim.service.d/10-runtime.conf' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"${release_path}/flysim-session"' "$INFRA_DIR/05-deploy.sh" \ && grep -qF '"${release_path}/flysim-session"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without flysim-session while the session runtime runs" \ && pass "05-deploy.sh refuses a release without flysim-session while the session runtime runs" \
@ -1479,6 +1470,234 @@ check_cpuset_partition_refuses "RAYON_THREADS consumes the whole cpuset" "1,3" 2
check_cpuset_partition_refuses "not enough left for ENCODER_CORES plus a page cpu" "1,3,5,7" 2 2 "not enough for ENCODER_CORES" check_cpuset_partition_refuses "not enough left for ENCODER_CORES plus a page cpu" "1,3,5,7" 2 2 "not enough for ENCODER_CORES"
rm -f "$cpuset_partition_bin" rm -f "$cpuset_partition_bin"
# ---------------------------------------------------------------------------
# 3c2. The sim's CPUs are the sim's alone (PERF-02 review N1): the drop-in plan, the units, the
# deploy wiring and bin/fly-cpu-confine. A sustained CPU-bound process on a pinned sweep worker's
# CPU collapses the session runtime to 0.14x real time, so every slice that is not flysim.slice
# must be kept off its CPUs, and the session must not pin where that is not so.
# ---------------------------------------------------------------------------
echo "--- the sim's cpus are exclusive (flysim.slice, fly-cpu-confine) ---"
plan_bin="$(mktemp "${TMPDIR:-/tmp}/fly-lint-plan.XXXXXX")"
cat > "$plan_bin" <<PLANEOF
#!/usr/bin/env bash
set -euo pipefail
. "$INFRA_DIR/lib/common.sh"
"\$@"
PLANEOF
chmod +x "$plan_bin"
check_plan() {
local label="$1" cpuset="$2" rayon="$3" encoder="$4" plan sim other u cpus bad=""
plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; }
sim="$(awk '$1 == "flysim.slice" {print $2}' <<< "$plan")"
other="$(awk '$1 == "FLY_OTHER_CPUS=" {print $2}' <<< "$plan")"
[ "$sim" = "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$plan")" ] || bad="$bad SIM-list-differs-from-slice"
for u in flysim.service flysim-session.service; do
[ "$(awk -v u="$u" '$1 == u {print $2}' <<< "$plan")" = "$sim" ] || bad="$bad $u-not-on-sim-cpus"
done
# every other unit, and the confinement list, is disjoint from the sim's cpus
while read -r u cpus; do
case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=) continue ;; esac
if [ -n "$(comm -12 <(tr ',' '\n' <<< "$sim" | sort) <(tr ',' '\n' <<< "$cpus" | sort))" ]; then
bad="$bad $u-overlaps-sim"
fi
done <<< "$plan"
# sim + other is exactly CPUSET
[ "$(tr ',' '\n' <<< "$sim,$other" | sort -n | tr '\n' ' ')" = "$(tr ',' '\n' <<< "$cpuset" | sort -n | tr '\n' ' ')" ] || bad="$bad sim+other-is-not-CPUSET"
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycast flyshadow; do
grep -q "^${u}.service " <<< "$plan" || bad="$bad $u-missing"
done
if [ -z "$bad" ]; then
pass "cpuset_dropin_plan: $label: sim=$sim, nothing else can reach it, sim+other = CPUSET"
else
fail "cpuset_dropin_plan: $label:$bad"
fi
}
check_plan "release shape (sixteen cpus, four sim, four encoder)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4
check_plan "ten cpus, ENCODER_CORES=3" "1,3,5,7,9,11,13,15,17,19" 4 3
check_plan "eight cpus, default encoder" "1,3,5,7,9,11,13,15" 4 ""
check_plan "dev shape (RAYON_THREADS=2)" "0,2,4,6,8,10,12,14" 2 ""
# the generated drop-ins: a slice gets [Slice], a service [Service], both AllowedCPUs=
if [ "$("$plan_bin" cpuset_dropin_text flysim.slice 1,3,5,7 lint-env | grep -v '^#')" = "$(printf '[Slice]\nAllowedCPUs=1,3,5,7')" ] \
&& [ "$("$plan_bin" cpuset_dropin_text xvfb.service 9,11 lint-env | grep -v '^#')" = "$(printf '[Service]\nAllowedCPUs=9,11')" ]; then
pass "cpuset_dropin_text: [Slice] for flysim.slice, [Service] for a unit, AllowedCPUs= the list"
else
fail "cpuset_dropin_text: wrong drop-in text"
fi
rm -f "$plan_bin"
# units
for u in flysim flysim-session; do
if grep -qE '^Slice=flysim\.slice$' "$INFRA_DIR/units/$u.service" \
&& grep -qE '^ExecStartPre=-\+/opt/fly/bin/fly-cpu-confine apply$' "$INFRA_DIR/units/$u.service"; then
pass "$u.service runs in flysim.slice and applies the confinement before it starts"
else
fail "$u.service must have Slice=flysim.slice and ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply"
fi
done
if [ -f "$INFRA_DIR/units/flysim.slice" ] && grep -q '^\[Slice\]' "$INFRA_DIR/units/flysim.slice"; then
pass "units/flysim.slice exists (no dash in the name: a-b.slice would nest under a.slice)"
else
fail "units/flysim.slice is missing"
fi
if grep -rE '^Slice=' "$INFRA_DIR/units" | grep -vE '/flysim(-session)?\.service:Slice=flysim\.slice$'; then
fail "a unit other than flysim/flysim-session sets Slice= (flysim.slice is the sim's alone)"
else
pass "only flysim.service and flysim-session.service set Slice="
fi
# systemd nests a-b.slice under a.slice, and a child's cpuset is bounded by its parent's: the sim's
# slice (found as /fly.slice/fly-sim.slice/... in the N1 proof when it was named with a dash) must be
# top-level, beside system.slice and user.slice
for sl in "$INFRA_DIR"/units/*.slice; do
case "$(basename "$sl" .slice)" in
*-*) fail "$(basename "$sl"): a dash in a slice name nests it under the prefix slice" ;;
*) pass "$(basename "$sl"): top-level slice (no dash in the name)" ;;
esac
done
for u in fly-recap fly-retention; do
grep -qE '^CPUSchedulingPolicy=idle$' "$INFRA_DIR/units/$u.service" \
&& pass "$u.service runs at SCHED_IDLE" || fail "$u.service must set CPUSchedulingPolicy=idle (N1: batch work never competes)"
done
# deploy wiring
grep -qF 'cpuset_dropin_plan "$CPUSET"' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '/etc/fly/cpuset.env' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"$INFRA_DIR"/units/*.slice' "$INFRA_DIR/05-deploy.sh" \
&& grep -qE 'for name in .*\bfly-cpu-confine\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh converges the plan, cpuset.env, the slice unit and fly-cpu-confine" \
|| fail "05-deploy.sh must use cpuset_dropin_plan, write /etc/fly/cpuset.env, push units/*.slice and install fly-cpu-confine"
grep -qE 'FLY_SESSION_PIN=0' "$INFRA_DIR/05-deploy.sh" && grep -qE 'PARTITION_ACTIVE=1' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh turns session pinning off (FLY_SESSION_PIN=0) when no partition is in force" \
|| fail "05-deploy.sh must write FLY_SESSION_PIN=0 to fly.env unless the cpuset partition is in force"
# bin/fly-cpu-confine against a stub systemctl and a fake /proc
cc="$INFRA_DIR/bin/fly-cpu-confine"
cc_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-confine.XXXXXX")"
mkdir -p "$cc_dir/bin" "$cc_dir/proc" "$cc_dir/cg/.lxc"
echo 0-15 > "$cc_dir/cg/.lxc/cpuset.cpus"
cat > "$cc_dir/bin/systemctl" <<'STUB'
#!/usr/bin/env bash
echo "systemctl $*" >> "$STUB_LOG"
if [ "$1" = show ]; then
unit="${*: -1}"
case "$*" in
*ControlGroup*) var="CG_${unit%.service}"; var="${var//-/_}"; echo "${!var:-}" ;;
esac
fi
exit 0
STUB
cat > "$cc_dir/bin/timeout" <<'STUB'
#!/usr/bin/env bash
shift; exec "$@"
STUB
chmod +x "$cc_dir/bin/systemctl" "$cc_dir/bin/timeout"
printf 'FLY_SIM_CPUS=1,3,5,7\nFLY_OTHER_CPUS=9,11,13-15\n' > "$cc_dir/cpuset.env"
cc_run() {
PATH="$cc_dir/bin:$PATH" CPUSET_ENV="${CPUSET_ENV:-$cc_dir/cpuset.env}" PROC_ROOT="$cc_dir/proc" CGROUP_ROOT="${CGROUP_ROOT:-$cc_dir/cg}" STUB_LOG="$cc_dir/log" "$@"
}
: > "$cc_dir/log"
out="$(cc_run "$cc" apply 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 0 ] && [ "$(grep -c 'set-property --runtime .* AllowedCPUs=9,11,13-15' "$cc_dir/log")" = 3 ] \
&& grep -q 'set-property --runtime system.slice' "$cc_dir/log" && grep -q 'set-property --runtime user.slice' "$cc_dir/log" \
&& grep -q 'set-property --runtime init.scope' "$cc_dir/log"; then
pass "fly-cpu-confine apply confines system.slice, user.slice and init.scope to the non-sim cpus"
else
fail "fly-cpu-confine apply (rc=$rc): $out / $(cat "$cc_dir/log")"
fi
[ "$(cat "$cc_dir/cg/.lxc/cpuset.cpus")" = "9,11,13-15" ] \
&& pass "fly-cpu-confine apply also confines /.lxc (where pct exec lands) to the non-sim cpus" \
|| fail "fly-cpu-confine apply must write the non-sim cpus into /.lxc/cpuset.cpus (got $(cat "$cc_dir/cg/.lxc/cpuset.cpus"))"
out="$(cc_run "$cc" status 2>&1)"
grep -q '^/.lxc cpuset.cpus=9,11,13-15$' <<< "$out" \
&& pass "fly-cpu-confine status shows /.lxc" \
|| fail "fly-cpu-confine status must show /.lxc: $out"
# unwritable /.lxc: warn, still exit 0, slices still confined; absent /.lxc: nothing created
: > "$cc_dir/log"
mkdir -p "$cc_dir/cg2/.lxc"
mkdir "$cc_dir/cg2/.lxc/cpuset.cpus" # a directory: the write fails, like a read-only cgroup file
out="$(CGROUP_ROOT="$cc_dir/cg2" cc_run "$cc" apply 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 0 ] && grep -q 'WARNING: cannot write' <<< "$out" && [ "$(grep -c set-property "$cc_dir/log")" = 3 ]; then
pass "fly-cpu-confine apply warns, never fails, when /.lxc cannot be written (slices still confined)"
else
fail "fly-cpu-confine apply with an unwritable /.lxc (rc=$rc): $out"
fi
mkdir -p "$cc_dir/cg3"
CGROUP_ROOT="$cc_dir/cg3" cc_run "$cc" apply >/dev/null 2>&1
[ -z "$(ls -A "$cc_dir/cg3")" ] \
&& pass "fly-cpu-confine apply does not create /.lxc (lxc owns it)" \
|| fail "fly-cpu-confine apply must not create cgroups under the root: $(ls -A "$cc_dir/cg3")"
: > "$cc_dir/log"
out="$(CG_flysim=/system.slice/flysim.service cc_run "$cc" apply 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 3 ] && ! grep -q set-property "$cc_dir/log"; then
pass "fly-cpu-confine apply refuses (exit 3, changes nothing) while flysim still runs outside flysim.slice"
else
fail "fly-cpu-confine apply must refuse a sim outside flysim.slice (rc=$rc): $out"
fi
: > "$cc_dir/log"
out="$(CG_flysim=/flysim.slice/flysim.service cc_run "$cc" apply 2>&1)" && rc=0 || rc=$?
[ "$rc" -eq 0 ] && grep -q set-property "$cc_dir/log" \
&& pass "fly-cpu-confine apply proceeds once flysim runs in flysim.slice" \
|| fail "fly-cpu-confine apply should proceed for a sim in flysim.slice (rc=$rc): $out"
: > "$cc_dir/log"
out="$(CPUSET_ENV="$cc_dir/none" cc_run "$cc" apply 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 0 ] && ! grep -q set-property "$cc_dir/log"; then
pass "fly-cpu-confine apply is a no-op without /etc/fly/cpuset.env (no partition, no confinement)"
else
fail "fly-cpu-confine apply without cpuset.env must change nothing (rc=$rc): $out $(cat "$cc_dir/log")"
fi
: > "$cc_dir/log"
echo 0-15 > "$cc_dir/cg/cpuset.cpus.effective"
CGROUP_ROOT="$cc_dir/cg" cc_run "$cc" release >/dev/null 2>&1
[ "$(grep -c 'set-property --runtime .* AllowedCPUs=0-15$' "$cc_dir/log")" = 3 ] \
&& [ "$(cat "$cc_dir/cg/.lxc/cpuset.cpus")" = "0-15" ] \
&& pass "fly-cpu-confine release sets all three and /.lxc back to the container's whole cpuset (an empty AllowedCPUs= leaves the old mask in place)" \
|| fail "fly-cpu-confine release: $(cat "$cc_dir/log") / lxc=$(cat "$cc_dir/cg/.lxc/cpuset.cpus")"
# check: a fake /proc with a sim process in the slice, a clean neighbour, a kernel thread, then a hog
mkproc() { # pid comm cgroup allowed
mkdir -p "$cc_dir/proc/$1"
printf 'Name:\t%s\nCpus_allowed_list:\t%s\n' "$2" "$4" > "$cc_dir/proc/$1/status"
echo "$2" > "$cc_dir/proc/$1/comm"
echo "0::$3" > "$cc_dir/proc/$1/cgroup"
ln -sfn /bin/true "$cc_dir/proc/$1/exe"
}
mkproc 10 flysim /flysim.slice/flysim.service 1,3,5,7
mkproc 11 ffmpeg /system.slice/fly-recap.service 9,11,13-15
mkproc 12 kthreadd /init.scope 0-15
rm -f "$cc_dir/proc/12/exe"
if cc_run "$cc" check >/dev/null 2>&1; then
pass "fly-cpu-confine check: clean when only flysim.slice can reach the sim's cpus (kernel threads ignored)"
else
fail "fly-cpu-confine check flagged a clean /proc: $(cc_run "$cc" check 2>&1)"
fi
mkproc 13 hog /system.slice/hog.service 0-15
out="$(cc_run "$cc" check 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 1 ] && grep -q 'process 13 (hog).*sim cpu 1,3,5,7' <<< "$out"; then
pass "fly-cpu-confine check names a process that may run on a sim cpu"
else
fail "fly-cpu-confine check must flag the hog (rc=$rc): $out"
fi
# the check's own process chain (a pct exec shell) is noted, not failed; a stranger in /.lxc still fails
rm -rf "$cc_dir/proc/13"
mkproc 20 pctexec /.lxc 0-15
mkproc 21 bash /.lxc 0-15
mkproc 22 fly-cpu-confine /.lxc 0-15
printf 'Name:\tx\nPPid:\t21\nCpus_allowed_list:\t0-15\n' > "$cc_dir/proc/22/status"
printf 'Name:\tx\nPPid:\t20\nCpus_allowed_list:\t0-15\n' > "$cc_dir/proc/21/status"
printf 'Name:\tx\nPPid:\t1\nCpus_allowed_list:\t0-15\n' > "$cc_dir/proc/20/status"
out="$(SELF_PID=22 cc_run "$cc" check 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 0 ] && grep -q 'own process chain' <<< "$out" && ! grep -q '^process' <<< "$out"; then
pass "fly-cpu-confine check exits 0 when the only process on a sim cpu is its own pct exec chain"
else
fail "fly-cpu-confine check must not count its own process or ancestors (rc=$rc): $out"
fi
mkproc 23 tar /.lxc 0-15
out="$(SELF_PID=22 cc_run "$cc" check 2>&1)" && rc=0 || rc=$?
if [ "$rc" -eq 1 ] && grep -q '^process 23 (tar)' <<< "$out" && ! grep -q '^process 2[012] ' <<< "$out"; then
pass "fly-cpu-confine check still flags a different process in /.lxc"
else
fail "fly-cpu-confine check must flag a stranger in /.lxc (rc=$rc): $out"
fi
rm -rf "$cc_dir"
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 3d. bin/fly-watchdog check 7 (process age guard) — flypush uptime above # 3d. bin/fly-watchdog check 7 (process age guard) — flypush uptime above
# 24h forces a restart and records fly_watchdog_restarts_total{unit= # 24h forces a restart and records fly_watchdog_restarts_total{unit=

View file

@ -13,3 +13,7 @@ ExecStart=/opt/fly/bin/fly-recap
Nice=19 Nice=19
IOSchedulingClass=idle IOSchedulingClass=idle
CPUWeight=20 CPUWeight=20
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
CPUSchedulingPolicy=idle

View file

@ -11,3 +11,7 @@ Environment=FLY_MEDIA_DIR=/srv/fly/media
ExecStart=/opt/fly/bin/fly-retention ExecStart=/opt/fly/bin/fly-retention
Nice=15 Nice=15
IOSchedulingClass=idle IOSchedulingClass=idle
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
CPUSchedulingPolicy=idle

View file

@ -51,6 +51,16 @@ Restart=always
RestartSec=2 RestartSec=2
Nice=-5 Nice=-5
CPUWeight=400 CPUWeight=400
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
Slice=flysim.slice
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
MemoryMax=4G MemoryMax=4G
# No [Install] section, deliberately: `systemctl enable flysim-session.service` has nothing to # No [Install] section, deliberately: `systemctl enable flysim-session.service` has nothing to
# do, so it can never be pulled in beside flysim.service by fly.target. # do, so it can never be pulled in beside flysim.service by fly.target.

View file

@ -79,6 +79,16 @@ RestartSec=2
# bandwidth-bound sweep that is fighting its own SMT siblings. # bandwidth-bound sweep that is fighting its own SMT siblings.
Nice=-5 Nice=-5
CPUWeight=400 CPUWeight=400
# The sim's CPUs are the sim's alone (PERF-02 review N1). The session runtime pins its sweep
# workers one per CPU, and a pinned worker cannot leave a CPU that something else is hogging:
# measured 0.14x real time. So flysim runs in its own slice, flysim.slice, whose AllowedCPUs=
# 05-deploy.sh writes (the same set as this unit's cpuset drop-in), and `fly-cpu-confine apply`
# confines its siblings under the root cgroup (system.slice, user.slice, init.scope) to the other
# CPUs. It must NOT sit under a slice that excludes its CPUs: a child's cpuset is bounded by its
# parent's. The ExecStartPre refuses to confine anything while a sim unit is still outside the
# slice, and a failure of it never blocks the start (the `-`); `+` runs it as root.
Slice=flysim.slice
ExecStartPre=-+/opt/fly/bin/fly-cpu-confine apply
# The encoder, the browser and the sim must not share physical cores. # The encoder, the browser and the sim must not share physical cores.
# AllowedCPUs is per-host and per-container (PVE picks the container's # AllowedCPUs is per-host and per-container (PVE picks the container's
# cpuset at `pct create` time and it is NOT a set of whole cores — on this # cpuset at `pct create` time and it is NOT a set of whole cores — on this

11
infra/units/flysim.slice Normal file
View file

@ -0,0 +1,11 @@
# infra/units/flysim.slice — the sim's own slice (PERF-02 review N1).
# Named without a dash on purpose: systemd nests a slice named a-b.slice under a.slice, and a child's
# cpuset is bounded by its parent's; flysim.slice sits directly under the root slice, beside system.slice.
# flysim.service and flysim-session.service run here. 05-deploy.sh writes the drop-in
# flysim.slice.d/cpuset.conf (AllowedCPUs= the sim's CPUs) when the container has a cpuset
# partition; bin/fly-cpu-confine keeps every other slice off those CPUs. Nothing else belongs in
# this slice.
[Unit]
Description=The live sim (its CPUs are exclusive to it)
[Slice]

View file

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

View file

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

View file

@ -1159,6 +1159,7 @@ impl LegacyAgentWorker {
// the two brains carry the same instrumentation (PERF-01). // the two brains carry the same instrumentation (PERF-01).
agent.network.profile = crate::profile::enabled(); agent.network.profile = crate::profile::enabled();
let phase_before = agent.network.timings().total_ns(); let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.ticks"); let ticks_span = crate::profile::span("agent.ticks");
// One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped // One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped
// are its spike list, so the transition's bitset is their union. // are its spike list, so the transition's bitset is their union.
@ -1181,6 +1182,26 @@ impl LegacyAgentWorker {
"agent.ticks.phase_clock", "agent.ticks.phase_clock",
std::time::Duration::from_nanos(agent.network.timings().total_ns() - phase_before), std::time::Duration::from_nanos(agent.network.timings().total_ns() - phase_before),
); );
if crate::profile::enabled() {
let now = agent.network.timings();
for (name, after, before) in [
("agent.ticks.drive", now.drive_ns, phases_before.drive_ns),
("agent.ticks.sweep", now.sweep_ns, phases_before.sweep_ns),
(
"agent.ticks.observe",
now.observe_ns,
phases_before.observe_ns,
),
(
"agent.ticks.propagate",
now.propagate_ns,
phases_before.propagate_ns,
),
("agent.ticks.rates", now.rates_ns, phases_before.rates_ns),
] {
crate::profile::record(name, std::time::Duration::from_nanos(after - before));
}
}
if agent.network.ms != brain_ticks as f64 { if agent.network.ms != brain_ticks as f64 {
return Err(applied( return Err(applied(
ErrorCode::Internal, ErrorCode::Internal,

View file

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

View file

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

View file

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