Skip to content

Fix Gateway pressure checks on delegated Linux cgroups - #206308

Merged
vincentkoc merged 1 commit into
mainfrom
fix/delegated-cgroup-pressure-owner
Nov 27, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
fix/delegated-cgroup-pressure-owner

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Problem or Why

On Linux with a delegated cgroup v2 mount, Node can read memory counters from a different cgroup. The Gateway can retire idle workers while its service has headroom, or continue optional work while its own service is under pressure.

User Impact

The Gateway's pressure tick and optional-work check now follow the visible service cgroup. The existing warning and critical thresholds remain 80% and 90%. This applies to Node on a verified delegated cgroup v2 mount.

Why This Change Was Made

OpenClaw already maps a process's cgroup membership through the visible mount. The heartbeat selects this reader on startup and rechecks live membership, masks, limits and charge on delegated ticks. On an ordinary mount it keeps Node’s native tick. The leaf still counts raw charged memory. Optional work still checks the working set of visible ancestors separately.

The two native inputs have different contracts. Available memory comes from the cgroup ceiling and its current charge. Starting with libuv 1.52.1, the constrained limit also includes finite soft address-space and data limits. libuv change

Evidence

A private Linux/arm64 mount exposed a real 256 MiB service and an equally capped decoy at the path used by libuv. On Node 24.20.0 with libuv 1.52.1, stock issued no retirement at 251,133,952 B of real charge and issued a critical retirement at 249,585,664 B of decoy charge. The candidate issued a critical retirement and deferred optional work at 249,909,248 B of real charge. With 249,765,888 B charged only to the decoy it admitted optional work and emitted no retirement. These measurements exercise the real pressure callback, channel and optional-work predicate with unrelated logging and metrics stubbed. The test used disposable cgroups and synthetic pages.

A finite-limit control applied a 512 MiB soft data limit to the Node process under a 1 GiB cgroup high limit. At 82% service charge, both the identity-mounted stock and delegated candidate admitted optional work and emitted no retirement. At 93.5%, both emitted a warning and deferred work. The candidate read 69,427,200 B of service headroom while the native probe still returned 1 GiB.

One quiet process per case ran 128 pressure ticks. On the ordinary mount, stock and candidate median/p95 times were 14.8/53.5 and 14.4/37.0 µs. On the delegated mount they were 19.6/70.2 and 70.1/208.1 µs. The extra reads apply to delegated ticks. These samples measure a single callback in a fixture.

The regression tests cover membership moves, masked controllers, missing mount information and both sides of the libuv soft-limit change. Local review found no actionable P0–P2 issues. Exact-head CI

The absolute free-memory threshold in cron's extra-run decision is a separate follow-up. This change corrects the pressure signal. The Gateway's 768 MiB first-turn memory investigation remains open. Related report

@clawsweeper

clawsweeper Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@vincentkoc vincentkoc self-assigned this Nov 27, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. labels Nov 27, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review November 27, 2026 02:40
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 27, 2026
@clawsweeper

clawsweeper Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR makes Linux Gateway pressure checks read the mapped service cgroup instead of potentially unrelated native counters.

Example: A delegated mount exposes a 256 MiB service and an equally capped decoy cgroup.

  • Before: The reported stock run missed pressure at 251,133,952 bytes of service charge and triggered critical retirement from decoy charge.
  • After: The reported candidate run triggered critical retirement and deferred optional work at 249,909,248 bytes of service charge, while ignoring decoy-only pressure.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused implementation appears correct and the real-kernel fixture is relevant, but shipped runtime proof and CI failure attribution remain incomplete.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Gateway can retire idle workers because an unrelated cgroup is pressured, or continue optional work while its actual service allowance is nearly exhausted.
Reason: Correct service accounting has clear operational value, and the maintainer-authored direction preserves existing pressure thresholds without adding settings.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a current delegated-cgroup pressure bug, and source review found no definite introduced defect.

Reviewed head: b3e35db9180f0f6561d108e4f2475149ca2059c1

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Show a shipped Gateway's pressure tick and optional-work decision under real service-versus-decoy charge, plus focused regression results red on base and green on head; redact credentials, IPs and non-public endpoints.
Agent review details

How this fits together

