Watch
0
0
Fork
You've already forked hyperhive
0

subagent and bash daemons: the runs' memory ceiling sits on their cgroup node, not on the unit

This commit is contained in:
damocles 2026-11-26 14:22:57 +01:00
commit 897f8af77d

View file

@ -5,6 +5,14 @@
//! `memory.oom.group=1`, so the OOM killer takes a whole run, never part of
//! one and never the daemon.
//!
//! The memory ceiling is on the `<kind>/` node, not on the unit:
//! `memory.high` throttles every task below the cgroup it is set on, so on the
//! unit it would throttle the daemon in `daemon/` for what its runs use, and a
//! heavy build in a run would stall the MCP handshake. On `<kind>/` the runs
//! throttle together and the daemon, in its sibling leaf, does not. The value
//! comes in `HIVE_RUNS_MEMORY_HIGH` (bytes; `nix/agent-modules/memory-cap.nix`
//! sets it from the container's cap at boot).
//!
//! systemd enables no controller below a service's own cgroup, so
//! [`RunCgroups::init`] writes `+memory +pids` into the unit's and the
//! `<kind>/` node's `cgroup.subtree_control` itself. Without that the run
@ -35,6 +43,10 @@ const DAEMON_SUBGROUP: &str = "daemon";
const CGROUP_ROOT: &str = "/sys/fs/cgroup";
const CONTROLLERS: &str = "+memory +pids";
/// The byte count [`RunCgroups::init`] writes to the `<kind>/` node's
/// `memory.high`; no or an invalid value leaves the node unthrottled.
const MEMORY_HIGH_ENV: &str = "HIVE_RUNS_MEMORY_HIGH";
/// The program [`exec_entry`] execs. Its presence is what makes a process
/// an entry wrapper rather than the daemon.
const ENTRY_PROGRAM_ENV: &str = "HIVE_RUN_ENTRY_PROGRAM";
@ -58,21 +70,24 @@ const RELEASE_POLL: Duration = Duration::from_millis(250);
/// How long a killed run cgroup gets to empty before it is left in place.
const KILL_GRACE: Duration = Duration::from_secs(5);
/// The `<unit>/<kind>/` node run cgroups are created under.
/// The `<unit>/<kind>/` node run cgroups are created under, carrying the
/// runs' shared `memory.high`.
#[derive(Debug)]
pub struct RunCgroups {
parent: PathBuf,
}
impl RunCgroups {
/// Set up `<unit>/<kind>/` for this process's unit. `None`, with one
/// Set up `<unit>/<kind>/` for this process's unit, throttled at
/// `$HIVE_RUNS_MEMORY_HIGH` bytes if that is set. `None`, with one
/// warning, when this process is not in a delegated `daemon/` leaf on
/// cgroup v2 (a test, a dev shell, a unit without `Delegate=`): runs then
/// stay in the daemon's own cgroup.
#[must_use]
pub fn init(kind: &str) -> Option<Self> {
let memory_high = memory_high_from(std::env::var(MEMORY_HIGH_ENV).ok().as_deref());
let result = std::fs::read_to_string("/proc/self/cgroup")
.and_then(|own| Self::init_at(Path::new(CGROUP_ROOT), &own, kind));
.and_then(|own| Self::init_at(Path::new(CGROUP_ROOT), &own, kind, memory_high));
match result {
Ok(cgroups) => {
tracing::info!(parent = %cgroups.parent.display(), "run cgroups ready");
@ -90,7 +105,12 @@ impl RunCgroups {
/// [`RunCgroups::init`] against cgroup2 mounted at `root`, with
/// `proc_self_cgroup` the content of `/proc/self/cgroup`.
fn init_at(root: &Path, proc_self_cgroup: &str, kind: &str) -> io::Result<Self> {
fn init_at(
root: &Path,
proc_self_cgroup: &str,
kind: &str,
memory_high: Option<u64>,
) -> io::Result<Self> {
let own = proc_self_cgroup
.lines()
.find_map(|line| line.strip_prefix("0::"))
@ -113,6 +133,12 @@ impl RunCgroups {
Err(e) => return Err(e),
}
std::fs::write(parent.join("cgroup.subtree_control"), CONTROLLERS)?;
// Always written: a node left by an earlier daemon keeps its limit
// otherwise, after the cap that set it has gone.
let high = memory_high.map_or_else(|| "max".to_owned(), |bytes| bytes.to_string());
if let Err(e) = std::fs::write(parent.join("memory.high"), high) {
tracing::warn!(error = %e, "run cgroups: memory.high not set; runs are not throttled");
}
// Runs that outlived the previous daemon's grace leave empty dirs;
// a populated one belongs to a process still alive and stays.
for entry in std::fs::read_dir(&parent)?.flatten() {
@ -181,6 +207,19 @@ impl RunCgroup {
}
}
/// `memory.high` from the environment's text: a plain byte count, nothing else.
fn memory_high_from(value: Option<&str>) -> Option<u64> {
let value = value?;
let parsed = value.parse::<u64>().ok().filter(|bytes| *bytes > 0);
if parsed.is_none() {
tracing::warn!(
value,
"{MEMORY_HIGH_ENV} is not a byte count; runs are not throttled"
);
}
parsed
}
/// The program and extra environment that run `program` at `oom_score_adj`,
/// inside `cgroup` when there is one: this daemon's own binary, whose `main`
/// starts with [`exec_entry`].
@ -372,7 +411,7 @@ mod tests {
#[test]
fn init_enables_controllers_on_the_unit_and_the_kind_node() {
let (root, unit) = unit_tree();
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
assert_eq!(cgroups.parent, unit.join(KIND));
for node in [&unit, &unit.join(KIND)] {
let control =
@ -381,10 +420,45 @@ mod tests {
}
}
#[test]
fn the_runs_node_carries_the_ceiling_and_the_unit_and_daemon_leaf_do_not() {
let (root, unit) = unit_tree();
RunCgroups::init_at(root.path(), OWN, KIND, Some(5_726_623_061)).expect("init");
let high = |node: &Path| std::fs::read_to_string(node.join("memory.high")).ok();
assert_eq!(high(&unit.join(KIND)).as_deref(), Some("5726623061"));
assert_eq!(
high(&unit),
None,
"the daemon's own cgroup stays unthrottled"
);
assert_eq!(high(&unit.join(DAEMON_SUBGROUP)), None);
}
#[test]
fn without_a_ceiling_a_limit_an_earlier_daemon_left_is_lifted() {
let (root, unit) = unit_tree();
std::fs::create_dir_all(unit.join(KIND)).expect("node");
std::fs::write(unit.join(KIND).join("memory.high"), "1000").expect("old limit");
RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
assert_eq!(
std::fs::read_to_string(unit.join(KIND).join("memory.high")).expect("written"),
"max"
);
}
#[test]
fn the_ceiling_is_a_plain_positive_byte_count() {
assert_eq!(memory_high_from(Some("5726623061")), Some(5_726_623_061));
assert_eq!(memory_high_from(None), None);
for bad in ["", "0", "8G", "-1", "1.5", "infinity", " 100"] {
assert_eq!(memory_high_from(Some(bad)), None, "{bad:?}");
}
}
#[test]
fn init_refuses_a_process_outside_a_daemon_leaf() {
let (root, unit) = unit_tree();
let err = RunCgroups::init_at(root.path(), "0::/system.slice/x.service\n", KIND)
let err = RunCgroups::init_at(root.path(), "0::/system.slice/x.service\n", KIND, None)
.expect_err("not a daemon leaf");
assert!(err.to_string().contains(DAEMON_SUBGROUP), "{err}");
assert!(!unit.join("cgroup.subtree_control").exists());
@ -393,7 +467,7 @@ mod tests {
#[test]
fn init_refuses_cgroup_v1() {
let (root, _unit) = unit_tree();
assert!(RunCgroups::init_at(root.path(), "1:memory:/x\n", KIND).is_err());
assert!(RunCgroups::init_at(root.path(), "1:memory:/x\n", KIND, None).is_err());
}
#[test]
@ -404,7 +478,7 @@ mod tests {
std::fs::create_dir_all(&empty).expect("empty");
std::fs::create_dir_all(&populated).expect("populated");
std::fs::write(populated.join("cgroup.procs"), "42").expect("procs");
RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
assert!(!empty.exists());
assert!(populated.exists());
}
@ -412,7 +486,7 @@ mod tests {
#[test]
fn create_sets_oom_group_and_drop_removes_the_dir() {
let (root, unit) = unit_tree();
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
let run = cgroups.create("alpha-0").expect("create");
let dir = unit.join(KIND).join("alpha-0");
assert_eq!(run.dir, dir);
@ -440,7 +514,7 @@ mod tests {
#[test]
fn a_run_cgroup_kills_its_leftovers_only_when_asked() {
let (root, _unit) = unit_tree();
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
let run = cgroups.create("alpha-0").expect("create");
assert!(!run.kill_leftovers);
assert!(run.killing_leftovers().kill_leftovers);
@ -449,7 +523,7 @@ mod tests {
#[test]
fn create_replaces_an_empty_leftover_of_the_same_name() {
let (root, unit) = unit_tree();
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
std::fs::create_dir(unit.join(KIND).join("t1")).expect("leftover");
cgroups.create("t1").expect("create over an empty leftover");
}
@ -457,7 +531,7 @@ mod tests {
#[test]
fn entry_names_this_binary_and_the_run() {
let (root, _unit) = unit_tree();
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND).expect("init");
let cgroups = RunCgroups::init_at(root.path(), OWN, KIND, None).expect("init");
let run = cgroups.create("alpha-0").expect("create");
let (program, env) = entry(Path::new("claude"), 1000, Some(&run));
assert_eq!(program, Path::new("/proc/self/exe"));