Skip to content

feat(core): machine resource guard for delegated children - #626

Merged
ajianaz merged 4 commits into
developfrom
feat/resource-guard
Nov 12, 2026
Merged

ajianaz merged 4 commits into
developfrom
feat/resource-guard

Conversation

@ajianaz

@ajianaz ajianaz commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What

Part 1 of the delegation server-load guard: a new tole-core module, resource_guard, that decides whether a delegated child may start on this machine. It also adds the eight thresholds as [delegation] keys in the user config. This PR does not wire anything into delegate.rs; that is part 2.

Why

Owner requirement: delegation must never overload or crash the server, automatically. That applies to the orchestrator (depth 0) and the agent below it (depth 1), the two levels that can spawn at the default max_depth 2.

Today nothing in the delegation code reads memory, load, disk or process ids. max_live_processes counts only the Running nodes of ONE goal, so two sessions or goals can each run 8 children. This sandbox has run out of disk from build directories several times, so the risk is real.

Changes

  • tole-core/src/resource_guard.rs (new):
    • Probe trait: memory, load, disk(path) and pids, each returning Option. Tests use fixed probes, so every decision is deterministic.

    • Thresholds and their defaults:

      • min_free_memory_mb 1024
      • child_memory_mb 512
      • max_load_per_cpu 1.5
      • min_free_disk_mb 2048
      • min_free_pids_percent 10
      • spawn_interval_secs 2
      • machine_max_live max(2, CPUs)
      • child_nice 10
    • Thresholds::with(&Overrides): applies config values and bounds-checks every key. Zero, negative and absurd values are errors naming delegation.<key>.

    • Thresholds::admit(probe, Census, paths) -> Admit::{Go, Wait { reason }}: a Wait is a queue decision, never an error. It checks, in order:

      • the machine-wide live count against machine_max_live (all goals and sessions);
      • the gap since the last start against spawn_interval_secs;
      • memory, which must cover min_free_memory_mb + child_memory_mb × (children still ramping + 1): a child that started but has not used its memory yet is reserved;
      • the one-minute load per CPU;
      • the free share of process ids;
      • free disk on every path given (data dir, workspace, worktree dir).

      The first failing check gives the reason, for example queued: memory 612 MB free < 1536 MB needed.

    • Unreadable probes: a probe that cannot be read is skipped, never treated as fail-closed or as plenty. startup_notes returns ONE note naming the skipped checks, plus one line for each probe note (such as the memory.stat fallback).

    • LinuxProbe, with pure parse functions tested on fixtures:

      • memory: under a cgroup v2 limit, memory.max minus the WORKING SET, as Kubernetes counts it: memory.current less inactive_file of memory.stat (the file field when inactive_file is absent). memory.current includes reclaimable page cache, so after builds or checkouts it sits near the limit and limit − current would queue every spawn forever. If memory.stat is unreadable, the guard falls back to the conservative limit − current and says so in a startup note (new Probe::notes, default empty). With no limit (max), it uses MemAvailable. When both are known, the smaller headroom wins. The cgroup path comes from /proc/self/cgroup 0::. The pure parse_memory_stat_inactive_file and memory_from_files hold the logic.
      • load: /proc/loadavg.
      • disk: statvfs f_bavail, not f_bfree.
      • pids: cgroup pids.max/pids.current, else /proc/sys/kernel/pid_max against the THREADS in /proc (/proc/<pid>/task entries; pid_max bounds thread ids too). The free share uses saturating_mul.
    • apply_child_nice(cmd, nice): a pre-exec setpriority to max(the parent's niceness, child_nice). It never lowers niceness, and a failure never stops the spawn. It is unix only and a no-op elsewhere. The wiring PR will call it.

  • tole-cli/src/config.rs:
    • The eight keys join DelegationConfig. That table is already user layer only: a project config is ignored and shown as IGNORED in config check.
    • DelegationConfig::resource_thresholds(); config parsing validates through Thresholds::with.
    • config check renders the keys. None of the names contains a secret-like word.
  • Docs: a README config row, a threat-model section "Delegation resource guard", and a CHANGELOG entry.

Testing

All run locally on ee5c855 (develop is still 3850b5e, #623, already merged in), with CARGO_TARGET_DIR set and CARGO_INCREMENTAL=0.

  • cargo test --workspace --no-fail-fast passes: 1531 passed, 0 failed (83 suites).
  • cargo test -p tole-core --no-default-features passes: 532 passed, 0 failed.
  • cargo test -p tole-cli --no-default-features passes: 445 passed, 0 failed.
  • cargo fmt --all -- --check passes.
  • cargo clippy --workspace --all-targets -- -D warnings passes, and so do cargo clippy -p tole-core --no-default-features --all-targets and cargo clippy -p tole-cli --no-default-features.
  • cora review --no-llm --base origin/develop (cora v0.20.0): "No issues found". The LLM review is CI Cora Review.
  • Smoke test on this Linux sandbox:
    • the_linux_probe_reads_this_machine: memory, load, disk of the temp dir and pids are all readable, and a missing path is None.
    • a_child_runs_at_least_at_the_child_niceness: a spawned cat /proc/self/stat runs at niceness max(ours, 10), and at ours with 0.

New tests:

  • resource_guard::tests (21):
    • a boundary pair for every threshold (memory 1536/1535, load 1.50/1.51 per CPU, disk 2048/2047 on the second path, pids 900/901 of 1000, interval 2s/1s, live 3/4);
    • a ramping child's reserve making the second start wait;
    • zero CPUs counted as one;
    • a clock that went backwards waits;
    • unreadable probes: skipped, one note, and the remaining rules still apply;
    • bounds for every override;
    • each parse function on real-looking fixtures, including cgroup max, a hybrid v1/v2 /proc/self/cgroup, and a container limit below host memory;
    • the working set: a 4 GiB limit with 3.9 GiB current, of which 3.0 GiB is inactive_file, gives about 3.1 GiB of headroom and a child is admitted; the same current with inactive_file 0 waits; a missing or garbled memory.stat takes the conservative path and the note reaches startup_notes; a memory.stat without inactive_file uses file;
    • a u64::MAX pid limit does not overflow;
    • the live Linux probe, and child niceness.
  • config::tests::delegation_resource_keys_are_bounded_and_user_layer_only: every key mapped, bad values (zero, negative, out of range, non-numbers) rejected, a project config ignored, and config check rendering.

Red/green: each rule was broken on purpose, the named test was seen failing, the file was restored, and the test passed again. All 23 mutants were killed:

Broken variant Result
machine live count ignored killed
spawn interval ignored killed
ramping children not reserved killed
new child not reserved killed
load boundary > → >= killed
load check removed killed
pids check removed killed
pids boundary off by one killed
only the first disk path checked killed
disk boundary off by one killed
memory boundary off by one killed
cgroup limit ignored killed
cgroup max read as unparsable killed
startup note forgets disk killed
override bounds not checked killed
load override bound not checked killed
child nice not applied killed
config skips the guard bounds killed
page cache counted as used (the pre-fix math) killed
no file fallback in memory.stat killed
no conservative-path note killed
probe notes dropped from startup_notes killed
pid share multiply unsaturated killed

Size: 1,251 lines, which is over the ~900 target; the working-set fix added about 200. Roughly half is tests. If CI Cora cannot complete, the config keys (119 lines) can move into the part 2 wiring PR.

Related Issues

Follow-up to #585 (epic #583) and #623; owner requirement for delegation. Part 2 will wire the guard into Delegator::delegate and the drain, add a machine-wide live registry (ledger file store plus lease liveness in the data dir), add tole doctor lines, and add queued_reason and waited_secs to delegate replies (so a stuck queue is visible to the orchestrator and in tole doctor).

Checklist

  • Branch name follows convention (feat/resource-guard)
  • Branch is from develop
  • Commit messages follow Conventional Commits
  • No secrets or credentials committed
  • One logical change per PR

New tole-core module resource_guard (owner requirement: delegation must
not overload or crash the server). Thresholds::admit answers Go, or Wait
with a reason (a queue decision, never an error), from a Probe and a
machine-wide census: live delegated children across all goals and
sessions, the gap since the last start, free memory over a floor plus a
reserve per child still ramping up (cgroup v2 memory.max/current when a
limit is set, else MemAvailable; the smaller headroom wins), the
one-minute load per CPU, free process ids (cgroup pids.max, else
pid_max) and free disk for an unprivileged user on each checked path
(statvfs f_bavail). An unreadable probe is skipped with one startup
note. apply_child_nice starts a delegated child at niceness child_nice,
never below the parent's. The eight thresholds are [delegation] keys of
the user config only, bounded; the delegate tool wiring follows.
# Conflicts:
#	CHANGELOG.md
#	docs/threat-model.md
memory.current includes reclaimable page cache. After heavy file IO
(builds, git, checkouts) a container sits near memory.max while most of
it is inactive file cache, which the kernel frees only under pressure:
limit - current then reads about zero, every spawn queues and the queue
never drains. Headroom under a cgroup limit is now limit minus the
working set, memory.current less inactive_file of memory.stat (the file
field when inactive_file is absent), as Kubernetes counts it. When
memory.stat is unreadable the guard keeps the conservative
limit - current and says so in a startup note (new Probe::notes).

Also: the pid_max fallback counts threads (/proc/<pid>/task), since
pid_max bounds thread ids too, and the free pids share uses
saturating_mul.
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

✅ No issues found. Code looks good!


Review powered by cora-code · BYOK · MIT

@ajianaz
ajianaz merged commit 85472d2 into develop Nov 12, 2026
25 of 28 checks passed
@ajianaz
ajianaz deleted the feat/resource-guard branch November 20, 2026 08:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants