EDGE-02 notes: bus threads on an aux cpu (FLY_SESSION_AUX_CPUS, SESSION_AUX_CPUS in the deploy), fly-feed direct never rolled back, watchdog falls back to direct at the 4th failure and never reboots for the edge; runbook cost corrected

This commit is contained in:
acamilo 2026-10-02 04:22:39 +00:00
parent d5b576a2c1
commit eaae6fd82a
12 changed files with 345 additions and 31 deletions

View file

@ -201,8 +201,11 @@ Accepted for now and written down rather than fixed:
common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then
stops the binary and starts a new one under the same edge, which must unbind, reconnect and stops the binary and starts a new one under the same edge, which must unbind, reconnect and
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
host mask of `place_workers` (PERF-02), so they run on the host CPU with the listeners, never on host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
a pinned sweep CPU. never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review
N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the
sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts
one page CPU into `flysim.slice` for it).
- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an - **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an
`ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`; `ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`;
`flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and `flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and
@ -210,8 +213,8 @@ Accepted for now and written down rather than fixed:
mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim
all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct` all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct`
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
page on the feed (frames moving), and rolls itself back (to `direct`) when that does not happen page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
or when it is interrupted. It works on either runtime and survives `fly-runtime` changes. or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes.
- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off - **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off
the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle
header, so silence means a wedged subscription, which `Subscription::next` alone would never header, so silence means a wedged subscription, which `Subscription::next` alone would never
@ -219,7 +222,7 @@ Accepted for now and written down rather than fixed:
- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote - **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote
fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while
flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth
switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line). switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots.
Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to
connect to. connect to.
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the - **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the

View file

@ -197,6 +197,11 @@ 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}"
# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the
# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing.
SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}"
case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac
SESSION_AUX_LIST=""
DEPLOY_CPUS="" DEPLOY_CPUS=""
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to # 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. # flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
@ -208,6 +213,10 @@ if [ -n "${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 PARTITION_ACTIVE=1
if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then
_aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1
read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split"
fi
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" \
@ -606,6 +615,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
else else
echo "FLY_SESSION_PIN=0" echo "FLY_SESSION_PIN=0"
fi fi
# EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set.
if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then
echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}"
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
@ -614,7 +627,7 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# never enables: see that unit's header for the switch. Written # never enables: see that unit's header for the switch. Written
# unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs. # unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs.
# Watchdog check 2 reads this line to know whose /metrics carries the # Watchdog check 2 reads this line to know whose /metrics carries the
# feed counters (flysim's :9101, or flyedge's loopback :9102). # feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
# Validated and lowercased above (feed_via_normalize). # Validated and lowercased above (feed_via_normalize).
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}" echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over # Who serves the control API on :7401 (docs/design/flybus.md, "Control over
@ -758,7 +771,7 @@ 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
plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")"
log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')" 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

View file

@ -24,7 +24,10 @@
# (a box that only serves the feed) the wait ends at 2. # (a box that only serves the feed) the wait ends at 2.
# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks # If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it # the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
# only reports. A switch that is interrupted (ssh drops, INT/TERM/HUP) rolls back the same way. # only reports. `direct` is the safe terminal state: once the line says direct nothing, an
# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted
# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus`
# rolls back the same way as a failed one.
# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts # `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts
# flysim without blocking and does not wait for health or roll anything back: it is what the # flysim without blocking and does not wait for health or roll anything back: it is what the
# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up. # watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up.
@ -253,6 +256,9 @@ fi
# way back is direct: the state that worked. # way back is direct: the state that worked.
back="$before" back="$before"
if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi
# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never
# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it).
if [ "$command" = direct ]; then back=direct; fi
switching=0 switching=0
restarted=0 restarted=0
# shellcheck disable=SC2317 # runs from the EXIT trap # shellcheck disable=SC2317 # runs from the EXIT trap
@ -262,7 +268,11 @@ on_exit() {
if [ "$switching" -eq 1 ]; then if [ "$switching" -eq 1 ]; then
switching=0 switching=0
set_via "$back" || true set_via "$back" || true
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)" if [ "$command" = direct ]; then
record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)"
else
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)"
fi
if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi
fi fi
exit "$rc" exit "$rc"

View file