The host-memory owner reads kernel memory counters and supplies optional-work admission and the Gateway diagnostic heartbeat, which publishes pressure signals to idle-worker retirement consumers.

flowchart TD
  A[Process membership and mount information] --> B[Existing cgroup mapper]
  B --> C[Delegated memory reader]
  D[Kernel limits and charge] --> C
  C --> E[Optional work admission]
  C --> F[Gateway pressure heartbeat]
  F --> G[Idle worker retirement]
Loading

Technical review

Best possible solution:

Retain the existing cgroup mapper as the owner of delegated pressure inputs and complete runtime validation before landing.

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

Current main consumes native counters whose libuv path construction can address a decoy beneath a delegated mount; the body also reports matching real-cgroup before/after observations, which were not independently rerun.

Is this the best way to solve the issue?

The patch fixes the counter producer through the existing mapper, preserves separate ancestor working-set policy and ordinary native ticks, and avoids new configuration or persistent state.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Delegated cgroup mapping keeps the original intent (2f3debd: Map membership through the visible mount so sizing and worker budgets use the service's controller.)
  • Leaf and ancestor pressure semantics keeps the original intent (589a70a: Check each visible ancestor's working set independently while the process pressure reader covers leaf charge.)
  • Pressure handling independent of diagnostic collection keeps the original intent (c3b3d56: Detect startup pressure before ordinary diagnostic sampling while preserving existing thresholds and retirement ownership.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned change and current-main gap: The introduced diff replaces native pressure inputs only for verified delegated views and wires the reader into both diagnostic sampling and the independent pressure tick; fetched main still uses process.availableMemory() directly. (src/logging/diagnostic-memory.ts:354, b3e35db9180f)
  • Focused regression contracts: Added tests distinguish real and decoy charge, membership changes, masked counters, unavailable mount information, native-path selection, and libuv soft-limit semantics; the diagnostic test independently checks warning and critical channel publication. (src/infra/host-memory.test.ts:388, b3e35db9180f)
  • Determining dependency contract: The PR explicitly preserves libuv's memory-probe semantics: v1.52.1 combines cgroup and soft resource limits for constrained memory, while available memory independently subtracts raw cgroup charge from its cgroup ceiling. The native cgroup2 reader constructs paths without OpenClaw's delegated-mount translation. (src/unix/linux.c, 1cfa32ff59c0)
  • Existing ownership and intent: fix: size Linux Gateways from their delegated memory limit #206230 established the shared delegated-mount mapper; fix: pause optional Gateway work under parent memory pressure #206041 established separate ancestor working-set pressure checks. This PR extends the mapper to native pressure replacements while retaining that distinction. (src/infra/host-memory.ts:117, 2f246fd1c72d)
  • Reported runtime evidence and scope: The body reports real Linux ARM64 cgroups, service-versus-decoy controls, and a finite soft-data-limit control through the production pressure callback and channel, with unrelated logging and metrics stubbed. It explicitly leaves the broader first-turn OOM investigation at Reduce Gateway startup memory on constrained ARM64 hosts #192547 open. (b3e35db9180f)
  • Outstanding CI attribution: Exact-head check-dependencies failed during Run independent checks. Its annotation only reports exit code 1; log retrieval redirects to a blocked Azure host, so the failure cannot be classified as diff-caused or external. GitHub reports mergeable=true and mergeable_state=blocked. (b3e35db9180f)

Likely related people:

  • Vincent Koc: Raw commit 589a70a adds src/infra/host-memory.ts:264 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 589a70ac8763; files: src/infra/host-memory.ts)
  • Peter Steinberger: Raw commit 73c8498 adds src/logging/diagnostic-memory.ts:62 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 73c8498ea5ae; files: src/logging/diagnostic-memory.ts)
  • Josh Lehman: Raw commit 28aa5c8 adds src/infra/host-memory.ts:125 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 28aa5c88fd45; files: src/infra/host-memory.ts)

PR surface

Source +83, Tests +119. Total +202 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 109 26 +83
Tests 2 122 3 +119
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 231 29 +202

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Provide the shipped Gateway runtime evidence identified in the proof assessment.

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 November 26, 2026, 9:44 PM ET / November 27, 2026, 02:44 UTC.

