Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions crates/axe-core/src/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -197,6 +202,9 @@ pub struct Status {
pub admitting: bool,
/// Why new sessions are paused; null while admitting.
pub reason: Option<String>,
/// 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.
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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::<Vec<_>>()
.join("; ")
}

fn publish(&self, reason: Option<String>) {
fn publish(&self, reason: Option<String>, 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()),
Expand Down Expand Up @@ -929,7 +964,8 @@ pub fn remove_hold(path: &Path) -> Result<bool> {
}

/// 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() {
Expand All @@ -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);
}
}
52 changes: 49 additions & 3 deletions crates/axe-node/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let text = std::fs::read_to_string("/proc/self/cgroup").ok()?;
unit_of_cgroup(&text)
}

fn unit_of_cgroup(text: &str) -> Option<String> {
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()
}
Expand Down Expand Up @@ -188,6 +209,8 @@ pub struct Dispatcher {
/// The server refused bot operations (an older server); logged once.
bots_unsupported: bool,
drain: Option<Drain>,
/// When the admission report first saw the drain flag (RFC3339).
drain_since: Option<String>,
/// The runtimes runs go to, with their health (`runtime.rs`).
runtimes: Registry,
/// Cards to the owner not yet accepted by the server.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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<String>; 4] {
Expand Down
5 changes: 4 additions & 1 deletion crates/axe-server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions crates/axe/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,12 @@ fn admission_wait(a: &Value) -> Option<String> {
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")
Expand Down
98 changes: 93 additions & 5 deletions crates/axe/tests/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
Expand Down Expand Up @@ -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)",
Expand Down
Loading
Loading