@ -454,7 +454,12 @@ check_flyedge() {
record_fail flyedge record_fail flyedge
local n local n
n="$(fail_count flyedge)" n="$(fail_count flyedge)"
if [ "$n" -ge 4 ] && fails_within_minutes flyedge 15; then # From the 4th consecutive failure on, whatever the time the failures were spread over (passes
# are skipped while flysim is down, so a flapping flysim stretches the run past any window): the
# fallback to direct comes first and a reboot is never the answer to an edge fault. Only
# n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on
# the next pass instead of falling through to it.
if [ "$n" -ge 4 ]; then
log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)" log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)"
inc_counter "escalations_total" inc_counter "escalations_total"
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down" sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"

View file

@ -596,8 +596,9 @@ waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s)
`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with `flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with
`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA` `fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA`
back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback` back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback`
leaves the failed switch in place for the operator; an interrupted switch, ssh dropped or INT, TERM leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM
or HUP, rolls back too). Every switch is in the journal (`journalctl -t fly-feed`) and or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted
`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and
`/var/lib/fly/feed.log`. `/var/lib/fly/feed.log`.
### What to watch ### What to watch
@ -607,7 +608,7 @@ or HUP, rolls back too). Every switch is in the journal (`journalctl -t fly-feed
| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` | | `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` |
| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) | | edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) |
| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` | | flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` |
| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is one 6% thread on the host CPU, and the websocket writes it replaces were on that CPU in direct mode | a drop that persists for the hour: switch back (`fly-feed direct`) and compare | | `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare |
| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy | | `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy |
| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back | | `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back |
| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` | | `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` |
@ -651,7 +652,7 @@ not move much. The live switch is the real A/B: take the step 1 baseline and com
| --- | --- | --- | | --- | --- | --- |
| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs | | WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs |
| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) | | Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) |
| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher, on the host CPU, about 7% of a CPU at 30 Hz) and 1.1 ms in the edge (page CPUs) | | CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) |
| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs | | Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs |
| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run | | Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run |
| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both | | Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both |
@ -677,8 +678,15 @@ restore and warm-up; use the unstick rule's usual time.
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
counters. counters.
- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and - **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and
the publisher run inside flysim, on its `flysim-bus` runtime (two threads on the host CPU, with the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking
the listeners, not on a pinned sweep CPU). pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the
operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as
`FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to
the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about
1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the
critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof
flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the
deploy, restart flysim, and only then `fly-feed bus`.
- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A - **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A
reboot empties it; a crashed flysim's directory is removed by the next one. reboot empties it; a crashed flysim's directory is removed by the next one.
- **Control (`:7401`)** stays in flysim and is not part of this switch. - **Control (`:7401`)** stays in flysim and is not part of this switch.

View file

@ -138,6 +138,12 @@ RAYON_THREADS=3
# cpuset_partition (default 2 when unset). flycast gets its own group rather # cpuset_partition (default 2 when unset). flycast gets its own group rather
# than sharing the page group — see lib/common.sh's cpuset_partition header. # than sharing the page group — see lib/common.sh's cpuset_partition header.
ENCODER_CORES=2 ENCODER_CORES=2
# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in
# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when
# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the
# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs
# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`.
SESSION_AUX_CPUS=0
# --- CUDA LIF backend ------------------------------------------------------- # --- CUDA LIF backend -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what # 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what

View file

@ -202,31 +202,56 @@ 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 # cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's
# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's
# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu.
cpuset_aux_split() {
local page="$1" count="$2" n
n="$(echo "$page" | awk -F, '{print NF}')"
if [ "$count" -ge "$n" ]; then
die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS."
fi
echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)"
}
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service, # 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), 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.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the
# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it);
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the # flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
# slice is still bounded); # slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs; # xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
# flycast the encoder CPUs; # flycast the encoder CPUs;
# flyshadow page + encoder (never the sim's); # flyshadow page + encoder (never the sim's);
# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS);
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU # 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. # 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 # One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
# cpuset_partition does. # cpuset_partition does.
cpuset_dropin_plan() { cpuset_dropin_plan() {
local cpuset="$1" rayon="$2" encoder="${3:-2}" sim page enc u local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
read -r sim page enc <<< "$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1 local out
echo "flysim.slice $sim" out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
for u in flysim flysim-session; do echo "${u}.service $sim"; done read -r sim page enc <<< "$out"
if [ "$aux_count" -gt 0 ]; then
# not `read <<< "$(...)"`: die inside the substitution would only end the subshell
out="$(cpuset_aux_split "$page" "$aux_count")" || return 1
read -r page aux <<< "$out"
fi
slice_cpus="$sim"
[ -n "$aux" ] && slice_cpus="${sim},${aux}"
echo "flysim.slice $slice_cpus"
for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
echo "flycast.service $enc" echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}" echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $sim" echo "FLY_SIM_CPUS= $slice_cpus"
echo "FLY_OTHER_CPUS= ${page},${enc}" echo "FLY_OTHER_CPUS= ${page},${enc}"
[ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux"
return 0
} }
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to # cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to

