Skip to content

fix(exec): stop runaway Linux host command memory usage - #182111

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-child-memory-bound-20260919
Oct 24, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-child-memory-bound-20260919

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A runaway Linux Gateway exec child can exhaust host memory before the global OOM killer intervenes. Existing OOM-score adjustment changes victim preference, but does not bound allocation.

User Impact

Linux Gateway-hosted foreground, background, and live PTY command trees get an RSS-plus-swap watchdog. The default limit is the smallest of 8 GiB, one quarter of physical/cgroup-constrained memory, and half the memory remaining after the Gateway's resident usage. A sample over the bound immediately requests the existing tree-kill operation and returns memory-limit, observed usage, the bound, and recovery advice. Background polling/logs retain that explanation. No new config, dependency, or service changes.

This is sampled protection, not hard containment. The one-second interval allows overshoot; concurrent commands have independent budgets and shared pages may be counted repeatedly. Non-PTY commands retain a descendant owner. Reparented PTY daemons are outside the live ancestry monitor; use supervised non-PTY background execution for long-running work. Remote host=node, Codex-native shell commands, non-Linux hosts, and sandbox backends are outside this watchdog.

Design and Simplification

The existing supervisor owns cancellation, background lifetime, cleanup, and now memory sampling. The service relay exposes its retained tree root so the monitor includes adopted descendants. Procfs sampling avoids subprocess polling and virtual-address limits that interfere with V8/Go runtime reservations. Cgroup containment requires delegation and spawn-time placement; this safeguard requires neither. RLIMIT_AS/RLIMIT_DATA do not provide a tree RSS bound, and RLIMIT_RSS does not provide a modern Linux RSS bound (getrlimit).

Production LOC: +155 (324 added / 169 removed); test LOC: +196. Growth implements the missing watchdog and failure propagation. Outcome shaping and its types now live together in the existing output owner; the duplicated diagnostic failure union and obsolete max-lines exemption are removed. No second execution owner or cache was added.

The retained owner already reports uncertified cleanup and fences the supervisor when admission is revoked before command launch. The launch-policy regression explicitly asserts both denial of execution and that cleanup failure. This behavior already applied to service-hosted execution; distinguishing confirmed local refusal from uncertain launch delivery remains a separate lifecycle repair.

Proof

  • Exact-head Linux exec CI, a256dc489d9b38b5e562e34865404ede1d0aadd7: a real descendant allocating 384 MiB under a scaled 256 MiB default is killed before its 8-second timeout, returns memory-limit, and retains background guidance. Whole-test times: 1.200 s non-PTY / 1.041 s PTY. Actual terminal selection is asserted. Existing PTY/OOM-score behavior and all 11 launch-policy cases pass. These are reliability results, not latency/GC performance claims.
  • Red control: the child/PTY supervisor regression fails with the original production code (no kill), then passes with the change; sandbox exclusion passes on both. Budget, nonleader-thread descendant, swap, and sampler-retirement tests pass.
  • Local focused exec/process tests, changed-file lint/format, targeted core typecheck, export-name guard, and required import-closure/planner tests pass. Closure/planner proof: 178 tests. No local full test suite or Testbox lease.
  • Independent subagent review (autoreview route unavailable): clean, including the repair and rebase conflict resolution. Autoreview's route mismatch was not bypassed or reconfigured.
  • First CI found three attributable issues: stale max-lines baseline, a type-import cycle, and launch-policy tests intercepting only the former spawn path. Repaired together; their exact-head CI jobs now pass. Required rebase onto main 38bf89ccf774 preserved the upstream error formatter in an import-only conflict; range-diff confirms no other patch changes.

Remaining CI Failures: Attributed Baseline / Unrelated

Final CI run 40056137055 has three non-aggregate failures; security-fast and all changed execution-owner checks pass. The CI gate is red because of these failures. No CI reruns were requested.