@vincentkoc

Copy link
Copy Markdown
Member Author

The exact-head suites passed all 75 tests, including the membership move, masked controller, finite limit, and genuine diagnostic-channel publication cases. 31 host-memory tests and 44 diagnostic tests.

The optional full-Gateway proof remains outside this change. The stock and candidate kernel controls exercised the production pressure callback, its retirement signal, and the optional-work decision under swapped service and decoy charge. They cover the changed decision directly. A packaged Gateway run would answer the separate question of which idle workers actually retired during a session. The broader Gateway memory report stays open.

The draft dependency check reported the same three unrelated exports as main: readUpdateDatabaseEngineConfig, DoctorContributionPending, and formatUpdateSnapshotCapacity. Draft check and scheduled main check.

@vincentkoc
vincentkoc merged commit 398c8db into main Nov 27, 2026
287 of 289 checks passed
@vincentkoc
vincentkoc deleted the fix/delegated-cgroup-pressure-owner branch November 27, 2026 02:55
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 27, 2026
* commit '7df6cb759f9e604921536a700e2f527c5516e7de': (185 commits)
  docs: clarify what telemetry OpenClaw sends and how to opt out
  refactor(ui): remove retired stream-follow test seams (#206316)
  fix: distinguish missing command results from unknown outcomes (#206313)
  fix(build): reuse stamps after identical pnpm installs (#206282)
  chore(ci): inventory Gateway model catalog worker lifecycles (#206251)
  fix: keep failed image inspections inside chat activity (#206283)
  fix: clarify sent-message labels and chat activity icons (#206048)
  fix(cron): use the service's free memory for extra automation runs (#206322)
  test(android): reuse the shared TLS fixture (#206280)
  fix(ui): restore New Session recovery during startup (#206319)
  test(macos): align new Gateway URL expectations (#206281)
  feat: let doctor --fix tell when its startup repairs have nothing to do (#206246)
  fix(android): pause idle gateway discovery without blocking consumers (#196209)
  fix(ci): prepare the Android SDK for scheduled CodeQL scans (#203843)
  fix(memory): read delegated cgroup pressure from the mapped leaf (#206308)
  improve(config): reuse plugin metadata during auto-enable (#206289)
  improve: copy only the selected model for agent completions (#206287)
  fix(pr): refresh tooling before preparing reviewed incoming PRs (#206236)
  fix: keep Gateway ready while plugins drain after updates (#206299)
  fix(crabbox): keep unused prepared mirrors reusable (#206267)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
* fix(runtime): defer optional work under host memory pressure

* style(infra): format memory pressure admission

* style(gateway): format the deferred prewarm check

(cherry picked from commit 9f50802)

Companion audit: #207993 selected later for publication fixture isolation. #206779 required if the new Cron host-memory fixture spoofs platform: preserve native SQLite namespace. #206041/#206230/#206308/#206746 are separate cgroup detection and optimization changes; #206322 is service-aware cron run budget, #206483 forks chat and #206384 changes a main-only warmer.

Release adaptation: Extend the stable optional-memory owner and its existing callers only. Preserve cgroup/Bun/macOS behavior and upstream threshold cases; omit main-only prompt warmer, cgroup diagnosis, and Cron platform-spoof changes.

Co-authored-by: RomneyDa <[email protected]>
obviyus added a commit that referenced this pull request Nov 30, 2026
…iners (#208754)

Fixes #208631

## What Problem This Solves

A Gateway that runs in a memory-limited Linux container or systemd unit (cgroup v2) counts file cache as used memory. Normal file work fills the cgroup with cache that the kernel frees on demand, so the Gateway logs `memory pressure: level=critical reason=process_memory_threshold` every 5 minutes and never clears. The same false signal publishes `openclaw.memory.critical`, which retires idle SQLite workers and clears session caches, defers optional work, refuses extra automation runs, and starts no update-hash workers, while most of the limit is free.

## User Impact

- Cache-heavy Gateways in containers and memory-limited units no longer report critical pressure or throw away warm workers and caches when only reclaimable file cache fills the limit.
- Real pressure still reports: anonymous memory, active file cache and kernel charges still count. A charge above `memory.high` still reports no headroom.
- Bare hosts, macOS and Bun keep their readings. cgroup v1 and hosts without a visible cgroup v2 leaf keep Node's reading (unchanged; see Limits).

## Why This Change Was Made

Root cause: the leaf cgroup's headroom was `limit - memory.current`, and `memory.current` includes page cache. It was computed in two places, both raw: Node's native `process.availableMemory()` (libuv reads the leaf's `memory.current`) consumed at `src/logging/diagnostic-memory.ts:371` and `src/infra/host-memory.ts:62,305,310`, and OpenClaw's delegated-mount reader `readDelegatedCgroupMemory` (`src/infra/host-memory.ts:286`, "Node counts raw charges, including file cache"). The same module already used the working set (`memory.current - inactive_file`) for ancestor cgroups and the lean worker budget.

The fix gives `src/infra/host-memory.ts` one reader, `readProcessMemory()`, for the process limit and the headroom left in it:

- With a verified cgroup v2 view (ordinary or delegated mount), it reads the leaf files directly: headroom = limit - (`memory.current` - `inactive_file`). The charge is read unclipped, so above `memory.high` the headroom is 0, not cache credit added to libuv's clipped 0.
- This is the working set that kubelet eviction and cAdvisor use ([Kubernetes node-pressure eviction](https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/#active-file-memory-is-not-considered-as-available-memory), [cgroup v2 memory interface](https://docs.kernel.org/admin-guide/cgroup-v2.html#memory-interface-files)).
- An ordinary leaf without memory counters (the root cgroup) and every non-cgroup-v2 case keep Node's native reading.
- All four consumers read it: diagnostic pressure and the `openclaw.memory.critical` channel, `isMemoryPressureHigh`, cron's extra-run admission, and update-hash worker sizing. The delegated-only and cron-only capture readers are removed. The cgroup view is mapped once per membership (the existing `isMemoryPressureHigh` cache, now shared).
- Cron shares the definition on purpose: it asks whether 1 GiB is available to a new run, and inactive cache is given back on demand. Earlier changes kept the raw leaf only to match Node (#206308, #206322).

Supersedes #208658 (draft), which corrected only the diagnostic signal.

## Evidence

Red on base, green on fix. The fix's unit fixtures (1000-byte leaf, `memory.current` 950, `inactive_file` 945) run against base 7215944 with the base API: on both ordinary (`/`) and delegated (`/pod`) mount roots, `isMemoryPressureHigh()` returned true and `openclaw.memory.critical` was published. With the fix: no pressure, no retirement. With anonymous memory holding the same charge (`inactive_file` 50): `critical`, `usedBytes: 900`, retirement published. Above `memory.high` (high 512 MiB, current 768 MiB, inactive 128 MiB): headroom 0.

E2E on real cgroup v2 (Linux 7.2 kernel, Docker `--memory=2g --memory-swap=2g`), an isolated Gateway from the repo Dockerfile, built from base 7215944 and from this branch. Numbers from the container's `memory.stat`:

| Phase | Base | Fix |
| --- | --- | --- |
| Idle (anon ~0.85 GB) | no critical | no critical |
| File cache fills the limit (`memory.current` 2.14 GB, `inactive_file` 1.24-1.26 GB, anon 0.80-0.88 GB) | `level=critical reason=process_memory_threshold ... thresholdRatio=111.1% limit=2 GiB used=2 GiB` | no critical |
| Anonymous memory to 93% working set (anon 2.11 GB, `inactive_file` 17 MB) | (already critical, throttled) | `level=critical reason=process_memory_threshold ... thresholdRatio=103.9% limit=2 GiB used=1.87 GiB` |

A 1 GiB limit OOM-kills a stock Gateway during startup (RSS 963 MB at ready), so the runs use 2 GiB. The fix column was rerun on the PR's product code (f8371b6; later commits change tests only) with the same results.

The other consumers, called from the built `dist` of each image:

| Case | Base | Fix |
| --- | --- | --- |
| 2 GiB leaf full of file cache (`inactive_file` 2.14 GB, anon 0.4 MB) | cron headroom 0.00 GiB (no extra run), `isMemoryPressureHigh()` true | cron headroom 1.98 GiB, `isMemoryPressureHigh()` false |
| Leaf without memory controller files (`0::/nomem`) | host reading 50.75 GiB, false | host reading 50.70 GiB, false |

Cost: on that kernel, the leaf reads take 13.1 µs per call vs 8.5 µs for the native pair; the pressure check runs once per second.

Checks: `host-memory`, `diagnostic-memory`, `worker-pool-sizing`, cron delegated/cross-tick/run-queue admission, page-cache, runtime-services maintenance and cron maintenance tests pass. Core typecheck (source and tests) and changed-file lint pass. `check:changed` also reports plugin-boundary and dead-export failures in files this change does not touch.

## Limits

- Active file cache still counts as used, as in kubelet. On this kernel (MGLRU on), re-reading the same file kept it in `inactive_file` (active 5 MB of 1.27 GB). Not tested on a classic-LRU kernel, where re-read cache can move to `active_file` and still count.
- cgroup v1 keeps Node's raw reading; OpenClaw already does not detect v1 limits.
- Unchanged here: libuv's soft rlimits still lower the reported limit while headroom stays cgroup-wide, and a tighter parent limit is still checked only by `isMemoryPressureHigh`'s ancestor check.

Co-authored-by: Sleep8h <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
* fix: pause optional Gateway work under parent memory pressure

* fix: resolve visible cgroup controllers from their mounted subtree

* fix: retain visible memory limits above covered controllers

* fix: honor controller masks on the visible mount only

* fix: keep existing cgroup budget readers independent of admission

* refactor: name parsed cgroup mount fields

(cherry picked from commit 589a70a)

Release adaptation: take the pressure-owner slices of #206230 (verified mount mapping), #206308 (delegated leaf), and #206746 (mount discovery reused per membership). Do not import resource sizing, diagnostics or #206322 cron scheduling APIs; none are needed by stable optional callers.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…6308)

(cherry picked from commit 398c8db)

Release adaptation: Preceded by the bounded #206230 release backport f51e20db20e2, which owns mapping of delegated cgroup views and their budget.

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
…iners (openclaw#208754)

Fixes openclaw#208631

## What Problem This Solves

A Gateway that runs in a memory-limited Linux container or systemd unit (cgroup v2) counts file cache as used memory. Normal file work fills the cgroup with cache that the kernel frees on demand, so the Gateway logs `memory pressure: level=critical reason=process_memory_threshold` every 5 minutes and never clears. The same false signal publishes `openclaw.memory.critical`, which retires idle SQLite workers and clears session caches, defers optional work, refuses extra automation runs, and starts no update-hash workers, while most of the limit is free.

## User Impact

- Cache-heavy Gateways in containers and memory-limited units no longer report critical pressure or throw away warm workers and caches when only reclaimable file cache fills the limit.
- Real pressure still reports: anonymous memory, active file cache and kernel charges still count. A charge above `memory.high` still reports no headroom.
- Bare hosts, macOS and Bun keep their readings. cgroup v1 and hosts without a visible cgroup v2 leaf keep Node's reading (unchanged; see Limits).

## Why This Change Was Made

Root cause: the leaf cgroup's headroom was `limit - memory.current`, and `memory.current` includes page cache. It was computed in two places, both raw: Node's native `process.availableMemory()` (libuv reads the leaf's `memory.current`) consumed at `src/logging/diagnostic-memory.ts:371` and `src/infra/host-memory.ts:62,305,310`, and OpenClaw's delegated-mount reader `readDelegatedCgroupMemory` (`src/infra/host-memory.ts:286`, "Node counts raw charges, including file cache"). The same module already used the working set (`memory.current - inactive_file`) for ancestor cgroups and the lean worker budget.

The fix gives `src/infra/host-memory.ts` one reader, `readProcessMemory()`, for the process limit and the headroom left in it:

- With a verified cgroup v2 view (ordinary or delegated mount), it reads the leaf files directly: headroom = limit - (`memory.current` - `inactive_file`). The charge is read unclipped, so above `memory.high` the headroom is 0, not cache credit added to libuv's clipped 0.
- This is the working set that kubelet eviction and cAdvisor use ([Kubernetes node-pressure eviction](https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/#active-file-memory-is-not-considered-as-available-memory), [cgroup v2 memory interface](https://docs.kernel.org/admin-guide/cgroup-v2.html#memory-interface-files)).
- An ordinary leaf without memory counters (the root cgroup) and every non-cgroup-v2 case keep Node's native reading.
- All four consumers read it: diagnostic pressure and the `openclaw.memory.critical` channel, `isMemoryPressureHigh`, cron's extra-run admission, and update-hash worker sizing. The delegated-only and cron-only capture readers are removed. The cgroup view is mapped once per membership (the existing `isMemoryPressureHigh` cache, now shared).
- Cron shares the definition on purpose: it asks whether 1 GiB is available to a new run, and inactive cache is given back on demand. Earlier changes kept the raw leaf only to match Node (openclaw#206308, openclaw#206322).

Supersedes openclaw#208658 (draft), which corrected only the diagnostic signal.

## Evidence

Red on base, green on fix. The fix's unit fixtures (1000-byte leaf, `memory.current` 950, `inactive_file` 945) run against base 3f68ec0 with the base API: on both ordinary (`/`) and delegated (`/pod`) mount roots, `isMemoryPressureHigh()` returned true and `openclaw.memory.critical` was published. With the fix: no pressure, no retirement. With anonymous memory holding the same charge (`inactive_file` 50): `critical`, `usedBytes: 900`, retirement published. Above `memory.high` (high 512 MiB, current 768 MiB, inactive 128 MiB): headroom 0.

E2E on real cgroup v2 (Linux 7.2 kernel, Docker `--memory=2g --memory-swap=2g`), an isolated Gateway from the repo Dockerfile, built from base 3f68ec0 and from this branch. Numbers from the container's `memory.stat`:

| Phase | Base | Fix |
| --- | --- | --- |
| Idle (anon ~0.85 GB) | no critical | no critical |
| File cache fills the limit (`memory.current` 2.14 GB, `inactive_file` 1.24-1.26 GB, anon 0.80-0.88 GB) | `level=critical reason=process_memory_threshold ... thresholdRatio=111.1% limit=2 GiB used=2 GiB` | no critical |
| Anonymous memory to 93% working set (anon 2.11 GB, `inactive_file` 17 MB) | (already critical, throttled) | `level=critical reason=process_memory_threshold ... thresholdRatio=103.9% limit=2 GiB used=1.87 GiB` |

A 1 GiB limit OOM-kills a stock Gateway during startup (RSS 963 MB at ready), so the runs use 2 GiB. The fix column was rerun on the PR's product code (f8371b6; later commits change tests only) with the same results.

The other consumers, called from the built `dist` of each image:

| Case | Base | Fix |
| --- | --- | --- |
| 2 GiB leaf full of file cache (`inactive_file` 2.14 GB, anon 0.4 MB) | cron headroom 0.00 GiB (no extra run), `isMemoryPressureHigh()` true | cron headroom 1.98 GiB, `isMemoryPressureHigh()` false |
| Leaf without memory controller files (`0::/nomem`) | host reading 50.75 GiB, false | host reading 50.70 GiB, false |

Cost: on that kernel, the leaf reads take 13.1 µs per call vs 8.5 µs for the native pair; the pressure check runs once per second.

Checks: `host-memory`, `diagnostic-memory`, `worker-pool-sizing`, cron delegated/cross-tick/run-queue admission, page-cache, runtime-services maintenance and cron maintenance tests pass. Core typecheck (source and tests) and changed-file lint pass. `check:changed` also reports plugin-boundary and dead-export failures in files this change does not touch.

## Limits

- Active file cache still counts as used, as in kubelet. On this kernel (MGLRU on), re-reading the same file kept it in `inactive_file` (active 5 MB of 1.27 GB). Not tested on a classic-LRU kernel, where re-read cache can move to `active_file` and still count.
- cgroup v1 keeps Node's raw reading; OpenClaw already does not detect v1 limits.
- Unchanged here: libuv's soft rlimits still lower the reported limit while headroom stays cgroup-wide, and a tighter parent limit is still checked only by `isMemoryPressureHigh`'s ancestor check.

Co-authored-by: Sleep8h <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant