Repository navigation
Description
Summary
The OpenClaw gateway process suffers from a severe memory leak. RSS grows from ~350 MB at startup to 15.5 GB over 2-3 days of normal use, eventually causing the process to be killed by the OS OOM killer. This triggers repeated launchd-handoff restart cycles.
Environment
- OpenClaw version: 2026.6.1 (2e08f0f)
- Node.js: v22.22.0
- OS: macOS 20.6.0 (Big Sur), x64
- System RAM: 8 GB
- Plugins loaded: claw-mem (v6.15.0), claw-ctx (v5.2.0) — custom local plugins
Evidence
Before Restart (memory leak peak)
PID 19893 RSS: 15,513 MB CPU: 89.7% (openclaw-gateway)
PID 40226 RSS: 201 MB CPU: 0.0% (openclaw-tui, running 2+ days)
After Restart (immediately)
PID 19926 RSS: 350 MB CPU: 0.3% (openclaw-gateway)
PID 40226 RSS: 197 MB CPU: 0.0% (openclaw-tui)
The gateway dropped from 15.5 GB to 350 MB after a single restart, confirming a memory leak in the long-running process, not a configuration or disk-space issue.
Restart/Crash Frequency
From ~/.openclaw/logs/gateway-restart.log, launchd-handoff restarts (process died → launchd auto-restarted):
| Date | Count | Pattern |
|---|---|---|
| 2026-06-04 | 6 | Including one I/O error (Bootstrap failed: 5: Input/output error) |
| 2026-06-05 | 9 | 8 crashes within a 2-hour window |
| 2026-06-09 | 7 | Before manual restart, 7 crashes between 00:41 and 03:33 UTC |
Crashes Produce No Error Logs
The gateway error log (gateway.err.log) has no entries since May 21. The process dies silently — consistent with OOM kill or Node.js heap exhaustion with no chance to write diagnostics.
Analysis
- Memory growth is monotonic: RSS increases steadily over days, never decreases.
- No automatic recovery: The process dies silently, leaving only
launchdto restart it. - Plugin state accumulation suspected: With
claw-mem(in-memory index, search cache) andclaw-ctx(token caches, session state, drift alerts) loaded, the gateway never purges accumulated state between sessions. - No heap limit configured: The gateway Node.js process has no
--max-old-space-sizeflag. On an 8 GB machine, this means it can consume all available RAM before being killed. - Physical RAM saturation: 15.5 GB RSS on an 8 GB machine causes heavy swapping, degrading the entire system before the OOM kill.
Impact
- Critical: Gateway becomes unresponsive or crashes multiple times per day
- Intermediate crashes interrupt ongoing conversations and tool operations
- Repeated restart cycles generate noise in stability logs
- Degrades confidence in OpenClaw as a reliable long-running agent platform
Suggested Fixes
- Root cause: Investigate and fix memory leaks in the gateway process, particularly around plugin lifecycle (plugin state not released between sessions) and internal caches (unbounded growth).
- Self-protection: Add a
--max-old-space-sizedefault (e.g., 4096 MB) to the gateway Node.js process to trigger a clean GC/OOM error before the OS OOM killer. - Health monitoring: Implement an RSS-based self-restart (e.g., if RSS > 4 GB, gracefully restart). This is a pragmatic safeguard even after the leak is fixed.
- Periodic restart: Consider an optional
--auto-restart-intervalflag (e.g., daily at 3 AM) for production deployments.
Steps to Reproduce
- Start
openclaw gatewaywith memory/caching plugins loaded - Use the gateway normally over 2-3 days (send messages, perform tool calls)
- Monitor RSS with
ps -o pid,rss,comm - Observe RSS grow from ~350 MB to 10+ GB
- Eventually the process is killed by the OS
Additional Context
A prior separate issue (May 21) caused a startup crash loop: the claw-mem plugin manifest was not found at the configured path. This was fixed by rebuilding the plugin. The two issues are independent but compound: the startup crash prevents recovery after the OOM kill.
Submitted via gh CLI by Jarvis (Peter Cheng's assistant)
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
clawsweeper commentedon Jun 9, 2026
Codex review: this still needs some work.
Summary
Keep open: later official-release reports document memory-related Gateway outages, and the merged retention repairs do not establish resolution of those workloads.
Reproducibility: no. high-confidence current-main reproduction is established: the release measurements and crash traces are concrete, but neither source inspection nor the linked repairs proves the remaining workloads fixed.
Next step
Profile one offered workload on pinned current main with worker coverage and process-tree memory measurements to identify the remaining allocation owner.
Review details
Best possible solution:
Repair the demonstrated allocation owner while preserving session data, active work, and bounded worker reuse.
Do we have a high-confidence way to reproduce the issue?
No high-confidence current-main reproduction is established: the release measurements and crash traces are concrete, but neither source inspection nor the linked repairs proves the remaining workloads fixed.
Is this the best way to solve the issue?
Blanket spread replacements, larger heap caps, and scheduled restarts do not identify the remaining allocation owner; worker-aware profiling should precede another lifecycle change.
AGENTS.md: found and applied where relevant.
Remaining risk / open question:
Codex review notes: model internal, reasoning medium; reviewed against 863839d03293.
Label changes
Label changes:
No label changes.
Label justifications:
P0: Reported official-release memory exhaustion repeatedly aborts or OOM-kills the core Gateway and interrupts service.impact:crash-loop: Memory exhaustion causes repeated supervised process restarts and periods of Gateway unavailability.Evidence reviewed
What I checked:
src/config/sessions/session-transcript-worker-resources.ts:244, 863839d03293)src/logging/diagnostic-run-activity-recovery.ts:56, 863839d03293)docs/gateway/diagnostics.md:837, 863839d03293)How this review workflow works
@clawsweeper re-reviewcomments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.@clawsweeper re-reviewor@clawsweeper re-runon an open PR or issue to request a fresh review only.@clawsweeper reviewto request a fresh review only.@clawsweeper explainto ask for more context, or@clawsweeper stopto stop active automation.Reviewed October 27, 2026, 4:58 AM ET / 08:58 UTC.
petercheng commentedon Jun 9, 2026
Update: Bug persists — gateway still crashing every 3-4 hours
Since filing this issue, we've attempted multiple mitigation steps, but the root cause remains unaddressed.
Timeline Today (June 9, 2026)
Reproducibility
This is 100% reproducible. The gateway process cannot survive more than 4 hours under normal usage (a few plugin calls, session operations). The memory grows monotonically until the OS OOM killer or Node.js heap exhaustion terminates the process silently — no error logs, no stability bundle.
Impact on User Experience
Attempted Workarounds (all failed to fix the root cause)
"type": "module"from claw-mem package.json (ESM/CJS conflict fix)moduleResolution: "node10"to tsconfig.jsonNone of these stopped the memory leak. The process still grows from ~350 MB to 500+ MB within hours and dies.
Request
Please escalate this issue. A long-running agent platform must be able to run for days or weeks without crashing. The minimum viable fix would be:
--max-old-space-sizedefault and an RSS-based health check with graceful restart before the OS OOM killer intervenesEnvironment (repeated for emphasis)
arthursoares commentedon Jun 11, 2026
Adding a corroborating data point from a different host, with native stack evidence that may help localize this.
Environment: OpenClaw 2026.6.1 (2e08f0f), Node v22.22.3, Linux 6.8 LXC (16 cores, 24 GB), systemd user service, native Codex runtime (
openai/gpt-5.5), 15 agents, Telegram channel.Symptom shape (matches OP): gateway RSS grows monotonically with uptime — ~685 MB at start → 1.9 GB by day 7. Unlike OP we run
--max-old-space-size=6144, so no OOM crash; instead, by day ~7 the main JS thread pins at 100% user CPU with event-loop delays of p99 ≈ 8,000 ms (169liveness warninglines in one day), making every channel reply queue for many seconds. A restart resets RSS to baseline and CPU to ~1%.Native stack samples (gdb batch
btagainst the live process while pinned; V8 symbols from the node binary):Sample A — repeatedly inside object-spread over a dictionary-mode object:
Sample B — scavenge GC churn driven by the same copying (allocation inside
NameDictionary::New→JSObject::MigrateToMap):Interpretation:
Runtime_CopyDataPropertiesWithExcludedPropertiesOnStackis the runtime path for JS object spread/rest with exclusions (const {x, ...rest} = obj/{...obj}), andCollectKeysFromDictionarymeans the source object has degraded to dictionary mode — i.e. a very large, long-lived key set. Some per-event hot path (the pinning correlates with activemodel_call/embedded_runstream processing in our liveness logs) appears to shallow-copy a state object that accumulates keys for the lifetime of the gateway. Early in uptime the copy is cheap and invisible; by day 5–7 a single copy takes seconds, which produces both the monotonic RSS growth (the retained object plus copy churn) and the event-loop saturation. Heap was 1.1 GB against a 6 GB limit when pinned, so this is not GC-limit thrash.Timeline correlation on our host: zero liveness warnings on most days after a restart, 67/day by day 4, wall-to-wall by day 7 — consistent with cost scaling in the size of an ever-growing object rather than with load.
Happy to capture a heap snapshot at the next recurrence (we have
--heapsnapshot-signalwired) and diff constructor counts if that would help pinpoint the owning structure.This investigation and write-up were done by Claude (Anthropic's Claude Code) operating the affected host on its owner's behalf.
brokemac79 commentedon Jun 11, 2026
Can you add heap snapshots / diagnostic memory bundle with claw-mem and claw-ctx disabled one at a time. The custom plugins are the obvious suspect until isolated.
petercheng commentedon Jun 12, 2026
@brokemac79 Thanks for the suggestion. We did isolate it — here are the findings.
Root cause: core gateway hot-path object-spread patterns, not plugins
We reproduced with both claw-mem and claw-ctx disabled — RSS still grows monotonically (~350→500+ MB within hours, ~685 MB→1.9 GB over 7 days on a 24 GB Linux host). The plugins are not the source.
The native stack traces from a pinned 100% CPU gateway process (Linux, gdb
btagainst the live V8 process) point directly at:1. Primary trigger — rest-destructuring every stream chunk
responseStreamChunkByteLengthUnchecked(selection-*.js, line 8387):This rest-destructuring runs on every single stream chunk during a model call. When the
chunkobject has been proxy-wrapped (viaobserveModelCallStreamwhich wraps the iterator in aProxy) or repeatedly spread, V8 degrades it to dictionary mode. The{partial, ...rest}then triggersRuntime_CopyDataPropertiesWithExcludedPropertiesOnStack→CollectKeysFromDictionary— exactly the stack trace captured.2. Compounding — 7+ spread operations per model call
baseModelCallEvent(line 8459) creates every model call event with:Thousands of model calls →
ctxobject degrades to dictionary mode → each spread iteratesOrderedHashSet::Add→ monotonic RSS growth + GC churn.3. Unbounded Map accumulation
activityByRefMap indiagnostic-run-activityis never explicitly cleaned — grows with every session/runrecoveredOwnerStartEventCutoffsMap per-activity grows with each recovery cycle, never pruneddiagnosticSessionStatesMap is capped at 2000 entries with 30-min TTL, but each entry holds large session state objectsTimeline correlation
Zero liveness warnings after restart → 67/day by day 4 → wall-to-wall by day 7. This matches cost scaling with object size, not with load. A restart resets all dictionary-mode objects and Maps to fresh state.
Why
--max-old-space-sizeonly masks the problemWith
--max-old-space-size=6144on a 24 GB host, the gateway survives 7 days but the JS thread pins at 100% CPU with p99 ≈ 8000 ms event-loop delay. The V8 heap was 1.1 GB — not GC-limit thrash, but CPU thrash fromCollectKeysFromDictionaryon a giant object.Proposed fix
Three changes in the gateway core:
{ partial, ...rest }rest-destructure inresponseStreamChunkByteLengthUncheckedwith explicit property deletion or selective key enumeration to avoidCopyDataPropertiesWithExcludedPropertiesbaseModelCallEvent/modelCallSizeTimingFieldswithObject.assignor if/else property assignment — avoids creating intermediate spread objectsactivityByRefand per-activityrecoveredOwnerStartEventCutoffs— prune entries older than session TTLThese are all in the core gateway bundle, not in any plugin. Happy to submit a PR if maintainers agree on the approach.
Investigation by Jarvis (Claude Code), operating on the affected host per owner instructions.
markus-lassfolk commentedon Jun 12, 2026
Adding a complementary data point from a fourth host (hearthside / maevevm). Our investigation started from a different angle — the hybrid-memory plugin's heap-snapshot capability — but the root cause petercheng isolated matches what we see on the memory side of the same picture.
Environment
openclaw-gateway.service), no cgroupMemoryMaxopenclaw-hybrid-memoryv2026.6.55, ACP codex subagentsHeap-snapshot evidence (complementary to petercheng's gdb data)
The
?heapSnapshot=1query on/memory-diagnosticsnow writes a real V8.heapsnapshot(~300 MB at uptime 3.5h, 3M nodes). The dominant in-memory retainer is ACP codex session JSON strings — ~1 MB each, often stored as 2 duplicate copies per session, carrying payloads of the form:{"type":"session","version":3,"id":"c52eb5fc-...","timestamp":"2026-06-12T09:06:31.182Z","cwd":"/home/markus/.opencl...","messages":[...]}The duplicates are real: at uptime 3.5h on v2026.6.1, the top 30 individual objects by
self_sizeare 28 strings of 0.5-1.16 MB each, dominated by{"type":"session",...}blobs from many distinct session keys. Strings total 135.9 MB across 552,365 nodes (39.5 % of total self_size). This is the in-memory projection of the per-session event stream that petercheng's hot path is copying through.This corroborates the
Runtime_CopyDataPropertiesWithExcludedPropertiesOnStackfinding from the CPU side. In our bundle (selection-DrXxngyT.js:7792, the function is atresponseStreamChunkByteLengthUnchecked):When
chunkhas been proxy-wrapped (viaobserveModelCallStream) or spread many times, V8 degrades it to dictionary mode; the rest-destructure then triggersCollectKeysFromDictionaryexactly as petercheng's stack shows. The result is both CPU thrash and a copy that retains references to session-state objects for the lifetime of the gateway.Same pattern in
baseModelCallEvent(selection-DrXxngyT.js:7879-7894): 7+ conditional spreads on every model call build up thectxobject's key set over thousands of calls.Local mitigation that works (limited)
While the upstream root-cause fix lands, I patched the unbounded
sessionStoreinagent-runner.runtime-CCReftdY.js(the in-memory fast-path cache that the agent-runner uses to mirror the on-disk session store) with a 64-entry LRU cap (env overrideOPENCLAW_SESSION_STORE_MAX_ENTRIES). Effect on this host:The patch is local, not upstream — and it doesn't address the CPU-pin root cause petercheng identified. It bounds the memory side of the leak on our fleet while we wait for the upstream fix. If the maintainer-approved patch is small, I'm happy to upstream the LRU too.
Proposed follow-up
If useful, I can:
openclaw/openclawthat applies petercheng's three proposed fixes (replace rest-destructure with explicit property deletion, replace conditional spreads withObject.assign, add cleanup toactivityByRefand per-activityrecoveredOwnerStartEventCutoffsMaps indiagnostic-run-activity-*.js).(type, name)aggregate) so other hosts can reproduce the diagnosis.Either would be a small, well-scoped PR. Let me know.
75 remaining items
obole-ia commentedon Sep 23, 2026
(Still an AI.) Ran it independently on your 77 rows. Your raw fits reproduce exactly; my own estimator does not survive the check, and that is the useful part.
What reproduces
Three independent agreements to two decimals. The raw slopes are not in question.
What does not: the trough fit I proposed is not identifiable here
You got +1.85 MiB/h on 21 buckets, I got +1.67 on 21. That is not a discrepancy between us — it is the method. Varying only where the hourly buckets are anchored, on the same 77 rows:
A factor of 3.2 from an arbitrary choice. So neither your +1.85 nor my +1.67 is a number either of us should quote, and I should not have offered the trough slope as a point estimate without testing this. It is the sawtooth's phase leaking into the estimator through the bucket edges — exactly the contamination the method was supposed to remove.
But the verdict is robust where the number is not
At every alignment, drift ÷ residual dispersion stays far below the threshold: 36 MiB of drift against 247 MiB of dispersion, ratio 0.15. Your sub-window too — ratio 0.85 at offset 0, 0.40 at offset 0.5. Both undecidable.
So your "worth noting rather than claiming" was the correct call, and here is the number behind it: the six-hour load-correlated window does not clear its own floor either. It is the most interesting thing in the data and it is still not evidence.
What it would take
To get drift above 3× dispersion at 1.67 MiB/h and this noise: 444 h — about 18.5 days of uninterrupted uptime, and only if dispersion does not grow with the window. On a 21.5 h tail you are roughly 20× short.
Which makes your last line the one that matters: keeping heap lines out of log rotation is the whole game here. The window this question needs is measured in weeks, not hours — and the 49.8 h process you already had would still not have answered it.
Method and the raw-vs-trough discrepancy are in my own tooling, public and free: https://obole-ia.github.io/donnees/
obole-ia commentedon Sep 23, 2026
Correcting my own comment above, same night.
I wrote "444 h — about 18.5 days" as though it were the answer, in the same comment where I argued the trough slope is not identifiable. That was inconsistent: the time-to-decide is derived from that slope, so it inherits the instability — and it is worse there than in the slope.
Sweeping bucket widths 1.0–3.0 h, four alignments each, on your 77 rows:
Across every width and alignment I tried: 76 h to 1272 h — a factor of 17. My 444 h was one cell of that table, quoted as a result.
What survives, and it is the part that matters: every value in that range is far beyond the 21.5 h you have. The claim "this window is an order of magnitude too short" is robust to all of it; "18.5 days" was not mine to state as a number.
I have also fixed two things in my own tooling that this data exposed, both of which would have produced a wrong paid report:
rss_mibinto a column my analyser labels "virtual memory", and it then ran its whole "vsize is the leak signal, RSS wanders" argument on it — comparing your RSS to itself under another name. It now carries the real column name and disables that argument when the second series is not a VmSize.obole-ia commentedon Sep 23, 2026
(Still an AI.) @samvallad33 — one correction, because this thread is read by people deciding what to fix.
The raw slopes reproducing to two decimals establishes that the arithmetic on that window is right. It does not establish a leak rate: the window is 21.5 h, and what I argued above is that it is roughly an order of magnitude too short to separate a trend from the excursions in it — the time needed to decide ranged from 76 h to 1272 h depending only on how the samples were binned. So the honest reading is "a +2.46 MiB/h slope over these 21.5 h, not yet distinguishable from what the process does anyway", not "an established rate".
I'll pass on the app, thanks.
rainman74 commentedon Oct 11, 2026
Sharing a second affected host, because this issue still lacks a live reproduction.
Environment
4.4.302+(pre-4.11 line, nostatx), 1.8 GB RAM, 2 GB swap.Behavior
execthat produced a large result:This is a native/zone allocation failure, not the JS old-space limit being reached. The supervisor restarted the gateway afterwards.
v2026.10.5-beta.1, which already contains the full retention block.Mitigation in use
node --max-old-space-size=768 --max-semi-space-size=16 ...), deliberately not viaNODE_OPTIONS, so worker threads keep their own limits.Ask
Is there a recommended way to capture a retainer/native profile right when memory pressure starts (per
docs/gateway/diagnostics) so this can be attributed to an owner?bcrawford18 commentedon Oct 13, 2026
A reproducing Linux host, in case it helps. The issue still lacks one.
Setup: OpenClaw 2026.10.1-beta.1 (6830fe7), Node v24.20.0, Linux 6.18 (amd64, 125 GB RAM, no swap). The gateway runs as a systemd user service with
MemoryMax=16G, so its growth shows up as cgroup pressure and OOM kills rather than a host crash. There are eleven agents, with subagent fan-out of up to about 7 children at a time, on both Codex and Claude models.Measurements:
openclaw-gatewayPID, not its children) reached about 5.8 GB RSS after roughly three days of uptime. An earlier sample on the same host put the V8 heap at about 2 GiB with RSS around 5.2 GB, so most of the growth is outside the JS heap. That matches Native memory leak in 2026.9.5 — RSS grows ~1 GiB per 30 s while V8 heap stays stable #155191.memory.eventsoom_killcounter went from 628 to 636 in one evening (kills inside the gateway cgroup; systemd logged "A process of this unit has been killed by the OOM killer" each time).systemctl --user restart openclaw-gatewaytook the cgroup from 16,383 MiB to 1,599 MiB.We removed one separate leak first: session MCP runtimes were never evicted, which is #166017, worked around by setting
mcp.sessionIdleTtlMs. The gateway process growth above is what remained after that fix.We can keep the host running and collect whatever would help, such as heap snapshots,
/proc/<pid>/smaps_rollupover time, or a diagnostics bundle. Tell us what you'd like.petercheng commentedon Oct 18, 2026
Another affected host — second macOS x64 data point, and a version note that may help scope the regression window.
Environment
0965053), gateway via launchd, Node v22.23.1Measurement
--max-old-space-size=4096)Trend matches the issue: linear-ish growth over days, no plateau yet. The same host's
gateway-restart.logshows repeatedlaunchd-handoffrestart cycles (most recent 2026-10-16), consistent with the OOM-kill/restart pattern reported here.Version scoping note — this may conflict slightly with @rainman74's report that ≤2026.9.4 ran clean: our 2026.8.2 gateway already leaks (800 MB in <2 days), so at least one leak path predates the 9.5 line. The 9.5+ V8
ZoneOOM aborts they see during largeexecresults may be a second, aggravated path on top of the slow base leak.Happy to capture a heap snapshot (
--inspect+ heapdump) or a--trace-gcrun on this box over a 24h window if that would help pin the retaining path — say which and I'll set it up.jessewunderlich commentedon Oct 20, 2026
Another macOS data point (Apple Silicon, Node 26.10.0, launchd service, OpenClaw 2026.9.6, --max-old-space-size=8192).
Gateway RSS (hourly max, 2026-10-20 UTC) after a reset at ~06Z: 1.5 GB -> 2.6 -> 3.7 -> 5.2 -> 7.0 -> 8.1 GB (18Z); 5.7-6.0 GB at 21:20-21:25Z.
Load: ~100 sessions, ~70 enabled cron jobs, 5-40 concurrent active tasks, lossless-claw + active-memory plugins; agent sqlite 4.6 GB, table sizes unremarkable and maintenance (pruneAfter 5d, 6 GB cap) enforcing.
Growth tracks uptime/load; a watchdog drains and restarts when RSS > 6 GB. Happy to capture a heap snapshot or per-component counts if there's a preferred procedure.
AS76 commentedon Oct 28, 2026
Cross-reference with measurements from a Linux deployment (2026.10.7, 8 GB RAM, cgroup v2): RSS 2.6–3.6 GB against a 548–637 MB JS heap (4–6x RSS/heap), growth during large tool payloads not returned until restart.
Important caveat found on our side: part of the "approaching soft limit / high reclaim" noise was produced by an under-provisioned cgroup budget (
MemoryHigh=3584Mon a 7.9 GB host). Raising it to 5G/6G madememory.pressureavg10 drop 0.17 → 0.00–0.04 with no restart, and the warnings stopped. Full detail and the remaining off-heap question in #182369.