Failed job Attribution
checks-node-changed-2 test/clawrouter-managed-gateway.e2e.test.ts:109: catalog returns count: 0, missing the configured model. Reproduced identically on unchanged main 1fead915921e307018bdb7b8d2a2e7d80c9d8d4a using that revision's official CI runtime and matching packaged plugins from main run 40054969997. Failure occurs before the agent turn; fixture CLI uses the unchanged managed-child owner.
checks-node-changed-12 test/gateway.multi.e2e.test.ts, scheduler-disabled Gateway edit: cron.add rejects the fixture's model override against its single-model allowlist. Same exact rejection reproduced on unchanged main 1fead915921e with the same official artifacts. The fixture and model-selection owner are unchanged by this PR.
checks-node-changed-compact-small-18 src/gateway/server-methods/chat-send-message-injection.isolated-gateway.test.ts:220: a 1-second chat.send timeout. Initial focused PR run reproduced it; then five main-parent runs (38bf89ccf774) and five PR-head runs passed, six tests each. This synthetic steering flow does not execute a shell child; diagnostic-events changes are type-only. Meets the lane's explicit unrelated-flake criterion; the original failures remain recorded, not claimed fixed.

Baseline E2E commands used the supported OPENCLAW_E2E_USE_PREBUILT_DIST=1 mode, one worker, and only the failing file/case. Artifact build-info matched the checked-out main SHA; original generated directories were preserved and restored. An earlier attempt omitted that flag and began automatic build preparation; it was stopped (143) and excluded from evidence, then official artifacts were restored afresh. No Team production changes or sandbox writes.

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 24, 2026 02:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T02:56:40.709570Z a256dc4 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Oct 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Adds a sampled Linux host-command memory watchdog that kills over-budget process trees and preserves actionable failure diagnostics.

Example: A Linux command descendant allocates 384 MiB under a 256 MiB memory budget.

  • Before: The supervisor has no memory watchdog and lets the command continue until another termination condition occurs.
  • After: The watchdog requests tree termination and reports memory-limit with observed usage, the budget, and recovery advice.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The owner-approved safeguard has useful focused coverage, but three concrete integration and guard failures prevent readiness.
Proof confidence 🦐 gold shrimp (3/6) The supplied host facts identify this as maintainer-authored, outside the ordinary contributor proof gate; recorded validation is mocked or macOS-based, with Linux watchdog cases explicitly deferred.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An unbounded Linux host command can exhaust memory needed by the Gateway and other host workloads.
Reason: The maintainer-authored direction approves automatic sampled protection and explicitly bounds its supported transports and limitations.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep this PR open: the watchdog addresses a real gap, but the patch introduces an import cycle, a stale baseline entry, and broken launch-authority test coverage.

Priority: P2
Reviewed head: 5db471aa1a4b0aee261db11afc350b932f22ca00

Before merge

  • Share the failure kind through a dependency-free contract (P2) - Importing bash-tools.exec-types here creates the static cycle diagnostic-events → bash-tools.exec-types → secrets/store/secret-store → logging/subsystem → diagnostic-events. The repository's architecture guard includes type imports, and the exact-head madge-import-cycles check fails. Put the shared failure-kind contract in a leaf module so diagnostics does not depend on the agent types' transitive runtime graph.
  • Remove the obsolete runtime baseline entry with the suppression (P2) - Removing the max-lines suppression leaves src/agents/bash-tools.exec-runtime.ts listed at config/max-lines-baseline.txt:173. check-max-lines-ratchet explicitly rejects stale entries, matching the exact-head max-lines failure. Remove that entry as part of this cutover.
  • Move launch-authority probes onto the relay launch boundary (P2) - Every Linux host exec now supplies memoryLimitBytes, so this condition selects the service relay even when OPENCLAW_SERVICE_MARKER is empty. bash-tools.exec-launch-policy.integration.test.ts still injects before/after revocation only through spawnAndWait, which the relay bypasses. Its Gateway child cases therefore never inject revocation or count the launch, producing the three exact-head CI failures. Update the fixture to exercise the actual relay launch boundary while preserving policy-rejection and source-retirement assertions; these failures do not themselves establish an authorization bypass.

