Repository navigation
improve: keep the lean Gateway from running out of memory on its first start - #203790
Conversation
Lean holds post-ready maintenance until the Gateway goes quiet after startup, so a first turn no longer shares its memory with the maintenance isolates that work starts. Lean also skips the Linux command spawn broker, as hosts with 1 GiB or less already do, and the Linux directory watch helper ends itself after its caller dies with a timer instead of a second isolate. The directory watch helper and natively spawned SQLite read-only helpers become the preferred Linux OOM victims under the existing child OOM policy.
Post-ready maintenance admits its root before it waits for the barrier, so lean's idle check now ignores roots that are waiting on the barrier. The spawn broker placement reads the configured profile from the config being started when an in-process restart brings no CLI snapshot.
Post-ready maintenance and retained plugin cleanup now wait for the barrier before they admit root work, so lean's idle check counts only real requests. Profile prediction resolves dotenv values into an isolated env, as bootstrap would, without changing process env.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR defers lean startup background work, skips its Linux command broker, and reduces helper memory and OOM exposure. Example: A lean Gateway starts in a 1.5 GiB Linux container and immediately receives an agent turn.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Partial Merge readiness✅ Ready for maintainer review Keep open: this PR provides a useful, measured reduction in lean Gateway startup memory, and current main retains the overlapping startup work; no actionable correctness defect was found. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway startup resolves resource policy and launches request and background runtimes; the scheduler controls background admission, while process owners launch and retire command, watch, and SQLite helpers. flowchart TD
A[Gateway startup] --> B[Resource profile selector]
B --> C[Command spawn placement]
B --> D[Post ready scheduler]
E[Active request roots] --> D
D --> F[Maintenance cron and prewarming]
C --> G[Child process owners]
G --> H[Linux OOM preference]
Technical reviewBest possible solution: Retain the bounded lean-only scheduling and direct-spawn changes using the existing resource, scheduler, and process owners. Do we have a high-confidence way to reproduce the issue? Source confirms startup background work can overlap the first turn; the reported OOM is intermittent, and both paired lean arms completed three runs, so a deterministic current-main OOM reproduction is not established. Is this the best way to solve the issue? The patch addresses measured startup competition with bounded deferral and an existing direct-spawn mode, while preserving macOS watcher isolation and standard release timing. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d2915cd01c60. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +165, Tests +378, Docs +24. Total +567 across 20 files. Added test files: 3. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReviewed November 22, 2026, 11:36 PM ET / November 23, 2026, 04:36 UTC (Revision 3). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Lean spawns SQLite readers directly, so their OOM score write ran synchronously on Gateway request paths. The watch helper and native readers now raise their score with an asynchronous write. Also satisfy the assertion-safety and mock-exports ratchets.
Evidence and CI attribution for head
|
| File | Contents |
|---|---|
report.md |
the campaign report |
cases.json |
every case: exit code, verified turns, oom/oom_kill/max deltas |
comparison.json |
the paired per-round metrics and startup series for the PR, the merge base 80e233cd and 1a0a24dc |
startup-isolates.json |
per-sample worker isolates and Gateway child processes |
quick-checks.json |
auto 4 GiB → lean, auto 8 GiB → standard |
harness-manifest.json |
harness and driver hashes |
upgrade-proof-summary.json |
the latest-stable upgrade capture described below |
Upgrade capture (k-upgrade-3072, PR head 8d78ba4e):
- Starting release: in a 3 GiB container, the Gateway ran stable
2026.11.6and created three synthetic Knowledge records, saved through agent turns. - After upgrading to the candidate:
- Under
auto, the candidate resolvedlean(reasonmemory, cgroup v2 limit 3 GiB). configPreserved,sessionMessagesPreservedandrecordsPreservedare alltrue.- The HTTP server started listening, and the agent database recovered after background inspection.
- A first turn completed:
chat.send, thenagent.wait ✓in 1.9 s.
- Under
- Shutdown: it logs
Plugin runtime still owns resources. The same line appears in the1a0a24dcupgrade capture, so it is pre-existing and not changed by this PR.
The code delta from 8d78ba4e to bd3318d3 touches only the OOM-score write and test and type hygiene. The campaign measurements came from 8d78ba4e.
CI attribution (run 45101871140 on 8d78ba4e)
Caused by this PR, fixed in bd3318d3:
checks-node-changed-compact-large-21(server-worker-placement-session-evidence.test.ts,{ writeFileSync: 1 }): the OOM-score write for natively spawned SQLite readers and the watch helper was synchronous on the request path. It is now an asynchronous write.checks-fast-baseline-ratchets: the job died with "runner lost communication". Running the ratchets locally against80e233cdfound two failures from this PR, both now fixed:assertion-safety: an uncommentedasinserver-startup-resource-profile.ts, replaced with a type guard.mock-exports: avi.mockwithoutimportOriginalincontext.lean.test.ts.- The other ratchets pass.
Inherited. Each of these was reproduced with the same failing tests on the merge base 80e233cd, in a detached checkout with pnpm vitest run (e2e config where applicable):
| Job | Failing test file(s) | Base result |
|---|---|---|
| compact-large-8-2 | server-http.openai-compat.test.ts (3× "policy changed", 401 vs 200) |
same 3 fail |
| compact-large-5-1 | server.sessions.create.projects.test.ts |
3 fail on base |
| compact-small-4-2 | server.sessions.create.durability.test.ts |
8 fail on base |
| compact-large-40-1 | server-methods/sessions-create-device-folder.test.ts (revoked while validating) |
same 1 fails |
| checks-node-changed-2 | gateway-skill-authoring-plugin.e2e.test.ts |
same failure (expected [] to have a length of 1) |
| compact-small-4-3 | server.openclaw-id-member-suspension.test.ts, server.config-security-policy.test.ts |
3 / 2 fail on base |
| compact-large-8-1 | server.plugin-reload-send-revocation.product.test.ts |
fails on base |
| compact-large-4-2 | server.sessions.create.lifecycle.test.ts (durable replay revocation), server.chat-abort-initiator.product.test.ts |
1 / 1 fail on base |
| compact-large-9 | flows/doctor-health.legacy-update.test.ts, mcp-http.async-scope.test.ts, server.chat-membership-authority.product.test.ts |
3 / 1 / 1 fail on base |
| compact-large-31 | server-cron-failure-repair.final-effect.test.ts |
11 fail on base |
| checks-node-changed-3 | agents/bash-tools.exec-gateway-approval.e2e.test.ts (hook token source across reload) |
same failure |
The remaining failures are not jobs in their own right: openclaw/ci-gate is the aggregate of the above, and the auto-response, dispatch and PR context and evidence cancellations came from the draft → ready transition.
A fresh CI run is now on bd3318d3.
🦞 Made with OpenClaw
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
CI attribution for head
|
| Job | Failing test(s) | Evidence |
|---|---|---|
| compact-large-40-2 | server-http.openai-compat ×3 ("policy changed", 200 vs 401) | Same 3 fail on 80e233c |
| compact-large-5-1 | server.sessions.create.projects:1013 | Fails on 80e233c |
| compact-small-4-3 | server.openclaw-id-member-suspension ×3, server.config-security-policy | Both fail on 80e233c |
| compact-small-4-4 | server.session-row-baselines.integration, server.session-row-deltas.integration | Both fail on 80e233c |
| checks-node-changed-2 | gateway-skill-authoring-plugin.e2e:217 | Same failure on 80e233c |
| compact-large-4-3 | server.sessions.create.lifecycle (durable replay revocation), server.chat-abort-initiator.product | Both fail on 80e233c |
| compact-small-4-2 | server.sessions.create.durability ×3 | Fails on 80e233c (8 there) |
| compact-large-10-1 | mcp-http.async-scope:266 | Fails on 80e233c |
| compact-large-29 | server-methods/sessions-create-device-folder:178 | Fails on 80e233c |
| compact-large-41 | flows/doctor-health.legacy-update:336 ×3 | Same 3 fail on 80e233c |
| compact-large-21 | server.talk-consult-history ("isolates registered Talk replay across authenticated callers") | Fails on 80e233c |
| compact-large-31 | server-cron-failure-repair.final-effect | Fails on 80e233c |
| checks-node-changed-3 | agents/bash-tools.exec-gateway-approval.e2e:524 | Same failure on 80e233c |
| compact-large-19-1 | server.chat-membership-authority.product:149 | Fails on 80e233c |
| compact-large-40-1 | server.plugin-reload-send-revocation.product | Fails on 80e233c |
| compact-large-40-1 | server.guest-history-http (200 vs 404 at :69 via the revocation-during-snapshot race at :101) | See note below |
| check-docs | format:check flags only src/update/AGENTS.md |
This PR doesn't touch it; added on main in 2e8c1ad (#203914), and main CI run 45112229424 failed check-docs on that commit |
| ci-gate | aggregate of the jobs above | — |
server.guest-history-http note. This test passes locally on 80e233c and on bd3318d3 alone, under bun, both as a single file and in the full 12-file shard with 3 workers. It fails with the CI assertion on d2915cd01c alone (no PR changes) and on the merge tree 8bd56e2e. The test file is identical in both. The likely cause is #203847, "check runtime and HTTP authority once at request start" (14f185b), which landed on main between the merge base and d2915cd01c.
The CI runner has 4 CPUs and 16 GiB, so the Gateway resolves the standard profile there, and this PR's lean-only paths are inactive.
The single job rerun (attempt 2) was diagnostic only and failed the same way.
ClawSweeper's exact-head review of bd3318d3 reported no findings.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…es (#203241) * fix(gateway): shutdown never first-imports chunks an in-place update replaced * test(gateway): guard built shutdown against late first-imports * fix(gateway): keep broker close functions visible to dead-export scan * fix(process): supervisor shutdown warnings never first-import their logger; guard tracks pre-signal modules * test(ci): watch supervisor shutdown owners for the late-import guard * test(gateway): readable late-import entry parsing * test(gateway): stop the guard Gateway after startup maintenance settles * test(gateway): guard only hashed dist chunks that a swap removes * test(gateway): skip the SIGTERM guard where taskkill stops the Gateway * fix(gateway): prime supervisor shutdown logger from the shutdown runtime; add restart worker to PR wrapper inventory * fix(memory-core): own the manager runtime loader in a leaf module so closing never loads the provider * fix(state): agent lease cleanup handler loads with the state worker; guard stop budget and watch paths * fix(cron): claimed runs load their finalization before shutdown can need it; watch memory loader owners * fix(cron): scheduled runs also load finalization with their scheduler (cherry picked from commit 78a6ca1) Release adaptation: Preserve the stable cron dispatch preamble and command set, without main-only cron.importLegacyMemberSources; scheduler and queue still prepare finalization together. The shutdown-runtime overlap is supplied by the preceding #203185 backport. Companions: #203185 selected and applied first. #203839 replaces test process ownership separately and is not required for this guard: the stable fixture supports the same child, entrypoint and stop APIs. #203790, #202507, #202495 startup/resource changes, #201024 cgroup sizing, #197395 cron backoff, and #204210/#203458/#203271 wrapper-only overlaps are not dependencies. Co-authored-by: RomneyDa <[email protected]>
…t start (openclaw#203790) * perf(gateway): cut the lean first-start memory peak Lean holds post-ready maintenance until the Gateway goes quiet after startup, so a first turn no longer shares its memory with the maintenance isolates that work starts. Lean also skips the Linux command spawn broker, as hosts with 1 GiB or less already do, and the Linux directory watch helper ends itself after its caller dies with a timer instead of a second isolate. The directory watch helper and natively spawned SQLite read-only helpers become the preferred Linux OOM victims under the existing child OOM policy. * fix(gateway): release lean post-ready work past its own waiters Post-ready maintenance admits its root before it waits for the barrier, so lean's idle check now ignores roots that are waiting on the barrier. The spawn broker placement reads the configured profile from the config being started when an in-process restart brings no CLI snapshot. * fix(gateway): wait for post-ready work before admitting its root Post-ready maintenance and retained plugin cleanup now wait for the barrier before they admit root work, so lean's idle check counts only real requests. Profile prediction resolves dotenv values into an isolated env, as bootstrap would, without changing process env. * fix(gateway): keep retained plugin cleanup scheduling unchanged * fix(gateway): raise helper OOM scores off the event loop Lean spawns SQLite readers directly, so their OOM score write ran synchronously on Gateway request paths. The watch helper and native readers now raise their score with an asynchronous write. Also satisfy the assertion-safety and mock-exports ratchets.
Related: #202379, #202373
What Problem This Solves
In a small container (1.5 GiB), the Gateway can run out of memory and be killed by the kernel a few seconds into its first start, while its first agent turn runs. On main
1a0a24dc, the lean profile hit this in 1 of 3 runs. The peak comes from start-up work all happening at once: the first turn, background maintenance, a process that launches commands, and a file-watching process.User Impact
On hosts that auto-select the lean profile (under 8 GiB, or
gateway.resources.profile: "lean"), the first turn after a start no longer competes with background start-up work for memory. Lean also uses one fewer helper process.When memory runs out on Linux, the kernel now picks the file-watching helper or a database read helper before the Gateway. Both recover on their own.
Standard-profile hosts are unchanged, apart from that Linux kill preference and one fewer thread inside the file-watching helper.
Trade-offs on lean:
Why This Change Was Made
Approved scope from #202379 (items 1, 2 and 4); the plan is in #202379 (comment).
worker.js) is unchanged. It already starts on demand, and it can't restart.oom_score_adj1000, under the existing Linux child policy and itsOPENCLAW_CHILD_OOM_SCORE_ADJ=0opt-out.docs/platforms/linux.md.Known bounded case: the retained-plugin cleanup idle task still waits inside its own admission, which is unchanged. If it fires at 30 s while the barrier is still held, lean's release waits for the 60 s cap.
Evidence
Real-behaviour campaign: done; the pass criterion is met. Read the numbers with care (n=3).
I re-ran the
1a0a24dcintegration campaign on this head (8d78ba4e) with the same harness and method. Each case ran in its own Studio Crabbox local-container lease built from the pushed commit, under the membench lock, withMALLOC_ARENA_MAX=2, pinned profiles, and startup samples at +2/4/6/8 s and at first ready. I added a lean 1.5 GiB ×3 control on the merge base80e233cd. Failures stay in the denominator, and nothing was rerun.Completion:
oom/oom_kill0 in every round.Paired results, lean at 1.5 GiB, PR vs merge base (median and range; MiB unless noted):
memory.events maxHow to read these:
memory.peakisn't informative here. It reached the 1,536 MiB limit in every 1.5 GiB round on both arms, because page cache fills the limit.session-accessor.sqlite-archiveand somesession-transcriptisolates from the +8 s window. Butdisk-budget,git-operation,fs-safe-copyanddiscoverystill appear there: they're either turn-driven or started outside the post-ready barrier. That isn't attributed yet.Redacted evidence: https://gist.github.com/jalehman/36f79343b766a90a8a504e79bc3e420f. It holds the report, per-case receipts,
comparison.json, startup isolates, the quick checks, and the latest-stable upgrade capture, which shows2026.11.6→ candidate with config, sessions and records preserved and a completed first turn. CI attribution: #203790 (comment).The campaign measured
8d78ba4e. The current headbd3318d3changes only how the helper OOM score is written (now an asynchronous write, so lean's direct SQLite reader spawns don't do synchronous/procwrites on request paths), plus ratchet hygiene.Tests. Fail-first where the behaviour is new:
scheduleGatewayPostReadyMaintenancewith the lean release: fails on the pre-fix ordering.process.env.Existing suites pass: post-ready lifecycle, the import boundary, spawn-broker context, directory watch (including parent death with open pipes), owned-directory observation, SQLite reader sessions, Linux OOM score, idle tasks, gateway work admission, and the wrapper source closure.
Also pass:
tsgo:core, scoped oxlint, format, docs format,config:docs:checkandgit diff --check.Three independent Astra reviews were run:
🦞 Made with OpenClaw