Skip to content

fix: prevent Code Mode worker OOM after databases close - #169956

Merged
steipete merged 5 commits into
mainfrom
upd/upd-l1562
Oct 12, 2026
Merged

steipete merged 5 commits into
mainfrom
upd/upd-l1562

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Code Mode workers running out of memory after a long-running Gateway has opened and closed many databases. Closed SQLite admissions retained full schema and row-write metadata, which every new worker inherited.

User Impact

Workers can start after hundreds of databases close, using the existing memory limits. Open siblings continue sharing validation facts; reopening after the final connection closes validates again. No migration or operator action is required.

Why This Change Was Made

The admission registry retires payloads after the final native connection closes or its worker exits. Only the host decides final retirement, because a worker can have an older view of its siblings. Reopening creates a fresh admission; both scoped and unscoped row-cache tokens identify that generation.

The existing open-identity map guards repeated close callbacks. Intermediate handle count changes use the shared cells directly; only a thread's first/final handle publishes and exchanges metadata. Minimal host-owned identity descriptors remain until explicit retirement to preserve SQLite POSIX locks.

Production is +199/-159 lines (net +40), down from net +122 in the first revision. The reduction removes the parallel close-tracking WeakSet and duplicate connection ownership, consolidates generation reads/increments and schema revocation, and unifies the committed/pending scoped-token construction. Tests are +451/-65 lines.

Evidence

  • The original owner retained 300 closed records: 41,504,700 serialized bytes. The real Code Mode worker failed with ERR_WORKER_OUT_OF_MEMORY. The final reproducer retains zero records (2 serialized bytes); the same worker starts after 300 closes with 21,287,536 bytes of heap, under its unchanged 64 MiB limit.
  • The owner regression passes all 6 tests in 19.99 seconds wall time (17.70 seconds in Vitest, dominated by shared compiler preparation). It covers final close, reopen, failed initial admission, stale snapshots, 300 closed databases, explicit descriptor retirement, and direct/retained workers. A two-worker negative control reproduced premature retirement before the host-only fix; both variants now preserve the later sibling. A real SQLite negative control also reproduced an unscoped-token collision across close/reopen and different committed updates; generation-aware committed/pending tokens now pass that regression. Admission, format, and worker tests pass.
  • The final cross-lane run passes 1,197 tests across 82 files in 795.77 seconds wall time. The 83-file inventory retains only the existing PostgreSQL transaction-lock service-dependent skip. Existing platform-specific skips remain. Admission, format, corruption, ownership, session, and worker tests are covered.
  • Validation: the full node scripts/check-changed.mjs --base 27be5cd3a50a3674b2d31e4ebf6912d7c9d29b09 --timed run exits 0 in 773.90 seconds, including all core/test typechecks, dead-export scans, lint, and production guards; the final Madge run exits 0 with zero cycles. Independent Codex review of the final staged candidate is clean through P2. All proof used local synthetic data and isolated state; no remote leases or live Gateway state were used.
  • Performance gate is still blocked: the shared host remained only 40–59% idle after this lane's validation stopped, with other CI compiler work active. No other lane's process was stopped, and no idle comparison is claimed. The final broad run's deletion cases passed (active 45.705s, restart-draining 41.804s, legacy-retiring 32.270s); the earlier baseline restart-draining result was 49.888s. Those are unmatched runs and do not establish a speedup or regression. The required same-command, back-to-back idle baseline/candidate comparison remains outstanding before landing. No timeout, retry, or assertion was relaxed.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR releases SQLite admission payloads after the final connection closes while retaining identity descriptors for lock safety.

Example: Start a Code Mode worker after opening and closing 300 databases.

  • Before: The reported reproduction retains 41,504,700 serialized bytes and fails with ERR_WORKER_OUT_OF_MEMORY.
  • After: The reported reproduction retains zero admission records and starts the worker under its unchanged 64 MiB limit.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-level regression coverage and reported real-worker measurements support the repair, but both previously identified correctness defects remain.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its body reports isolated real Code Mode worker measurements, and the inspected regressions exercise real SQLite and direct and retained workers.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Code Mode workers can run out of memory after a long-running Gateway opens and closes many databases.