Findings

  • [P2] Share the failure kind through a dependency-free contract — src/infra/diagnostic-events.ts:2
  • [P2] Remove the obsolete runtime baseline entry with the suppression — src/agents/bash-tools.exec-runtime.ts:685
  • [P2] Move launch-authority probes onto the relay launch boundary — src/process/supervisor/supervisor.ts:413-415

Tests

  • Missing end-to-end proof: The supplied evidence does not demonstrate the watchdog through a Linux Gateway on a fresh install and latest-stable upgrade, including foreground, background, and PTY failure recovery.
Agent review details

How this fits together

Gateway exec prepares host commands, the process supervisor owns their transport and cleanup, and command outcomes flow into foreground results, background polling, and diagnostics.

flowchart TD
  A[Gateway exec] --> B[Process supervisor]
  B --> C[Child relay or PTY]
  B --> D[Procfs memory sampler]
  D --> E[Existing tree cancellation]
  C --> F[Exec outcome]
  E --> F
  F --> G[Foreground results and background polling]
Loading

Technical review

Best possible solution:

Keep the supervisor-owned watchdog, share its failure type through a leaf contract, and repair the baseline and relay-boundary tests.

Do we have a high-confidence way to reproduce the issue?

Current main has no host-command memory budget, and the added Linux regression identifies a concrete allocating descendant; no target code was executed during this review.

Is this the best way to solve the issue?

The existing supervisor is the appropriate watchdog owner, and the documented sampled safeguard is proportionate, but the dependency and consumer-test repairs are necessary.

Full review comments:

  • [P2] Share the failure kind through a dependency-free contract — src/infra/diagnostic-events.ts:2
    Importing bash-tools.exec-types here creates the static cycle diagnostic-events → bash-tools.exec-types → secrets/store/secret-store → logging/subsystem → diagnostic-events. The repository's architecture guard includes type imports, and the exact-head madge-import-cycles check fails. Put the shared failure-kind contract in a leaf module so diagnostics does not depend on the agent types' transitive runtime graph.
    Confidence: 0.99
  • [P2] Remove the obsolete runtime baseline entry with the suppression — src/agents/bash-tools.exec-runtime.ts:685
    Removing the max-lines suppression leaves src/agents/bash-tools.exec-runtime.ts listed at config/max-lines-baseline.txt:173. check-max-lines-ratchet explicitly rejects stale entries, matching the exact-head max-lines failure. Remove that entry as part of this cutover.
    Confidence: 0.99
  • [P2] Move launch-authority probes onto the relay launch boundary — src/process/supervisor/supervisor.ts:413-415
    Every Linux host exec now supplies memoryLimitBytes, so this condition selects the service relay even when OPENCLAW_SERVICE_MARKER is empty. bash-tools.exec-launch-policy.integration.test.ts still injects before/after revocation only through spawnAndWait, which the relay bypasses. Its Gateway child cases therefore never inject revocation or count the launch, producing the three exact-head CI failures. Update the fixture to exercise the actual relay launch boundary while preserving policy-rejection and source-retirement assertions; these failures do not themselves establish an authorization bypass.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d7e7e402df15.

Provenance checked

Testing

Proof path: unit tests only.

Security

None.

Evidence

Acceptance criteria:

  • pnpm check:madge-import-cycles
  • pnpm check:max-lines-ratchet
  • pnpm test src/agents/bash-tools.exec-launch-policy.integration.test.ts
  • pnpm test src/process/child-memory.test.ts src/process/supervisor/supervisor.test.ts src/agents/bash-tools.exec.pty.test.ts
  • git diff --check

What I checked:

  • Pinned introduction and clean checkout: Reviewed the introduced merge-base-to-head diff; base-only agent-command changes are outside this PR's edits, and the checkout remained clean. (5db471aa1a4b)
  • Current main lacks the watchdog: Current main passes timeout and output callbacks into the supervisor without a memory budget; its existing OOM adjustment changes victim preference rather than imposing this bound. (src/agents/bash-tools.exec-runtime.ts:680, d7e7e402df15)
  • Introduced static dependency cycle: The new diagnostic-events import closes diagnostic-events → bash-tools.exec-types → secret-store → logging/subsystem → diagnostic-events; the exact-head architecture check reports madge-import-cycles failure. (src/infra/diagnostic-events.ts:2, 5db471aa1a4b)
  • Introduced baseline mismatch: The patch removes the runtime's max-lines suppression but retains its entry in config/max-lines-baseline.txt; the ratchet explicitly rejects stale entries, and the exact-head check reports max-lines failure. (config/max-lines-baseline.txt:173, 5db471aa1a4b)
  • Launch-authority fixture misses the new transport: Linux memory budgets now select the relay through ownProcessTree, bypassing the integration test's spawnAndWait hook; CI reports three corresponding Gateway child failures. (src/process/supervisor/supervisor.ts:413, 5db471aa1a4b)
  • Accepted safeguard boundaries: The maintainer-authored direction explicitly accepts sampling overshoot, independent command budgets, repeated shared-page accounting, and escaped PTY descendants; these documented tradeoffs do not require another product decision. Public docs: docs/tools/exec.md. (docs/tools/exec.md:17, 5db471aa1a4b)

PR surface

Source +155, Tests +148, Docs +8. Total +311 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 285 130 +155
Tests 3 149 1 +148
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 442 131 +311

Review metrics

Metric Value Why it matters
Production versus test LOC Production +285/-130; tests +149/-1 Production growth primarily implements procfs sampling and supervisor integration; outcome shaping moves to its existing output owner.

Labels

Label changes:

  • add P2: Useful Linux reliability protection with focused implementation and validation repairs.
  • add merge-risk: 🚨 compatibility: Existing Linux host commands exceeding the new automatic budget will terminate where they previously continued; the maintainer-authored direction explicitly accepts this behavior.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Useful Linux reliability protection with focused implementation and validation repairs.
  • merge-risk: 🚨 compatibility: Existing Linux host commands exceeding the new automatic budget will terminate where they previously continued; the maintainer-authored direction explicitly accepts this behavior.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 23, 2026, 10:52 PM ET / October 24, 2026, 02:52 UTC.

Monitor resident and swapped memory of supervised host command trees, kill over-budget work, and preserve actionable memory-limit failures in foreground and background results. Keep sandbox policy and OOM victim preference with their existing owners. Document sampled protection and PTY reparenting limits.
@steipete
steipete force-pushed the steipete/perf-micro-agent-child-memory-bound-20260919 branch from 5db471a to a256dc4 Compare October 24, 2026 02:54
@steipete

Copy link
Copy Markdown
Contributor Author

Landing under the authorized inherited/unrelated-failure exception on exact head a256dc489d9b38b5e562e34865404ede1d0aadd7.

The three remaining non-aggregate failures in CI 40056137055 are documented in the PR body:

  • ClawRouter's empty catalog and the cron fixture's model-allowlist rejection both reproduce identically on unchanged main 1fead915921e, using its matching official CI runtime and plugin artifacts from 40054969997.
  • The synthetic chat.send timeout passed five complete runs on main parent 38bf89ccf774 and five subsequent complete runs on the PR head, meeting the lane's explicit unrelated-flake criterion. The original timeout remains recorded; it is not claimed fixed.

All changed execution-owner checks and security-fast pass. The exact-head real memory-hog tests pass in 1.200 s (non-PTY) and 1.041 s (PTY), with memory-limit and retained background guidance. Independent code review and attribution review are clean. No CI reruns were requested. The native helper's workspace preflight selected a second checkout outside the lane; this uses the explicitly authorized exact-head merge fallback while preserving the single-worktree constraint.

@steipete
steipete merged commit 2d8051e into main Oct 24, 2026
160 of 168 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-child-memory-bound-20260919 branch October 24, 2026 03:17
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
)

* fix(exec): bound Linux host command memory usage

Monitor resident and swapped memory of supervised host command trees, kill over-budget work, and preserve actionable memory-limit failures in foreground and background results. Keep sandbox policy and OOM victim preference with their existing owners. Document sampled protection and PTY reparenting limits.

* fix(exec): keep outcome types and launch policy proof with their owners
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant