diff --git a/docs/4-implementation/scheduler/coordinator.md b/docs/4-implementation/scheduler/coordinator.md index fe2b7d7cc..71a8cd66f 100644 --- a/docs/4-implementation/scheduler/coordinator.md +++ b/docs/4-implementation/scheduler/coordinator.md @@ -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=`. At boot the container derives two values from a byte count: -`BUN_JSC_forceRAMSize` (75%, claude-code's heap ceiling) and `MemoryHigh=` on -`hive-subagent-daemon` and on `hive-bash-daemon` (two thirds each; the bash -daemon's covers every bash task, so a build storm throttles before the -container's cap). Neither is in the agent's build, so a +`BUN_JSC_forceRAMSize` (75%, claude-code's heap ceiling) and +`HIVE_RUNS_MEMORY_HIGH` in `hive-subagent-daemon`'s and `hive-bash-daemon`'s +environment (two thirds each). Each daemon writes it to `memory.high` of the +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. `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 diff --git a/hive-agent-sock/src/run_cgroup.rs b/hive-agent-sock/src/run_cgroup.rs index 023fa7526..f6bdc0da6 100644 --- a/hive-agent-sock/src/run_cgroup.rs +++ b/hive-agent-sock/src/run_cgroup.rs @@ -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 `/` 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 `/` 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 //! `/` 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 `/` 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 `//` node run cgroups are created under. +/// The `//` node run cgroups are created under, carrying the +/// runs' shared `memory.high`. #[derive(Debug)] pub struct RunCgroups { parent: PathBuf, } impl RunCgroups { - /// Set up `//` for this process's unit. `None`, with one + /// Set up `//` 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 { + 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 { + fn init_at( + root: &Path, + proc_self_cgroup: &str, + kind: &str, + memory_high: Option, + ) -> io::Result { 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 { + let value = value?; + let parsed = value.parse::().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")); diff --git a/nix/agent-modules/mcp.nix b/nix/agent-modules/mcp.nix index d47f35fc6..9e979ca36 100644 --- a/nix/agent-modules/mcp.nix +++ b/nix/agent-modules/mcp.nix @@ -458,8 +458,9 @@ in # actually chose and leaves the daemon serving, which is also what # lets it report the kill rather than vanish and be restarted. OOMPolicy = "continue"; - # `MemoryHigh=` is a drop-in from ./memory-cap.nix, sized at boot from - # the container's cap. + # The runs' memory ceiling is `HIVE_RUNS_MEMORY_HIGH`, a drop-in from + # ./memory-cap.nix sized at boot from the container's cap. Not + # `MemoryHigh=`: that would throttle the daemon with its runs. User = userName; Group = userName; } diff --git a/nix/agent-modules/memory-cap.nix b/nix/agent-modules/memory-cap.nix index 9b1dc2c43..846d92528 100644 --- a/nix/agent-modules/memory-cap.nix +++ b/nix/agent-modules/memory-cap.nix @@ -19,15 +19,14 @@ # it in login shells that no unit starts (`nixos-container root-login`). # `hive-agent` and `hive-subagent-daemon` spawn `claude` as a plain child, # which inherits it, so neither unit may set or unset it. -# - `MemoryHigh=` on `hive-subagent-daemon` and on `hive-bash-daemon`, two -# thirds of the cap each, as generator drop-ins. Each daemon's cgroup holds -# its children (nested `claude` sessions, bash tasks), so a `cargo` or -# `nix build` storm throttles itself there before the container's -# `MemoryMax=`. `High`, not `Max`: past it the kernel reclaims hard and the -# work slows down, so the last third stays free for the agent's own turn. -# -# Tested by `checks.script-test-agent-memory-cap` and -# `checks.module-eval-agent-memory`. +# - `HIVE_RUNS_MEMORY_HIGH`, two thirds of the cap, in `hive-subagent-daemon`'s +# and `hive-bash-daemon`'s environment (generator drop-ins). Each daemon +# writes it to `memory.high` of the cgroup node holding its runs +# (`run_cgroup` in `hive-agent-sock`), so a `cargo` or `nix build` storm +# throttles itself before the container's `MemoryMax=`. Not `MemoryHigh=` on +# 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`, `checks.module-eval-agent-memory`. { pkgs, ... }: let # 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 dir="$1/$unit.service.d" ${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 ''; @@ -69,7 +68,7 @@ let else why="is missing" 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 ''} ''; diff --git a/nix/script-tests/agent-memory-cap.sh b/nix/script-tests/agent-memory-cap.sh index aa186eb73..a62a24cb7 100644 --- a/nix/script-tests/agent-memory-cap.sh +++ b/nix/script-tests/agent-memory-cap.sh @@ -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" fi -# check +# check # check() { case=$1 @@ -53,8 +53,8 @@ check() { # The subagent daemon and the bash daemon each get one, and nothing else is written. local unit for unit in hive-subagent-daemon hive-bash-daemon; do - got=$(cat "$out/normal/$unit.service.d/50-memory-high.conf" 2>&1) - if [ "$got" != "[Service]"$'\n'"MemoryHigh=$want_high" ]; then + got=$(cat "$out/normal/$unit.service.d/50-runs-memory-high.conf" 2>&1) + if [ "$got" != "[Service]"$'\n'"Environment=HIVE_RUNS_MEMORY_HIGH=$want_high" ]; then fail "unit generator's drop-in for $unit:"$'\n'"$got" fi done @@ -67,7 +67,7 @@ check() { got=$(env -i "$dir/check" 2>&1) local want_warn= 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 if [ "$got" != "$want_warn" ]; then fail "boot check printed:"$'\n'"$got"$'\n'"wanted:"$'\n'"$want_warn"