Skip to content

Bound Nested Claude Sessions' Tool-Call Scopes as One Tree and Reap Their Orphans - #2599

Merged
ptr727 merged 5 commits into
developfrom
feature/wsl-1903
Oct 8, 2026
Merged

ptr727 merged 5 commits into
developfrom
feature/wsl-1903

Conversation

@ptr727

@ptr727 ptr727 commented Oct 8, 2026

Copy link
Copy Markdown
Owner

Summary

Closes on promotion: #1903

A claude session started from a tool call ran its own tool calls in fresh scopes, so a chain of agents calling agents had no total ceiling. Stopping the parent's scopes killed the nested claude before its own SessionEnd sweep ran, which left its scopes running unreported. This bounds the chain as one tree and reaps what it orphans, without the rejected design from #1900 of running nested tool calls inside the parent's scope.

Tree ceiling (tool-containment.py).

  • Every tool-call scope joins claude-tree-<root session>.slice. The root's id reaches nested sessions as AGENT_CONTAINMENT_ROOT, which the prefix puts in every contained command's environment, so a nested claude and its own tool calls inherit it. Each scope keeps its own name and its own ceiling.
  • The tree's ceiling is put on the slice with systemctl --user set-property --runtime before the first scope joins. Later calls see the slice's cgroup and skip that step, so the steady-state cost is one stat. If setting the ceiling fails, the command still runs under its own scope's ceiling, stays out of the uncapped slice, and prints why.
  • The id's dashes are dropped from the slice name, since a dash is a slice-hierarchy level and would leave a chain of empty parent slices for every root.
  • Each scope's description records the pid of the agent that ran it, found as the nearest claude ancestor of the prefix. That record is the usable test the issue comment asked for.

Ceiling values. 32768 tasks and 50% of RAM for the tree, against 8192 and 25% per scope, overridable as AGENT_CONTAINMENT_TREE_TASKS_MAX and AGENT_CONTAINMENT_TREE_MEMORY_MAX.

  • Memory at twice a scope's. One heavy build alone meets its own scope's ceiling first and never trips the tree's out-of-memory kill. That kill is the rejected design's failure mode, because it picks the largest process in the tree, and that could be a nested claude. It takes at least two scopes at full use together to reach it, and then the largest process is most likely a build.
  • Tasks at four times a scope's. That leaves room for several parallel workers each building, and still ends a recursive chain about 128 times below this host's pid_max. The incident in A Probe's Self-Recursive Command Shim Ran Unbounded and Unreaped, Taking Down the Host #1890 reached about 568k processes.
  • Your call. The tree's 50% applies to a whole orchestration run, parallel claude -p workers included, so a run that fans out heavy builds shares it. The override is there if that proves tight.

Orphan reaping (stray-process-sweep.py).

  • After stopping its own scopes, the SessionEnd sweep re-reads the process table. That stop is what killed any nested agent. The sweep then stops each scope in its tree whose recorded agent is gone, or whose pid now runs something else, and names that scope's session id. Each stop can end an agent nested a level deeper, so the sweep reads the table again and repeats, up to four rounds and within 20 seconds of the hook's 35-second timeout. A scope it runs out of rounds or time for is reported with its stop line. A scope whose agent still runs is left alone. A scope recording no agent, started by an older prefix, is never stopped. An unreadable process table stops nothing.
  • Only a session that was handed no root ends its tree. It stops the slice and reverts its drop-ins once nothing is left in it. Otherwise it names what keeps the tree in place: another session's scope whose agent still runs, or one recording no agent. A nested session's sweep clears its tree's orphans but never ends the root's slice.
  • Slice membership comes from each scope's Slice property. systemctl show -p ConsistsOf on a slice does not list its scopes, which an earlier iteration of this branch hit on this host when its slice stop ended a nested scope unreported.
  • stray-process-sweep.py --orphans is a read-only, machine-wide report for a session that ended with no sweep at all. It lists each scope whose agent is gone, grouped by tree, with the session id and a stop line, and lists unrecorded scopes apart as unknown. Exit 0 means clean, 1 means a finding, and 2 means it could not check. The kit README now points the maintainer at it instead of at "stop only the ones whose session has ended".

Tests. Both hooks' self-tests gain the tree matrix. test_install.py now runs both self-tests (POSIX only), so CI covers them, since before this change only the guard's self-test ran there.

Follow-Up

Local Strict Review

Four passes ran. The first found four things. A chain two levels deep left its deepest scopes unreported, now fixed by the round loop. The tree-ending guard was too loose, and is now if inherited. The hook's time budget was at risk, now bounded by a deadline. And requirement 9 had drifted, now #2598. The second pass found the root's report calling a just-orphaned scope live, now fixed. The third found a docstring nit, now fixed, and the fourth found nothing.

Verification (WSL2, Debian 13, systemd 257)

Simulated chain: a fake root agent (a claude-named symlink to python3) runs a tool call through this branch's prefix. That call starts a fake nested agent, which sets its own session id and runs a setsid sleep tool call. All ids are constructed.

