Skip to content

improve: reduce memory-monitoring overhead for concurrent commands - #189629

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-child-memory-batched-proc-scan-20260919
Oct 31, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-child-memory-batched-proc-scan-20260919

Conversation

@steipete

@steipete steipete commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Concurrent Linux exec commands repeat process-memory monitoring work, increasing Gateway allocation and CPU under load.

User Impact

Memory monitoring shares a process census at higher concurrency while sparse workloads retain descendant-only walks. RSS-plus-swap limits and process-tree termination remain unchanged. No configuration or migration is required.

Why This Change Was Made

One scheduler selects the scan mode with hysteresis and feeds one accounting/enforcement path. A census reads each process status once for parent PID, RSS and swap. Shared ticks may sample another command less than one second early. Quiet trees retain their five-second interval; near-bound or newly expanded trees retain one-second sampling.

The hosted review correctly identified a global waiting barrier in the first revision. The repaired owner gives the census 250 ms before falling back to independent walks, keeps at most one unresolved census, and schedules completed watches independently while other reads remain pending. An unreadable unrelated process also falls back to owned-tree walks. The existing approximately six-second runaway bound remains protected.

Runtime growth is net +135 lines for the census, shared scheduler and independent pending-read lifecycle; per-watch timers and a duplicate traversal array are removed. Tests add 129 lines; existing benchmark scripts add 115. No persistent cache, schema, public setting, or alternate accounting owner is added.

Evidence

Final reviewed head: e200e5564b9c2e712caef1875a8d055f66b0a049. Codex autoreview of the complete repaired candidate, followed by a clean final-threshold review, against original base a5b6c876b9c5d806a7808a970333d3aba609b8a6 is scoped-clean at P0–P2. 50 focused child-memory/supervisor tests pass, along with affected typecheck, lint and formatting.

Both pending-read regressions fail on the previous 3f7fb448762b with zero limit callbacks, then pass on the repair: another command grows over its limit and is killed before the blocked read is released, with both two and twenty watches. Cancellation, callback context, mode boundaries/idle reset and unrelated permission errors remain covered. Overlapping roots get 144/128 KiB RSS+swap totals with one shared descendant read; exact original-base replay reads it twice.

Real Linux worst-phase runaway results on repaired source: baseline 5.009 s, sparse 5.006 s, shared 5.030 s, all within six seconds, with SIGKILL and the visible memory-bound diagnostic. The immutable benchmark bundle matches the committed owner source.

The final switch enters shared mode at 20 active watches and retains it at 12 or more (reset when empty). Five alternating pairs at each count, 5 s warmup/15 s capture, give these strategy medians:

Watches Walk allocation MB/s Shared allocation MB/s Walk CPU ms/s Shared CPU ms/s
1 0.389 0.572 5.577 10.966
2 0.652 0.607 4.919 7.620
4 0.406 0.595 7.427 17.142
8 0.615 0.619 7.550 9.429
12 0.837 0.521 7.361 4.368
20 1.235 0.596 10.286 5.343

Both selected shared-mode thresholds win allocation and CPU. Forced-strategy bundles are byte-identical to those generated from the final production source; no production override exists. Two walk A/A controls at four watches measured allocation 0.439→0.429 and 0.374→0.393 MB/s, CPU 7.362→9.520 and 5.782→6.929 ms/s, so small CPU differences are not treated as reliable wins. Final original-versus-production comparisons use five alternating pairs per count, 30 s warmup and 60 s capture. V8 allocation includes collected objects and excludes external Buffer storage. Medians (observed maximum in parentheses):

Watchers Metric Original Final
1 Allocation MB/s 0.105330 (0.120304) 0.111645 (0.126245)
1 Total CPU ms/s 3.3723 (5.9796) 3.5518 (3.8452)
1 Main-thread CPU ms/s 2.8432 (4.5086) 3.0056 (3.2339)
20 Allocation MB/s 0.934641 (0.950375) 0.236121 (0.585098)
20 Total CPU ms/s 10.0776 (16.3014) 7.4449 (12.6594)
20 Main-thread CPU ms/s 5.0654 (7.9262) 5.0294 (6.3274)

Dense allocation falls 74.7%; observed total CPU falls 26.1%, with main-thread median nearly unchanged. Allocation ranges are 0.902864–0.950375→0.218622–0.585098 MB/s at 20 and 0.092210–0.120304→0.103177–0.126245 at one. Five-sample nearest-rank p95 equals the observed maximum; it is not a reliable tail-distribution estimate.

Accepted implementation tradeoff: the requested single owner costs 6.31 KB/s (+6.0%) of median allocation at one watcher for a 0.699 MB/s reduction at twenty. The quiet-path CPU medians rise 0.180 ms/s total and 0.162 ms/s main; CPU variation in identical-baseline controls is larger. This is an explicitly retained sparse cost, not a zero-overhead claim. The conditional threshold avoids the much larger unconditional-census penalty.

Baseline A/A controls, with identical 30/60 s timing: at one watcher allocation 0.111237→0.112646 MB/s, total CPU 4.77318→3.17928 ms/s, main 3.99482→2.741; at twenty allocation 0.953797→0.992035 MB/s, total CPU 9.365→25.9583 ms/s, main 4.7911→14.50685. These controls establish substantial CPU/timer noise, not a precise CPU speedup forecast.

Tail limitation: dense event-loop p99 medians are 30.49→33.55 ms and window-maximum medians 46.47→99.55 ms; largest observed maxima 47.78→291.77 ms. The dense baseline A/A alone moves p99 30.08→71.17 ms and maximum 37.06→202.90 ms without a corresponding GC increase. Sparse baseline also reached 253.89 ms. Keep every outlier: this host cannot establish event-loop-tail neutrality or attribute the longer window to the sampler. The accepted performance decision rests on the large repeatable allocation reduction, fewer procfs operations and independently proven enforcement bound, with this timing uncertainty explicit. No production tail-latency claim is made.

The existing callback-based reader is retained: the earlier reusable-Buffer/FileHandle experiment in #182234 regressed allocation 1.242→3.952 MiB/s (+218.2%). This change removes redundant traversal and parses PPid/RSS/swap from one status buffer; it does not repeat that rejected reader experiment.

Separate 20-watch work-count capture (30 s warmup/15 s capture) reduces FSREQCALLBACK 5,340→612 (-88.5%), FSREQPROMISE 600→3 (-99.5%), PROMISE 13,862→1,520 (-89.0%), and timeouts 61→7. Three directory reads confirm one census per shared tick with no fallback in this probe. Capture-window CPU profiles (warmup excluded) reduce owner-inclusive samples 116→20, native file-read samples 70→9, and descendant-directory-read samples 17→0; owner self samples remain 4→4. Instrumented profiles/counts are excluded from timing medians.

Workload: Node 26.12.1 in a Linux container with a fixed synthetic forest of 20 roots, each with nine worker-thread-spawned descendants (200 processes). Crossover compares forced strategies only in benchmark bundles; there is no production override. Final timing windows have request context in both arms. Results cover the procfs owner, not whole-Gateway throughput; database and workspace contents do not enter this owner path.

Reproduction uses committed scripts/perf/child-memory-fixture.cjs forest 20 9 <roots.json> and scripts/perf/child-memory-measure.ts --roots <roots.json> --trees 20 --descendants 9 --watched <count> --owner <bundled-owner> --warmup-seconds <warmup> --seconds <capture> --output <result.json>. Real timer proof uses scripts/perf/child-memory-adaptive-runaway.ts --owner <bundled-owner> --observers 1|20 --output <result.json>.

pnpm check:changed completed: all selected checks passed except fixture type errors (corrected, targeted replay passes) and inherited Knip src/tts/directive-facts.ts: resolveTtsDirectiveBody. Exact-parent reproduction exits 1 with that export and no resolution errors. This main regression was introduced by #189504 (ec004ac80b18) and repaired by #189589 (5353794239ba). Exact final-head CI run 41233673123 is GREEN under the native watcher, which excludes superseded older runs. Hosted Codex also completed on e200e5564b9c with no findings. Native scripts/pr review/preparation/landing is used; no CI bypass is needed.

@clawsweeper

clawsweeper Bot commented Oct 31, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts size: L labels Oct 31, 2026
@steipete
steipete marked this pull request as ready for review October 31, 2026 18:03
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 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-31T19:21:37.142317Z e200e55 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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:feature Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR shares Linux process-memory scans across concurrent commands while retaining individual walks for sparse workloads.

Example: Eight Linux commands have active memory watches.

  • Before: Each watch independently schedules and scans its command tree.
  • After: A shared scheduler obtains one process census for the watches.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-level measurements support the approach, but the global sampling barrier introduces a definite enforcement-independence regression.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied Linux owner-level measurements report real-procfs scans and sparse/shared runaway termination, while the final baseline comparison is explicitly pending.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Concurrent Linux commands increase Gateway allocation and CPU by repeating process-memory monitoring work.
Reason: The feature-history owner authored this direction, and dense-workload crossover measurements support sharing scans while retaining sparse walks.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored optimization has clear value, but shared scheduling can stall unrelated commands' memory enforcement.

Priority: P2
Reviewed head: 3f7fb448762b8bad88a86230d45bc915bdfb69ed

Before merge

  • Keep unrelated watches enforceable while procfs reads are pending (P2) - With eight watches, leave /proc/100/status pending and let command 200 exceed its bound: readForest() awaits the first read before any watch's sample runs, so command 200 receives no limit callback until that unrelated read settles. In sparse mode, Promise.allSettled similarly prevents later sampling rounds while one tree remains pending because sampling prevents scheduling another timer. The base's independent timers allow unrelated watches to continue. This is the independence failure already documented in perf(process): reduce exec memory sampler allocation #182234; the new cancellation test resolves its blocked read before asserting the other limits. Preserve independent enforcement and test it before releasing the blocked read.

Findings

  • [P2] Keep unrelated watches enforceable while procfs reads are pending — src/process/child-memory.ts:187-188

