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
5 changed files with 109 additions and 33 deletions

View file

@ -480,10 +480,12 @@ the last drop-in because it can't read the swarm caps file,
the file carries that drop-in's `MemoryMax=`. the file carries that drop-in's `MemoryMax=`.
At boot the container derives two values from a byte count: At boot the container derives two values from a byte count:
`BUN_JSC_forceRAMSize` (75%, claude-code's heap ceiling) and `MemoryHigh=` on `BUN_JSC_forceRAMSize` (75%, claude-code's heap ceiling) and
`hive-subagent-daemon` and on `hive-bash-daemon` (two thirds each; the bash `HIVE_RUNS_MEMORY_HIGH` in `hive-subagent-daemon`'s and `hive-bash-daemon`'s
daemon's covers every bash task, so a build storm throttles before the environment (two thirds each). Each daemon writes it to `memory.high` of the
container's cap). Neither is in the agent's build, so a cgroup node its runs live in, so a build storm throttles before the
container's cap, and the daemon itself, in a sibling cgroup, is never
throttled for what its runs use. Neither is in the agent's build, so a
changed cap reaches them at the next container start without a rebuild. changed cap reaches them at the next container start without a rebuild.
`infinity` sets neither. A missing or malformed file sets neither as well, and `infinity` sets neither. A missing or malformed file sets neither as well, and
`hyperhive-memory-cap-check.service` logs a warning naming the path in the `hyperhive-memory-cap-check.service` logs a warning naming the path in the

View file

@ -5,6 +5,14 @@
//! `memory.oom.group=1`, so the OOM killer takes a whole run, never part of //! `memory.oom.group=1`, so the OOM killer takes a whole run, never part of
//! one and never the daemon. //! 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 //! systemd enables no controller below a service's own cgroup, so
//! [`RunCgroups::init`] writes `+memory +pids` into the unit's and the //! [`RunCgroups::init`] writes `+memory +pids` into the unit's and the
//! `<kind>/` node's `cgroup.subtree_control` itself. Without that the run //! `<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 CGROUP_ROOT: &str = "/sys/fs/cgroup";
const CONTROLLERS: &str = "+memory +pids"; 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 /// The program [`exec_entry`] execs. Its presence is what makes a process
/// an entry wrapper rather than the daemon. /// an entry wrapper rather than the daemon.
const ENTRY_PROGRAM_ENV: &str = "HIVE_RUN_ENTRY_PROGRAM"; 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. /// How long a killed run cgroup gets to empty before it is left in place.
const KILL_GRACE: Duration = Duration::from_secs(5); 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)] #[derive(Debug)]
pub struct RunCgroups { pub struct RunCgroups {
parent: PathBuf, parent: PathBuf,
} }
impl RunCgroups { 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 /// 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 /// cgroup v2 (a test, a dev shell, a unit without `Delegate=`): runs then
/// stay in the daemon's own cgroup. /// stay in the daemon's own cgroup.
#[must_use] #[must_use]
pub fn init(kind: &str) -> Option<Self> { 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") 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 { match result {
Ok(cgroups) => { Ok(cgroups) => {
tracing::info!(parent = %cgroups.parent.display(), "run cgroups ready"); tracing::info!(parent = %cgroups.parent.display(), "run cgroups ready");
@ -90,7 +105,12 @@ impl RunCgroups {
/// [`RunCgroups::init`] against cgroup2 mounted at `root`, with /// [`RunCgroups::init`] against cgroup2 mounted at `root`, with
/// `proc_self_cgroup` the content of `/proc/self/cgroup`. /// `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 let own = proc_self_cgroup
.lines() .lines()
.find_map(|line| line.strip_prefix("0::")) .find_map(|line| line.strip_prefix("0::"))
@ -113,6 +133,12 @@ impl RunCgroups {
Err(e) => return Err(e), Err(e) => return Err(e),
} }
std::fs::write(parent.join("cgroup.subtree_control"), CONTROLLERS)?; 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; // Runs that outlived the previous daemon's grace leave empty dirs;
// a populated one belongs to a process still alive and stays. // a populated one belongs to a process still alive and stays.
for entry in std::fs::read_dir(&parent)?.flatten() { 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`, /// 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` /// inside `cgroup` when there is one: this daemon's own binary, whose `main`
/// starts with [`exec_entry`]. /// starts with [`exec_entry`].
@ -372,7 +411,7 @@ mod tests {
#[test] #[test]
fn init_enables_controllers_on_the_unit_and_the_kind_node() { fn init_enables_controllers_on_the_unit_and_the_kind_node() {
let (root, unit) = unit_tree(); 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)); assert_eq!(cgroups.parent, unit.join(KIND));
for node in [&unit, &unit.join(KIND)] { for node in [&unit, &unit.join(KIND)] {
let control = 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] #[test]
fn init_refuses_a_process_outside_a_daemon_leaf() { fn init_refuses_a_process_outside_a_daemon_leaf() {
let (root, unit) = unit_tree(); 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"); .expect_err("not a daemon leaf");
assert!(err.to_string().contains(DAEMON_SUBGROUP), "{err}"); assert!(err.to_string().contains(DAEMON_SUBGROUP), "{err}");
assert!(!unit.join("cgroup.subtree_control").exists()); assert!(!unit.join("cgroup.subtree_control").exists());
@ -393,7 +467,7 @@ mod tests {
#[test] #[test]
fn init_refuses_cgroup_v1() { fn init_refuses_cgroup_v1() {
let (root, _unit) = unit_tree(); 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] #[test]
@ -404,7 +478,7 @@ mod tests {
std::fs::create_dir_all(&empty).expect("empty"); std::fs::create_dir_all(&empty).expect("empty");
std::fs::create_dir_all(&populated).expect("populated"); std::fs::create_dir_all(&populated).expect("populated");
std::fs::write(populated.join("cgroup.procs"), "42").expect("procs"); 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!(!empty.exists());
assert!(populated.exists()); assert!(populated.exists());
} }
@ -412,7 +486,7 @@ mod tests {
#[test] #[test]
fn create_sets_oom_group_and_drop_removes_the_dir() { fn create_sets_oom_group_and_drop_removes_the_dir() {
let (root, unit) = unit_tree(); 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 run = cgroups.create("alpha-0").expect("create");
let dir = unit.join(KIND).join("alpha-0"); let dir = unit.join(KIND).join("alpha-0");
assert_eq!(run.dir, dir); assert_eq!(run.dir, dir);
@ -440,7 +514,7 @@ mod tests {
#[test] #[test]
fn a_run_cgroup_kills_its_leftovers_only_when_asked() { fn a_run_cgroup_kills_its_leftovers_only_when_asked() {
let (root, _unit) = unit_tree(); 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 run = cgroups.create("alpha-0").expect("create");
assert!(!run.kill_leftovers); assert!(!run.kill_leftovers);
assert!(run.killing_leftovers().kill_leftovers); assert!(run.killing_leftovers().kill_leftovers);
@ -449,7 +523,7 @@ mod tests {
#[test] #[test]
fn create_replaces_an_empty_leftover_of_the_same_name() { fn create_replaces_an_empty_leftover_of_the_same_name() {
let (root, unit) = unit_tree(); 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"); std::fs::create_dir(unit.join(KIND).join("t1")).expect("leftover");
cgroups.create("t1").expect("create over an empty leftover"); cgroups.create("t1").expect("create over an empty leftover");
} }
@ -457,7 +531,7 @@ mod tests {
#[test] #[test]
fn entry_names_this_binary_and_the_run() { fn entry_names_this_binary_and_the_run() {
let (root, _unit) = unit_tree(); 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 run = cgroups.create("alpha-0").expect("create");
let (program, env) = entry(Path::new("claude"), 1000, Some(&run)); let (program, env) = entry(Path::new("claude"), 1000, Some(&run));
assert_eq!(program, Path::new("/proc/self/exe")); assert_eq!(program, Path::new("/proc/self/exe"));

View file

@ -458,8 +458,9 @@ in
# actually chose and leaves the daemon serving, which is also what # actually chose and leaves the daemon serving, which is also what
# lets it report the kill rather than vanish and be restarted. # lets it report the kill rather than vanish and be restarted.
OOMPolicy = "continue"; OOMPolicy = "continue";
# `MemoryHigh=` is a drop-in from ./memory-cap.nix, sized at boot from # The runs' memory ceiling is `HIVE_RUNS_MEMORY_HIGH`, a drop-in from
# the container's cap. # ./memory-cap.nix sized at boot from the container's cap. Not
# `MemoryHigh=`: that would throttle the daemon with its runs.
User = userName; User = userName;
Group = userName; Group = userName;
} }

View file

@ -19,15 +19,14 @@
# it in login shells that no unit starts (`nixos-container root-login`). # it in login shells that no unit starts (`nixos-container root-login`).
# `hive-agent` and `hive-subagent-daemon` spawn `claude` as a plain child, # `hive-agent` and `hive-subagent-daemon` spawn `claude` as a plain child,
# which inherits it, so neither unit may set or unset it. # which inherits it, so neither unit may set or unset it.
# - `MemoryHigh=` on `hive-subagent-daemon` and on `hive-bash-daemon`, two # - `HIVE_RUNS_MEMORY_HIGH`, two thirds of the cap, in `hive-subagent-daemon`'s
# thirds of the cap each, as generator drop-ins. Each daemon's cgroup holds # and `hive-bash-daemon`'s environment (generator drop-ins). Each daemon
# its children (nested `claude` sessions, bash tasks), so a `cargo` or # writes it to `memory.high` of the cgroup node holding its runs
# `nix build` storm throttles itself there before the container's # (`run_cgroup` in `hive-agent-sock`), so a `cargo` or `nix build` storm
# `MemoryMax=`. `High`, not `Max`: past it the kernel reclaims hard and the # throttles itself before the container's `MemoryMax=`. Not `MemoryHigh=` on
# work slows down, so the last third stays free for the agent's own turn. # the unit, which would throttle the daemon beside its runs too. `High`, not
# # `Max`, so the last third stays free for the agent's own turn.
# Tested by `checks.script-test-agent-memory-cap` and # Tested by `checks.script-test-agent-memory-cap`, `checks.module-eval-agent-memory`.
# `checks.module-eval-agent-memory`.
{ pkgs, ... }: { pkgs, ... }:
let let
# Sets `bytes`. Exits for `infinity`, and runs `noCap` when there is no file # Sets `bytes`. Exits for `infinity`, and runs `noCap` when there is no file
@ -55,7 +54,7 @@ let
for unit in hive-subagent-daemon hive-bash-daemon; do for unit in hive-subagent-daemon hive-bash-daemon; do
dir="$1/$unit.service.d" dir="$1/$unit.service.d"
${pkgs.coreutils}/bin/mkdir -p "$dir" ${pkgs.coreutils}/bin/mkdir -p "$dir"
printf '[Service]\nMemoryHigh=%s\n' "$((bytes * 2 / 3))" > "$dir/50-memory-high.conf" printf '[Service]\nEnvironment=HIVE_RUNS_MEMORY_HIGH=%s\n' "$((bytes * 2 / 3))" > "$dir/50-runs-memory-high.conf"
done done
''; '';
@ -69,7 +68,7 @@ let
else else
why="is missing" why="is missing"
fi fi
echo "<4>/run/hive/memory-max-bytes $why: no BUN_JSC_forceRAMSize heap ceiling and no MemoryHigh= on hive-subagent-daemon or hive-bash-daemon; the host's MemoryMax= on the container still applies." >&2 echo "<4>/run/hive/memory-max-bytes $why: no BUN_JSC_forceRAMSize heap ceiling and no memory ceiling on the subagent and bash daemons' runs; the host's MemoryMax= on the container still applies." >&2
exit 0 exit 0
''} ''}
''; '';

View file

@ -31,7 +31,7 @@ if ! printf '%s\n' "$EXTRA_INIT" | grep -qxF '. /etc/hyperhive/memory-cap.sh'; t
fail "/etc/set-environment does not source the snippet" fail "/etc/set-environment does not source the snippet"
fi fi
# check <description> <expected BUN_JSC_forceRAMSize or ""> <expected MemoryHigh or ""> # check <description> <expected BUN_JSC_forceRAMSize or ""> <expected HIVE_RUNS_MEMORY_HIGH or "">
# <why the boot check warns, or ""> # <why the boot check warns, or "">
check() { check() {
case=$1 case=$1
@ -53,8 +53,8 @@ check() {
# The subagent daemon and the bash daemon each get one, and nothing else is written. # The subagent daemon and the bash daemon each get one, and nothing else is written.
local unit local unit
for unit in hive-subagent-daemon hive-bash-daemon; do for unit in hive-subagent-daemon hive-bash-daemon; do
got=$(cat "$out/normal/$unit.service.d/50-memory-high.conf" 2>&1) got=$(cat "$out/normal/$unit.service.d/50-runs-memory-high.conf" 2>&1)
if [ "$got" != "[Service]"$'\n'"MemoryHigh=$want_high" ]; then if [ "$got" != "[Service]"$'\n'"Environment=HIVE_RUNS_MEMORY_HIGH=$want_high" ]; then
fail "unit generator's drop-in for $unit:"$'\n'"$got" fail "unit generator's drop-in for $unit:"$'\n'"$got"
fi fi
done done
@ -67,7 +67,7 @@ check() {
got=$(env -i "$dir/check" 2>&1) got=$(env -i "$dir/check" 2>&1)
local want_warn= local want_warn=
if [ -n "$want_why" ]; then if [ -n "$want_why" ]; then
want_warn="<4>$cap $want_why: no BUN_JSC_forceRAMSize heap ceiling and no MemoryHigh= on hive-subagent-daemon or hive-bash-daemon; the host's MemoryMax= on the container still applies." want_warn="<4>$cap $want_why: no BUN_JSC_forceRAMSize heap ceiling and no memory ceiling on the subagent and bash daemons' runs; the host's MemoryMax= on the container still applies."
fi fi
if [ "$got" != "$want_warn" ]; then if [ "$got" != "$want_warn" ]; then
fail "boot check printed:"$'\n'"$got"$'\n'"wanted:"$'\n'"$want_warn" fail "boot check printed:"$'\n'"$got"$'\n'"wanted:"$'\n'"$want_warn"