diff --git a/crates/axe-core/src/admission.rs b/crates/axe-core/src/admission.rs index 2cfe88f..bcf15c0 100644 --- a/crates/axe-core/src/admission.rs +++ b/crates/axe-core/src/admission.rs @@ -19,6 +19,11 @@ //! if it had been constrained, so it must reach its resume threshold. Admission //! is open only while every signal is clear. //! +//! A node that started less than `cpu_window_seconds` ago has no CPU window +//! yet: that unknown is reported as "node restarting", not as pressure, and the +//! status carries `restarting` while it is the only cause (the server's pause +//! wake ignores it, see `watch_pause`). +//! //! Bot runs are not held by that pause. They stop only at a hard floor derived //! from the same thresholds: disk or memory below half its pause threshold, or //! unreadable. CPU never holds bots, and the floor has no hysteresis. @@ -197,6 +202,9 @@ pub struct Status { pub admitting: bool, /// Why new sessions are paused; null while admitting. pub reason: Option, + /// True while the only cause of the pause is the CPU window of a node + /// that just started ("node restarting"): not a pressure pause. + pub restarting: bool, /// Whether new bot runs may start (the hard floor, see the module docs). pub bots_admitting: bool, /// Why bot runs are held at the floor; null while admitting bots. @@ -221,6 +229,7 @@ pub fn handle(resources: Option<&Resources>) -> Handle { enabled: false, admitting: true, reason: None, + restarting: false, bots_admitting: true, bots_reason: None, checked_at: None, @@ -231,6 +240,7 @@ pub fn handle(resources: Option<&Resources>) -> Handle { enabled: true, admitting: false, reason: Some("not sampled yet".into()), + restarting: false, bots_admitting: false, bots_reason: Some("not sampled yet".into()), checked_at: None, @@ -260,6 +270,7 @@ pub fn view(h: &Handle) -> Value { ); status.admitting = false; status.reason = Some(stale.clone()); + status.restarting = false; status.bots_admitting = false; status.bots_reason = Some(stale); } @@ -301,6 +312,7 @@ pub fn reported(report: Option<&(Value, Instant)>) -> Value { let why = json!(format!("unknown: dispatcher last reported {since}s ago")); v["admitting"] = Value::Null; v["reason"] = why.clone(); + v["restarting"] = json!(false); if bots { v["bots_admitting"] = Value::Null; v["bots_reason"] = why; @@ -312,6 +324,7 @@ pub fn reported(report: Option<&(Value, Instant)>) -> Value { let why = json!(format!("status stale: dispatcher last checked {age}s ago")); v["admitting"] = json!(false); v["reason"] = why.clone(); + v["restarting"] = json!(false); if bots { v["bots_admitting"] = json!(false); v["bots_reason"] = why; @@ -523,6 +536,11 @@ impl Gate { let was = self.admitting; self.admitting = self.signals.iter().all(|s| s.level == Level::Clear); let reason = (!self.admitting).then(|| self.reason()); + let restarting = !self.admitting + && self + .signals + .iter() + .all(|s| s.level == Level::Clear || self.restarting(s)); let floor_was = self.bot_floor.is_none(); self.bot_floor = self.floor_reason(); for line in changes { @@ -540,7 +558,13 @@ impl Gate { None => (self.emit)("axe admission: admitting bot runs"), } } - self.publish(reason); + self.publish(reason, restarting); + } + + /// Whether `s` is unknown only because the node started less than a CPU + /// window ago. + fn restarting(&self, s: &Signal) -> bool { + s.kind == Kind::Cpu && s.level == Level::Unknown && self.warming_up() } /// Why bot runs are held: disk or memory unreadable, or below half its @@ -605,16 +629,27 @@ impl Gate { self.signals .iter() .filter(|s| s.level != Level::Clear) - .map(|s| describe(&self.cfg, s, &self.path)) + .map(|s| { + if self.restarting(s) { + format!( + "node restarting: cpu window warming up ({} of {} s)", + self.clock.now().saturating_sub(self.started).as_secs(), + self.cfg.cpu_window_seconds + ) + } else { + describe(&self.cfg, s, &self.path) + } + }) .collect::>() .join("; ") } - fn publish(&self, reason: Option) { + fn publish(&self, reason: Option, restarting: bool) { let status = Status { enabled: true, admitting: self.admitting, reason, + restarting, bots_admitting: self.bot_floor.is_none(), bots_reason: self.bot_floor.clone(), checked_at: Some(crate::db::now()), @@ -929,7 +964,8 @@ pub fn remove_hold(path: &Path) -> Result { } /// Applies a hold to an admission view: `admitting` goes false with the hold -/// first in `reason`; bot fields are untouched. Always sets `hold`. +/// first in `reason` (so it is no longer a restart-only pause); bot fields +/// are untouched. Always sets `hold`. pub fn apply_hold(view: &mut Value, hold: &HoldState) { view["hold"] = hold.json(); if let Some(why) = hold.reason() { @@ -942,5 +978,6 @@ pub fn apply_hold(view: &mut Value, hold: &HoldState) { }; view["admitting"] = json!(false); view["reason"] = json!(reason); + view["restarting"] = json!(false); } } diff --git a/crates/axe-node/src/dispatch.rs b/crates/axe-node/src/dispatch.rs index f09dc41..a93fc88 100644 --- a/crates/axe-node/src/dispatch.rs +++ b/crates/axe-node/src/dispatch.rs @@ -66,6 +66,27 @@ impl NoPick { } } +/// The admission reason while the node drains (SIGUSR1). +fn drain_reason(unit: Option<&str>, since: &str) -> String { + match unit { + Some(u) => format!("node draining for a restart ({u}) since {since}"), + None => format!("node draining for a restart since {since}"), + } +} + +/// This process's systemd unit (`axe-node.service`), from the last component +/// of its cgroup v2 path; `None` outside a service. +fn node_unit() -> Option { + let text = std::fs::read_to_string("/proc/self/cgroup").ok()?; + unit_of_cgroup(&text) +} + +fn unit_of_cgroup(text: &str) -> Option { + let path = text.lines().find_map(|l| l.strip_prefix("0::"))?; + let last = path.trim_end().rsplit('/').next()?; + last.ends_with(".service").then(|| last.to_string()) +} + fn now_unix() -> i64 { time::OffsetDateTime::now_utc().unix_timestamp() } @@ -188,6 +209,8 @@ pub struct Dispatcher { /// The server refused bot operations (an older server); logged once. bots_unsupported: bool, drain: Option, + /// When the admission report first saw the drain flag (RFC3339). + drain_since: Option, /// The runtimes runs go to, with their health (`runtime.rs`). runtimes: Registry, /// Cards to the owner not yet accepted by the server. @@ -447,6 +470,7 @@ impl Dispatcher { stt_dir: crate::transcribe::default_dir(), bots_unsupported: false, drain: None, + drain_since: None, runtimes, alerts: Vec::new(), alert_failed: false, @@ -1151,17 +1175,20 @@ impl Dispatcher { let mut view = admission::view(&self.admission); admission::apply_hold(&mut view, &hold); if draining { - // A drain admits no new task session either: say so first. - let why = "node draining for a restart"; + // A drain admits no new task session either: say so first, with + // the unit and since when, so it is not taken for pressure. + let since = self.drain_since.get_or_insert_with(db::now).clone(); + let why = drain_reason(node_unit().as_deref(), &since); let reason = match view["reason"] .as_str() .filter(|_| view["admitting"] == false) { Some(r) => format!("{why}; {r}"), - None => why.to_string(), + None => why, }; view["admitting"] = json!(false); view["reason"] = json!(reason); + view["restarting"] = json!(false); view["draining"] = json!(true); } view["pools"] = self.pools(); @@ -2263,6 +2290,25 @@ mod tests { s.parse().unwrap() } + /// The drain reason names the node's unit and since when it drains. + #[test] + fn drain_reason_names_the_unit_and_start() { + let cg = "0::/user.slice/user-1000.slice/user@1000.service/app.slice/axe-node.service\n"; + let unit = unit_of_cgroup(cg); + assert_eq!(unit.as_deref(), Some("axe-node.service")); + assert_eq!( + drain_reason(unit.as_deref(), "2026-12-01T23:31:12Z"), + "node draining for a restart (axe-node.service) since 2026-12-01T23:31:12Z" + ); + // A shell or session scope is no unit name worth reporting. + assert_eq!(unit_of_cgroup("0::/user.slice/session-3.scope\n"), None); + assert_eq!(unit_of_cgroup("12:cpu:/x.service\n"), None); + assert_eq!( + drain_reason(None, "T"), + "node draining for a restart since T" + ); + } + /// The argv a fresh, resumed and bot run of built-in agent `agent` /// renders, as `spawn` and `bots::spawn_bot` build it (no rule model). fn golden_argv(cfg: &Config, agent: &str) -> [Vec; 4] { diff --git a/crates/axe-server/src/server.rs b/crates/axe-server/src/server.rs index 43b2f98..fce5fbe 100644 --- a/crates/axe-server/src/server.rs +++ b/crates/axe-server/src/server.rs @@ -2040,7 +2040,10 @@ const PAUSE_RECHECK: std::time::Duration = std::time::Duration::from_secs(30); /// task once for the episode (a keyed wake), naming the cause. fn watch_pause(st: &State) -> Result<()> { let view = st.admission(); - let paused = view["admitting"] == false; + // A node that just started has no CPU window yet ("node restarting"): it + // is not a pressure pause, so it neither starts nor continues an episode + // (a drain's episode ends there instead of waking with the warm-up text). + let paused = view["admitting"] == false && view["restarting"] != true; let due = { let mut p = st.pause.lock().unwrap_or_else(|e| e.into_inner()); if !paused { diff --git a/crates/axe/src/cli.rs b/crates/axe/src/cli.rs index 6844d1a..49e887d 100644 --- a/crates/axe/src/cli.rs +++ b/crates/axe/src/cli.rs @@ -1130,6 +1130,12 @@ fn admission_wait(a: &Value) -> Option { if a["enabled"] != true || a["admitting"] == true { return None; } + if a["restarting"] == true { + return Some(format!( + "{}; starts automatically once the node has a CPU window", + a["reason"].as_str().unwrap_or("node restarting") + )); + } Some(format!( "resource admission paused ({}); starts automatically when pressure clears", a["reason"].as_str().unwrap_or("unknown") diff --git a/crates/axe/tests/admission.rs b/crates/axe/tests/admission.rs index 7927294..5adee22 100644 --- a/crates/axe/tests/admission.rs +++ b/crates/axe/tests/admission.rs @@ -304,10 +304,14 @@ fn startup_is_unknown_until_a_full_cpu_window_and_band_values_must_recover() { assert!(!g.check()); assert_eq!(level(&g, "cpu"), "unknown"); assert_eq!(level(&g, "memory"), "constrained"); - assert!(admission::view(&g.handle())["reason"] - .as_str() - .unwrap() - .contains("warming up (0 of 60 s window)")); + let v = admission::view(&g.handle()); + assert_eq!( + v["reason"], + "memory 17.0% available (pause < 15% available, resume > 20% available); \ + node restarting: cpu window warming up (0 of 60 s)" + ); + // Memory in its band is a real pause, not only a restart. + assert_eq!(v["restarting"], false); rig.run(&mut g, 50, 10); assert_eq!(level(&g, "cpu"), "unknown"); rig.run(&mut g, 10, 10); @@ -319,6 +323,90 @@ fn startup_is_unknown_until_a_full_cpu_window_and_band_values_must_recover() { assert!(g.admitting()); } +/// A node that just started pauses for its first CPU window, reported as +/// "node restarting" (not pressure) until the window is full. +#[test] +fn startup_warm_up_reads_node_restarting_not_pressure() { + let rig = Rig::default(); + let mut g = rig.gate(defaults()); + assert!(!g.check()); + let v = admission::view(&g.handle()); + assert_eq!( + (&v["admitting"], &v["restarting"], &v["reason"]), + ( + &false.into(), + &true.into(), + &"node restarting: cpu window warming up (0 of 60 s)".into() + ) + ); + // The signal row keeps its own reading. + assert_eq!(v["signals"][2]["reading"], "warming up (0 of 60 s window)"); + rig.run(&mut g, 30, 10); + let v = admission::view(&g.handle()); + assert_eq!(v["restarting"], true); + assert_eq!( + v["reason"], + "node restarting: cpu window warming up (30 of 60 s)" + ); + // A real cause during the warm-up makes it a pressure pause again. + rig.set_disk(Ok(GIB)); + rig.run(&mut g, 10, 10); + let v = admission::view(&g.handle()); + assert_eq!(v["restarting"], false); + assert!( + v["reason"] + .as_str() + .unwrap() + .ends_with("; node restarting: cpu window warming up (40 of 60 s)"), + "{v}" + ); + rig.set_disk(Ok(100 * GIB)); + rig.run(&mut g, 20, 10); + let v = admission::view(&g.handle()); + assert_eq!( + (&v["admitting"], &v["restarting"]), + (&true.into(), &false.into()) + ); + // Past the warm-up, a CPU gap is no restart. + rig.set_cpu_error(Some("no /proc/stat")); + rig.run(&mut g, 10, 10); + let v = admission::view(&g.handle()); + assert_eq!( + (&v["admitting"], &v["restarting"]), + (&false.into(), &false.into()) + ); + assert!( + v["reason"] + .as_str() + .unwrap() + .starts_with("cpu unknown: unavailable"), + "{v}" + ); +} + +/// A hold on a restarting node is not a restart-only pause. +#[test] +fn a_hold_clears_restarting() { + let rig = Rig::default(); + let mut g = rig.gate(defaults()); + g.check(); + let mut v = admission::view(&g.handle()); + assert_eq!(v["restarting"], true); + let hold = admission::HoldState::Active(admission::Hold { + until: "2999-01-01T00:00:00Z".into(), + reason: Some("roll".into()), + set_at: None, + set_by: None, + task: Some(7), + }); + admission::apply_hold(&mut v, &hold); + assert_eq!(v["restarting"], false); + assert!(v["reason"] + .as_str() + .unwrap() + .starts_with("admission hold until 2999-01-01T00:00:00Z (roll); node restarting")); +} + #[test] fn unavailable_readings_pause_and_must_recover_past_resume() { let rig = Rig::default(); @@ -442,7 +530,7 @@ fn repeated_samples_log_transitions_only() { [ "axe admission: disk unknown -> clear: disk /fake/workspace 100.0 GiB free (pause < 15 GiB free)", "axe admission: memory unknown -> clear: memory 50.0% available (pause < 15% available)", - "axe admission: paused new sessions: cpu unknown: warming up (0 of 60 s window) (resume < 80% busy over 60 s)", + "axe admission: paused new sessions: node restarting: cpu window warming up (0 of 60 s)", // CPU warming up never holds bot runs. "axe admission: admitting bot runs", "axe admission: cpu unknown -> clear: cpu 10.0% busy over 60 s (pause > 90% busy over 60 s)", diff --git a/crates/axe/tests/admission_dispatch.rs b/crates/axe/tests/admission_dispatch.rs index 039cbd8..9da2c3c 100644 --- a/crates/axe/tests/admission_dispatch.rs +++ b/crates/axe/tests/admission_dispatch.rs @@ -811,13 +811,13 @@ fn deferred_fallback_slot_is_held_and_released_on_resolution_or_shutdown() { (&false.into(), &true.into()), "{a}" ); + let reason = a["reason"].as_str().unwrap(); assert!( - a["reason"] - .as_str() - .unwrap() - .starts_with("node draining for a restart; disk "), + reason.starts_with("node draining for a restart") && reason.contains(" since 20"), "{a}" ); + assert!(reason.contains("; disk "), "{a}"); + assert_eq!(a["restarting"], false, "{a}"); let t = task(&env, id4); assert_eq!((t.state.as_str(), t.claimed_by), ("escalated", None)); let _ = id; @@ -1324,6 +1324,77 @@ fn a_lapsed_hold_tells_its_holder_task_and_bot() { d.shutdown().unwrap(); } +/// A node that just started waits for its CPU window ("node restarting"): +/// not a pressure pause, so however long it lasts no bot is woken; a real +/// cause on top of it is one and wakes. +#[test] +fn a_restarting_node_is_no_pause_episode() { + let (env, cfg) = env( + 1, + &format!("bots = 1\n{BOT_AGENTS}\n[server]\npause_wake_seconds = 1"), + ); + let mut conn = env.conn(); + add_bot(&env, "b1"); + let t1 = add(&mut conn, "pending", &[]); + let c = db::Changes { + owner: Some("bot:b1".into()), + ..Default::default() + }; + db::set_task(&mut conn, &Actor::new("human"), t1, &c).unwrap(); + let rig = Rig::default(); + // A window far longer than the test: the node stays restarting. + let mut res = defaults(); + res.cpu_window_seconds = 100_000; + let gate = rig.gate(res); + let mut d = live(&env, cfg, gate); + let pause_wakes = || -> Vec { + axe::bot::wakes(&env.conn(), "b1", false, 100) + .unwrap() + .into_iter() + .map(|w| w.body) + .filter(|b| b.starts_with("Task admission paused for ")) + .collect() + }; + let pass = |d: &mut Live, millis: u64| { + let end = Instant::now() + Duration::from_millis(millis); + while Instant::now() < end { + rig.advance(10); + d.poll().unwrap(); + std::thread::sleep(Duration::from_millis(200)); + } + }; + pass(&mut d, 3000); + let a = d.srv.get("/api/admission"); + assert_eq!( + (&a["admitting"], &a["restarting"]), + (&false.into(), &true.into()), + "{a}" + ); + assert!( + a["reason"] + .as_str() + .unwrap() + .starts_with("node restarting: cpu window warming up ("), + "{a}" + ); + assert!(admissions(&conn).is_empty()); + assert!(pause_wakes().is_empty(), "{:?}", pause_wakes()); + // `axe task show` says why the task waits. + let show = d.srv.ok(&["task", "show", &t1.to_string()]); + assert!( + show.contains("\nwaiting: node restarting: cpu window warming up ("), + "{show}" + ); + rig.set_disk(Ok(10 * GIB)); + pass(&mut d, 3000); + let w = pause_wakes(); + assert_eq!(w.len(), 1, "{w:?}"); + assert!(w[0].contains("disk /fake/workspace 10.0 GiB free"), "{w:?}"); + assert!(w[0].contains("node restarting"), "{w:?}"); + env.go(); + d.shutdown().unwrap(); +} + /// A pause lasting past `[server] pause_wake_seconds` wakes the owning bot /// of each ready pending task once for the episode, naming the cause and its /// tasks; a new episode wakes again. diff --git a/docs/user/concepts/architecture.md b/docs/user/concepts/architecture.md index f38619b..a90d51f 100644 --- a/docs/user/concepts/architecture.md +++ b/docs/user/concepts/architecture.md @@ -65,7 +65,10 @@ gate's hard floor, so a full task queue never delays a bot's reply. Waiting tasks stay `pending` and spend nothing. `axe admission show`, `axe task show` and `axe task list` show why; a pause or hold lasting past `[server] pause_wake_seconds` (10 min) wakes the owning bot of each ready task once per -episode, naming the cause (`server.rs` `watch_pause`). +episode, naming the cause (`server.rs` `watch_pause`). A draining node reports +`node draining for a restart () since