Tests

  • Missing end-to-end proof: The final original-versus-candidate performance comparison remains pending, and supplied tests do not show another command being enforced while a procfs read stays unresolved.
Agent review details

How this fits together

The process supervisor registers command roots and memory limits with the Linux watchdog, which reads procfs and requests existing process-tree termination when usage exceeds a command's bound.

flowchart TD
  A[Process supervisor] --> B[Active memory watches]
  B --> C[Shared scheduler]
  C --> D[Individual tree walks]
  C --> E[Process census]
  D --> F[Per-command accounting]
  E --> F
  F --> G[Existing tree termination]
Loading

Technical review

Best possible solution:

Share procfs work within the existing owner while keeping each command's enforcement independent of stalled reads.

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

Source establishes the failure: with eight watches, leave the first census status read pending and make another command exceed its bound; its enforcement callback cannot run until the read settles. No target code was executed during this read-only review.

Is this the best way to solve the issue?

Batching at the existing watchdog owner is appropriate, and the sparse/shared split has measured motivation, but a complete-census barrier does not preserve the independent-enforcement contract.

Full review comments:

  • [P2] Keep unrelated watches enforceable while procfs reads are pending — src/process/child-memory.ts:187-188
    With eight watches, leave /proc/100/status pending and let command 200 exceed its bound: readForest() awaits the first read before any watch's sample runs, so command 200 receives no limit callback until that unrelated read settles. In sparse mode, Promise.allSettled similarly prevents later sampling rounds while one tree remains pending because sampling prevents scheduling another timer. The base's independent timers allow unrelated watches to continue. This is the independence failure already documented in perf(process): reduce exec memory sampler allocation #182234; the new cancellation test resolves its blocked read before asserting the other limits. Preserve independent enforcement and test it before releasing the blocked read.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Watcher scheduling and adaptive intervals changes intended behavior with a stated reason (a450743: Reduce quiet-tree sampling cost while retaining independent watchers and accepting approximately six-second runaway detection.)
  • Byte parsing and native file reading keeps the original intent (c737f7a: Avoid decoding and token allocations while retaining callback-based native file reading and RSS-plus-swap accounting.)
  • Benchmark and runaway fixtures keeps the original intent (a450743: Provide reproducible real-procfs measurements and phase-aligned runaway termination proof.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/process/child-memory.test.ts src/process/supervisor/supervisor.test.ts --maxWorkers=1
  • pnpm tsgo:core
  • Verify the new pending-read regressions fail on the reviewed PR head and pass after the repair.
  • Complete the committed real-timer performance and runaway workloads against the original owner and repaired candidate.

What I checked:

  • Pinned introduced change: The introduced diff replaces independent watcher timers with one scheduler and adds conditional process-census sampling. (src/process/child-memory.ts:160, 3f7fb448762b)
  • Global sampling barrier: Every shared-mode callback waits for the complete census; subsequent rounds in either mode wait for every selected watch to settle, while schedule refuses to arm timers during sampling. (src/process/child-memory.ts:187, 3f7fb448762b)
  • Cancellation coverage releases the blocked read: The added cancellation test resolves the pending read before checking other commands' limits, so it does not establish independent enforcement while that read remains pending. (src/process/child-memory.test.ts:268, 3f7fb448762b)
  • Earlier independent-enforcement regression: perf(process): reduce exec memory sampler allocation #182234 records a rejected serialized implementation whose independent-tree regression withheld an over-limit callback while another tree's procfs read remained pending.
  • Current-main behavior: The fetched main retains the original independent watcher implementation; the central batching change is not already implemented there. (src/process/child-memory.ts:115, 110d1f0dc699)
  • Performance evidence boundary: The PR supplies real-procfs crossover measurements and runaway termination observations, but explicitly leaves the final original-versus-candidate comparison pending; both crossover arms use the new scheduler. (scripts/perf/child-memory-measure.ts:194, 3f7fb448762b)

PR surface

Source +102, Tests +115, Docs +2, Other +117. Total +336 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 144 42 +102
Tests 1 117 2 +115
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 4 157 40 +117
Total 7 421 85 +336

Labels

Label changes:

  • add P2: A useful performance improvement needs a focused repair to preserve independent memory enforcement.
  • add merge-risk: 🚨 availability: A pending procfs read can delay unrelated runaway-command termination and expose the host to additional memory pressure.
  • 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: A useful performance improvement needs a focused repair to preserve independent memory enforcement.
  • merge-risk: 🚨 availability: A pending procfs read can delay unrelated runaway-command termination and expose the host to additional memory pressure.
  • 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 31, 2026, 2:20 PM ET / 18:20 UTC.

@steipete
steipete merged commit 3a46423 into main Oct 31, 2026
134 of 135 checks passed
@steipete
steipete deleted the steipete/perf-micro-child-memory-batched-proc-scan-20260919 branch October 31, 2026 20:10
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 1, 2026
…penclaw#189629)

* perf(process): share memory scans for concurrent commands

* fix(process): keep memory watches independent of stalled reads

* perf(process): select measured sampler crossover with hysteresis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts 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