Merge port/edge-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE): the video feed over flybus (off by default), fly-feed switch, aux cpus for the bus threads

This commit is contained in:
acamilo 2026-10-02 04:57:52 +00:00
commit fc5a579027
18 changed files with 1825 additions and 70 deletions

View file

@ -136,7 +136,8 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame
audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset.
flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an
embedded flybus router and the `fly-edge` process serves the same bytes
(`docs/design/flybus.md`, "Feed over the bus").
(`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
"Feed over the bus").
- Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM
pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat`
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,

View file

@ -1,8 +1,9 @@
# flybus: the communications bus
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
`FLY_CONTROL_VIA=bus`, both off by default**. Written 2026-09-22, amended 2026-09-23 (EDGE-01)
and 2026-10-01 (CTRL-01, "Control over the bus", below). Index only; the
`FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
authority for the API and the wire format is the crate's own
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
the draft is the [conformance report](session-framework/bus-conformance.md).
@ -190,6 +191,50 @@ Accepted for now and written down rather than fixed:
- **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a
Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`.
### Amendment 2026-10-01: the feed in production (EDGE-02)
- **The session runtime needed nothing.** `flysim-session` serves its listeners through
`flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was
written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs`
runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of
one store, direct and bus, records both feeds over a WebSocket and requires every frame in
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
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
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
`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
start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus
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`
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
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
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
report.
- **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
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), 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
connect to.
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the
env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no
binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and
the edge both follow fly.env at their next start, so a disagreement never leaves the stage with
no feed.
- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens
on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
## Control over the bus (2026-10-01, CTRL-01)
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the

View file

@ -127,6 +127,19 @@ FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
# container is not in the env file unless the operator put it there, and this deploy writes the env
# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at
# their next start, so the feed stays served either way) but the mode would change at the next
# restart of flysim, which is not what anyone meant. Said once, loudly, here.
FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \
| tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then
log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \
"this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \
"If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both."
fi
# CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a
# `vgl` on a container that never had VirtualGL installed would only show up as
# flystage refusing to start, i.e. a black stream, minutes after the deploy
@ -184,6 +197,11 @@ NEED_RELOAD=0
# ---------------------------------------------------------------------------
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
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=""
# 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.
@ -195,6 +213,10 @@ if [ -n "${CPUSET:-}" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
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"
else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -430,6 +452,17 @@ The 'current' symlink has NOT been moved."
log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string"
fi
# The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's
# ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed.
# Refused when the env file asks for bus, and when the container is in bus mode now (an edge
# that is running keeps running, but the first time it restarts there is nothing to start; and
# the way back is `fly-feed direct`, which needs no binary of this release).
if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then
ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \
|| die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved."
log "05-deploy: the feed is on the bus; this release ships fly-edge"
fi
log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically"
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
else
@ -582,6 +615,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
else
echo "FLY_SESSION_PIN=0"
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}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as
@ -590,7 +627,7 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# never enables: see that unit's header for the switch. Written
# 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
# 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).
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
@ -734,7 +771,7 @@ 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
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=", "}')"
tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day
@ -787,7 +824,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-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
for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-feed 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

326
infra/bin/fly-feed Executable file
View file

@ -0,0 +1,326 @@
#!/usr/bin/env bash
# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself
# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over
# the bus"; the runbook's "Feed over the bus".
#
# Usage (INSIDE the container, as root):
# fly-feed status configured, running, the edge and its counters (any user)
# fly-feed bus [--no-restart] [--no-rollback]
# fly-feed direct [--no-restart] [--no-wait]
#
# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's
# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings
# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever
# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or
# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes
# hands at the start, so the stream is down for the length of a flysim restart, exactly like the
# unstick rule's) and waits until the page is on the feed again.
#
# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s):
# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it);
# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving);
# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the
# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit
# (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
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
# 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
# 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.
#
# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and
# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the
# next deploy writes `direct` back (the next flysim start would then follow it) and says so.
#
# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is
# selected, `fly-runtime`): a switch and its rollback are two.
#
# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}.
set -euo pipefail
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_EDGE_SERVICE:=flyedge.service}"
: "${FLY_PAGE_SERVICE:=flystage.service}"
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
: "${FLY_PROC_DIR:=/proc}"
: "${FLY_FEED_HEALTH_TIMEOUT:=300}"
: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}"
: "${FLY_FEED_LOCK:=/run/fly/feed.lock}"
: "${FLY_FEED_SAMPLE_SECONDS:=3}"
FEED_LOG="$FLY_FEED_LOG"
log() { echo "fly-feed: $*" >&2; }
die() { log "$*"; exit 1; }
record() {
if command -v logger >/dev/null 2>&1; then
logger -t fly-feed -- "$*" || true
fi
mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG"
}
usage() {
echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2
exit 2
}
# direct | bus | invalid:<value>. flysim reads the value case-insensitively; a missing line is direct.
configured() {
local value=""
if [ -f "$FLY_ENV_FILE" ]; then
value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)"
fi
value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')"
case "$value" in
""|direct) echo direct ;;
bus) echo bus ;;
*) echo "invalid:${value}" ;;
esac
}
# What the running flysim process started with (its environment, not the file): direct | bus |
# stopped | unknown.
running() {
local pid value
pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi
if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi
value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
case "$value" in
bus) echo bus ;;
*) echo direct ;;
esac
}
# The counters of whoever serves the feed in `via` mode.
metrics_url() {
if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi
}
# metric URL NAME -> the value of the first sample of NAME, or empty.
metric() {
curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true
}
# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these).
whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; }
# The page is on the feed: at least one client, and the frames counter moves over a sample.
page_on_feed() {
local url first second clients
url="$(metrics_url "$1")"
clients="$(metric "$url" fly_feed_clients)"
[ "$(whole "$clients")" -ge 1 ] || return 1
first="$(metric "$url" fly_frames_sent_total)"
sleep "$FLY_FEED_SAMPLE_SECONDS"
second="$(metric "$url" fly_frames_sent_total)"
[ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ]
}
page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; }
old_invocation=""
# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode.
healthy() {
local via="$1" deadline
deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
sleep 1
continue
fi
if ! page_unit_active; then
log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for"
return 0
fi
if page_on_feed "$via"; then
log "healthy (${via}): the page is on the feed and frames are moving"
return 0
fi
fi
sleep 1
done
return 1
}
# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner.
set_via() {
local value="$1" tmp
[ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)"
tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")"
awk -v v="$value" '
/^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next }
{ print }
END { if (!done) print "FLY_FEED_VIA=" v }
' "$FLY_ENV_FILE" >"$tmp"
chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp"
chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true
mv -f "$tmp" "$FLY_ENV_FILE"
}
locked=0
take_lock() {
[ "$locked" -eq 0 ] || return 0
mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true
exec 8>>"$FLY_FEED_LOCK"
flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching"
locked=1
}
restart_flysim() {
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
log "restarting ${FLY_SERVICE}"
# --no-block: a start that never becomes READY must not hold this process (and the lock);
# `healthy` proves it is talking to the new invocation.
systemctl restart --no-block "$FLY_SERVICE"
}
status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
echo "configured: ${conf}"
echo "running: ${run}"
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
echo " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
fi
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
echo "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
url="$(metrics_url "$run")"
if [ "$run" = bus ]; then
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
echo "edge healthz: ok"
else
echo "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
fi
echo "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
fi
echo "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
if [ -f "$FEED_LOG" ]; then echo "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
rollback=1
wait_for_health=1
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-rollback) rollback=0 ;;
--no-wait) wait_for_health=0 ;;
*) usage ;;
esac
done
case "$command" in
status) status_report; exit 0 ;;
bus|direct) ;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})"
before="$(configured)"
[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching"
if [ "$command" = bus ]; then
[ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)"
fi
take_lock
running_before="$(running)"
if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then
log "already ${command}: fly.env says it and the running flysim started that way; nothing to do"
status_report
exit 0
fi
# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When
# the line already said bus (a deploy wrote it, the running flysim never started that way), the
# way back is direct: the state that worked.
back="$before"
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
restarted=0
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
set_via "$back" || true
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
fi
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
switching=1
set_via "$command"
record "${command} (was ${before}; flysim was running ${running_before})"
if [ "$restart" -ne 1 ]; then
switching=0
log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it"
exit 0
fi
restarted=1
restart_flysim
if [ "$wait_for_health" -ne 1 ]; then
switching=0
record "${command}: flysim restart queued (--no-wait); health not checked"
log "restart queued; fly-feed status shows the result"
exit 0
fi
if healthy "$command"; then
switching=0
if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then
log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it"
systemctl stop "$FLY_EDGE_SERVICE" || true
fi
record "${command}: healthy"
log "the feed is served ${command}"
exit 0
fi
log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s"
if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then
set_via "$back"
switching=0
record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)"
restart_flysim
if healthy "$back"; then
log "rolled back to ${back}; it is healthy"
else
log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}"
fi
else
switching=0
record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})"
fi
exit 1

