Repository navigation
improve: reduce memory-monitoring overhead for concurrent commands - #189629
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs changes before merge. What this changesThis PR shares Linux process-memory scans across concurrent commands while retaining individual walks for sparse workloads. Example: Eight Linux commands have active memory watches.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 110d1f0dc699. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
PR surfaceSource +102, Tests +115, Docs +2, Other +117. Total +336 across 7 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 31, 2026, 2:20 PM ET / 18:20 UTC. |
|
Merged via squash.
|
…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
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 basea5b6c876b9c5d806a7808a970333d3aba609b8a6is 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
3f7fb448762bwith 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:
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):
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>andscripts/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 usesscripts/perf/child-memory-adaptive-runaway.ts --owner <bundled-owner> --observers 1|20 --output <result.json>.pnpm check:changedcompleted: all selected checks passed except fixture type errors (corrected, targeted replay passes) and inherited Knipsrc/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 one200e5564b9cwith no findings. Nativescripts/prreview/preparation/landing is used; no CI bypass is needed.