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.
This commit is contained in:
acamilo 2026-10-01 15:01:47 +00:00
parent 8fa98b0b03
commit ab537d1045
13 changed files with 515 additions and 36 deletions

View file

@ -488,7 +488,7 @@ sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loo
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. The legacy loop and process mode are
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

View file

@ -448,7 +448,7 @@ the CPU a thread runs on, never what an index of a parallel phase computes.
`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 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.

View file

@ -182,12 +182,16 @@ NEED_RELOAD=0
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
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
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(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"
else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -428,7 +432,7 @@ fi
# 2. 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
name="$(basename "$f")"
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
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
# 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}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# 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" \
"leaves cpuset.cpus.effective empty and the unit unstartable."
else
read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$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"
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
tmp_dropin="$(mktemp)"
# 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.
@ -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
# 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.
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge flysim-session flyshadow; do
case "$u" in
flysim|flysim-session) cpus="$sim_cpus" ;;
flycast) cpus="$encoder_cpus" ;;
flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;
*) cpus="$page_cpus" ;;
esac
{
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[Service]"
echo "AllowedCPUs=${cpus}"
} > "$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)"
# flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
# its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
# using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
# everything else. See that script's header for the cgroup semantics and the ordering rule.
# A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
mapfile -t plan_lines <<< "$plan"
for plan_line in "${plan_lines[@]}"; do
read -r u cpus <<< "$plan_line"
case "$u" in *=) continue ;; esac
cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then
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
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"
fi
else
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
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
@ -745,7 +770,7 @@ fi
# ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /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
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.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` and `init.scope` 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
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

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

@ -0,0 +1,147 @@
#!/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 and init.scope to the non-sim CPUs
# fly-cpu-confine release undo `apply` (those three 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)
#
# 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.
#
# Not reachable from here: a process the host starts into the container with `pct exec`
# (lxc-attach). Check where it lands with `check`; 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"
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
log "system.slice, user.slice and init.scope 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
log "system.slice, user.slice and init.scope 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 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
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
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,12p' "$0" >&2
exit 2
;;
esac

View file

@ -850,6 +850,56 @@ not a constant, and live in the operator's infra repo
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.
### 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`. 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.)
- **Not reachable from inside:** a process the host starts into the container with `pct exec`
(`lxc-attach`) is not placed by systemd, so these two slices may not cover it (which cgroup it
lands in has not been verified on the release container). `fly-cpu-confine check` lists every
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one): run it after
a deploy and after anything unusual. Run long operator jobs through
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`; the deploy itself
already pins its heavy steps to the page CPUs.
- **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
the three 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.
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=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"
}
# 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
# ---------------------------------------------------------------------------

View file

@ -147,7 +147,7 @@ check_exec_path() {
# stripping a leading '-' (systemd's "failure is ok" marker) and any
# /bin/sh -c '...' wrapper (checked as a shell built-in, always ok).
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
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" \
&& 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\""
if grep -qF 'flyshadow) cpus="${page_cpus},${encoder_cpus}" ;;' "$INFRA_DIR/05-deploy.sh"; then
pass "05-deploy.sh keeps flyshadow.service off flysim's CPUs"
else
fail "05-deploy.sh must give flyshadow.service the page and encoder CPUs, never flysim's"
fi
grep -qF 'echo "flyshadow.service ${page},${enc}"' "$INFRA_DIR/lib/common.sh" \
&& pass "cpuset_dropin_plan keeps flyshadow.service off flysim's CPUs (page + encoder; checked disjoint in section 3c2)" \
|| fail "cpuset_dropin_plan must give flyshadow.service the page and encoder CPUs, never flysim's"
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
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
fail "feed_via_normalize: got '$fv_out'"
fi
if grep -qE '^[[:space:]]*for u in flysim .*\bflyedge\b.*; do$' "$INFRA_DIR/05-deploy.sh"; then
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
# (the cpuset drop-ins for flyedge.service and flysim-session.service are checked from the plan, section 3c2)
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"
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" \
&& pass "05-deploy.sh installs fly-runtime" \
|| 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 '"${release_path}/flysim-session"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without flysim-session while the session runtime runs" \
@ -1479,6 +1470,189 @@ 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"
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"
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" 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
: > "$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/cpuset.cpus.effective"
CGROUP_ROOT="$cc_dir" cc_run "$cc" release >/dev/null 2>&1
[ "$(grep -c 'set-property --runtime .* AllowedCPUs=0-15$' "$cc_dir/log")" = 3 ] \
&& pass "fly-cpu-confine release sets all three 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")"
# 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
rm -rf "$cc_dir"
# ---------------------------------------------------------------------------
# 3d. bin/fly-watchdog check 7 (process age guard) — flypush uptime above
# 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
IOSchedulingClass=idle
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
Nice=15
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
Nice=-5
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
# 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.

View file

@ -79,6 +79,16 @@ RestartSec=2
# bandwidth-bound sweep that is fighting its own SMT siblings.
Nice=-5
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.
# 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

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]