Skip to content

fix(memory): exclude reclaimable file cache from cgroup process pressure - #208659

Closed
wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/cgroup-reclaimable-cache-pressure
Closed

wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/cgroup-reclaimable-cache-pressure

Conversation

@wangmiao0668000666

Copy link
Copy Markdown
Contributor

Fixes #208631

What Problem This Solves

On Linux with a cgroup v2 memory limit, a workload that reads or writes files fills the cgroup with page cache until memory.current reaches the limit. That is normal kernel behavior: the kernel drops those pages on demand. The diagnostic memory sampler counted that reclaimable cache as used memory, so a Gateway whose anonymous memory was a few percent of its limit logged

memory pressure: level=critical reason=process_memory_threshold rss=125.6 MiB ... limit=1 GiB used=1023.9 MiB

every five minutes and published openclaw.memory.critical. The channel's subscribers retire idle SQLite workers and clear session snapshot caches, so warm state was thrown away while memory was plentiful. Operators got up to 288 false critical alerts a day that never cleared and hid real pressure.

Why This Change Was Made

emitDiagnosticMemorySample (src/logging/diagnostic-memory.ts:373) computed usedBytes = limit - process.availableMemory(). On cgroup v2, libuv's available memory is memory.max - memory.current, and memory.current includes file cache. The delegated reader (readDelegatedCgroupMemory, src/infra/host-memory.ts:284) used the same raw memory.current.

The module already owns the correct accounting: cgroupV2WorkingSetBytes subtracts inactive_file for worker budgets and ancestor checks. This change reuses it rather than introducing a new owner:

  • Factor the inactive_file read out of cgroupV2WorkingSetBytes into cgroupV2InactiveFileBytes, then expose readReclaimableCgroupFileCacheBytes for the process leaf. It returns undefined unless the verified leaf exposes memory.stat, so the raw-charge fallback is preserved when the counter is unavailable.
  • Subtract that value from the process charge before classification, only once the raw charge reaches the warning ratio. Steady-state sampling keeps its single cgroup read; the extra memory.stat read happens only near the threshold.

Two boundaries are held:

  • The scheduler's availability reader stays raw. readDelegatedCgroupMemory.availableBytes and captureServiceAvailableMemoryReader also serve cron scheduling and worker sizing; a classification repair must not move them. Only process_memory_threshold in the diagnostic sampler changes.
  • The worker-retirement policy is untouched. The pressure channel and its subscribers keep their existing contract; only the classification that feeds them is corrected.

This is a narrower version of #197039, which was parked as a closed draft for lacking a performance qualification. It does not move the cgroup memory owner into src/process, does not change worker-retirement policy, and makes no performance claim.

Evidence

Red on base, green with the fix

src/logging/diagnostic-memory.test.ts → excludes reclaimable file cache from process pressure so warm cache never signals critical simulates the reported shape: a 1 GiB cgroup fully charged with 20 MiB anonymous and the rest reclaimable inactive cache. It asserts no pressure event and no retirement publication.

keeps genuine anonymous pressure after excluding reclaimable file cache proves the fix does not silence real pressure: 1 GiB charged with only 100 MiB reclaimable leaves a 924 MiB working set, still critical.

skips the reclaimable-cache read while raw usage stays below warning pins the gate: at 50% charge the cache reader is never called.

src/infra/host-memory.test.ts → reads reclaimable inactive file cache from the process leaf covers the new reader: no memory.stat means undefined (raw fallback), a present memory.stat yields inactive_file, and a moved leaf without its own memory.stat does not inherit the previous leaf's cache.

Counterfactual — reverting only the subtraction in diagnostic-memory.ts (keeping the export so the suite compiles):

 × excludes reclaimable file cache from process pressure so warm cache never signals critical
 × keeps genuine anonymous pressure after excluding reclaimable file cache
 Tests  2 failed | 44 passed (46)

With the fix restored:

 ✓ excludes reclaimable file cache from process pressure so warm cache never signals critical
 ✓ keeps genuine anonymous pressure after excluding reclaimable file cache
 Test Files  1 passed (1)
      Tests  47 passed (47)

The failing case is the reported defect: the sampler treats warm page cache as critical process pressure.

node scripts/run-vitest.mjs run src/logging/diagnostic-memory.test.ts src/infra/host-memory.test.ts
# src/logging/diagnostic-memory.test.ts  Tests  47 passed (47)
# src/infra/host-memory.test.ts           Tests  34 passed (34)

Consumer tests of the shared owner stay green:

node scripts/run-vitest.mjs run src/infra/worker-memory-budget.test.ts src/infra/shared-worker-host.test.ts
# Tests  21 passed (21)  +  Tests  9 passed (9)

oxlint and oxfmt --check are clean on the changed files.

Not tested

  • No live cgroup v2 reproduction here. This host runs cgroup v1, and Docker 20.10 cannot give the container a v2 memory controller, so the issue's docker run --memory=1g reproduction could not be run locally. The regression simulates the exact memory.current / inactive_file shape through the real reader and the real sampler, but a v2 runner should confirm the end-to-end alert disappears.
  • No before/after Gateway performance comparison. Like fix(memory): exclude inactive file cache from cgroup pressure #197039, this does not claim a worker-churn or CPU benefit. It fixes the correctness of the critical signal; the steady-state cost is unchanged because the extra memory.stat read happens only once the raw charge crosses the warning ratio.
  • The gate means a cgroup whose raw charge stays below 80% never reads memory.stat; if a future change needs cache-adjusted numbers at all levels, the gate would need widening.

On cgroup v2 a workload that touches files fills the cgroup with page
cache until memory.current reaches the limit. The diagnostic sampler
computed usedBytes as limit minus process.availableMemory(), so that
reclaimable cache counted as used memory and published
process_memory_threshold at level=critical every five minutes, plus
openclaw.memory.critical, while anonymous memory was a few percent of the
limit. The channel's subscribers retire idle SQLite workers and clear
snapshot caches, so warm state was discarded while memory was plentiful.

Subtract the leaf's inactive_file cache from the process charge before
classification. Reuse the existing cgroup memory owner: factor the
inactive_file read out of cgroupV2WorkingSetBytes and expose it as
readReclaimableCgroupFileCacheBytes, which stays undefined unless the
verified leaf exposes memory.stat, preserving the raw-charge fallback.

Only read the cache once the raw charge reaches the warning ratio, so
steady-state sampling keeps its single cgroup read. The scheduler's
availability reader stays raw, so only the diagnostic classification
moves; genuine anonymous pressure and the worker-retirement policy are
unchanged.

Fixes openclaw#208631.
@clawsweeper

clawsweeper Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Pull request received.

ClawSweeper review complete

ClawSweeper finished reviewing this revision.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 30, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 30, 2026
@clawsweeper

clawsweeper Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR subtracts inactive file cache before classifying Linux cgroup process-memory pressure.

Example: A 1 GiB cgroup contains 20 MiB of anonymous memory and 1004 MiB of inactive file cache.

  • Before: The sampler reports critical process pressure and publishes a retirement signal.
  • After: The sampler counts 20 MiB and publishes no process-pressure signal.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) A focused correction for a concrete problem, with two pressure-accounting defects and only mocked after-fix proof.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Cache-heavy Linux Gateways repeatedly report critical memory pressure and discard warm state despite low non-reclaimable usage.
Reason: The correction has clear value, but changing the area owner's explicitly retained raw-charge classification needs direction, and the implementation currently hides some genuine pressure.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR addresses a real false-alert problem that remains on main, but its subtraction can also suppress genuine memory pressure. The competing PR is still unmerged and does not yet justify closing this contribution.

Reviewed head: c541b4c3f63bac8cae2e6be3f4e122bce189e163
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should diagnostic process pressure switch from the explicitly retained raw-charge policy to verified cgroup working sets while scheduler availability remains raw?
  • Recommendation: Approve the narrow classification correction: Approve working-set diagnostics, retain scheduler and retirement ownership, and coordinate one complete implementation with fix: avoid false Gateway memory alerts from Linux file cache #208658.
  • Why: The existing area-owner change expressly retained raw leaf accounting, and neither this PR nor its linked issue records approval to replace that policy.

Before merge

  • Add real behavior proof - The supplied tests mock cache readings or filesystem counters and do not exercise a shipped Gateway on real cgroup v2; the author explicitly records that environment gap. Provide terminal output or logs showing the corrected alert and retirement behavior, with IPs, API keys, phone numbers and non-public endpoints redacted. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • [P2] Compute working set from the unclipped cgroup charge (P2) - When memory.current exceeds memory.high, both libuv and the delegated reader return zero available bytes, so rawUsedBytes becomes the limit rather than the actual charge. For memory.high=1 GiB, memory.max=2 GiB, memory.current=1.5 GiB and inactive_file=300 MiB, this subtraction reports 724 MiB and emits no process-pressure signal, although the actual working set is 1236 MiB and should remain critical. This is reachable with a soft cgroup ceiling and low Gateway RSS when other processes supply the charge. Read actual current-minus-inactive usage through the existing host-memory owner instead of subtracting from clipped headroom.
  • [P2] Match the cache credit to the sampled limit source (P2) - The new reader returns leaf cache without establishing that processLimitBytes is that leaf's ceiling. Node and readDelegatedMemory can instead return a smaller RLIMIT_AS or RLIMIT_DATA, while availability still comes from the cgroup ceiling. With a 1 GiB cgroup at full charge, a 512 MiB soft process limit and 128 MiB inactive cache, the existing critical process signal becomes 384 MiB out of 512 MiB and disappears. This changes the intentionally preserved soft-limit policy even though reclaimable group cache does not establish process-limit headroom. Apply cgroup refinement only when its ceiling matches the sampled limit; otherwise retain the existing raw fallback.

Findings

  • [P2] [P2] Compute working set from the unclipped cgroup charge — src/logging/diagnostic-memory.ts:397-398
  • [P2] [P2] Match the cache credit to the sampled limit source — src/logging/diagnostic-memory.ts:391-397