View file

@ -48,6 +48,7 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
: "${FFMPEG:=/usr/bin/ffmpeg}"
@ -156,7 +157,7 @@ write_textfile_metrics() {
{
echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)."
echo "# TYPE fly_watchdog_restarts_total counter"
for unit in flysim flystage flycast mediamtx flypush flystage-web; do
for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
done
# Check 7's own restart reason, kept as a separate labelset on the
@ -396,25 +397,86 @@ check_control_edge() {
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
# watchdog's own environment overrides both.
# ============================================================================
# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of
# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the
# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next
# restart, and judging the edge in that window would restart a flysim that is serving the feed
# itself. So: the running process when its environment can be read (flysim runs as the same user),
# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or
# no line, is direct.
feed_via() {
local via="" pid=""
pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)"
if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then
via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
elif [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then echo bus; else echo direct; fi
}
feed_metrics_url() {
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
echo "$FLY_FEED_METRICS_URL"
return
fi
local via=""
if [ -f "$FLY_ENV_FILE" ]; then
# Lowercased: flysim reads the value case-insensitively, so `Bus` is bus mode.
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then
if [ "$(feed_via)" = "bus" ]; then
echo "$FLY_EDGE_METRICS_URL"
else
echo "$FLY_METRICS_URL"
fi
}
# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200
# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down
# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go:
# a flysim that has only just answered may not have published yet. After that:
# 2nd consecutive failure restart flyedge (the escalation's restart)
# 3rd and the page and the encoder (escalate's chain)
# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed
# direct --no-wait` (a restart of flysim, one stream gap, then the page
# is served again by the process that always worked). It is logged as
# an escalation and leaves FLY_FEED_VIA=direct until an operator
# switches again; this check then does nothing.
check_flyedge() {
if [ "$(feed_via)" != "bus" ]; then
record_ok flyedge
return 0
fi
if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
return 0
fi
if is_active flyedge.service \
&& curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
record_ok flyedge
return 0
fi
record_fail flyedge
local n
n="$(fail_count flyedge)"
# 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)"
inc_counter "escalations_total"
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"
record_ok flyedge
elif [ "$n" -ge 2 ]; then
escalate flyedge flystage flycast
fi
}
check_flystage() {
local metrics frames clients ok=1
local metrics frames clients ok=1 chain=(flycast)
if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then
# The edge serves the page. While it is down or silent that is check 2a's to fix, and a
# restarted page would only reconnect to nothing (and count towards a reboot).
curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0
chain=(flyedge flycast)
fi
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
if [ -z "$metrics" ]; then
ok=0
@ -441,7 +503,7 @@ check_flystage() {
record_ok flystage
else
record_fail flystage
escalate flystage flycast
escalate flystage "${chain[@]}"
fi
}
@ -1266,6 +1328,7 @@ check_loop() {
main() {
check_flysim
check_flyedge
check_control_edge
check_flystage
check_flycast

View file

@ -6,12 +6,13 @@
# <unit>` and, on the 5-consecutive-failure escalation, a container
# reboot. This is the minimum NOPASSWD surface for exactly what
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
# mediamtx, flypush, and flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
# mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
# `enable`/`disable`, no arbitrary unit name, and no units this script
# does not itself restart (xvfb, pulse, flystage-web are never touched by
# fly-watchdog's checks, so they are not granted here).
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
@ -21,3 +22,6 @@ fly ALL=(root) NOPASSWD: /usr/sbin/reboot
# resets to a milestone archive through this one root wrapper, which validates the rung,
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset
# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on
# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait

View file

@ -539,6 +539,158 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
and the session runtime alike: everything one running iteration does except the pacing sleep.
Headroom is `1 - mean / 16.74` at real time.
## Feed over the bus (EDGE-02)
`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before
EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`,
`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way
(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes,
on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the
capture never see the difference.
**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the
env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it
says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not
failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the
edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s
stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by
hand, and flysim and the edge cannot disagree.
```
pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters
pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy)
pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back
```
### The live procedure
Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`),
`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is
claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`,
`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch
restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the
restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run
continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit
(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes
of two other restarts.
```
# 1. Before: the baseline to compare with (keep the output).
pct exec $CTID -- /opt/fly/bin/fly-feed status
pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "'
pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's
# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints
# "healthy (bus): the page is on the feed and frames are moving", exit 0.
pct exec $CTID -- /opt/fly/bin/fly-feed bus
# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this
# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the
# env file's value; flysim applies it at its next restart.)
# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day.
pct exec $CTID -- /opt/fly/bin/fly-feed status
```
What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes
`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner
kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`),
waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while
`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`
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 `bus`, ssh dropped or INT, TERM
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`.
### What to watch
| Where | Healthy in bus mode | Wrong looks like |
| --- | --- | --- |
| `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) |
| 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 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 |
| `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` |
| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer |
The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that
changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed
counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers
`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then
the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the
fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly
those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator
switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather
than restarting a page that has nothing to connect to, and its chain ends with the edge and the
encoder.
### Rolling back
- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own
feed, stops a lingering edge. It needs nothing from the release (it works on one without
`fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so
count it against the start limit.
- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and
`fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both
runtimes.
- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while
the env file says `bus` or the container is in bus mode: `fly-feed direct` and set
`FLY_FEED_VIA=direct` in the env file first, then roll back or deploy.
- A reboot keeps whatever `fly.env` says.
### What the rehearsal measured
Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome,
macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real
stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed`
and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so
**real-time factor is not comparable between the two runs**; the numbers below are the ones load does
not move much. The live switch is the real A/B: take the step 1 baseline and compare.
| Measure | direct | bus |
| --- | --- | --- |
| 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) |
| 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 |
| 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 |
| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box |
| Page | 0 decode errors | 0 decode errors, gaps only under that load |
Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM
restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once)
each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and
sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of
flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores
from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the
feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after
the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge
back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to
direct with the page connected again. The live restart is longer than these 6 s by the real
restore and warm-up; use the unstick rule's usual time.
### Notes
- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and
`fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*`
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
counters.
- **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 plus tokio's blocking
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
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.
## Shadow run (SHADOW-01)
The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The

15
infra/env/example.env vendored
View file

@ -138,6 +138,12 @@ RAYON_THREADS=3
# 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.
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 -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
@ -321,8 +327,13 @@ FLY_MACRO_MODE=raw
# Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the
# bus"). direct: flysim binds it, as always. bus: flysim publishes every
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
# the same bytes; enable that unit by hand (its header has the steps).
# Watchdog check 2 follows this setting to the edge's counters by itself.
# the same bytes. This line (written into fly.env by every deploy) is the only
# switch: flysim.service wants the edge, which starts only in bus mode.
# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts
# flysim, checks the page is back, rolls back by itself) and put the same value
# here afterwards, or the next deploy warns that it writes the old one back.
# Watchdog check 2 follows the running mode to the edge's counters by itself.
# Runbook: "Feed over the bus".
FLY_FEED_VIA=direct
# --- control path -------------------------------------------------------------
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,

View file

@ -202,31 +202,56 @@ 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
# 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,
# 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
# slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
# flycast the encoder CPUs;
# 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
# 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
local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
local out
out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
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
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $sim"
echo "FLY_SIM_CPUS= $slice_cpus"
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

View file

@ -459,9 +459,6 @@ else
grep -qE '^ConditionPathExists=/opt/fly/current/fly-edge$' "$EDGE_UNIT" \
&& pass "flyedge.service stays inactive on a release without fly-edge" \
|| fail "flyedge.service needs ConditionPathExists=/opt/fly/current/fly-edge (a release before it has none)"
grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=127\.0\.0\.1:' "$EDGE_UNIT" \
&& pass "flyedge.service keeps its metrics on loopback" \
|| fail "flyedge.service FLY_EDGE_METRICS_ADDR must be a 127.0.0.1 address"
fi
# Every unit a target's Wants=/Requires= names, with backslash continuations joined and
# comments dropped: fly.target spreads both lists over several physical lines, and the
@ -1601,6 +1598,389 @@ else
rm -rf "$fe_fixture"
fi
# ---------------------------------------------------------------------------
# 3b2b. EDGE-02: the feed on the bus in production. fly.env's FLY_FEED_VIA is the one switch:
# flysim.service Wants= the edge, the edge's ExecCondition= skips it in direct mode, `fly-feed`
# rewrites the line and restarts flysim, the watchdog judges the edge only while flysim itself
# serves it through the bus. Driven for real against stubs.
# ---------------------------------------------------------------------------
echo "--- EDGE-02: flyedge is skipped in direct mode, started by every flysim start in bus mode ---"
grep -qE '^Wants=.*\bflyedge\.service\b' "$INFRA_DIR/units/flysim.service" \
&& pass "flysim.service Wants=flyedge.service (every flysim start brings the edge up in bus mode)" \
|| fail "flysim.service must Want flyedge.service: a stop and start of flysim (fly-loop-reset) would leave the edge down"
grep -qE '^ExecCondition=.*FLY_FEED_VIA.*\[Bb\]\[Uu\]\[Ss\]' "$EDGE_UNIT" \
&& pass "flyedge.service runs only when FLY_FEED_VIA is bus (ExecCondition=, any case)" \
|| fail "flyedge.service needs an ExecCondition= on FLY_FEED_VIA (case-insensitive bus)"
if grep -qE '^\[Install\]' "$EDGE_UNIT"; then
fail "flyedge.service has an [Install] section; flysim's Wants= is what starts it"
else
pass "flyedge.service has no [Install] section"
fi
grep -qE '^Environment=FLY_EDGE_METRICS_ADDR=[0-9.]+:9102$' "$EDGE_UNIT" \
&& pass "flyedge.service serves its metrics on :9102 (the dashboard's second target; the watchdog uses loopback)" \
|| fail "flyedge.service FLY_EDGE_METRICS_ADDR must be an address on :9102"
if grep -qE '^Wants=.*flyedge' "$INFRA_DIR/units/flysim-session.service"; then
fail "flysim-session.service Wants flyedge.service, whose Requires=flysim.service would start the unit it Conflicts with"
else
pass "flysim-session.service (the standalone rehearsal unit) does not pull the edge in"
fi
grep -qE 'for name in .*\bfly-feed\b.*; do$' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh installs fly-feed" \
|| fail "05-deploy.sh must converge bin/fly-feed to /opt/fly/bin"
grep -qF 'this release has no fly-edge' "$INFRA_DIR/05-deploy.sh" \
&& grep -qF '"${release_path}/fly-edge"' "$INFRA_DIR/05-deploy.sh" \
&& pass "05-deploy.sh refuses a release without fly-edge while the feed is on the bus (before the symlink moves)" \
|| fail "05-deploy.sh must refuse a release without fly-edge when FLY_FEED_VIA is bus (env file or container)"
grep -qE '^fly ALL=\(root\) NOPASSWD: /usr/bin/systemctl restart flyedge\.service$' "$INFRA_DIR/config/fly-sudoers" \
&& grep -qE '^fly ALL=\(root\) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait$' "$INFRA_DIR/config/fly-sudoers" \
&& pass "sudoers lets the watchdog restart flyedge and run exactly 'fly-feed direct --no-wait'" \
|| fail "config/fly-sudoers must grant the watchdog 'systemctl restart flyedge.service' and 'fly-feed direct --no-wait'"
echo "--- fly-feed: bus, direct, status, rollback ---"
ff_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-feed.XXXXXX")"
mkdir -p "$ff_dir/bin" "$ff_dir/release" "$ff_dir/proc/4242" "$ff_dir/run"
cat > "$ff_dir/bin/systemctl" <<'FFSTUB'
#!/usr/bin/env bash
echo "$*" >> "$FF_DIR/systemctl.log"
case "$1" in
restart) n=$(( $(cat "$FF_DIR/invocation" 2>/dev/null || echo 1) + 1 )); echo "$n" > "$FF_DIR/invocation"
# the new flysim's environment is whatever fly.env says now
v="$(awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' "$FF_ENV")"
printf 'FLY_FEED_VIA=%s\0' "$v" > "$FF_DIR/proc/4242/environ" ;;
show) case "$*" in
*MainPID*) echo 4242 ;;
*InvocationID*) echo "inv$(cat "$FF_DIR/invocation" 2>/dev/null || echo 1)" ;;
esac ;;
is-active)
case "${*: -1}" in
flystage.service) [ "${FF_PAGE:-1}" = 1 ]; exit $? ;;
flyedge.service) [ "${FF_EDGE_ACTIVE:-0}" = 1 ]; exit $? ;;
esac ;;
esac
exit 0
FFSTUB
cat > "$ff_dir/bin/curl" <<'FFSTUB'
#!/usr/bin/env bash
url="${*: -1}"
quiet=0; for a in "$@"; do [ "$a" = /dev/null ] && quiet=1; done
case "$url" in
http://control/healthz) [ "${FF_CONTROL_OK:-1}" = 1 ] || exit 22; exit 0 ;;
http://edge/healthz) [ "${FF_EDGE_OK:-1}" = 1 ] || exit 22; exit 0 ;;
http://sim/metrics|http://edge/metrics)
n=$(( $(cat "$FF_DIR/frames" 2>/dev/null || echo 1000) + 30 )); echo "$n" > "$FF_DIR/frames"
[ "${FF_FLAT:-0}" = 1 ] && n=1000
echo "fly_feed_clients ${FF_CLIENTS:-1}"; echo "fly_frames_sent_total $n"
echo "fly_edge_snapshot_age_seconds 0.03"; echo "fly_edge_bus_lost_total 0" ;;
*) exit 22 ;;
esac
FFSTUB
printf '#!/usr/bin/env bash\necho 0\n' > "$ff_dir/bin/id"
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/bin/logger"
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"
chmod +x "$ff_dir"/bin/* "$ff_dir/release/fly-edge"
ff_env="$ff_dir/fly.env"
fly_feed() {
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=3 FLY_FEED_SAMPLE_SECONDS=0 \
"$@" bash "$INFRA_DIR/bin/fly-feed" "${FF_ARGS[@]}"
}
ff_reset() { # ff_reset VIA_IN_FILE VIA_RUNNING
printf 'FLY_GAME=pokemon-red\nFLY_FEED_VIA=%s\nFLY_MACRO_MODE=raw\n' "$1" > "$ff_env"
chmod 0640 "$ff_env"
printf 'FLY_FEED_VIA=%s\0' "$2" > "$ff_dir/proc/4242/environ"
: > "$ff_dir/systemctl.log"; rm -f "$ff_dir/feed.log" "$ff_dir/frames" "$ff_dir/invocation"
}
ff_restarts() { grep -c '^restart --no-block flysim.service$' "$ff_dir/systemctl.log" || true; }
ff_reset direct direct
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
if printf '%s\n' "$ff_out" | grep -qx 'configured: direct' && printf '%s\n' "$ff_out" | grep -qx 'running: direct'; then
pass "fly-feed status: direct, running direct"
else
fail "fly-feed status wrong: $ff_out"
fi
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed && [ "$(grep -c '^FLY_FEED_VIA=' "$ff_env")" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env" \
&& grep -qx 'FLY_GAME=pokemon-red' "$ff_env" && grep -qx 'FLY_MACRO_MODE=raw' "$ff_env" \
&& [ "$(stat -c %a "$ff_env")" = 640 ] && [ "$(ff_restarts)" = 1 ] && grep -q 'bus: healthy' "$ff_dir/feed.log"; then
pass "fly-feed bus: one FLY_FEED_VIA line, the rest and the mode kept, flysim restarted once, healthy on the edge's counters"
else
fail "fly-feed bus: wrong ($(tr '\n' ' ' < "$ff_env"); restarts $(ff_restarts); $(cat "$ff_dir/feed.log" 2>/dev/null))"
fi
FF_ARGS=(bus)
: > "$ff_dir/systemctl.log"
if fly_feed && [ "$(ff_restarts)" = 0 ]; then
pass "fly-feed bus when already bus and running bus: nothing to do, no restart"
else
fail "fly-feed bus must not restart flysim when fly.env and the running process already say bus"
fi
# A deploy wrote bus but the running flysim started direct: `bus` applies it (and a bus fly.env is not its own way back).
ff_reset bus direct
FF_ARGS=(bus)
if fly_feed && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=bus' "$ff_env"; then
pass "fly-feed bus applies a fly.env that says bus to a flysim that started direct"
else
fail "fly-feed bus must restart flysim when fly.env says bus and it is running direct"
fi
ff_reset bus bus
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
if printf '%s\n' "$ff_out" | grep -q '^edge healthz: ok'; then
pass "fly-feed status in bus mode reads the edge"
else
fail "fly-feed status in bus mode must report the edge's healthz"
fi
ff_reset Bus direct
FF_ARGS=(status)
ff_out="$(fly_feed 2>&1 || true)"
printf '%s\n' "$ff_out" | grep -qx 'configured: bus' \
&& pass "fly-feed reads FLY_FEED_VIA=Bus as bus (flysim lowercases it)" \
|| fail "fly-feed must read FLY_FEED_VIA case-insensitively"
# A bus that never becomes healthy (the edge answers 503) rolls back to direct and says so.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_EDGE_OK=0; then
fail "fly-feed bus must exit non-zero when the edge never becomes healthy"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 2 ] && grep -q 'automatic rollback' "$ff_dir/feed.log"; then
pass "fly-feed bus rolls back to direct, restarting flysim again, when the edge is not healthy"
else
fail "fly-feed bus rollback wrong ($(grep FLY_FEED_VIA "$ff_env"); restarts $(ff_restarts))"
fi
# A page that never reaches the feed (no clients) is not healthy either; --no-rollback leaves the switch in place.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_CLIENTS=0; then
fail "fly-feed bus must not call a feed with no page on it healthy while flystage is active"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env"; then
pass "fly-feed bus: a page that never connects is a failed switch, rolled back"
else
fail "fly-feed bus with no client must roll back"
fi
ff_reset direct direct
FF_ARGS=(bus --no-rollback)
if fly_feed FF_EDGE_OK=0; then
fail "--no-rollback: must still fail"
elif grep -qx 'FLY_FEED_VIA=bus' "$ff_env" && [ "$(ff_restarts)" = 1 ]; then
pass "fly-feed bus --no-rollback leaves the switch as it is when unhealthy"
else
fail "--no-rollback must leave FLY_FEED_VIA=bus and restart once"
fi
# Frames that never advance are not a feed.
ff_reset direct direct
FF_ARGS=(bus)
if fly_feed FF_FLAT=1; then fail "flat frames counter must not be healthy"; else pass "fly-feed bus: a frames counter that does not move is not healthy"; fi
# No page unit: the wait ends at the edge's healthz.
ff_reset direct direct
FF_ARGS=(bus)
fly_feed FF_PAGE=0 FF_CLIENTS=0 \
&& pass "fly-feed bus on a box with no active page unit waits for the edge only" \
|| fail "fly-feed bus with flystage inactive must succeed on the edge's healthz alone"
# A release without fly-edge refuses before touching anything.
ff_reset direct direct
rm -f "$ff_dir/release/fly-edge"
FF_ARGS=(bus)
if fly_feed; then
fail "fly-feed bus must refuse a release without fly-edge"
elif grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ]; then
pass "fly-feed bus refuses a release without fly-edge, changing and restarting nothing"
else
fail "refusal must leave fly.env and flysim alone"
fi
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge"
# direct: the way back, which works with no fly-edge at all and stops a lingering edge.
ff_reset bus bus
rm -f "$ff_dir/release/fly-edge"
FF_ARGS=(direct)
if fly_feed FF_EDGE_ACTIVE=1 && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 1 ] \
&& grep -qx 'stop flyedge.service' "$ff_dir/systemctl.log" && grep -q 'direct: healthy' "$ff_dir/feed.log"; then
pass "fly-feed direct: back to flysim on :7400 with no fly-edge in the release, a lingering edge stopped"
else
fail "fly-feed direct wrong ($(grep FLY_FEED_VIA "$ff_env"); $(cat "$ff_dir/systemctl.log" | tr '\n' ';'))"
fi
printf '#!/usr/bin/env bash\ntrue\n' > "$ff_dir/release/fly-edge"; chmod +x "$ff_dir/release/fly-edge"
ff_reset bus bus
FF_ARGS=(direct --no-restart)
fly_feed && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" && [ "$(ff_restarts)" = 0 ] \
&& pass "fly-feed direct --no-restart writes the line and restarts nothing" \
|| fail "--no-restart must only write fly.env"
ff_reset bus bus
FF_ARGS=(direct --no-wait)
fly_feed FF_CONTROL_OK=0 && [ "$(ff_restarts)" = 1 ] && grep -qx 'FLY_FEED_VIA=direct' "$ff_env" \
&& pass "fly-feed direct --no-wait (the watchdog's fallback) restarts flysim and returns without a health wait" \
|| fail "--no-wait must restart flysim and return 0 whatever the health"
ff_reset 'buss' direct
FF_ARGS=(bus)
if fly_feed; then fail "fly-feed must refuse an invalid FLY_FEED_VIA"; else pass "fly-feed refuses an invalid FLY_FEED_VIA in fly.env, touching nothing"; fi
# An interrupted switch (INT/TERM/HUP) rolls back: the stub restart hangs the health wait; kill it mid-way.
ff_reset direct direct
FF_ARGS=(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_EDGE_OK=0 \
bash "$INFRA_DIR/bin/fly-feed" bus >/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 'interrupted or failed' "$ff_dir/feed.log" 2>/dev/null; then
pass "fly-feed bus interrupted mid-switch puts FLY_FEED_VIA back"
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' ';'))"
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"
echo "--- fly-watchdog: check 2a (the edge) and check 2 in bus mode ---"
wf_dir="$(mktemp -d "${TMPDIR:-/tmp}/fly-lint-wdedge.XXXXXX")"
mkdir -p "$wf_dir/bin" "$wf_dir/proc/4242" "$wf_dir/run" "$wf_dir/state" "$wf_dir/textfile"
cat > "$wf_dir/bin/systemctl" <<'WFSTUB'
#!/usr/bin/env bash
case "$1" in
show) echo 4242 ;;
is-active) [ "${WF_EDGE_ACTIVE:-1}" = 1 ]; exit $? ;;
restart) echo "restart $2" >> "$WF_DIR/actions.log" ;;
esac
exit 0
WFSTUB
cat > "$wf_dir/bin/sudo" <<'WFSTUB'
#!/usr/bin/env bash
if [ "$1" = /usr/bin/systemctl ]; then shift; exec systemctl "$@"; fi
echo "sudo $*" >> "$WF_DIR/actions.log"
exit 0
WFSTUB
cat > "$wf_dir/bin/curl" <<'WFSTUB'
#!/usr/bin/env bash
url="${*: -1}"
case "$url" in
http://control/healthz) [ "${WF_CONTROL_OK:-1}" = 1 ] || exit 22 ;;
http://edge/healthz) [ "${WF_EDGE_OK:-1}" = 1 ] || exit 22 ;;
http://edge/metrics) echo "fly_frames_sent_total ${WF_EDGE_FRAMES:-100}"; echo "fly_feed_clients 1" ;;
http://sim/metrics) echo "fly_frames_sent_total ${WF_SIM_FRAMES:-0}"; echo "fly_feed_clients 0" ;;
*) exit 22 ;;
esac
WFSTUB
printf '#!/usr/bin/env bash\ncat >/dev/null\n' > "$wf_dir/bin/systemd-cat"
chmod +x "$wf_dir"/bin/*
sed '$d' "$INFRA_DIR/bin/fly-watchdog" > "$wf_dir/wd.sh"
wd_edge() { # wd_edge VIA_RUNNING 'ENV...' -- COMMANDS
local via="$1"; shift
printf 'FLY_FEED_VIA=%s\0' "$via" > "$wf_dir/proc/4242/environ"
env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" \
FLY_CONTROL_URL=http://control FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge \
WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" \
"$@" bash -c "source '$wf_dir/wd.sh'; $WD_CMDS" >/dev/null 2>&1 || true
}
wd_acts() { cat "$wf_dir/actions.log" 2>/dev/null | tr '\n' ';'; }
wd_reset() { : > "$wf_dir/actions.log"; rm -f "$wf_dir/run"/*; }
echo 'FLY_FEED_VIA=bus' > "$wf_dir/fly.env"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge direct
[ -z "$(wd_acts)" ] && pass "check 2a does nothing in direct mode" || fail "check 2a acted in direct mode: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0 WF_CONTROL_OK=0
[ -z "$(wd_acts)" ] && pass "check 2a leaves a down flysim to check 1" || fail "check 2a acted while flysim was down: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=1
[ -z "$(wd_acts)" ] && pass "check 2a: a healthy edge is left alone" || fail "check 2a acted on a healthy edge: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge'
wd_edge bus WF_EDGE_OK=0
[ -z "$(wd_acts)" ] && pass "check 2a lets the first failed pass go (a flysim that only just answered)" || fail "check 2a acted on the first failure: $(wd_acts)"
wd_reset; WD_CMDS='check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"restart flyedge.service;") pass "check 2a: the second failed pass restarts flyedge" ;;
*) fail "check 2a second failure should restart flyedge only: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge'
wd_edge bus WF_EDGE_OK=0
case "$(wd_acts)" in
"restart flyedge.service;restart flyedge.service;restart flystage.service;restart flycast.service;") pass "check 2a: the third restarts the page and the encoder as well" ;;
*) fail "check 2a third failure: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; 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: 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)" ;;
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_edge bus WF_EDGE_OK=1 WF_EDGE_ACTIVE=0
case "$(wd_acts)" in
"restart flyedge.service;") pass "check 2a: an inactive edge in bus mode is a failure like an unhealthy one" ;;
*) fail "check 2a inactive edge: $(wd_acts)" ;;
esac
# fly.env says bus but the running flysim started direct (a deploy, not yet restarted): it serves the feed itself.
wd_reset; WD_CMDS='check_flyedge; check_flyedge; check_flyedge; check_flyedge'
wd_edge direct WF_EDGE_OK=0 WF_EDGE_ACTIVE=0
[ -z "$(wd_acts)" ] && pass "check 2a follows the running flysim, not fly.env: a pending switch is not an outage" || fail "check 2a acted on a pending switch: $(wd_acts)"
WD_CMDS='feed_metrics_url'
got="$(printf 'FLY_FEED_VIA=direct\0' > "$wf_dir/proc/4242/environ"; env WF_DIR="$wf_dir" PATH="$wf_dir/bin:$PATH" FLY_PROC_DIR="$wf_dir/proc" FLY_ENV_FILE="$wf_dir/fly.env" FLY_METRICS_URL=http://sim FLY_EDGE_METRICS_URL=http://edge WD_RUN_DIR="$wf_dir/run" WD_STATE_DIR="$wf_dir/state" TEXTFILE_DIR="$wf_dir/textfile" bash -c "source '$wf_dir/wd.sh'; feed_metrics_url" 2>/dev/null || true)"
[ "$got" = http://sim ] && pass "check 2 reads flysim's counters while the running flysim serves the feed itself" || fail "check 2 URL for a pending switch: $got"
# Check 2 in bus mode: an unhealthy edge is check 2a's, not a reason to restart the page; a healthy
# edge with a flat frames counter restarts the page and, after three, the edge and the encoder.
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage'
wd_edge bus WF_EDGE_OK=0
[ -z "$(wd_acts)" ] && pass "check 2 in bus mode leaves a silent edge to check 2a (the page is not restarted)" || fail "check 2 restarted things while the edge was down: $(wd_acts)"
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage'
wd_edge bus WF_EDGE_OK=1 WF_EDGE_FRAMES=100
case "$(wd_acts)" in
"restart flystage.service;restart flystage.service;restart flystage.service;restart flyedge.service;restart flycast.service;")
pass "check 2 in bus mode: frames flat restarts the page, then the edge and the encoder in the chain" ;;
*) fail "check 2 bus chain: $(wd_acts)" ;;
esac
wd_reset; WD_CMDS='check_flystage; check_flystage; check_flystage; check_flystage'
wd_edge direct WF_SIM_FRAMES=100
case "$(wd_acts)" in
*"restart flyedge"*) fail "check 2 in direct mode must not touch the edge: $(wd_acts)" ;;
*) pass "check 2 in direct mode never restarts the edge" ;;
esac
rm -rf "$wf_dir"
# ---------------------------------------------------------------------------
# 3c. lib/common.sh cpuset_partition — the three-way cpuset split used by
# 05-deploy.sh section 3b (flysim / page-capture / flycast). Run as its own
@ -1687,8 +2067,8 @@ set -euo pipefail
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; }
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" "$aux" 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"
@ -1697,7 +2077,7 @@ check_plan() {
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
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
bad="$bad $u-overlaps-sim"
fi
@ -1715,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 "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 "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=

View file

@ -1,30 +1,41 @@
# infra/units/flyedge.service — pushed to /etc/systemd/system/flyedge.service.
#
# The feed WebSocket served from flysim's feed bus (docs/design/flybus.md,
# "Feed over the bus"; services/flysim/crates/fly-edge). DISABLED BY DEFAULT:
# it is in no target's Wants=/Requires= and 07-enable.sh does not enable it.
# With FLY_FEED_VIA=direct (the default, written into /etc/fly/fly.env by
# 05-deploy.sh) flysim binds 127.0.0.1:7400 itself and this unit has nothing
# to do. To move the feed onto the bus on one container:
# "Feed over the bus"; services/flysim/crates/fly-edge). Whether it runs is
# decided by one line, FLY_FEED_VIA in /etc/fly/fly.env (05-deploy.sh writes it
# from the env file's FLY_FEED_VIA, default `direct`):
#
# 1. FLY_FEED_VIA=bus in the env file, then 05-deploy.sh (rewrites fly.env);
# 2. systemctl enable --now flyedge.service; systemctl restart flysim.service
# (flysim stops binding :7400, the edge binds it once the first snapshot
# is on the bus);
# 3. nothing for the watchdog: check 2 reads FLY_FEED_VIA from fly.env and
# follows the feed counters to this unit's loopback /metrics.
# direct flysim binds 127.0.0.1:7400 itself. ExecCondition= below fails, so
# this unit starts as "skipped" (inactive, no failure, no restart).
# bus flysim publishes on its feed bus and leaves :7400 to this unit.
#
# Back: FLY_FEED_VIA=direct, deploy, systemctl disable --now flyedge.service,
# restart flysim.
# flysim.service has Wants= on this unit, so EVERY start of flysim (the unstick
# rule's restart, fly-loop-reset's stop and start, fly-reset-to-milestone, a
# crash-restart, a reboot through fly.target) starts the edge in bus mode and
# skips it in direct mode; fly.env alone decides, and flysim and the edge can
# never disagree. This unit is in no target and has no [Install] section:
# `systemctl enable` has nothing to do.
#
# Switching a running container (infra/bin/fly-feed, "Feed over the bus" in
# docs/runbook.md; it is the whole procedure, with a health check and its own
# rollback):
#
# fly-feed bus FLY_FEED_VIA=bus in fly.env, restart flysim, wait for
# the edge and a client
# fly-feed direct the way back
#
# Ordering (docs/design/flybus.md, amendment "Feed store lifecycle"): flysim
# owns the router and its store under /run/fly/bus, so it starts first and
# the edge follows it. Requires= makes an explicit stop or restart of flysim
# (the unstick rule's `systemctl restart flysim.service` included) stop or
# restart the edge with it. A crash-restart of flysim is covered by the edge
# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms,
# so nothing here has to be restarted by hand. The edge holds no state; the
# store is flysim's and a new router removes the previous one's directory.
# owns the router and its store under /run/fly/bus, so it starts first and the
# edge follows it. Requires= makes an explicit stop or restart of flysim stop
# or restart the edge with it. A crash-restart of flysim is covered by the edge
# itself: it drops its clients, unbinds :7400 and reconnects every 500 ms, so
# nothing here has to be restarted by hand. The edge holds no state; the store
# is flysim's and a new router removes the previous one's directory.
#
# CPUs: 05-deploy.sh writes this unit's cpuset drop-in on the page CPUs, never
# flysim's (the sim's CPUs are the sim's alone, docs/runbook.md "CPU partition").
# The router and the publisher run inside flysim, on its own two-thread bus
# runtime.
[Unit]
Description=flyedge: the feed WebSocket served from flysim's feed bus
After=flysim.service
@ -42,15 +53,17 @@ User=fly
EnvironmentFile=/etc/fly/fly.env
Environment=FLY_FEED_BIND=127.0.0.1:7400
Environment=FLY_BUS_DIR=/run/fly/bus
# Its own read-only /metrics and /healthz, for watchdog check 2 in bus mode.
# Loopback only: nothing off the container needs the edge's counters.
Environment=FLY_EDGE_METRICS_ADDR=127.0.0.1:9102
# Its own read-only /metrics and /healthz: watchdog check 2 reads them in bus mode (over
# loopback), and so can the metrics dashboard, as a second target beside flysim's :9101, which
# reads 0 for the feed counters in bus mode. Same exposure as :9101 (the container's network).
Environment=FLY_EDGE_METRICS_ADDR=0.0.0.0:9102
# Only in bus mode. EnvironmentFile= is the same fly.env flysim reads, so this is the value
# flysim started with (flysim reads it case-insensitively, so does this). Exit 1 means
# "skip": the unit goes inactive without failing and without being restarted.
ExecCondition=/bin/sh -c 'case "$$FLY_FEED_VIA" in [Bb][Uu][Ss]) ;; *) exit 1;; esac'
ExecStart=/opt/fly/current/fly-edge
Restart=always
RestartSec=2
# A few snapshots in flight and a WebSocket per client; the store itself is
# flysim's (tmpfs, bounded by feedbus::limits at 32 MiB).
MemoryMax=256M
[Install]
WantedBy=fly.target

View file

@ -14,11 +14,15 @@
[Unit]
Description=flysim: the fly brain, emulator, and control/feed APIs
After=network.target
# Every start of flysim starts the feed edge when fly.env says FLY_FEED_VIA=bus, and skips it in
# direct mode (units/flyedge.service decides): a stop and start of flysim (fly-loop-reset,
# fly-reset-to-milestone) would otherwise leave the stage with nothing on :7400, because
# flyedge.service's Requires= stops the edge with flysim but does not bring it back.
# Every start of flysim starts the control edge when fly.env says FLY_CONTROL_VIA=bus, and skips
# it in direct mode (units/flycontrol-edge.service decides): a stop and start of flysim
# (fly-loop-reset, fly-reset-to-milestone) would otherwise leave :7401 dead, because the edge's
# Requires= stops it with flysim but does not bring it back.
Wants=flycontrol-edge.service
Wants=flyedge.service flycontrol-edge.service
StartLimitIntervalSec=300
StartLimitBurst=5

View file

@ -18,8 +18,9 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow};
use axum::extract::State;
@ -32,6 +33,19 @@ use flysim::feedbus;
use flysim::metrics::{Metrics, metric};
use tokio::sync::{oneshot, watch};
/// A subscription that has delivered nothing for this long is not serving: the loop publishes a
/// header at least every `1 / idle_snapshot_hz` even when paused, so silence this long means the
/// bus is wedged, not that the fly is idle. `/healthz` turns 503 so the watchdog restarts the edge
/// (it restarts nothing while flysim itself is unhealthy: that is flysim's check).
pub const STALE_AFTER: Duration = Duration::from_secs(15);
static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
/// Milliseconds since the process first asked, plus one so that 0 can mean "never".
fn now_ms() -> u64 {
EPOCH.elapsed().as_millis() as u64 + 1
}
/// What the edge needs to know. Built from flysim's own configuration, so both processes read
/// one environment file and cannot disagree about the port, the bus directory or the cadence.
#[derive(Debug, Clone)]
@ -75,9 +89,41 @@ pub struct EdgeMetrics {
pub decode_failures: AtomicU64,
/// Sessions that reached the bus but could not bind the feed port.
pub bind_failures: AtomicU64,
/// [`now_ms`] when the last snapshot was taken off the bus; 0 before the first.
last_snapshot_ms: AtomicU64,
}
impl EdgeMetrics {
/// Note that a snapshot has just been taken off the bus.
fn snapshot_arrived(&self) {
self.snapshots.fetch_add(1, Ordering::Relaxed);
self.last_snapshot_ms.store(now_ms(), Ordering::Relaxed);
}
/// Seconds since the last snapshot came off the bus, or `None` before the first.
pub fn snapshot_age(&self) -> Option<Duration> {
match self.last_snapshot_ms.load(Ordering::Relaxed) {
0 => None,
at => Some(Duration::from_millis(now_ms().saturating_sub(at))),
}
}
/// Whether the edge is serving: subscribed, and hearing from the bus within [`STALE_AFTER`].
pub fn health(&self) -> Result<(), String> {
self.health_within(STALE_AFTER)
}
fn health_within(&self, stale_after: Duration) -> Result<(), String> {
if self.connected.load(Ordering::Relaxed) != 1 {
return Err("waiting for the feed bus".to_owned());
}
match self.snapshot_age() {
Some(age) if age <= stale_after => Ok(()),
Some(age) => Err(format!("no snapshot for {} s", age.as_secs())),
None => Err("no snapshot yet".to_owned()),
}
}
pub fn render(&self) -> String {
let mut out = String::with_capacity(1_024);
let feed = &self.feed;
@ -116,6 +162,13 @@ impl EdgeMetrics {
"1 while the edge is subscribed to the feed bus and serving.",
self.connected.load(Ordering::Relaxed),
);
metric(
&mut out,
"fly_edge_snapshot_age_seconds",
"gauge",
"Seconds since the last snapshot came off the feed bus (-1 before the first).",
self.snapshot_age().map_or(-1.0, |age| age.as_secs_f64()),
);
metric(
&mut out,
"fly_edge_bus_lost_total",
@ -218,10 +271,9 @@ async fn prometheus(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoRespons
}
async fn healthz(State(metrics): State<Arc<EdgeMetrics>>) -> impl IntoResponse {
if metrics.connected.load(Ordering::Relaxed) == 1 {
(StatusCode::OK, "ok")
} else {
(StatusCode::SERVICE_UNAVAILABLE, "waiting for the feed bus")
match metrics.health() {
Ok(()) => (StatusCode::OK, "ok".to_owned()),
Err(why) => (StatusCode::SERVICE_UNAVAILABLE, why),
}
}
@ -291,7 +343,7 @@ async fn serve(
listener: tokio::net::TcpListener,
) {
let (snapshots, receiver) = watch::channel(Arc::new(first));
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
metrics.snapshot_arrived();
tracing::info!(feed = %config.feed_bind, bus = %config.bus_dir.display(), "serving the feed from the bus");
metrics.connected.store(1, Ordering::Relaxed);
@ -317,7 +369,7 @@ async fn serve(
Ok(snapshot) => {
drop(message);
snapshots.send_replace(Arc::new(snapshot));
metrics.snapshots.fetch_add(1, Ordering::Relaxed);
metrics.snapshot_arrived();
}
Err(error) => {
metrics.decode_failures.fetch_add(1, Ordering::Relaxed);
@ -342,3 +394,32 @@ async fn serve(
tracing::warn!("the feed listener took more than 5 s to stop");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn health_needs_the_bus_and_recent_snapshots() {
let metrics = EdgeMetrics::default();
assert_eq!(metrics.snapshot_age(), None);
assert!(metrics.health().unwrap_err().contains("waiting"));
metrics.connected.store(1, Ordering::Relaxed);
assert!(metrics.health().unwrap_err().contains("no snapshot yet"));
metrics.snapshot_arrived();
assert_eq!(metrics.health(), Ok(()));
std::thread::sleep(Duration::from_millis(40));
assert!(metrics.snapshot_age().unwrap() >= Duration::from_millis(40));
assert!(
metrics
.health_within(Duration::from_millis(10))
.unwrap_err()
.contains("no snapshot for")
);
metrics.snapshot_arrived();
assert_eq!(metrics.health_within(Duration::from_millis(30)), Ok(()));
metrics.connected.store(0, Ordering::Relaxed);
assert!(metrics.health().is_err());
assert!(metrics.render().contains("fly_edge_snapshot_age_seconds"));
}
}

View file

@ -49,3 +49,5 @@ axum = "0.8"
futures-util = "0.3"
tokio-tungstenite = "0.29"
tower = { version = "0.5", features = ["util"] }
# EDGE-02: the session runtime serves the feed over the bus (tests/feed_bus.rs).
fly-edge = { path = "../fly-edge" }

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
/// ([`place_threads`]).
pub const SESSION_PIN_ENV: &str = "FLY_SESSION_PIN";
/// Process mode: a CPU list for the service process (router, coordinator, listeners, checkpoint
/// writer) and the environment process, instead of the sweep's host CPU (BUS-01). It must lie in
/// the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs).
/// A CPU list for the threads that are not the sim, instead of the sweep's host CPU. It must lie
/// in the unit's cpuset (on the containers, `flysim.slice`'s AllowedCPUs, where 05-deploy.sh adds
/// 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";
/// How the service composes its session, beyond flysim's own [`Config`].
@ -348,8 +352,29 @@ fn place_threads(config: &Config, options: &mut ServiceOptions) {
);
return;
}
if std::env::var_os(SESSION_AUX_CPUS_ENV).is_some() {
tracing::warn!("{SESSION_AUX_CPUS_ENV} is for process mode; ignored");
// In-process and thread modes: FLY_SESSION_AUX_CPUS names cpus of the unit's cpuset that are
// 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) {
Some(placement) => tracing::info!(

View file

@ -0,0 +1,480 @@
//! EDGE-02: the session runtime serves the feed over the bus.
//!
//! `flysim-session` runs behind `flysim::serve`, so `FLY_FEED_VIA=bus` should work on it exactly
//! as on `flysim`. This runs the real `flysim-session` binary (the toy connectome, the real
//! cartridge, a store seeded by a legacy fresh start) twice from copies of the same store:
//!
//! - `direct`: the binary binds the feed port and a WebSocket client records it;
//! - `bus`: the binary binds nothing on the feed port, `fly-edge` (in process) does, and the same
//! client records that. The binary is then stopped and started again under the same edge, which
//! must unbind, reconnect and serve the new instance.
//!
//! The two recordings are compared snapshot by snapshot on the sim frame: the header minus the
//! fields that are wall clock by definition, and the three attachments byte for byte. Gated on
//! `FLY_ROM` (source `bin/rom-env.sh`): without it the test returns early.
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Child, Command as Process, Stdio};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use fly_edge::{EdgeConfig, EdgeMetrics};
use flysim::config::{Config, FeedVia};
use flysim::eventlog::EventRing;
use flysim::simloop::{Command, Shared, Sim, booting_snapshot};
use flysim::snapshot::MacroMode;
use futures_util::{SinkExt as _, StreamExt as _};
use serde_json::Value;
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::Message as WsMessage;
fn rom_path() -> Option<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
fn free_port() -> SocketAddr {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
}
/// The service configuration: slow enough that a recorder on a loaded box sees every frame, every
/// frame published, no timed checkpoints.
fn config(rom: &Path, dataset: &Path, dir: &Path, via: FeedVia, bus_dir: &Path) -> Config {
let mut config = Config::default();
config.paths.rom = rom.to_path_buf();
config.paths.dataset = dataset.to_path_buf();
config.paths.save_dir = dir.join("durable");
config.paths.hot_dir = dir.join("hot");
config.loop_.game = "pokemon-red".to_owned();
config.loop_.speed = 0.25;
config.loop_.threads = 1;
config.loop_.snapshot_hz = 240.0;
config.loop_.hot_seconds = 1e9;
config.loop_.checkpoint_seconds = 1e9;
config.macros.mode = MacroMode::Raw;
config.chat.enabled = false;
config.feed.via = via;
config.feed.bus_dir = bus_dir.to_path_buf();
config.feed.bind = free_port();
config.control.bind = free_port();
config.control.metrics_bind = Some(free_port());
config
}
/// A store seeded by a legacy fresh start, shut down cleanly (as `service_parity` does).
fn seed_by_legacy_fresh_start(rom: &Path, dataset: &Path, dir: &Path) {
let mut config = config(rom, dataset, dir, FeedVia::Direct, dir);
config.loop_.speed = 1.0;
let shared = Arc::new(Shared::new(config.clone(), EventRing::new()));
let (commands, command_rx) = mpsc::channel::<Command>(64);
let (snapshots_tx, mut snapshots) =
watch::channel(Arc::new(booting_snapshot(0, 0, MacroMode::Raw)));
let thread = std::thread::spawn(move || -> anyhow::Result<()> {
let mut sim = Sim::boot(shared, snapshots_tx, command_rx)?;
sim.run(&flysim::sdnotify::Notifier::from_env())
});
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
loop {
snapshots.changed().await.unwrap();
if snapshots.borrow().header.frame >= 120 {
break;
}
}
let (reply, ack) = tokio::sync::oneshot::channel();
commands.send(Command::Shutdown { reply }).await.unwrap();
let _ = ack.await;
});
thread.join().unwrap().unwrap();
}
fn seed(from: &Path, to: &Path) {
for sub in ["durable", "hot"] {
let dst = to.join(sub);
std::fs::create_dir_all(&dst).unwrap();
if let Ok(entries) = std::fs::read_dir(from.join(sub)) {
for entry in entries.flatten() {
if entry.file_type().unwrap().is_file() {
std::fs::copy(entry.path(), dst.join(entry.file_name())).unwrap();
}
}
}
}
}
/// A running `flysim-session`, stopped (SIGTERM, then kill) when dropped.
struct Service {
child: Child,
config: Config,
}
impl 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"));
std::fs::write(&path, toml::to_string(&config).unwrap()).unwrap();
let log = std::fs::File::create(work.join(format!("{name}.log"))).unwrap();
let child = Process::new(env!("CARGO_BIN_EXE_flysim-session"))
.arg("--config")
.arg(&path)
.env("FLY_SESSION_PROFILE", "toy")
.env("FLY_SESSION_DIR", work.join(format!("{name}-session")))
// The test process's own cpus are not the sim's.
.env("FLY_SESSION_PIN", "0")
.env_remove("FLY_FEED_VIA")
.env_remove("FLY_BUS_DIR")
.env_remove("FLY_FEED_BIND")
.env_remove("FLY_CONTROL_BIND")
.env_remove("FLY_METRICS_ADDR")
.envs(envs.iter().copied())
.stdout(Stdio::null())
.stderr(log)
.spawn()
.expect("flysim-session starts");
Service { child, config }
}
/// SIGTERM and wait for the clean stop (the unit's own way to stop it).
fn stop(&mut self) {
let pid = self.child.id().to_string();
let _ = Process::new("kill").args(["-TERM", &pid]).status();
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
if self.child.try_wait().unwrap().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
/// Whether `flysim-session` itself holds the feed port (a connect succeeds and the peer is
/// not the edge): used only for the direct run, where it must.
fn log(&self, work: &Path, name: &str) -> PathBuf {
work.join(format!("{name}.log"))
}
fn feed_bind(&self) -> SocketAddr {
self.config.feed.bind
}
}
impl Drop for Service {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// What one running snapshot comes to on the wire.
#[derive(Debug, Clone, PartialEq)]
struct Seen {
header: Value,
attachments: Vec<Vec<u8>>,
}
fn comparable(header: &Value) -> Value {
let mut value = header.clone();
let map = value.as_object_mut().expect("a header is an object");
for key in ["wallMs", "uptimeSeconds", "realtimeFactor", "seq"] {
map.remove(key);
}
if let Some(sugar) = map.get_mut("sugar").and_then(Value::as_object_mut) {
sugar.remove("cooldownMs");
}
for list in ["events", "chat"] {
if let Some(items) = map.get_mut(list).and_then(Value::as_array_mut) {
for item in items {
if let Some(item) = item.as_object_mut() {
item.remove("wallMs");
}
}
}
}
value
}
fn parse(message: &[u8]) -> Seen {
let read = |at: usize| u32::from_le_bytes(message[at..at + 4].try_into().unwrap()) as usize;
let header_len = read(0);
let header: Value = serde_json::from_slice(&message[4..4 + header_len]).unwrap();
let mut at = 4 + header_len;
let mut attachments = Vec::new();
while at < message.len() {
let len = read(at);
attachments.push(message[at + 4..at + 4 + len].to_vec());
at += 4 + len;
}
Seen {
header,
attachments,
}
}
type Ws =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
/// Connect (retrying while nothing listens yet) and say `hello`.
async fn connect(addr: SocketAddr, within: Duration, log: &Path) -> Ws {
let url = format!("ws://{addr}/feed");
let deadline = Instant::now() + within;
loop {
match tokio_tungstenite::connect_async(&url).await {
Ok((mut ws, _)) => {
let hello = serde_json::json!({ "protocol": 1, "client": "feed-bus-test", "wants": ["frame", "audio", "spikes"] });
ws.send(WsMessage::Text(hello.to_string().into()))
.await
.unwrap();
return ws;
}
Err(error) => {
assert!(
Instant::now() < deadline,
"{url}: {error}\n--- {} ---\n{}",
log.display(),
std::fs::read_to_string(log).unwrap_or_default()
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
}
/// Running snapshots (three attachments) by sim frame, until `frames` of them or `within`.
async fn record(ws: &mut Ws, frames: usize, within: Duration) -> BTreeMap<u64, Seen> {
let deadline = tokio::time::Instant::now() + within;
let mut seen = BTreeMap::new();
while seen.len() < frames {
let Ok(Some(Ok(message))) = tokio::time::timeout_at(deadline, ws.next()).await else {
break;
};
if let WsMessage::Binary(bytes) = message {
let snapshot = parse(&bytes);
if snapshot.attachments.len() == 3 {
let frame = snapshot.header["frame"].as_u64().unwrap();
seen.insert(frame, snapshot);
}
}
}
seen
}
fn fresh_dir(root: &Path, seeded: &Path, name: &str) -> PathBuf {
let dir = root.join(name);
seed(seeded, &dir);
dir
}
#[test]
fn the_session_runtime_serves_the_same_feed_over_the_bus() {
let Some(rom) = rom_path() else { return };
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 runtime = tokio::runtime::Runtime::new().unwrap();
const FRAMES: usize = 90;
let within = Duration::from_secs(90);
// Direct: the service binds the feed port itself.
let direct = {
let dir = fresh_dir(root.path(), &seeded, "direct");
let bus = root.path().join("direct-bus");
let mut service = Service::start(
config(&rom, &dataset, &dir, FeedVia::Direct, &bus),
root.path(),
"direct",
);
let recorded = runtime.block_on(async {
let mut ws = connect(
service.feed_bind(),
Duration::from_secs(60),
&service.log(root.path(), "direct"),
)
.await;
record(&mut ws, FRAMES, within).await
});
service.stop();
assert!(!bus.join("edge.sock").exists(), "direct mode opened a bus");
recorded
};
assert!(
direct.len() >= FRAMES,
"direct recorded {} running snapshots",
direct.len()
);
// Bus: the service leaves the feed port to the edge.
let bus_dir = root.path().join("bus");
let bus = {
let dir = fresh_dir(root.path(), &seeded, "bus");
let service_config = config(&rom, &dataset, &dir, FeedVia::Bus, &bus_dir);
let edge_addr = service_config.feed.bind;
let edge_metrics = Arc::new(EdgeMetrics::default());
let edge = EdgeConfig {
retry: Duration::from_millis(100),
..EdgeConfig::from_flysim(&service_config, None)
};
let _edge = runtime.spawn(fly_edge::run(edge, Arc::clone(&edge_metrics)));
let mut service = Service::start(service_config.clone(), root.path(), "bus");
let recorded = runtime.block_on(async {
// Nothing is bound until the edge has its first snapshot, and it is the edge that binds.
let mut ws = connect(
edge_addr,
Duration::from_secs(60),
&root.path().join("bus.log"),
)
.await;
let recorded = record(&mut ws, FRAMES, within).await;
assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1);
recorded
});
service.stop();
// The edge notices, drops its clients and unbinds the port.
let lost = Instant::now();
while edge_metrics.connected.load(Ordering::Relaxed) != 0 {
assert!(
lost.elapsed() < Duration::from_secs(10),
"the edge never saw the bus go"
);
std::thread::sleep(Duration::from_millis(50));
}
assert!(edge_metrics.bus_lost.load(Ordering::Relaxed) >= 1);
// A new instance under the same edge: it reconnects by itself and serves the new router.
let mut again = Service::start(service_config, root.path(), "bus-again");
runtime.block_on(async {
let mut ws = connect(
edge_addr,
Duration::from_secs(60),
&root.path().join("bus-again.log"),
)
.await;
let after = record(&mut ws, 10, within).await;
assert!(
after.len() >= 10,
"after the restart: {} running snapshots",
after.len()
);
});
assert_eq!(edge_metrics.connected.load(Ordering::Relaxed), 1);
again.stop();
recorded
};
assert!(
bus.len() >= FRAMES,
"bus recorded {} running snapshots",
bus.len()
);
// The same frames, the same bytes.
let mut compared = 0;
for (frame, a) in &direct {
let Some(b) = bus.get(frame) else { continue };
assert_eq!(
comparable(&a.header),
comparable(&b.header),
"frame {frame}: header"
);
assert_eq!(a.attachments.len(), b.attachments.len(), "frame {frame}");
for (index, (x, y)) in a.attachments.iter().zip(&b.attachments).enumerate() {
assert!(x == y, "frame {frame}: attachment {index} differs");
}
compared += 1;
}
eprintln!(
"session feed: direct {} and bus {} running snapshots, {compared} frames in common and identical",
direct.len(),
bus.len()
);
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
/// loop -- the workers float over the process's CPUs as they always have.
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 {
/// 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)
}
/// 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
/// 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
@ -448,6 +501,29 @@ impl<'a, T> SharedSlice<'a, T> {
mod tests {
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]
fn every_index_runs_exactly_once() {
for workers in [1usize, 2, 3, 7] {

View file

@ -196,6 +196,13 @@ where
let bus_runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.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()
.build()
.context("building the bus runtime")?;