View file

@ -1836,6 +1836,26 @@ if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && grep -q 'interrupted or failed' "
else else
fail "an interrupted fly-feed bus must roll back ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))" fail "an interrupted fly-feed bus must roll back ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))"
fi fi
# N2 (EDGE-02 notes): an interrupted `fly-feed direct` is never rolled back to bus: direct is the
# safe terminal state, and flysim is restarted so the running process matches the line.
ff_reset bus bus
env FF_DIR="$ff_dir" FF_ENV="$ff_env" PATH="$ff_dir/bin:$PATH" FLY_ENV_FILE="$ff_env" \
FLY_RELEASE_DIR="$ff_dir/release" FLY_PROC_DIR="$ff_dir/proc" FLY_FEED_LOG="$ff_dir/feed.log" \
FLY_FEED_LOCK="$ff_dir/run/feed.lock" FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim \
FLY_EDGE_METRICS_URL=http://edge FLY_FEED_HEALTH_TIMEOUT=30 FLY_FEED_SAMPLE_SECONDS=0 FF_CONTROL_OK=0 \
bash "$INFRA_DIR/bin/fly-feed" direct >/dev/null 2>&1 &
ff_pid=$!
sleep 2
kill -TERM "$ff_pid" 2>/dev/null || true
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$ff_pid" 2>/dev/null || break; sleep 0.5; done
(kill -0 "$ff_pid" 2>/dev/null && kill -KILL "$ff_pid" 2>/dev/null) || true
wait "$ff_pid" 2>/dev/null || true
if grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && ! grep -q 'FLY_FEED_VIA=bus' "$ff_env" \
&& grep -q 'kept: direct is the safe state' "$ff_dir/feed.log" 2>/dev/null && [ "$(ff_restarts)" -ge 2 ]; then
pass "fly-feed direct interrupted mid-switch stays on direct (never back to bus), flysim restarted to match"
else
fail "an interrupted fly-feed direct must end on direct ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null | tr '\n' ';'))"
fi
rm -rf "$ff_dir" rm -rf "$ff_dir"
echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---" echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---"
@ -1912,6 +1932,21 @@ case "$(wd_acts)" in
*"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: the fourth failed pass puts the feed back on flysim (fly-feed direct --no-wait)" ;; *"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: the fourth failed pass puts the feed back on flysim (fly-feed direct --no-wait)" ;;
*) fail "check 2a fourth failure must run fly-feed direct --no-wait: $(wd_acts)" ;; *) fail "check 2a fourth failure must run fly-feed direct --no-wait: $(wd_acts)" ;;
esac esac
# N3 (EDGE-02 notes): failures spread over more than 15 minutes (passes are skipped while flysim is
# down) still fall back to direct from the 4th, and a long run of edge failures never reboots.
wd_reset; WD_CMDS='f="$(fails_file flyedge)"; for i in 1 2 3 4 5 6; do echo $(( $(now) - 7200 + i )) >> "$f"; done; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"sudo /opt/fly/bin/fly-feed direct --no-wait;") pass "check 2a: failures older than 15 minutes still fall back to direct, with no restart chain and no reboot" ;;
*) fail "check 2a with a stretched failure run must run fly-feed direct only: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
if ! grep -q reboot "$wf_dir/actions.log" 2>/dev/null && [ ! -e "$wf_dir/state/last-reboot" ]; then
pass "check 2a: eight failed passes (fly-feed direct unable to fix it) never reboot the container"
else
fail "an edge fault must never reboot: $(wd_acts)"
fi
wd_reset; WD_CMDS='check_flyedge; check_flyedge' wd_reset; WD_CMDS='check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0 wd_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0
case "$(wd_acts)" in case "$(wd_acts)" in
@ -2032,8 +2067,8 @@ set -euo pipefail
PLANEOF PLANEOF
chmod +x "$plan_bin" chmod +x "$plan_bin"
check_plan() { check_plan() {
local label="$1" cpuset="$2" rayon="$3" encoder="$4" plan sim other u cpus bad="" local label="$1" cpuset="$2" rayon="$3" encoder="$4" aux="${5:-0}" 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; } plan="$("$plan_bin" cpuset_dropin_plan "$cpuset" "$rayon" "$encoder" "$aux" 2>&1)" || { fail "cpuset_dropin_plan: $label: died: $plan"; return 0; }
sim="$(awk '$1 == "flysim.slice" {print $2}' <<< "$plan")" sim="$(awk '$1 == "flysim.slice" {print $2}' <<< "$plan")"
other="$(awk '$1 == "FLY_OTHER_CPUS=" {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" [ "$sim" = "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$plan")" ] || bad="$bad SIM-list-differs-from-slice"
@ -2042,7 +2077,7 @@ check_plan() {
done done
# every other unit, and the confinement list, is disjoint from the sim's cpus # every other unit, and the confinement list, is disjoint from the sim's cpus
while read -r u cpus; do while read -r u cpus; do
case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=) continue ;; esac case "$u" in flysim.slice|flysim.service|flysim-session.service|FLY_SIM_CPUS=|FLY_AUX_CPUS=) continue ;; esac
if [ -n "$(comm -12 <(tr ',' '\n' <<< "$sim" | sort) <(tr ',' '\n' <<< "$cpus" | sort))" ]; then if [ -n "$(comm -12 <(tr ',' '\n' <<< "$sim" | sort) <(tr ',' '\n' <<< "$cpus" | sort))" ]; then
bad="$bad $u-overlaps-sim" bad="$bad $u-overlaps-sim"
fi fi
@ -2060,6 +2095,29 @@ check_plan() {
} }
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 "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 "ten cpus, ENCODER_CORES=3" "1,3,5,7,9,11,13,15,17,19" 4 3
check_plan "release shape with one aux cpu (EDGE-02 N1)" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1
check_plan "release shape with two aux cpus" "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2
# The aux cpu is the last page cpu, is in flysim.slice, is in FLY_SIM_CPUS (so fly-cpu-confine keeps every
# other process off it), is named in FLY_AUX_CPUS and is in no page or encoder unit.
aux_plan="$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 1 2>&1)"
if [ "$(awk '$1 == "flysim.slice" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \
&& [ "$(awk '$1 == "FLY_SIM_CPUS=" {print $2}' <<< "$aux_plan")" = "1,3,5,7,35" ] \
&& [ "$(awk '$1 == "FLY_AUX_CPUS=" {print $2}' <<< "$aux_plan")" = "35" ] \
&& [ "$(awk '$1 == "xvfb.service" {print $2}' <<< "$aux_plan")" = "9,11,13,15,29,31,33" ] \
&& ! grep -q "FLY_AUX_CPUS=" <<< "$("$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,29,31,33,35,17,19,37,39" 4 4 2>&1)"; then
pass "cpuset_dropin_plan: the aux cpu (35) is flysim.slice's, in FLY_SIM_CPUS, off every page unit; none without SESSION_AUX_CPUS"
else
fail "cpuset_dropin_plan: aux cpu wiring wrong: $aux_plan"
fi
if "$plan_bin" cpuset_dropin_plan "1,3,5,7,9,11,13,15,17,19" 4 3 3 >/dev/null 2>&1; then
fail "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu must be refused"
else
pass "cpuset_dropin_plan: SESSION_AUX_CPUS that leaves no page cpu is refused"
fi
grep -q 'FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}' "$INFRA_DIR/05-deploy.sh" \
&& grep -q 'SESSION_AUX_EFFECTIVE")"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh writes FLY_SESSION_AUX_CPUS and passes the aux count to the plan" \
|| fail "05-deploy.sh must write FLY_SESSION_AUX_CPUS and pass SESSION_AUX_EFFECTIVE to cpuset_dropin_plan"
check_plan "eight cpus, default encoder" "1,3,5,7,9,11,13,15" 4 "" 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 "" 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= # the generated drop-ins: a slice gets [Slice], a service [Service], both AllowedCPUs=

View file

@ -83,9 +83,13 @@ pub const SESSION_PROFILE_ENV: &str = "FLY_SESSION_PROFILE";
/// `0` keeps every thread floating over the cpuset; anything else, or unset, places them /// `0` keeps every thread floating over the cpuset; anything else, or unset, places them
/// ([`place_threads`]). /// ([`place_threads`]).
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN"; pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
/// Process mode: a CPU list for the service process (router, coordinator, listeners, checkpoint /// A CPU list for the threads that are not the sim, instead of the sweep's host CPU. It must lie
/// writer) and the environment process, instead of the sweep's host CPU (BUS-01). It must lie in /// in the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs, where 05-deploy.sh adds
/// the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs). /// it with `SESSION_AUX_CPUS`) and is exclusive to those threads. Process mode (BUS-01): the
/// service process (router, coordinator, listeners, checkpoint writer) and the environment
/// process. In-process and thread modes (EDGE-02): the `flysim-bus` runtime, i.e. the feed
/// publisher, the router and the control services; the sweep workers, the dispatcher and every
/// other thread are placed on the rest.
pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS"; pub const SESSION_AUX_CPUS_ENV: &str = "FLY_SESSION_AUX_CPUS";
/// How the service composes its session, beyond flysim's own [`Config`]. /// How the service composes its session, beyond flysim's own [`Config`].
@ -348,8 +352,29 @@ fn place_threads(config: &Config, options: &mut ServiceOptions) {
); );
return; return;
} }
if std::env::var_os(SESSION_AUX_CPUS_ENV).is_some() { // In-process and thread modes: FLY_SESSION_AUX_CPUS names cpus of the unit's cpuset that are
tracing::warn!("{SESSION_AUX_CPUS_ENV} is for process mode; ignored"); // not the sim's. The sweep and the dispatcher are placed on the rest, and the bus runtime
// (feed publisher, router, control services) on these (EDGE-02 review N1).
if let Some(value) = std::env::var(SESSION_AUX_CPUS_ENV).ok().filter(|v| !v.is_empty()) {
match flybrain_core::pool::parse_cpu_list(&value) {
None => tracing::warn!("{SESSION_AUX_CPUS_ENV}={value:?} is not a cpu list; ignored"),
Some(aux) => match flybrain_core::pool::place_workers_aux(workers, &aux) {
Some((placement, aux)) => {
tracing::info!(
sweep_workers = ?placement.workers,
host = ?placement.host,
bus_aux = ?aux,
"sweep workers pinned one per cpu; the bus runtime on the aux cpus, every \
other thread on the host cpus"
);
return;
}
None => tracing::warn!(
"{SESSION_AUX_CPUS_ENV}={value:?} is not inside the cpuset, or leaves fewer \
cpus than sweep threads; ignored (the bus runtime shares the host cpus)"
),
},
}
} }
match flybrain_core::pool::place_workers(workers) { match flybrain_core::pool::place_workers(workers) {
Some(placement) => tracing::info!( Some(placement) => tracing::info!(

View file

@ -121,6 +121,11 @@ struct Service {
impl Service { impl Service {
fn start(config: Config, work: &Path, name: &str) -> Service { fn start(config: Config, work: &Path, name: &str) -> Service {
Service::start_env(config, work, name, &[])
}
/// [`Service::start`] with extra environment, which wins over the test's defaults.
fn start_env(config: Config, work: &Path, name: &str, envs: &[(&str, &str)]) -> Service {
let path = work.join(format!("{name}.toml")); let path = work.join(format!("{name}.toml"));
std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap(); std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap();
let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap(); let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap();
@ -136,6 +141,7 @@ impl Service {
.env_remove("FLY_FEED_BIND") .env_remove("FLY_FEED_BIND")
.env_remove("FLY_CONTROL_BIND") .env_remove("FLY_CONTROL_BIND")
.env_remove("FLY_METRICS_ADDR") .env_remove("FLY_METRICS_ADDR")
.envs(envs.iter().copied())
.stdout(Stdio::null()) .stdout(Stdio::null())
.stderr(log) .stderr(log)
.spawn() .spawn()
@ -400,3 +406,75 @@ fn the_session_runtime_serves_the_same_feed_over_the_bus() {
); );
assert!(compared >= FRAMES / 2, "only {compared} frames in common"); assert!(compared >= FRAMES / 2, "only {compared} frames in common");
} }
/// The cpus a `/proc/.../status` says a thread may run on.
fn allowed_cpus(status: &Path) -> Vec<usize> {
let text = std::fs::read_to_string(status).unwrap_or_default();
let line = text
.lines()
.find_map(|l| l.strip_prefix("Cpus_allowed_list:"))
.unwrap_or("")
.trim()
.to_owned();
flybrain_core::pool::parse_cpu_list(&line).unwrap_or_default()
}
/// EDGE-02 review N1: with `FLY_SESSION_AUX_CPUS` the feed publisher's runtime (`flysim-bus`, its
/// blocking pool included) runs on the aux cpu alone, and no other thread of the service may.
/// Needs a toy store and three cpus (two sweep workers and one aux); no ROM.
#[test]
fn the_bus_threads_run_on_the_aux_cpu_and_nothing_else_does() {
let allowed = allowed_cpus(Path::new("/proc/self/status"));
if allowed.len() < 3 {
eprintln!("skipping: needs three cpus, have {allowed:?}");
return;
}
let Some(rom) = rom_path() else { return };
let aux = *allowed.last().unwrap();
let dataset = fly_session::legacy_parity::toy::dir();
let root = tempfile::tempdir().unwrap();
let seeded = root.path().join("seeded");
std::fs::create_dir_all(&seeded).unwrap();
seed_by_legacy_fresh_start(&rom, &dataset, &seeded);
let dir = fresh_dir(root.path(), &seeded, "aux");
let mut config = config(&rom, &dataset, &dir, FeedVia::Bus, &root.path().join("aux-bus"));
config.loop_.threads = 2;
let aux_text = aux.to_string();
let service = Service::start_env(
config,
root.path(),
"aux",
&[("FLY_SESSION_PIN", "1"), ("FLY_SESSION_AUX_CPUS", &aux_text)],
);
let task_dir = PathBuf::from(format!("/proc/{}/task", service.child.id()));
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let mut bus = 0;
let mut others = Vec::new();
for task in std::fs::read_dir(&task_dir).into_iter().flatten().flatten() {
let comm = std::fs::read_to_string(task.path().join("comm"))
.unwrap_or_default()
.trim()
.to_owned();
let cpus = allowed_cpus(&task.path().join("status"));
if comm == "flysim-bus" {
bus += 1;
assert_eq!(cpus, vec![aux], "a flysim-bus thread is on {cpus:?}, not on {aux}");
} else {
others.push((comm, cpus));
}
}
if bus >= 2 && others.len() >= 3 {
for (comm, cpus) in &others {
assert!(!cpus.contains(&aux), "thread {comm} may run on the aux cpu {aux}: {cpus:?}");
}
return;
}
assert!(
Instant::now() < deadline,
"never saw the bus threads: {bus} bus, {} others",
others.len()
);
std::thread::sleep(Duration::from_millis(200));
}
}

View file

@ -33,6 +33,9 @@ type Job = dyn Fn(usize) + Sync;
/// (`1..workers`) runs on `WORKER_CPUS[i - 1]`. Unset -- the default, and always for the legacy /// (`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. /// loop -- the workers float over the process's CPUs as they always have.
static WORKER_CPUS: OnceLock<Vec<usize>> = OnceLock::new(); static WORKER_CPUS: OnceLock<Vec<usize>> = OnceLock::new();
/// The CPUs of the process's auxiliary threads (the bus runtime), when [`place_workers_aux`]
/// reserved some outside the sim's set.
static AUX_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.
@ -296,6 +299,56 @@ pub fn place_workers(workers: usize) -> Option<Placement> {
Some(placement) Some(placement)
} }
/// Splits `allowed` like [`split_cpus`], after taking `aux` out of it: `aux` must be a non-empty
/// subset of `allowed` and leave at least `workers` CPUs for the sim. Returns the sim's placement
/// (sweep workers, dispatcher and host, never an `aux` CPU) and the aux list. `None` otherwise.
pub fn split_cpus_aux(
allowed: &[usize],
workers: usize,
aux: &[usize],
) -> Option<(Placement, Vec<usize>)> {
let mut aux = aux.to_vec();
aux.sort_unstable();
aux.dedup();
if aux.is_empty() || aux.iter().any(|c| !allowed.contains(c)) {
return None;
}
let rest: Vec<usize> = allowed.iter().copied().filter(|c| !aux.contains(c)).collect();
Some((split_cpus(&rest, workers)?, aux))
}
/// [`place_workers`] with `aux` CPUs reserved for the process's auxiliary threads (the feed
/// publisher and the bus runtime): the sweep workers, the dispatcher and every ordinary thread
/// stay off them, and [`confine_to_aux`] (the bus runtime's `on_thread_start`) puts a thread on
/// them. `None`, and nothing changed, when `aux` is not a subset of the allowed CPUs, leaves too
/// few for the sim, or a placement was already made. Placement decides only the CPU.
pub fn place_workers_aux(workers: usize, aux: &[usize]) -> Option<(Placement, Vec<usize>)> {
if WORKER_CPUS.get().is_some() {
return None;
}
let (placement, aux) = split_cpus_aux(&affinity::allowed()?, workers, aux)?;
if !affinity::set_current(&placement.host) {
return None;
}
WORKER_CPUS.set(placement.workers.clone()).ok()?;
let _ = AUX_CPUS.set(aux.clone());
Some((placement, aux))
}
/// Confines the calling thread to the aux CPUs [`place_workers_aux`] reserved. A no-op (false)
/// when none were: the thread keeps what it inherited.
pub fn confine_to_aux() -> bool {
match AUX_CPUS.get() {
Some(aux) => affinity::set_current(aux),
None => false,
}
}
/// The aux CPUs reserved by [`place_workers_aux`], if any.
pub fn aux_cpus() -> Option<&'static [usize]> {
AUX_CPUS.get().map(Vec::as_slice)
}
/// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its /// [`place_workers`] with a plan made elsewhere (BUS-01): a separate agent process is handed its
/// placement by the launcher, which split the service's cpuset, instead of splitting its own mask. /// placement by the launcher, which split the service's cpuset, instead of splitting its own mask.
/// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and /// Confines the calling thread (and every thread it spawns afterwards) to `placement.host` and
@ -448,6 +501,29 @@ impl<'a, T> SharedSlice<'a, T> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn aux_cpus_are_taken_out_of_the_sim_set() {
// The release layout plus one page cpu: sweep 3,5,7, host 1, bus threads on 9.
let (placement, aux) = split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[9]).expect("a plan");
assert_eq!(placement.workers, vec![3, 5, 7]);
assert_eq!(placement.host, vec![1]);
assert_eq!(aux, vec![9]);
// No aux cpu is ever a worker or host cpu, whatever its position.
let (p, a) = split_cpus_aux(&[1, 3, 5, 7, 9, 11], 4, &[3, 11, 3]).expect("a plan");
assert_eq!(a, vec![3, 11]);
assert!(p.workers.iter().chain(&p.host).all(|c| !a.contains(c)));
// Refused: not in the allowed set, empty, or too few left for the sim.
assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[9]), None);
assert_eq!(split_cpus_aux(&[1, 3, 5, 7, 9], 4, &[]), None);
assert_eq!(split_cpus_aux(&[1, 3, 5, 7], 4, &[7]), None);
}
#[test]
fn confining_to_aux_without_a_reservation_is_a_no_op() {
assert!(aux_cpus().is_none());
assert!(!confine_to_aux());
}
#[test] #[test]
fn every_index_runs_exactly_once() { fn every_index_runs_exactly_once() {
for workers in [1usize, 2, 3, 7] { for workers in [1usize, 2, 3, 7] {

View file

@ -196,6 +196,13 @@ where
let bus_runtime = tokio::runtime::Builder::new_multi_thread() let bus_runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2) .worker_threads(2)
.thread_name("flysim-bus") .thread_name("flysim-bus")
// EDGE-02 review N1: the router, the publisher and the artifact copies cost
// milliseconds a frame; on the sim's dispatcher cpu they stall every barrier. When the
// session reserved aux cpus (FLY_SESSION_AUX_CPUS) these threads, the blocking pool
// included, run there; otherwise they keep the host mask they inherited.
.on_thread_start(|| {
flybrain_core::pool::confine_to_aux();
})
.enable_all() .enable_all()
.build() .build()
.context("building the bus runtime")?; .context("building the bus runtime")?;