diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index 039b8d0..7989f83 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -589,6 +589,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT # so FLY_ENCODER-style flipping between backends across restarts keeps the # checkpoint: the compatibility string this script gates on does not move. echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" + # Where the session worker writes fly_brain_backend (which hardware runs the + # LIF tick, and the GPU fallback count): the same textfile directory as + # fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA"). + echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom" # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # kill switch: POST /chat answers 403 and the feed header omits `chat`, so # the CHAT panel blanks without touching flybridge or the page. flysim reads diff --git a/infra/bin/fly-watchdog b/infra/bin/fly-watchdog index 2166b49..46cb64d 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -48,6 +48,8 @@ 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}" +# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick. +: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}" : "${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 @@ -175,6 +177,9 @@ write_textfile_metrics() { echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" + echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend." + echo "# TYPE fly_watchdog_backend_degraded gauge" + echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)" # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # is -1 until the first probe completes, the same "unknown, not # broken" convention fly_watchdog_encoder_degraded uses; a value at or @@ -711,6 +716,39 @@ check_encoder() { "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" } +# ============================================================================ +# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the +# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks +# for the card and the CPU is what runs, the GPU fell back (operator decision +# 2026-10-02: automatic, the stream keeps going, logged here, no paging). +# +# Like check 8 this takes NO remediation. A restart cannot repair a dead card +# and costs the run its in-memory state; the fallback is a CPU run from the +# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the +# card to a human. fly_brain_backend is not duplicated into this file's own +# .prom, for the reason check 8 gives. +# ============================================================================ +check_backend() { + local wanted live fallbacks + if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then + # No session worker has written it (the legacy loop, a CPU deploy, or not started yet). + echo -1 > "${WD_RUN_DIR}/backend_degraded" + return 0 + fi + wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + live="$(awk '/^fly_brain_backend\{/ && $NF == 1 { + if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \ + "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then + echo 1 > "${WD_RUN_DIR}/backend_degraded" + log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \ + "Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'" + else + echo 0 > "${WD_RUN_DIR}/backend_degraded" + fi +} + # ============================================================================ # Check 9: capture freeze (infra/docs/capture-freeze.md). # @@ -1333,6 +1371,7 @@ main() { check_flystage check_flycast check_encoder + check_backend check_mediamtx check_flypush check_disk diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 4d6aa75..9d4a0a0 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -1190,15 +1190,40 @@ pct exec -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backe ``` The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables -(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker and does **not** -ignore them: without the feature, or when the backend cannot start, `Agent.Initialize` fails -with `BACKEND_FAILURE`, and the worker logs `LIF backend cuda: attached, device-owned state` -when it starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the +(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without +the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with +`BACKEND_FAILURE`; a build with it logs `LIF backend cuda: attached, device-owned state` when +the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual -drive, plastic gains, about 110 KB) go up and the spike lists come down. A CUDA failure mid-run -fails the agent; a restore into that worker runs on the CPU from the last checkpoint (bit-exact, so nothing is -migrated). Build all binaries with the feature: `FLY_CARGO_FEATURES=cuda` now reaches -`flysim-session`, `fly-shadow` and `fly-session` too. +drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the +feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too. + +**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no +paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches +a dead card in a loop: + +- A CUDA error on a frame whose host state was current (the first frame after a start or a + restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there. +- Any other CUDA error mid-run fails the agent (the device held the only current copy of the + membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on + the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact, + so the CPU run equals one that never had a GPU. +- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and + a CPU worker, not a failed `Agent.Initialize`. +- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still + dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU. + +Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure, +with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs), +`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the +textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and +`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises +`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It +takes no remediation and pages no one (a restart cannot fix a dead card and would cost the +run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host, +and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2` +(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0` +and redeploy if the card is not coming back soon. It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index a04a63d..5a27e8a 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -535,6 +535,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "tempfile", ] [[package]] diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index e414126..89f4e26 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -417,6 +417,10 @@ struct Endpoints { own: Via, store_root: PathBuf, sockets: PathBuf, + /// The GPU fallback record the worker processes share (`flybrain_core::lif::health`): a + /// replacement worker that is a new process must not re-attach a GPU that failed in an + /// earlier one. Emptied when this launcher starts. + gpu_marker: PathBuf, next_socket: AtomicU64, listeners: Mutex>, } @@ -575,6 +579,13 @@ pub fn die_with_parent(command: &mut std::process::Command) { } impl Launcher { + /// GPU failures that moved the LIF tick to the CPU under this launcher: its worker + /// processes' (the marker) and, for workers in this process, this process's. + pub fn gpu_fallbacks(&self) -> u64 { + flybrain_core::lif::health::marker_fallbacks(&self.endpoints.gpu_marker) + .max(flybrain_core::lif::health::fallbacks()) + } + /// Connects the supervisor and prepares the launcher. Nothing is started yet. pub async fn start( router: Router, @@ -588,6 +599,8 @@ impl Launcher { std::fs::create_dir_all(&sockets).map_err(|e| { flybus::BusError::new(flybus::ErrorCode::StoreFailure, format!("sockets: {e}")) })?; + let gpu_marker = sockets.join("lif-gpu-fallbacks"); + flybrain_core::lif::health::reset_marker(&gpu_marker); let endpoints = Endpoints { router, via: mode.transport(via), @@ -597,6 +610,7 @@ impl Launcher { }, store_root: store_root.into(), sockets, + gpu_marker, next_socket: AtomicU64::new(0), listeners: Mutex::new(Vec::new()), }; @@ -1036,6 +1050,7 @@ impl Launcher { .arg(flybrain_core::pool::format_cpu_list(&cpus.sweep)); } } + command.env(flybrain_core::lif::health::MARKER_ENV, &self.endpoints.gpu_marker); command.stdin(std::process::Stdio::null()); die_with_parent(&mut command); let child = command.spawn().map_err(|e| { diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 79174b0..f7d4a02 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -42,6 +42,7 @@ use flybrain_core::envelope::{ agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, }; use flybrain_core::json::JsonValue; +use flybrain_core::lif::health as lif_health; use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version}; use serde_json::{Value, json}; @@ -521,9 +522,6 @@ pub struct LegacyAgentWorker { tick_spikes: Option>, staged: Option, activated: BTreeSet, - /// Set once the GPU backend has failed in this worker: every agent it builds from then on - /// (a restore after the failure) runs on the CPU. - backend_fault: Option, /// Every mutation this worker applied, reported as its progress counter. mutations: u64, /// Reinforcement calls applied since the fly's fresh start; captured. @@ -722,7 +720,6 @@ impl LegacyAgentWorker { prepared: None, transition_start_ms: 0.0, tick_spikes: None, - backend_fault: None, staged: None, activated: BTreeSet::new(), mutations: 0, @@ -877,6 +874,63 @@ impl LegacyAgentWorker { /// Builds a network and readout over `dataset`, before any state is installed, and checks /// every identity the profile pins: kernel and plasticity versions, frame size, rate roles. + /// The backend this agent runs on, attached. A GPU that already failed in this process is + /// not tried again, and one that cannot be attached now (a lost device, a failed CUDA init + /// after a restart) is a fallback to the CPU with a warning, never a failed worker + /// (operator decision, 2026-10-02): the stream keeps going from the same checkpoint, which + /// is backend-neutral. A build without the `cuda` feature that is asked for the GPU is a + /// misconfiguration and still fails `Agent.Initialize`. + /// + /// Each attach builds a new backend (about 57 MiB of device memory) while the agent it + /// replaces may still be alive; harmless on a 24 GB card, to be budgeted when GPU-03 batches + /// flies onto an 8 GB one. + fn attach_backend( + &self, + agent: &mut NeuralAgent, + wanted: LifBackend, + ) -> Result { + let LifBackend::Cuda { .. } = wanted else { + agent.network.set_backend(LifBackend::Cpu).map_err(|e| { + DomainError::before(ErrorCode::BackendFailure, format!("LIF backend cpu: {e}")) + })?; + return Ok(LifBackend::Cpu); + }; + if LifBackend::cuda_compiled() { + if lif_health::gpu_unusable() { + eprintln!( + "legacy agent {}: LIF backend cpu (the GPU failed earlier in this process: {})", + self.config.agent_id, + lif_health::last_reason().unwrap_or_default() + ); + return Ok(LifBackend::Cpu); + } + return match agent.network.set_backend(wanted) { + Ok(()) => Ok(wanted), + Err(e) => { + lif_health::record_fallback(&format!( + "agent {}: attaching {} failed: {e}", + self.config.agent_id, + wanted.label() + )); + Ok(LifBackend::Cpu) + } + }; + } + agent.network.set_backend(wanted).map_err(|e| { + DomainError::before( + ErrorCode::BackendFailure, + format!("LIF backend {}: {e}", wanted.label()), + ) + })?; + Ok(wanted) + } + + /// A GPU failure in this worker: the GPU is out for the process, and the metric says so. + fn gpu_failed(config: &LegacyAgentConfig, reason: &str) { + lif_health::record_fallback(&format!("agent {}: {reason}", config.agent_id)); + lif_health::write_textfile(LifBackend::Cpu, config.lif_backend.clone().unwrap_or_default()); + } + fn build_agent( &self, dataset: Arc, @@ -944,19 +998,10 @@ impl LegacyAgentWorker { // Without the core's `FLY_LIF_CUDA` test hook: the backend is this worker's choice. agent.network.configure_sweep(plan); } - let backend = self.config.lif_backend.clone().map_err(|e| { + let wanted = self.config.lif_backend.clone().map_err(|e| { DomainError::before(ErrorCode::BackendFailure, format!("LIF backend: {e}")) })?; - let backend = match (&self.backend_fault, backend) { - (Some(_), LifBackend::Cuda { .. }) => LifBackend::Cpu, - (_, backend) => backend, - }; - agent.network.set_backend(backend).map_err(|e| { - DomainError::before( - ErrorCode::BackendFailure, - format!("LIF backend {}: {e}", backend.label()), - ) - })?; + let backend = self.attach_backend(&mut agent, wanted)?; if backend != LifBackend::Cpu { eprintln!( "legacy agent {}: LIF backend {} attached, device-owned state", @@ -964,6 +1009,7 @@ impl LegacyAgentWorker { backend.label() ); } + lif_health::write_textfile(backend, wanted); let fingerprint = self.profile.dataset_fingerprint.clone(); let graph = AgentGraph { dataset_digest: dataset_digest(&fingerprint), @@ -1204,19 +1250,19 @@ impl LegacyAgentWorker { // would scan out of `last_spike_ms`. let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)]; if let Err(e) = agent.network.step_frame(ticks, &mut bits) { - eprintln!( - "legacy agent {}: {e}; the agent fails and the next restore runs on the CPU", - self.config.agent_id - ); - self.backend_fault = Some(e.to_string()); + // The device state was the only current copy, so this worker cannot go on: it fails + // and the replacement restores the last checkpoint on the CPU (the GPU is out for + // the process). + Self::gpu_failed(&self.config, &format!("{e}; the agent fails, a replacement restores the last checkpoint on the CPU")); return Err(applied( ErrorCode::BackendFailure, format!("the brain ticks failed: {e}"), )); } if let Some(fault) = agent.network.take_backend_fault() { - eprintln!("legacy agent {}: {fault}", self.config.agent_id); - self.backend_fault = Some(fault); + // The host state was current: the frame finished on the CPU in this call, and this + // worker continues there. + Self::gpu_failed(&self.config, &fault); } self.tick_spikes = Some(bits); drop(ticks_span); @@ -1591,7 +1637,7 @@ impl LegacyAgentWorker { let _span = crate::profile::span("agent.capture.sync_host"); let agent = self.agent.as_mut().expect("initialized"); if let Err(e) = agent.network.sync_host() { - self.backend_fault = Some(e.to_string()); + Self::gpu_failed(&self.config, &format!("device state read-back: {e}")); return Err(applied( ErrorCode::BackendFailure, format!("the device state cannot be read back: {e}"), diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 24d5f41..09ec40c 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -991,6 +991,11 @@ impl LegacyRig { self.launch(agent_id).await } + /// GPU failures so far that moved a worker's LIF tick to the CPU ([`Launcher::gpu_fallbacks`]). + pub fn gpu_fallbacks(&self) -> u64 { + self.launcher.gpu_fallbacks() + } + pub async fn stop(mut self) { self.launcher.reap_all(&id("done")).await; } @@ -1577,12 +1582,53 @@ pub async fn run_on_worker_from_then_capture( Ok((records, captured.expect("a capture was asked for"))) } +/// [`run_on_worker`] with the coordinator's recovery for a failed frame (GPU-02): the agent is +/// Failed, so the last checkpoint (the script's `checkpoints`) is restored into a replacement +/// worker, and the script goes on from the step after it. Returns the records and, for each +/// recovery, the index of the step whose checkpoint was restored. The restore resets the +/// readout's transients by design, so the matching CPU reference is the script with a +/// `ScriptStep::Restore` after that step ([`script_with_restore_after`]). +pub async fn run_on_worker_recovering( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, +) -> Result<(Vec, Vec), String> { + let mut recovered = Vec::new(); + let (records, _) = run_script_with(rig, agent_id, script, None, false, Some(&mut recovered)).await?; + Ok((records, recovered)) +} + +/// `script` with a restore into a fresh agent right after step `at` (an index into `steps`), and +/// its checkpoints moved onto the steps' new positions: the CPU reference for a run that +/// recovered from the checkpoint at `at`. +pub fn script_with_restore_after(script: &LegacyScript, at: usize) -> LegacyScript { + let mut alt = script.clone(); + alt.steps.insert(at + 1, ScriptStep::Restore); + alt.checkpoints = script + .checkpoints + .iter() + .map(|&i| if i > at { i + 1 } else { i }) + .collect(); + alt +} + async fn run_script( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, start: Option<(&flybrain_core::agent::AgentState, u64)>, capture_at_end: bool, +) -> Result<(Vec, Option>), String> { + run_script_with(rig, agent_id, script, start, capture_at_end, None).await +} + +async fn run_script_with( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<(&flybrain_core::agent::AgentState, u64)>, + capture_at_end: bool, + mut recovered: Option<&mut Vec>, ) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { @@ -1594,7 +1640,12 @@ async fn run_script( } }; let mut records = vec![first]; - for (index, step) in script.steps.iter().enumerate() { + // The last checkpoint, for a recovery: (step, records so far, the capture, and the driver + // state a restore returns to). + let mut last_checkpoint: Option<(usize, usize, Captured, u64, TypedValue, RationalNs)> = None; + let mut index = 0usize; + while index < script.steps.len() { + let step = &script.steps[index]; let mut record = match step { ScriptStep::Frame { sugar, @@ -1602,9 +1653,31 @@ async fn run_script( rewards, next_context, } => { - driver + match driver .frame(index + 1, sugar, *frame, rewards, next_context) - .await? + .await + { + Ok(record) => record, + Err(e) if recovered.is_some() && last_checkpoint.is_some() => { + let (at, kept, captured, boundary, context, remainder) = + last_checkpoint.take().expect("checked"); + eprintln!( + "recovery: step {} failed ({e}); restoring the checkpoint after step {at} into a replacement", + index + 1 + ); + driver.boundary = boundary; + driver.context = context.clone(); + driver.remainder = remainder; + let target = rig.replace(agent_id).await?; + driver.restore_into(target, &captured).await?; + records.truncate(kept); + recovered.as_mut().expect("checked").push(at); + last_checkpoint = Some((at, kept, captured, boundary, context, remainder)); + index = at + 1; + continue; + } + Err(e) => return Err(e), + } } ScriptStep::Rollback { frame, context } => { driver.rollback(index + 1, *frame, context).await? @@ -1632,8 +1705,20 @@ async fn run_script( if script.checkpoints.contains(&index) { let captured = driver.capture().await?; record.state = Some(payload_state_digest(&captured.bytes)?); + records.push(record); + last_checkpoint = Some(( + index, + records.len(), + captured, + driver.boundary, + driver.context.clone(), + driver.remainder, + )); + index += 1; + continue; } records.push(record); + index += 1; } let captured = if capture_at_end { Some(driver.capture().await?.bytes) diff --git a/services/flysim/crates/fly-session/tests/cuda_fallback.rs b/services/flysim/crates/fly-session/tests/cuda_fallback.rs new file mode 100644 index 0000000..30e5339 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/cuda_fallback.rs @@ -0,0 +1,256 @@ +//! GPU-02 notes round (N2, operator decision 2026-10-02): a GPU failure on the live brain falls +//! back to the CPU and the session keeps going from the last checkpoint, with no loop re-attaching +//! a dead device. +//! +//! The fault-injection hook (`flybrain_core::lif::cuda::inject`, or `FLY_LIF_CUDA_FAULT` for a +//! worker process) raises a CUDA error where a real one would surface. Against the CPU reference +//! on the real connectome: +//! +//! - **Permanent, mid-run** (the device held the only current state): the agent fails, a +//! replacement worker restores the last checkpoint on the CPU and the records are those of the CPU +//! reference with a restore at that checkpoint -- in-process, and as a process, where the +//! replacement is a new process that must not re-attach the GPU (no second failure). +//! - **Init failure** (a lost device at a restart): `Agent.Initialize` succeeds on the CPU, with +//! a warning and a counted fallback, and a restore into a replacement stays on the CPU. +//! - **Transient** (the host state was current: the first batch): the frame finishes on the CPU in +//! the call, bit-exact, and no recovery is needed; the fallback is counted and the GPU is not +//! re-attached by a later restore. +//! +//! Needs `--features cuda` and `data/fafb-v783`. The cases that run a real device also need +//! `FLY_GPU02_CUDA=1` and a visible card; the init-failure case needs neither. +#![cfg(feature = "cuda")] + +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RewardEvent, + RigAgent, ScriptStep, fafb_dir, frame_pool, +}; +use fly_session::types::id; +use fly_session_types::gameboy::{Location, ReadoutContext}; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use flybrain_core::lif::cuda::inject; +use flybrain_core::lif::health; + +fn pokered_channels() -> Vec { + let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + file["cases"][1]["macroChannels"] + .as_array() + .expect("the Pokemon Red macro group") + .iter() + .map(|c| c.as_str().expect("a channel").to_owned()) + .collect() +} + +/// Frames with sugar and reward pulses, a checkpoint every 25 steps, an optional restore. +fn script(frames: usize, restore_at: Option) -> LegacyScript { + let channels = pokered_channels(); + let bound = |k: usize| -> Vec { + let take: &[usize] = match k % 120 { + 0..20 => &[], + 20..50 => &[0, 1, 9], + _ => &[1, 4, 5, 6], + }; + take.iter().map(|i| channels[*i].clone()).collect() + }; + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k % 97 == 12 { vec![400.0] } else { vec![] }, + frame: k % 6, + rewards: if k % 11 == 0 { + vec![RewardEvent { + value: 0.5, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: ReadoutContext { + boot: k < 10, + bound: bound(k), + location: (k > 5).then_some(Location { + area: 12, + x: 3 + (k / 40) as u32, + y: 7, + }), + }, + }); + if restore_at == Some(k) { + steps.push(ScriptStep::Restore); + } + } + let last = steps.len() - 1; + let checkpoints = (0..steps.len()) + .filter(|i| i % 25 == 24) + .chain([last]) + .collect(); + LegacyScript { + name: "gpu02-fallback".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(6, 783)), + initial_frame: 0, + initial_context: ReadoutContext { + boot: true, + bound: vec![], + location: None, + }, + steps, + checkpoints, + } +} + +fn agent(dir: &std::path::Path, script: &LegacyScript) -> RigAgent { + RigAgent { + agent_id: id("fly-a"), + port_id: id("p1"), + dataset_dir: dir.to_path_buf(), + profile: LegacyProfileKind::Production, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + } +} + +fn reset() { + inject::clear(); + health::reset_for_tests(); +} + +struct Outcome { + records: Vec, + recovered: Vec, + fallbacks: u64, +} + +async fn run(dir: &std::path::Path, script: &LegacyScript, mode: ExecutionMode) -> Outcome { + let root = tempfile::tempdir().expect("tmp"); + let mut rig = LegacyRig::start(root.path(), mode, &[agent(dir, script)]) + .await + .expect("the rig"); + let (records, recovered) = + legacy_parity::run_on_worker_recovering(&mut rig, &id("fly-a"), script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + let fallbacks = rig.gpu_fallbacks(); + rig.stop().await; + Outcome { + records, + recovered, + fallbacks, + } +} + +fn reference(dir: &std::path::Path, script: &LegacyScript) -> Vec { + let dataset = Arc::new(load_brain_dataset_from_dir(dir).expect("the dataset loads")); + DirectSource { dataset } + .records(script) + .expect("the CPU reference runs") +} + +/// The records of the CPU reference with a restore after step `at`, minus that restore's own +/// record (the recovery has none), against what the recovered run recorded. +fn assert_recovered_equals_reference( + dir: &std::path::Path, + script: &LegacyScript, + at: usize, + got: &[ParityRecord], + case: &str, +) { + let alt = legacy_parity::script_with_restore_after(script, at); + let mut want = reference(dir, &alt); + want.remove(at + 2); // records[0] is the first record, step i is records[i + 1] + assert_eq!(want.len(), got.len(), "{case}: record count"); + for (i, (w, g)) in want.iter().zip(got).enumerate() { + let (mut w, mut g) = (w.clone(), g.clone()); + w.index = 0; + g.index = 0; + assert_eq!(w, g, "{case}: record {i} differs from the CPU reference"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_gpu_failure_falls_back_to_the_cpu_and_the_session_continues() { + let Some(dir) = fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let device = std::env::var_os("FLY_GPU02_CUDA").is_some(); + let frames = 120; + // SAFETY: the only test in this binary; no worker (thread or child) exists yet. + unsafe { std::env::set_var("FLY_LIF_CUDA", "1") }; + let plain = script(frames, None); + + // Init failure: a restart whose CUDA init fails. No device needed. + reset(); + inject::fail_attach(true); + let with_restore = script(frames, Some(60)); + let got = run(&dir, &with_restore, ExecutionMode::InProcess).await; + assert!(got.recovered.is_empty(), "nothing failed mid-run"); + assert_eq!(got.fallbacks, 1, "one failed attach; the restore did not try the GPU again"); + legacy_parity::compare(&reference(&dir, &with_restore), &got.records) + .unwrap_or_else(|e| panic!("init failure: {e}")); + assert!(health::gpu_unusable()); + eprintln!("init failure: continued on the CPU, {} records identical", got.records.len()); + + if !device { + eprintln!("skipping the device cases: FLY_GPU02_CUDA is not set"); + reset(); + return; + } + + // Control: the GPU, no fault, no fallback. + reset(); + let started = inject::batches(); + let got = run(&dir, &plain, ExecutionMode::InProcess).await; + // A game frame is one batch; the warm-up before the first frame is many. The faults below + // go off `frames - 50` batches from the run's end: mid-run, never in the warm-up. + let run_batches = inject::batches() - started; + assert!(run_batches > frames as u64); + assert_eq!(got.fallbacks, 0, "the GPU attached"); + legacy_parity::compare(&reference(&dir, &plain), &got.records) + .unwrap_or_else(|e| panic!("control: {e}")); + + // Transient: the first batch (the warm-up) fails with the host state current. The frame + // finishes on the CPU in the call: no recovery, bit-exact, and the GPU stays out. + reset(); + inject::fail_batch_after(0); + let got = run(&dir, &with_restore, ExecutionMode::InProcess).await; + assert!(got.recovered.is_empty(), "the call finished on the CPU"); + assert_eq!(got.fallbacks, 1, "counted once; the restore did not re-attach the GPU"); + legacy_parity::compare(&reference(&dir, &with_restore), &got.records) + .unwrap_or_else(|e| panic!("transient: {e}")); + eprintln!("transient: finished on the CPU in place, {} records identical", got.records.len()); + + // Permanent, mid-run, in-process: the device held the only current state. + reset(); + inject::fail_batch_after(run_batches - 50); + let got = run(&dir, &plain, ExecutionMode::InProcess).await; + assert_eq!(got.recovered.len(), 1, "one recovery, no loop"); + assert_eq!(got.fallbacks, 1); + assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent in-process"); + eprintln!( + "permanent in-process: recovered from the checkpoint after step {}, {} records identical", + got.recovered[0], + got.records.len() + ); + + // Permanent, mid-run, as a process: the replacement is a new process, which must read the + // failure from the launcher's marker. With the fault armed in every process at the same + // batch, a replacement that re-attached the GPU would fail again about 50 frames after the + // restore (its warm-up is the same length, then 50 frames to the same batch). + reset(); + unsafe { std::env::set_var("FLY_LIF_CUDA_FAULT", format!("batch={}", run_batches - 50)) }; + let got = run(&dir, &plain, ExecutionMode::Process).await; + unsafe { std::env::remove_var("FLY_LIF_CUDA_FAULT") }; + assert_eq!(got.recovered.len(), 1, "the replacement process stayed on the CPU"); + assert_eq!(got.fallbacks, 1); + assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent process"); + eprintln!( + "permanent process: recovered from the checkpoint after step {}, {} records identical", + got.recovered[0], + got.records.len() + ); + reset(); +} diff --git a/services/flysim/crates/fly-session/tests/cuda_session.rs b/services/flysim/crates/fly-session/tests/cuda_session.rs index 445180f..a8188f3 100644 --- a/services/flysim/crates/fly-session/tests/cuda_session.rs +++ b/services/flysim/crates/fly-session/tests/cuda_session.rs @@ -11,8 +11,9 @@ //! //! An explicit job: `--features cuda`, `FLY_GPU02_CUDA=1`, a visible device and `data/fafb-v783`. //! `FLY_GPU02_FRAMES` sets the length (default 300 frames, about 5,000 ticks). The worker picks the -//! GPU up from `FLY_LIF_CUDA=1`, set here before any worker starts; a build or a host that cannot -//! attach the backend fails `Agent.Initialize` rather than passing on the CPU. +//! GPU up from `FLY_LIF_CUDA=1`, set here before any worker starts. A host that cannot attach the +//! backend now falls back to the CPU (GPU-02 notes, `cuda_fallback.rs`), so this test asserts that +//! no fallback was recorded: a pass on the CPU would mean nothing. #![cfg(feature = "cuda")] use std::sync::Arc; @@ -156,6 +157,12 @@ async fn the_gpu_worker_matches_the_cpu_reference_on_fafb() { let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) .await .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); + assert_eq!( + rig.gpu_fallbacks(), + 0, + "{} x{threads}: the GPU did not attach, so this ran on the CPU", + mode.label() + ); rig.stop().await; legacy_parity::compare(&want, &got) .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); diff --git a/services/flysim/crates/flybrain-core/Cargo.toml b/services/flysim/crates/flybrain-core/Cargo.toml index e8173f7..c28730f 100644 --- a/services/flysim/crates/flybrain-core/Cargo.toml +++ b/services/flysim/crates/flybrain-core/Cargo.toml @@ -29,6 +29,7 @@ libc = "0.2" [dev-dependencies] base64.workspace = true +tempfile = "3" [[example]] name = "bench" diff --git a/services/flysim/crates/flybrain-core/src/lif.rs b/services/flysim/crates/flybrain-core/src/lif.rs index b761d94..53b0d08 100644 --- a/services/flysim/crates/flybrain-core/src/lif.rs +++ b/services/flysim/crates/flybrain-core/src/lif.rs @@ -21,6 +21,9 @@ use crate::version::version_for; #[cfg(feature = "cuda")] pub mod cuda; +/// Whether the GPU may still be used in this process, and the fallback record. +pub mod health; + /// Version of the default configuration; kept verbatim so existing checkpoints stay loadable. pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2"; @@ -333,7 +336,12 @@ pub struct LifNetwork { /// Version string of this configuration; pin it in checkpoints. pub version: String, pub plasticity: RewardModulatedStdp, + /// Membrane potentials. **Stale while a device-owned GPU backend is attached** and + /// `cuda().is_some_and(|b| b.host_stale())`: the device holds the current copy until + /// [`LifNetwork::sync_host`]. Read it only after a `sync_host`, or use + /// [`LifNetwork::export_state`], which reads the device itself. pub membrane: Vec, + /// Refractory counters; stale on the same terms as `membrane`. pub refractory: Vec, pub baseline: Vec, pub last_spike_ms: Vec, diff --git a/services/flysim/crates/flybrain-core/src/lif/cuda.rs b/services/flysim/crates/flybrain-core/src/lif/cuda.rs index 2287578..280b7fb 100644 --- a/services/flysim/crates/flybrain-core/src/lif/cuda.rs +++ b/services/flysim/crates/flybrain-core/src/lif/cuda.rs @@ -64,6 +64,88 @@ use crate::error::{Error, Result}; use super::LifNetwork; +/// Fault injection for the failure path: a CUDA error raised where a real one would surface, so +/// the fallback can be tested and drilled without breaking a card. Off unless armed. Armed by +/// `FLY_LIF_CUDA_FAULT` (read once, by the first backend built) or by the setters; a comma list of +/// `init` (every attach fails, as with a lost device), `batch=N` (the N-th batch of this process, +/// counted from 0, fails after its kernels ran) and `sync=N` (the N-th device download). +pub mod inject { + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::OnceLock; + + const NEVER: u64 = u64::MAX; + static INIT: AtomicBool = AtomicBool::new(false); + static BATCH_AT: AtomicU64 = AtomicU64::new(NEVER); + static SYNC_AT: AtomicU64 = AtomicU64::new(NEVER); + static BATCHES: AtomicU64 = AtomicU64::new(0); + static SYNCS: AtomicU64 = AtomicU64::new(0); + static ENV: OnceLock<()> = OnceLock::new(); + + pub(super) fn load_env() { + ENV.get_or_init(|| { + let Ok(spec) = std::env::var("FLY_LIF_CUDA_FAULT") else { + return; + }; + for item in spec.split(',').map(str::trim) { + match item.split_once('=') { + None if item == "init" => INIT.store(true, Ordering::SeqCst), + Some(("batch", n)) => BATCH_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst), + Some(("sync", n)) => SYNC_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst), + _ => eprintln!("FLY_LIF_CUDA_FAULT: ignoring {item:?}"), + } + } + }); + } + + /// Every attach fails from now on (a lost device), or stops failing. + pub fn fail_attach(on: bool) { + INIT.store(on, Ordering::SeqCst); + } + /// The batch that is `after` batches from now fails, once. + pub fn fail_batch_after(after: u64) { + BATCH_AT.store(BATCHES.load(Ordering::SeqCst) + after, Ordering::SeqCst); + } + /// The device download that is `after` downloads from now fails, once. + pub fn fail_sync_after(after: u64) { + SYNC_AT.store(SYNCS.load(Ordering::SeqCst) + after, Ordering::SeqCst); + } + /// Batches this process has launched so far (a warm-up is many; a game frame is one). + pub fn batches() -> u64 { + BATCHES.load(Ordering::SeqCst) + } + /// Disarms everything. + pub fn clear() { + INIT.store(false, Ordering::SeqCst); + BATCH_AT.store(NEVER, Ordering::SeqCst); + SYNC_AT.store(NEVER, Ordering::SeqCst); + } + + pub(super) fn attach() -> super::Result<()> { + load_env(); + if INIT.load(Ordering::SeqCst) { + return Err(super::Error::new( + "CUDA init failed: injected fault (CUDA_ERROR_NO_DEVICE)", + )); + } + Ok(()) + } + fn hit(counter: &AtomicU64, at: &AtomicU64, what: &str) -> super::Result<()> { + let n = counter.fetch_add(1, Ordering::SeqCst); + if n == at.load(Ordering::SeqCst) { + return Err(super::Error::new(format!( + "CUDA {what} failed: injected fault #{n} (CUDA_ERROR_LAUNCH_FAILED)" + ))); + } + Ok(()) + } + pub(super) fn batch() -> super::Result<()> { + hit(&BATCHES, &BATCH_AT, "batch") + } + pub(super) fn sync() -> super::Result<()> { + hit(&SYNCS, &SYNC_AT, "download") + } +} + /// Threads per block, and therefore neurons per block in the sweep and the compaction. Must match /// `LIF_BLOCK` in `cuda/lif.cu`, because the spike bitset words are per-warp ballots. const BLOCK: u32 = 256; @@ -262,6 +344,7 @@ impl CudaLif { } pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result { + inject::attach()?; let max_ticks = max_ticks.max(1); let neurons = network.data.meta.neurons; if neurons == 0 { @@ -482,6 +565,7 @@ impl CudaLif { /// Copy `membrane` and `refractory` from the device into the network's host arrays. pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> { + inject::sync()?; self.stream .memcpy_dtoh(&self.membrane, &mut network.membrane[..]) .map_err(|error| driver_error("membrane download", error))?; @@ -499,6 +583,7 @@ impl CudaLif { /// The device's `membrane` and `refractory`, copied out without touching the network: what /// [`LifNetwork::export_state`] reads while the host arrays are stale. pub fn download_state(&self) -> Result<(Vec, Vec)> { + inject::sync()?; let mut membrane = vec![0.0f32; self.neurons]; let mut refractory = vec![0u8; self.neurons]; self.stream @@ -659,6 +744,7 @@ impl CudaLif { self.stream .synchronize() .map_err(|error| driver_error("synchronize", error))?; + inject::batch()?; self.kernel_ms += f64::from( self.batch_start .elapsed_ms(&self.batch_end) diff --git a/services/flysim/crates/flybrain-core/src/lif/health.rs b/services/flysim/crates/flybrain-core/src/lif/health.rs new file mode 100644 index 0000000..dcdcad7 --- /dev/null +++ b/services/flysim/crates/flybrain-core/src/lif/health.rs @@ -0,0 +1,145 @@ +//! Whether this process may use the GPU for the LIF tick, and the record of why it may not. +//! +//! A GPU failure (a batch, a sync or an attach) is final for the process: [`record_fallback`] +//! marks the GPU unusable and every backend chosen afterwards is the CPU, so a dead or flaky +//! device is never re-attached in a loop. A restart is a new process and tries the device again; +//! if that attach fails it is a fallback too, not a crash. Checkpoints are backend-neutral, so +//! the CPU continues from the same state. +//! +//! The state is per process, and a worker that runs as a child process starts with none. The +//! launcher therefore points its children at a marker file ([`MARKER_ENV`]): each fallback +//! appends a line to it, and the file (not the child's memory) is then the record, shared by the +//! launcher's later workers. The launcher empties the file when it starts, which is what ends +//! the fallback with the process that owns it. +//! +//! [`render_prometheus`] and [`write_textfile`] expose it as `fly_brain_backend{backend=..}` and +//! `fly_brain_backend_fallbacks_total` for the watchdog. + +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use super::LifBackend; + +/// The marker file's path, set by the launcher for its worker processes. +pub const MARKER_ENV: &str = "FLY_LIF_GPU_MARKER"; + +/// Where [`write_textfile`] puts the metrics, if set: a node_exporter textfile-collector file. +pub const PROM_ENV: &str = "FLY_BRAIN_BACKEND_PROM"; + +/// The log line's stable prefix: what `fly-watchdog` and `fly-check` grep for. +pub const LOG_PREFIX: &str = "LIF_GPU_FALLBACK"; + +static FALLBACKS: AtomicU64 = AtomicU64::new(0); +static LAST_REASON: Mutex> = Mutex::new(None); + +fn marker() -> Option { + std::env::var_os(MARKER_ENV) + .filter(|path| !path.is_empty()) + .map(PathBuf::from) +} + +fn marker_lines(path: &Path) -> Vec { + std::fs::read_to_string(path) + .map(|text| text.lines().map(str::to_owned).collect()) + .unwrap_or_default() +} + +/// Empties the marker: the launcher calls this when it starts, so a fallback lasts as long as the +/// process that owns the workers and not across a restart. +pub fn reset_marker(path: &Path) { + let _ = std::fs::remove_file(path); +} + +/// Marks the GPU unusable for this process lifetime, counts the fallback and logs it as one +/// `LIF_GPU_FALLBACK` line on stderr (the journal). +pub fn record_fallback(reason: &str) { + let reason = reason.replace(['\n', '\r'], " "); + FALLBACKS.fetch_add(1, Ordering::SeqCst); + *LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = Some(reason.clone()); + if let Some(path) = marker() { + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + let _ = writeln!(file, "{reason}"); + } + } + eprintln!("{LOG_PREFIX}: the GPU is unusable for this process, the LIF tick runs on the CPU from here on: {reason}"); +} + +/// True once any fallback was recorded, here or (with a marker) by a sibling worker. +pub fn gpu_unusable() -> bool { + fallbacks() > 0 +} + +/// Fallbacks recorded: the marker's lines when there is a marker, else this process's count. +pub fn fallbacks() -> u64 { + match marker() { + Some(path) => marker_lines(&path).len() as u64, + None => FALLBACKS.load(Ordering::SeqCst), + } +} + +/// The fallbacks recorded in the marker file at `path` (what a launcher's worker processes wrote). +pub fn marker_fallbacks(path: &Path) -> u64 { + marker_lines(path).len() as u64 +} + +/// The latest fallback's reason. +pub fn last_reason() -> Option { + match marker() { + Some(path) => marker_lines(&path).pop(), + None => LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()).clone(), + } +} + +/// Clears this process's record (tests only; a marker is cleared with [`reset_marker`]). +#[doc(hidden)] +pub fn reset_for_tests() { + FALLBACKS.store(0, Ordering::SeqCst); + *LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// Prometheus text: which backend runs (`1` on exactly one of the two labels), which one was +/// asked for, and the fallbacks so far. +pub fn render_prometheus(active: LifBackend, wanted: LifBackend) -> String { + let on = |backend: &str, is: bool| { + format!("fly_brain_backend{{backend=\"{backend}\"}} {}\n", u8::from(is)) + }; + let cuda = matches!(active, LifBackend::Cuda { .. }); + let mut out = String::new(); + out.push_str("# HELP fly_brain_backend 1 for the hardware the LIF tick runs on, 0 for the other. cpu while FLY_LIF_CUDA=1 asks for cuda means the GPU fell back.\n# TYPE fly_brain_backend gauge\n"); + out.push_str(&on("cpu", !cuda)); + out.push_str(&on("cuda", cuda)); + out.push_str(&format!( + "# HELP fly_brain_backend_wanted 1 when FLY_LIF_CUDA=1 asks for the GPU.\n# TYPE fly_brain_backend_wanted gauge\nfly_brain_backend_wanted {}\n", + u8::from(matches!(wanted, LifBackend::Cuda { .. })) + )); + out.push_str(&format!( + "# HELP fly_brain_backend_fallbacks_total GPU failures that moved the LIF tick to the CPU (a failed batch or sync, or an attach that failed) since the process started.\n# TYPE fly_brain_backend_fallbacks_total counter\nfly_brain_backend_fallbacks_total {}\n", + fallbacks() + )); + out +} + +/// Writes [`render_prometheus`] to [`PROM_ENV`] (temp file and rename), if set. A failure is +/// reported on stderr and otherwise ignored: a metric must not stop the brain. +pub fn write_textfile(active: LifBackend, wanted: LifBackend) { + let Some(path) = std::env::var_os(PROM_ENV).filter(|p| !p.is_empty()) else { + return; + }; + let path = PathBuf::from(path); + let tmp = path.with_extension(format!("prom.{}", std::process::id())); + let text = render_prometheus(active, wanted); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let written = std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &path)); + if let Err(error) = written { + let _ = std::fs::remove_file(&tmp); + eprintln!("lif backend metric: cannot write {}: {error}", path.display()); + } +} diff --git a/services/flysim/crates/flybrain-core/tests/gpu_health.rs b/services/flysim/crates/flybrain-core/tests/gpu_health.rs new file mode 100644 index 0000000..557c647 --- /dev/null +++ b/services/flysim/crates/flybrain-core/tests/gpu_health.rs @@ -0,0 +1,57 @@ +//! The GPU fallback record (`lif::health`): one failure makes the GPU unusable for the process, +//! it is counted and logged once per failure, a marker file carries it to sibling worker +//! processes, and the metric text names the backend that runs. + +use flybrain_core::lif::LifBackend; +use flybrain_core::lif::health; + +#[test] +fn a_failure_marks_the_gpu_unusable_and_is_exported() { + // The only test in this binary: it owns the process-wide record and the environment. + health::reset_for_tests(); + assert!(!health::gpu_unusable()); + assert_eq!(health::fallbacks(), 0); + + let cuda = LifBackend::Cuda { device: 0 }; + let before = health::render_prometheus(cuda, cuda); + assert!(before.contains("fly_brain_backend{backend=\"cuda\"} 1")); + assert!(before.contains("fly_brain_backend{backend=\"cpu\"} 0")); + assert!(before.contains("fly_brain_backend_fallbacks_total 0")); + + health::record_fallback("device lost\nsecond line"); + assert!(health::gpu_unusable()); + assert_eq!(health::fallbacks(), 1); + assert_eq!(health::last_reason().as_deref(), Some("device lost second line")); + let after = health::render_prometheus(LifBackend::Cpu, cuda); + assert!(after.contains("fly_brain_backend{backend=\"cpu\"} 1")); + assert!(after.contains("fly_brain_backend{backend=\"cuda\"} 0")); + assert!(after.contains("fly_brain_backend_wanted 1")); + assert!(after.contains("fly_brain_backend_fallbacks_total 1")); + + // With a marker the file is the record: a sibling process's failure counts here, and + // resetting it (a new launcher) ends the fallback. + let dir = tempfile::tempdir().expect("tmp"); + let marker = dir.path().join("lif-gpu-fallbacks"); + let prom = dir.path().join("fly_brain_backend.prom"); + // SAFETY: single test in this binary, no other thread reads the environment. + unsafe { + std::env::set_var(health::MARKER_ENV, &marker); + std::env::set_var(health::PROM_ENV, &prom); + } + assert!(!health::gpu_unusable(), "an empty marker is a clean slate"); + std::fs::write(&marker, "from a worker process\n").expect("marker"); + assert!(health::gpu_unusable()); + assert_eq!(health::fallbacks(), 1); + health::record_fallback("second"); + assert_eq!(health::fallbacks(), 2); + assert_eq!(health::marker_fallbacks(&marker), 2); + health::write_textfile(LifBackend::Cpu, cuda); + let text = std::fs::read_to_string(&prom).expect("textfile"); + assert!(text.contains("fly_brain_backend_fallbacks_total 2"), "{text}"); + health::reset_marker(&marker); + assert!(!health::gpu_unusable()); + unsafe { + std::env::remove_var(health::MARKER_ENV); + std::env::remove_var(health::PROM_ENV); + } +}