Tests

  • Missing end-to-end proof: Provide redacted before/after Gateway output on real cgroup v2 for cache-only usage and genuine anonymous pressure on ordinary and delegated mounts, including charge above memory.high; the supplied counterfactual test run is self-reported.
Agent review details

How this fits together

The Gateway diagnostic heartbeat converts process and cgroup memory readings into alerts and a diagnostics-channel signal consumed by idle-worker retirement and snapshot-cache cleanup.

flowchart TD
  A[Linux cgroup counters] --> B[Host memory reader]
  C[Node memory APIs] --> D[Diagnostic sampler]
  B --> D
  D --> E[Pressure classification]
  E --> F[Diagnostic alerts]
  E --> G[Worker retirement and cache cleanup]
Loading

Technical review

Best possible solution:

Keep diagnostic refinement in host-memory.ts, compute working sets from matching cgroup counters and ceilings, and preserve raw fallback for other process-limit sources.

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

I did not run a reproduction; current-main accounting and the linked report's cgroup counters establish the false-alert path, and source inspection establishes the introduced undercount.

Is this the best way to solve the issue?

Reusing the host-memory owner is appropriate, but subtracting cache from reconstructed availability loses above-limit usage and mixes cgroup cache with potentially different process limits.

Full review comments:

  • [P2] [P2] Compute working set from the unclipped cgroup charge — src/logging/diagnostic-memory.ts:397-398
    When memory.current exceeds memory.high, both libuv and the delegated reader return zero available bytes, so rawUsedBytes becomes the limit rather than the actual charge. For memory.high=1 GiB, memory.max=2 GiB, memory.current=1.5 GiB and inactive_file=300 MiB, this subtraction reports 724 MiB and emits no process-pressure signal, although the actual working set is 1236 MiB and should remain critical. This is reachable with a soft cgroup ceiling and low Gateway RSS when other processes supply the charge. Read actual current-minus-inactive usage through the existing host-memory owner instead of subtracting from clipped headroom.
    Confidence: 0.99
  • [P2] [P2] Match the cache credit to the sampled limit source — src/logging/diagnostic-memory.ts:391-397
    The new reader returns leaf cache without establishing that processLimitBytes is that leaf's ceiling. Node and readDelegatedMemory can instead return a smaller RLIMIT_AS or RLIMIT_DATA, while availability still comes from the cgroup ceiling. With a 1 GiB cgroup at full charge, a 512 MiB soft process limit and 128 MiB inactive cache, the existing critical process signal becomes 384 MiB out of 512 MiB and disappears. This changes the intentionally preserved soft-limit policy even though reclaimable group cache does not establish process-limit headroom. Apply cgroup refinement only when its ceiling matches the sampled limit; otherwise retain the existing raw fallback.
    Confidence: 0.96

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 bf848c90cedc.

Provenance checked

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Raw commit 398c8db adds src/infra/host-memory.ts:278 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 398c8db23048; files: src/infra/host-memory.ts)
  • Peter Steinberger: Raw commit 97e3c87 adds src/infra/host-memory.ts:78 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 97e3c87fc9a1; files: src/infra/host-memory.ts)
  • Josh Lehman: Raw commit d486658 adds src/infra/host-memory.ts:122 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d4866585915c; files: src/infra/host-memory.ts)

PR surface

Source +44, Tests +106. Total +150 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 50 6 +44
Tests 2 106 0 +106
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 156 6 +150

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 merge-risk: 🚨 availability: Undercounting genuine cgroup pressure suppresses alerts and idle-worker reclamation while a constrained Gateway continues retaining memory.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • merge-risk: 🚨 availability: Undercounting genuine cgroup pressure suppresses alerts and idle-worker reclamation while a constrained Gateway continues retaining memory.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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 readiness starts with the lower of the proof and patch scores. It is capped at 3/6 if the fix is partial, the change offers little benefit, a product decision is still open, or the PR reverses an earlier decision without saying why. ✨ 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 29, 2026, 7:30 PM ET / November 30, 2026, 00:30 UTC.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing as a duplicate of #208658, which opened two minutes earlier for the same issue (#208631) and has a more correct implementation.

My version subtracted reclaimable cache from reconstructed availability. ClawSweeper found two real defects in that approach, both of which #208658 already avoids by using working sets only when the verified leaf matches the sampled limit:

  1. Clipped headroom undercounts above-limit charge. When memory.current exceeds memory.high, both libuv and the delegated reader return zero available bytes, so the reconstructed charge saturates at the limit instead of the actual charge. Subtracting cache then hides genuine pressure.
  2. Cache credit is not tied to the limit source. A smaller RLIMIT_AS/RLIMIT_DATA can supply processLimitBytes while availability comes from the cgroup ceiling; subtracting leaf cache from that mix changes the intentionally preserved soft-limit policy.

I have posted those as review notes on #208658 so its author can keep the guard it already has. Thanks.

@wangmiao0668000666
wangmiao0668000666 deleted the fix/cgroup-reclaimable-cache-pressure branch November 30, 2026 00:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Linux cgroup v2: reclaimable page cache raises level=critical process_memory_threshold and publishes memory.critical every sample

1 participant