Reason: The change addresses a concrete runtime failure through the existing owner, and its maintainer author explicitly accepts the final-close validation tradeoff.

Merge readiness

⛔ Needs changes before merge - 3 items remain

This PR addresses a concrete Code Mode memory failure, but both previously reported snapshot-handling defects remain unfixed.

Priority: P1
Reviewed head: e7cdf03dfae247a961d15fd331d4b0fb6aeeab9a

Before merge

  • Preserve no-op installation for unchanged admission updates (P2) - Every install now calls publish(), including install([]). Ordinary broker replies and task contexts reach this path when admissions have not changed. publish() scans every published database, rebuilds the environment array, and increments the registry revision, defeating the next capture cursor's constant-work fast path. With hundreds of live admissions, unchanged RPCs therefore regain registry-wide work. Perform retirement cleanup only when affected records change, preserving no-op installation for unchanged updates. This previously reported finding remains unfixed.
  • Remove exited-worker references from published snapshots (P2) - When a worker exits while a host connection remains open, releaseWorker deletes its reference only from the mutable record. Published snapshots have a separate references Map, and publish() without a record does not refresh that map. The next worker inherits the exited worker's entry and sends it back during admission; install merges that missing entry into the host record again. Repeated worker turnover consequently accumulates dead reference cells in future worker snapshots. Refresh affected snapshots after removal and prevent stale transfers from restoring exited-worker references. This previously reported finding remains unfixed.
  • Explain or restore the original intent of Unchanged admission installation - b4c73df: Make unchanged installation a no-op and avoid registry-wide work during ordinary worker requests.

Findings

  • [P2] Preserve no-op installation for unchanged admission updates — src/infra/sqlite-database-admission-record.ts:350-351
  • [P2] Remove exited-worker references from published snapshots — src/infra/sqlite-database-admission-record.ts:211-214

Provenance

  • Unchanged admission installation changes intended behavior without addressing why it exists (b4c73df: Make unchanged installation a no-op and avoid registry-wide work during ordinary worker requests.)
Agent review details

How this fits together

The SQLite admission registry shares validated database facts and write revisions between native connections and workers through bootstrap snapshots and broker messages.

flowchart TD
  A[Native SQLite connections] --> B[Admission registry]
  C[Connection close and worker exit] --> B
  B --> D[Published snapshots]
  D --> E[Worker bootstrap and broker messages]
  E --> F[SQLite and Code Mode workers]
  B --> G[Retained identity descriptors]
Loading

Technical review

Best possible solution:

Keep host-owned final-close cleanup while preserving unchanged-install fast paths and removing exited-worker references from transferable snapshots.

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

Current main retains admission payloads after connection closure, and the PR reports an isolated 300-database reproduction that exhausts the real Code Mode worker; this read-only review verified the source path without executing it.

Is this the best way to solve the issue?

Cleanup belongs in the existing admission owner, and the explicitly accepted final-close revalidation tradeoff is reasonable, but publication and worker-reference cleanup need the two focused repairs below.

Full review comments:

  • [P2] Preserve no-op installation for unchanged admission updates — src/infra/sqlite-database-admission-record.ts:350-351
    Every install now calls publish(), including install([]). Ordinary broker replies and task contexts reach this path when admissions have not changed. publish() scans every published database, rebuilds the environment array, and increments the registry revision, defeating the next capture cursor's constant-work fast path. With hundreds of live admissions, unchanged RPCs therefore regain registry-wide work. Perform retirement cleanup only when affected records change, preserving no-op installation for unchanged updates. This previously reported finding remains unfixed.
    Confidence: 0.99
  • [P2] Remove exited-worker references from published snapshots — src/infra/sqlite-database-admission-record.ts:211-214
    When a worker exits while a host connection remains open, releaseWorker deletes its reference only from the mutable record. Published snapshots have a separate references Map, and publish() without a record does not refresh that map. The next worker inherits the exited worker's entry and sends it back during admission; install merges that missing entry into the host record again. Repeated worker turnover consequently accumulates dead reference cells in future worker snapshots. Refresh affected snapshots after removal and prevent stale transfers from restoring exited-worker references. This previously reported finding remains unfixed.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 39eeaed359b7.