claude-tool-f1903aaa-...-0001-<pid>-<rand>.scope  Claude Code command, agent pid <root agent>
claude-tool-f1903bbb-...-0002-<pid>-<rand>.scope  Claude Code command, agent pid <nested agent>
$ systemctl --user show -p TasksMax -p MemoryMax claude-tree-f1903aaa000040008000000000000001.slice
MemoryMax=33638129664
TasksMax=32768
(each scope: Slice=claude-tree-f1903aaa000040008000000000000001.slice, TasksMax=8192, MemoryMax=16819064832)
# root SessionEnd sweep
agent-safety: stopped 1 command scope this session left running.
agent-safety: stopped 1 command scope in this session's tree that a session which has since ended left running.
  claude-tool-f1903bbb-...-0002-<pid>-<rand>.scope  1 process  session f1903bbb-0000-4000-8000-000000000002, agent pid <nested agent> gone
    pid <n>  age 3s  sleep 117

Afterwards, no claude-tree-f1903* slice, scope, or drop-in remained, and pgrep found nothing.

The crash case killed the nested agent with SIGKILL and ran no sweep. --orphans then reported the nested scope under tree claude-tree-f1903aaa...slice, with its session id, agent pid ... gone, and its sleep. It exited 1 and handed over systemctl --user stop <scope>, and that line, plus stop and revert on the slice, cleared everything.

  • Overhead: 28.2 ms against 24.6 ms per contained call for the installed prefix (20-call mean), from the agent lookup in /proc and the slice stat.
  • Both self-tests pass, also with os.getuid and os.posix_spawn removed to stand in for Windows. test_install.py passes, 157 tests. Mutation checks on the new cases were all caught, the round loop, the root guard, the deadline, and the live-scope report included.
  • ruff format, ruff check, mypy, the prose gate (with comments), markdownlint, cspell, editorconfig, and the eol check are clean.

🤖 Generated with Claude Code

ptr727 and others added 4 commits October 8, 2026 14:46
Every tool-call scope now joins a slice named for the root session of
its chain of nested claude sessions, carrying a total ceiling of 32768
tasks and 50% of RAM, while each scope keeps its own 8192 and 25%. The
root id travels to nested sessions in AGENT_CONTAINMENT_ROOT.

Each scope records the pid of the agent that ran it. The SessionEnd
sweep stops scopes in its tree whose agent is gone, naming the nested
session, and the root ends its empty tree and reverts the ceiling.
`stray-process-sweep.py --orphans` reports, read-only, every scope on
the machine whose agent is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sweep judged agent liveness once, so a scope whose agent ended
only when a shallower orphan was stopped stayed running unreported.
It now re-reads the process table after each stop, up to four rounds,
inside a 20 second share of the hook's timeout, and names each stopped
scope from the table read before its stop.

Only a session handed no root ends its tree, and the root reports
another session's live scope that keeps the tree in place. README
sentences are shortened and the stop's bound is stated consistently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The root's report listed every scope left in its tree as belonging to
a running session, including ones it had just judged ended and those
recording no agent. It now names a scope as live only where its
recorded agent runs, lists scopes recording no agent apart, and claims
neither when the process table could not be read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI lite review requested due to automatic review settings October 8, 2026 22:02
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Oct 8, 2026
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: Repository: ptr727/ProjectTemplate/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6f7a0514-2eed-469e-a16f-8557b3d5ab05
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.85%. Comparing base (1ff98e3) to head (57fb491).
⚠️ Report is 4 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2599   +/-   ##
========================================
  Coverage    58.85%   58.85%           
========================================
  Files           16       16           
  Lines         8181     8181           
========================================
  Hits          4815     4815           
  Misses        3366     3366           
Flag Coverage Δ
python-3.13 58.85% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved cleanup deadline, PID reuse, failed-read handling, and missing-tree issues remain.

3 open findings
What changed in this PR

Extends Claude tool containment across nested session trees with shared ceilings and orphan cleanup.

Changes:

  • Adds root propagation and tree-wide task/memory limits.
  • Reaps nested orphan scopes and adds --orphans reporting.
  • Expands self-tests and operational documentation.

Outstanding findings affect deadline enforcement, PID reuse, incomplete property reads, and missing-tree handling in stray-process-sweep.py.

File Summary
host-setup/​agent-safety/​claude/​tool-containment.py Implements tree slices, aggregate limits, root propagation, and agent tracking.
host-setup/​agent-safety/​claude/​test_install.py Runs both hook self-tests on POSIX.
host-setup/​agent-safety/​claude/​stray-process-sweep.py Reaps and reports orphaned scopes; has unresolved review findings.
host-setup/​agent-safety/​claude/​README.md Documents tree containment and orphan recovery.

🧠 Review effort: Lite


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

A tool-call scope `systemctl show` did not answer for has no known
slice, and reading it as outside the tree could let the root end a
tree still holding it, so an incomplete answer is a failure to list.
Every systemctl call the tree phase makes now runs inside its share
of the hook's time, and one cut short stops nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727

ptr727 commented Oct 8, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 57fb491f78e832036265f889591dded640cc1e28, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@ptr727
ptr727 merged commit a1efe40 into develop Oct 8, 2026
13 checks passed
ptr727 added a commit that referenced this pull request Oct 8, 2026
…es (#2601)

## Summary

Promotes develop to main.

- #2600: count a finding a Copilot overview names only in its `Review
findings:` prose list, in `pr_review.py`.
- #2599: bound nested Claude sessions' tool-call scopes as one tree and
reap their orphans.

Fixes #2283
Fixes #1903

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@ptr727
ptr727 deleted the feature/wsl-1903 branch October 8, 2026 22:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants