Repository navigation
Description
Summary
The gateway leaks unclosed fs.FileHandle references on session transcript .jsonl.lock files. On Node 22 (the supported LTS line per the 2026.5.18 release notes) this surfaces only as a deprecation warning, but on Node 24+ V8 promotes FileHandle GC to a fatal ERR_INVALID_STATE, which crashes the gateway process whenever the V8 GC happens to sweep one before OC closes it.
In our deployment this manifests as a chronic ~2-hour crash cadence on a single bot that accumulated a large session backlog (2,446 JSONL files in ~/.openclaw/agents/main/sessions/). Other bots on the same host / OC / Node version don't crash — they have 5–100 sessions on disk and don't generate enough open-handle pressure for V8 to ever GC a leaked one.
Environment
- OC:
2026.5.18(npm) - Node:
25.9.0(three majors above the documented Node 22.19 minimum, but well within what users on rolling-release Homebrew get by default) - OS: macOS 26.4.1 arm64
- Bot has been running ~30h under sustained activity; heartbeat interval is the gateway default 7,200,000ms (
gateway/heartbeat: {"intervalMs":7200000} heartbeat: started) - Session count on disk: 2,446
.jsonlfiles; no stale.lockfiles at rest
Symptom
Every ~2h a stability bundle is written with reason: uncaught_exception and this error:
A FileHandle object was closed during garbage collection. This used to be allowed with a deprecation warning but is now considered an error. Please close FileHandle objects explicitly. File descriptor: <N> (/Users/<bot>/.openclaw/agents/main/sessions/<uuid>.jsonl.lock)
The FD number and session UUID rotate; the path pattern is invariant: always a .jsonl.lock file in the agent's `sessions/` directory.
On the next launchd-driven restart the gateway's `main-session-restart-recovery` logs:
```
warn marked 1 interrupted main session(s) from stale transcript locks
warn marked interrupted main session failed: agent:main:main:heartbeat (transcript tail is not resumable)
```
confirming the leaked handle was held by the heartbeat session.
After ~4 crashes in 8h, macOS launchd's anti-thrash kicks in (`Successfully spawned … because inefficient`) — downstream symptom, not the root cause.
Reproducer
- Run gateway on Node ≥24
- Accumulate ~2,000+ session JSONL files in the agent's sessions directory
- Let the default 2h heartbeat fire several times
- Crash typically occurs within 2–4 hours
Likely root cause
OC's session-store code opens FileHandles for transcript locks during heartbeat-session write / scan operations and doesn't always go through an explicit `.close()` on every return path (likely error paths or interrupted writes). On Node 22 this is harmless because GC-close was warn-only; on Node 24+ it's fatal.
The stability bundle includes the diagnostic-phase log up to seq=181 (load → normalize → plugins → channels) but does not include the throwing stack frame, since the crash is in V8's GC sweep rather than user code.
Suggested fix direction
Audit `FileHandle` open call sites in the session-store layer (anywhere transcript locks are taken) for non-explicit close paths, especially:
- Error returns mid-write
- Heartbeat-session interrupt handling on shutdown
- Session metadata scans — the likely dominant pressure source given the 2,446-session correlation
Wrapping with `try { … } finally { await handle.close() }` or porting to `fs.promises.readFile`-style auto-closing helpers should close the leak.
Workaround for affected users
Either downgrade Node to the documented 22.19+ LTS line, or prune old session JSONL files until the on-disk count is in the low hundreds.
Stability bundle excerpt (sanitized)
```json
{
"version": 1,
"generatedAt": "2026-05-21T04:32:40.158Z",
"reason": "uncaught_exception",
"process": { "pid": 72273, "platform": "darwin", "arch": "arm64", "node": "25.9.0", "uptimeMs": 7208113 },
"error": {
"name": "Error",
"code": "ERR_INVALID_STATE",
"message": "A FileHandle object was closed during garbage collection. This used to be allowed with a deprecation warning but is now considered an error. Please close FileHandle objects explicitly. File descriptor: 38 (/Users//.openclaw/agents/main/sessions/.jsonl.lock)"
}
}
```
I have 10 stability bundles over a 31h window with the same error signature (different FD / UUID each time) — happy to share more if useful.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
clawsweeper commentedon May 21, 2026
Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.
Latest ClawSweeper review: 2026-05-22 08:07 UTC / May 22, 2026, 4:07 AM ET.
Workflow note: Future ClawSweeper reviews update this same comment in place.
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 autofix,@clawsweeper automerge,@clawsweeper fix ci, or@clawsweeper address review.@clawsweeper explainto ask for more context, or@clawsweeper stopto stop active automation.Summary
Keep open: the report has credible crash-loop evidence and the current code still uses the session
.jsonl.lockFileHandle path, but currentmaindoes not have enough macOS/Node 25 heartbeat-with-exec proof or a direct FileHandle-leak fix to close this as implemented.Reproducibility: no. high-confidence current-main reproduction is available yet. The reporter's production evidence is strong and now points to macOS Node 25 heartbeat sessions that run
exec, but maintainer current-main Linux stress attempts did not reproduce the FileHandle GC crash.Ways to help us reproduce this
Next step
The report is credible and high impact, but the exact current-main leak path needs maintainer-led macOS/Node 25 reproduction before a safe automated repair PR.
Review details
Best possible solution:
Build a macOS arm64 Node 25 heartbeat-with-exec stress reproduction with forced GC/open-handle observation, then fix the exact session lifecycle or
fs-safesidecar-lock path and validate it against Node 22 plus Node 24/25.Do we have a high-confidence way to reproduce the issue?
No high-confidence current-main reproduction is available yet. The reporter's production evidence is strong and now points to macOS Node 25 heartbeat sessions that run
exec, but maintainer current-main Linux stress attempts did not reproduce the FileHandle GC crash.Is this the best way to solve the issue?
Unclear. The suggested explicit-close direction is correct in principle, but current source and
fs-safealready have centralized release paths, so the best fix should first isolate the leaking FileHandle instead of applying a broad speculative cleanup sweep.Label changes:
issue-rating: 🦐 gold shrimp: Current issue advisory state selects this label.clawsweeper:needs-info: Current issue advisory state selects this label.clawsweeper:needs-live-repro: Current issue advisory state no longer selects this label.issue-rating: 🐚 platinum hermit: Current issue advisory state no longer selects this label.Label justifications:
P1: The report describes repeated gateway crashes affecting an active bot under sustained session-store load on modern Node.impact:crash-loop: The stability bundle evidence shows uncaught exceptions repeatedly terminating the gateway process.impact:session-state: The failing path is the agent session transcript lock and restart recovery marks interrupted main sessions.Acceptance criteria:
@openclaw/fs-safe, validate the package source/contract and bump the pinned dependency with lockfile/release proof.What I checked:
openclaw@2026.5.18/Node 25.9.0, all crashing withERR_INVALID_STATEon.jsonl.lock; the latest reporter comment narrows the differentiator to heartbeat sessions that run child-processexec, while a maintainer comment says several AWS Linux Node 25 current-main stress probes did not reproduce the crash.acquireSessionWriteLock()still derives<session>.jsonl.lockand delegates to the process-wideSESSION_LOCKS.acquire(...)manager, so the reported lock-file path is still part of currentmain. (src/agents/session-write-lock.ts:716, 6981051682f2)@openclaw/fs-safe@0.2.7sidecar-lock implementation opens the lock withfs.open(..., "wx"), retains the FileHandle in the held-lock entry, and closes it inreleaseHeldLock(); its docs tell callers to release infinally, which makes the dependency boundary relevant to the reported GC-close crash. (npm:@openclaw/fs-safe@0.2.7/dist/sidecar-lock.js:219, d649786af91d)finally; this is relevant cleanup coverage, but it does not prove the macOS/Node 25 heartbeat/exec FileHandle GC crash is fixed. (src/agents/pi-embedded-runner/run/attempt.session-lock.ts:493, 6981051682f2)cleanupEmbeddedAttemptResources()releases its cleanup lock in a finalfinallyblock after session/tool/runtime cleanup, which supports the intended release shape but still leaves the exact leaking return path unidentified. (src/agents/pi-embedded-runner/run/attempt.subscription-cleanup.ts:115, 6981051682f2)src/agents/session-write-lock.test.ts:313, 6981051682f2)Likely related people:
src/agents/session-write-lock.ts,src/agents/session-write-lock.test.ts)@openclaw/fs-safedependency bump that owns the delegated FileHandle lock implementation. (role: recent area contributor; confidence: high; commits: 1becebe188eb, fb6e415d0c52, 1a7669bc63a0; files:src/agents/session-write-lock.ts,package.json,pnpm-lock.yaml).jsonl.lockcleanup, merged by Peter Steinberger. (role: feature-history contributor; confidence: medium; commits: e91a5b021648; files:src/agents/session-write-lock.ts,src/agents/session-write-lock.test.ts,src/gateway/server-startup-post-attach.ts)jalehman. (role: recent adjacent contributor; confidence: medium; commits: 9c00268914b9; files:src/agents/pi-embedded-runner/run/attempt.session-lock.ts,src/agents/pi-embedded-runner/run/attempt.subscription-cleanup.ts,src/agents/pi-embedded-runner/run/attempt.ts)src/agents/pi-embedded-runner/run/attempt.session-lock.ts,src/agents/pi-embedded-runner/run/attempt.ts,src/config/sessions/transcript-write-context.ts)Remaining risk / open question:
exec.@openclaw/fs-safesidecar-lock boundary, so a durable fix may require either local lifecycle changes or a dependency release and bump.fs-safebump reduce suspicion in nearby code, but they do not provide direct FileHandle GC-leak proof for this crash signature.Codex review notes: model gpt-5.5, reasoning high; reviewed against 6981051682f2.
joshavant commentedon May 22, 2026
Thanks for the detailed report. We tried several current-main reproductions on AWS Linux with Node 25.9.0, including large session directories, transcript append stress, real gateway/session soak, and gateway-shaped lock contention. So far we have not reproduced the unclosed
.jsonl.lockFileHandlecrash.Could you share a few more details to help narrow the remaining gap?
~/.openclawon local APFS, iCloud Drive, Dropbox, a network volume, or any synced filesystem?.jsonl.lockpayload if any lock file is present immediately after a crash?One current-main finding: lock contention between real OpenClaw-classified gateway processes behaves correctly in our probe: contenders time out, lock files are released, and we see no warning/uncaught/deleted lock FD signal. That points us toward a macOS-specific or real lifecycle-path reproduction rather than the normal transcript append lock path.
cjalden commentedon May 22, 2026
Thanks for digging in. Answers in order, with one promising lead at the bottom:
1. Filesystem
Local APFS, no sync layer:
/Users/<bot>/) is on the main data volume — same disk, not external.~/Library/CloudStoragedoesn't exist on the bot account), no Dropbox in the bot's home, no network mounts touching.openclaw/.sessions/or its files (xattrreturns empty).drwx------+) but that's just a single inherited ACE granting another local user read access — no kqueue/fsevents wedge that we know of.2. Process manager
macOS
launchdLaunchDaemon,KeepAlive=true, running as a non-admin local user:Nothing else (no pm2, no nodemon, no shell wrapper). After repeated crashes,
launchdeventually inserts an "anti-thrash" SIGTERM-then-relaunch cycle with reasoninefficient, but that's downstream of the crashes.3. Node 22 control
Downgraded the same host from Node 25.9.0 to Node 22.22.3 (same 22 LTS line; didn't try 22.19.x specifically). The affected bot has been running ~13 hours and ~6 heartbeat intervals with zero new
uncaught_exceptionstability bundles. Identical config, identical session directory, identical workload. So the crash is gated on Node ≥24's promotion of FileHandle GC toERR_INVALID_STATE.4. Stability bundle + matching gateway log
The interesting events from the snapshot leading up to the crash (full bundle available if you want it — happy to email or attach to the issue):
{ "seq": 100, "type": "session.state", "outcome": "processing", "reason": "run_started" } { "seq": 102, "type": "diagnostic.memory.sample", "memory": { "rssBytes": 856670208, "heapTotalBytes": 577814528, "heapUsedBytes": 452423000 } } { "seq": 103, "type": "diagnostic.liveness.warning", "level": "info", "eventLoopDelayMaxMs": 8262.8, "eventLoopUtilization": 0.436, "source": "agent:main:main:heartbeat(processing/model_call,q=0,age=13s last=model_call:started)" } { "seq": 104, "type": "diagnostic.heartbeat" } { "seq": 141, "type": "exec.process.completed", "target": "host", "mode": "child", "durationMs": 13, "exitCode": 0 } { "seq": 143, "type": "exec.process.completed", "target": "host", "mode": "child", "durationMs": 14, "exitCode": 0 } { "seq": 145, "type": "exec.process.completed", "target": "host", "mode": "child", "durationMs": 14, "exitCode": 0 } { "seq": 181, "type": "session.state", "outcome": "idle", "reason": "run_completed" } // ts 1779337959888 // 270 ms later, the crash: "error": { "code": "ERR_INVALID_STATE", "message": "... File descriptor: 38 (/Users/<bot>/.openclaw/agents/main/sessions/<uuid>.jsonl.lock)" } // process uptimeMs at crash: 7,208,113 (≈ 2h00m08s, i.e. exactly one heartbeat after start)The matching gateway log around the failing session (third-party plugin output redacted):
5.
.jsonl.lockpayloadNo
.lockfiles at rest in any agent's sessions dir right now (find ... -name "*.lock"returns empty). The on-restartmain-session-restart-recoverysweep removes/marks the stale lock when the next gateway starts, so by the time anyone could grep for one it's already gone. The earlier log shows the recovery message:warn marked interrupted main session failed: agent:main:main:heartbeat (transcript tail is not resumable). Happy to instrument a wrapper to snapshot the lock between crash and relaunch if you'd like the contents — let me know.6. Prune-alone test
Can't disambiguate cleanly from current data. We pruned the directory (2,446 → 204
.jsonlfiles) and the Node downgrade happened a few hours later — both interventions overlap the "no more crashes" window. To answer it properly I'd need to put Node 25 back with the pruned directory, which I'd rather not do while the bot is in service. If you want a controlled probe, I can stand it up on a side host.Lead worth chasing: heartbeat sessions that exec subprocesses
We have a handful of bots on the same host, same OC version, same Node. Only one crashes. The differentiator isn't volume — it's that the affected bot's heartbeat session actually runs work. From the bundle: 3
exec.process.completedevents fire during the heartbeat session's run, allmode: "child",target: "host". Every other bot's heartbeat is effectively a no-op (the heartbeat poll model_call returns "nothing to do") and never crashes, even on Node 25.9.0 with similarly-sized session histories.The crash happens 270 ms after
session.state: idle, reason: run_completed— i.e. during the post-session GC sweep, not during transcript writes. That matches your finding that the normal transcript-append lock path is clean.Suggested reproducer to try on macOS arm64:
exectool 2–3 times per heartbeat (any prompt that gets it to shell out a few times).run_completed.My best guess at the leak: somewhere in the heartbeat-session teardown path, a transcript-lock
FileHandleis overshadowed/reassigned by a code path that ran child-process I/O, so the original handle has no live reference and gets GC'd before the cleanup ever calls.close()on it. macOS may be hitting this where Linux doesn't because of differences in howchild_process.spawninteracts with parent FDs (or because of timing/GC scheduling differences in V8 on Darwin arm64).Will gladly run any additional probes you want, including reverting to Node 25 on a side instance to bisect prune-vs-runtime.
yaorenliang commentedon May 23, 2026
Additional crash data — same pattern, Node 26
Seeing the same crash on my setup with 3 stability snapshots in 2 days.
Environment
2026.5.19(Homebrew)26.0.0.jsonlfiles at time of crash (cleaned up from 1,580+)Crash log
All 3 crashes are the same
ERR_INVALID_STATEfrom FileHandle GC:Crash 1 — 2026-05-21T09:15:28Z (uptime: ~3.5h)
Crash 2 — 2026-05-22T04:20:22Z (uptime: ~62s)
Crash 3 — 2026-05-22T04:21:24Z (uptime: ~62s, immediately after crash-restart)
Additional observations
Memory pressure correlates with crash cadence: gateway RSS was at 4.2–4.5GB (threshold 3GB) before the crash series, with
memory pressure: level=criticallogged every 5 minutes.Cron jobs trigger the crash path: the
系统资源监控cron job failed at 08:18 withNo API key found for provider "tokenmp"after a hot-reload invalidated the auth profile — this suggests the session lock leak may be on error/timeout paths during cron session lifecycle, not just heartbeat.Active-memory plugin also affected: crash 1 points to the active-memory plugin's session lock in
/tmp/, not just the main agent sessions directory.Subagent session accumulation accelerates the problem: 383 completed subagent sessions (330 done + 50 failed) were tracked in
sessions.jsonalongside 97 dashboard sessions and 14 cron sessions — the sustained session-store load matches the original report's reproducer.Workaround attempt
Deleted 707MB of old trajectory/bak/checkpoint files (892 trajectory + 152 bak + 60 checkpoint files). Disk usage dropped from 1GB to 146MB but did not resolve the CPU/memory pressure — the leak is in-process, not on-disk.
Hope this helps narrow down the non-explicit close paths.
RomneyDa commentedon Jun 1, 2026
Fixed/de-risked on current
mainby the session-lock lifecycle fixes in #86427 and #87747.Additional maintainer proof run on macOS arm64:
.jsonl.lockFileHandle; both crashed with the expectedERR_INVALID_STATE, proving the harness catches this Node 24+ failure mode.mainforced-GC lifecycle proof passed on Node v24.16.0, v25.9.0, and v26.3.0 using realacquireSessionWriteLock, realcreateEmbeddedAttemptSessionLockController, and real cleanup paths..jsonlfiles, 80 heartbeat-style cycles per Node version, 3 child-process execs per cycle, forced GC after every cycle, periodic stale-lock sweeps, final.jsonl.lockcount 0.node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.session-lock.test.ts src/agents/embedded-agent-runner/run/attempt.subscription-cleanup.test.ts src/agents/session-write-lock.test.ts --reporter=verboseResult: 3 files passed, 101 tests passed.
This does not replay a full live-provider heartbeat interval, but it covers the reported FileHandle-GC crash class on the reported macOS arm64 + Node 25/26 axis with the real lock implementation and heartbeat/exec-shaped session lifecycle.
RomneyDa commentedon Jun 1, 2026
Closing as fixed/de-risked on current
mainby #86427 and #87747.Maintainer proof is recorded here: #84820 (comment)
Please open a new issue or ask to reopen this one if a current
mainor post-fix release still reproduces the Node 24+.jsonl.lockFileHandle GC crash with comparable stability-bundle evidence.