Provenance checked

  • Admission lifetime across final close changes intended behavior with a stated reason (bb7d32e: Retain physical-database validation across workers and idle reopens to avoid repeated schema and integrity checks.)
  • Identity descriptor custody keeps the original intent (bb7d32e: Keep descriptors open to preserve physical identity and avoid releasing sibling SQLite POSIX locks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/infra/sqlite-database-admission.retention.test.ts --maxWorkers=1
  • pnpm test src/infra/sqlite-database-admission.worker.test.ts --maxWorkers=1
  • node scripts/check-changed.mjs --base e7cdf03

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b4c73df adds src/infra/sqlite-database-admission-record.ts:311 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b4c73dfc0f64; files: src/infra/sqlite-database-admission-record.ts)

PR surface

Source +122, Tests +353, Docs +6. Total +481 across 18 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 156 34 +122
Tests 13 418 65 +353
Docs 2 19 13 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 593 112 +481

Review metrics

Metric Value Why it matters
Production versus test changes Production +156/-34; tests +418/-65 Production growth implements connection-reference and descriptor lifetimes; tests exercise distinct close, inheritance, and worker-lifecycle boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Retained database metadata can prevent Code Mode workers from starting in a long-running Gateway.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-12T14:50:39.916Z sha ae7c2d8 :: needs changes before merge. :: [P2] Preserve no-op installation for unchanged admission updates | [P2] Remove exited-worker references from published snapshots

Reviewed October 12, 2026, 11:01 AM ET / 15:01 UTC (Revision 2).

@steipete
steipete marked this pull request as ready for review October 12, 2026 14:55
@steipete

Copy link
Copy Markdown
Contributor Author

Merging at pinned head 7b5d24e069ab89ecf6261fb672828c0553974e13 past one inherited failure. checks-node-compact-small-1 (test/scripts/eager-import-closure.test.ts) reports src/infra/postgres-sync/connection.ts: unresolved ../database-engine/observation.js in the PR wrapper inventory. That comes from #169933 (9dc6466), which landed on main about 20 minutes ago. This PR touches neither file nor scripts/pr-lib/wrapper-components.txt. Every check this PR owns is green.

@steipete
steipete merged commit 19eddcf into main Oct 12, 2026
129 of 133 checks passed
@steipete
steipete deleted the upd/upd-l1562 branch October 12, 2026 15:43
steipete added a commit that referenced this pull request Oct 12, 2026
Keep a real sibling connection open while testing quarantine fact reuse, retaining physical admission without publishing unrelated generic catalog facts. Measure the WAL retry check count before the separate conflict probe can reopen the database. Preserve replacement validation, one-check and integrity assertions.

The fixtures assumed facts survived the final native close; 19eddcf (#169956) intentionally retires those facts. Generic schema admission in the first fixture repair also introduced an unrelated user_version read during quarantine DDL recapture; the follow-up removes that fixture-only interference. This is source-supported contract alignment, not a bisected first-bad attribution. Both changes are test-only.

Validation: pnpm test src/state/openclaw-quarantine-store.test.ts --maxWorkers=1 passed 14/14 on composition b3c4dcb (51.42s runner, 260.60s wrapper), clean final checkout and no owned survivors. pnpm test src/infra/startup-migration-checkpoint.inspection.test.ts --maxWorkers=1 passed 7/7 on composition 7732cef (239.80s runner, 305.35s wrapper), also clean with no owned survivors. The final file blobs match reviewed sources and V13. Both scoped Codex reviews found no actionable issue. The unchanged files have passing V12 lint and type gates plus V10 build, dependency/Knip, topology and ratchet gates. Those composition results qualify the changed files, not all of current main.
steipete added a commit that referenced this pull request Oct 12, 2026
The cancellation fixture compared the last unique worker across reads that may legitimately use different lanes. Record the actual worker for every history dispatch, verify the cancelled task's matching native reply before consumer rejection, and check survival and native-close policy for each dispatched reader. Keep the exact history content assertions.

Final-close admission retirement in 19eddcf (#169956) allows a reopened read to use discovery before a later read uses the history lane. This is source-supported fixture contract alignment, not a bisected first-bad attribution. Test-only: 31 lines added, 19 removed; no timeout increase or production change.

Validation: pnpm test src/gateway/session-history-worker-lifecycle.test.ts --maxWorkers=1 passed 14/14 on composition 7732cef (516.21s runner, 576.27s wrapper), with a clean final checkout and no owned survivors or restoration blockers. The repair patch is unchanged from the reviewed and tested V13 version. Integration preserves the independent runtime-config snapshot setup introduced on main by 7e48efb (#169714), so the complete integrated file is different from the tested V13 blob. Scoped Codex review found no actionable issue in the repair. V12 lint/type gates and V10 build, dependency/Knip, topology and ratchet gates passed on compositions containing the repair; those results are prior-composition evidence, not a focused rerun of the integrated file or certification of current main.
steipete added a commit that referenced this pull request Oct 12, 2026
Limit the zero-policy-read assertion to the fixture lifetime that keeps a native connection open. The cold fixture closes its final handle and must permit policy validation when it reopens. Both lifetimes still verify the migrated canonical key, retained or released handle, and absence of leaked cold leases.

This follows the admission retirement contract introduced by 19eddcf (#169956); it is source-supported contract alignment, not a bisected first-bad attribution. Test-only: eight lines added, six removed; runtime policy and migration behavior are unchanged.

Validation: pnpm test src/config/sessions/startup-migration.registry-recovery.test.ts --maxWorkers=1 passed 14/14 on composition 7732cef (244.61s runner, 311.20s wrapper), with a clean final checkout and no owned survivors or restoration blockers. The repair patch is unchanged from the reviewed and tested V13 version. Integration preserves the independent runtime-config snapshot setup introduced on main by 7e48efb (#169714), so the complete integrated file is different from the tested V13 blob. Scoped Codex review found no actionable issue in the repair. V12 lint/type gates and V10 build, dependency/Knip, topology and ratchet gates passed on compositions containing the repair; those results are prior-composition evidence, not a focused rerun of the integrated file or certification of current main.
steipete added a commit that referenced this pull request Oct 12, 2026
…170126)

* fix(doctor): admit migration-owned transcript writers

Prepare schema facts on the migration-owned handle before transcript writers consume its encoding. Final native close intentionally retires the preceding handle’s facts, so a newly opened migration connection must establish its own admission.

Preserves schema, format, integrity, lease and rollback behavior. Historical transcript normalization and both media migration siblings pass with all assertions intact.

* test(state): retain admission during cron migration reuse proof

Keep admitted readers live while testing historical snapshot versions and zero-query reopen reuse. Final-close retirement in #169956 explicitly requires readmission; the existing state checkonce tests retain that cold-lifetime contract. All migration, rollback, downgrade-refusal and statement assertions are preserved.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…#169956)

Per-database SQLite admission metadata was never retired, so every new worker inherited it for every database the process had ever opened (41.5 MB after 300 closed databases), and the 64 MiB Code Mode worker ran out of memory before executing. The admission registry now retires a database's facts after its final close or worker exit; open databases keep shared facts and a reopen re-admits. Also fixes a token collision across reopen. Inherited metadata after 300 closes: 2 bytes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Keep a real sibling connection open while testing quarantine fact reuse, retaining physical admission without publishing unrelated generic catalog facts. Measure the WAL retry check count before the separate conflict probe can reopen the database. Preserve replacement validation, one-check and integrity assertions.

The fixtures assumed facts survived the final native close; a2cefc9 (openclaw#169956) intentionally retires those facts. Generic schema admission in the first fixture repair also introduced an unrelated user_version read during quarantine DDL recapture; the follow-up removes that fixture-only interference. This is source-supported contract alignment, not a bisected first-bad attribution. Both changes are test-only.

Validation: pnpm test src/state/openclaw-quarantine-store.test.ts --maxWorkers=1 passed 14/14 on composition b3c4dcb (51.42s runner, 260.60s wrapper), clean final checkout and no owned survivors. pnpm test src/infra/startup-migration-checkpoint.inspection.test.ts --maxWorkers=1 passed 7/7 on composition 7732cef (239.80s runner, 305.35s wrapper), also clean with no owned survivors. The final file blobs match reviewed sources and V13. Both scoped Codex reviews found no actionable issue. The unchanged files have passing V12 lint and type gates plus V10 build, dependency/Knip, topology and ratchet gates. Those composition results qualify the changed files, not all of current main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
The cancellation fixture compared the last unique worker across reads that may legitimately use different lanes. Record the actual worker for every history dispatch, verify the cancelled task's matching native reply before consumer rejection, and check survival and native-close policy for each dispatched reader. Keep the exact history content assertions.

Final-close admission retirement in a2cefc9 (openclaw#169956) allows a reopened read to use discovery before a later read uses the history lane. This is source-supported fixture contract alignment, not a bisected first-bad attribution. Test-only: 31 lines added, 19 removed; no timeout increase or production change.

Validation: pnpm test src/gateway/session-history-worker-lifecycle.test.ts --maxWorkers=1 passed 14/14 on composition 7732cef (516.21s runner, 576.27s wrapper), with a clean final checkout and no owned survivors or restoration blockers. The repair patch is unchanged from the reviewed and tested V13 version. Integration preserves the independent runtime-config snapshot setup introduced on main by 5dbf215 (openclaw#169714), so the complete integrated file is different from the tested V13 blob. Scoped Codex review found no actionable issue in the repair. V12 lint/type gates and V10 build, dependency/Knip, topology and ratchet gates passed on compositions containing the repair; those results are prior-composition evidence, not a focused rerun of the integrated file or certification of current main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…#170081)

Limit the zero-policy-read assertion to the fixture lifetime that keeps a native connection open. The cold fixture closes its final handle and must permit policy validation when it reopens. Both lifetimes still verify the migrated canonical key, retained or released handle, and absence of leaked cold leases.

This follows the admission retirement contract introduced by a2cefc9 (openclaw#169956); it is source-supported contract alignment, not a bisected first-bad attribution. Test-only: eight lines added, six removed; runtime policy and migration behavior are unchanged.

Validation: pnpm test src/config/sessions/startup-migration.registry-recovery.test.ts --maxWorkers=1 passed 14/14 on composition 7732cef (244.61s runner, 311.20s wrapper), with a clean final checkout and no owned survivors or restoration blockers. The repair patch is unchanged from the reviewed and tested V13 version. Integration preserves the independent runtime-config snapshot setup introduced on main by 5dbf215 (openclaw#169714), so the complete integrated file is different from the tested V13 blob. Scoped Codex review found no actionable issue in the repair. V12 lint/type gates and V10 build, dependency/Knip, topology and ratchet gates passed on compositions containing the repair; those results are prior-composition evidence, not a focused rerun of the integrated file or certification of current main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…penclaw#170126)

* fix(doctor): admit migration-owned transcript writers

Prepare schema facts on the migration-owned handle before transcript writers consume its encoding. Final native close intentionally retires the preceding handle’s facts, so a newly opened migration connection must establish its own admission.

Preserves schema, format, integrity, lease and rollback behavior. Historical transcript normalization and both media migration siblings pass with all assertions intact.

* test(state): retain admission during cron migration reuse proof

Keep admitted readers live while testing historical snapshot versions and zero-query reopen reuse. Final-close retirement in openclaw#169956 explicitly requires readmission; the existing state checkonce tests retain that cold-lifetime contract. All migration, rollback, downgrade-refusal and statement assertions are preserved.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant