Skip to content

fix(doctor): prevent update repair OOM on large session stores - #126353

Merged
steipete merged 2 commits into
mainfrom
steipete/amazing-tesla-2eee79
Aug 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/amazing-tesla-2eee79

Conversation

@steipete

@steipete steipete commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #126115

Supersedes #126141.

What Problem This Solves

Fixes an issue where package-to-dev updates could activate the new core and then abort during post-core Doctor when a large recovered SQLite session corpus exhausted Node's heap. The failed finalization left the Gateway stopped until the operator manually diagnosed and repaired the update.

Why This Change Was Made

Doctor now scans session state through bounded, ordered storage-owner paths instead of materializing complete entry JSON corpora in memory. Canonical repair keeps compact decision facts, revalidates them before mutation, hydrates only bounded repair candidates, and applies entry rewrites in bounded transactions. Session SQLite migration validation and active-transcript inspection now use promoted identity columns and streaming projections instead of full entry snapshots.

This is the owner-level repair rather than a global heap increase. It does not add configuration, dependencies, protocol changes, compatibility shims, or a SQLite schema-version bump. The separate legacy sessions.json whole-file path remains tracked by #110835.

User Impact

Operators with large retained or recovered session databases can complete Doctor and update finalization without supplying a manual heap override. Existing session metadata, windows, payloads, repair ordering, and concurrent-write protections remain intact.

Evidence

  • Pre-fix owner reproduction: a 192 MiB synthetic canonical SQLite corpus aborts under a 512 MiB old-space cap in SQLite row extraction / JSON parsing.
  • Real built CLI flow on Node 24 arm64, doctor --repair --non-interactive --no-workspace-suggestions, under a 768 MiB old-space cap:
    • 660 sessions × 384 KiB (~247 MiB JSON): pass; 227.8 MiB post-GC heap.
    • 2,640 sessions × 384 KiB (~990 MiB JSON): pass; 227.6 MiB post-GC heap.
    • Exact session-node/window counts, entry_valid, and representative first/middle/last payload hashes were preserved.
  • Post-rebase focused owner coverage: 205 tests passed across 10 named files; the broader implementation pass covered 331 tests.
  • pnpm build passed.
  • node scripts/check-changed.mjs -- <all touched files> passed core production/test typecheck, lint, formatting, dead-export, import-cycle, database-first, native-schema, and repository guards.
  • git diff --check passed.
  • Fresh structured autoreview: clean; no accepted/actionable findings.
  • Production LOC: +1265/-972 (net +293). Tests/support: +725/-127 (net +598). The production growth establishes bounded scan/mutation ownership, compact concurrency decision tokens, and deterministic repair ordering while deleting the obsolete full-entry repair/list paths.

Proof gap: the reporter's private corpus is unavailable. Linux Testbox allocation was blocked before execution because the local Blacksmith CLI was unauthenticated; no alternate provider or login was used. The built end-to-end proof ran locally on Node 24 arm64 against the issue's 2,640-session scale.

Prevent post-core update finalization from retaining complete session JSON corpora. Move Doctor repair planning and rewrites onto ordered bounded SQLite owner scans with stale-decision revalidation and selective hydration.

Co-authored-by: Hannes Rudolph <[email protected]>
@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 19, 2026 16:13
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: XL maintainer Maintainer-authored PR labels Aug 19, 2026
@steipete

steipete commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Land-ready evidence for head be8481ee2512b5d229d00f498669a4a7db9345e8.

Root cause and repair: Doctor and session SQLite migration/repair paths retained complete entry JSON corpora. The session storage owner now supplies ordered bounded scans, compact promoted projections, stale-decision revalidation, selective hydration, and bounded writes. The obsolete full-entry repair/list paths are removed; there is no config, protocol, dependency, or SQLite schema-version change.

Built full-flow proof on Node 24.19.0 arm64 with a 768 MiB old-space cap:

  • 660 sessions × 384 KiB (247 MiB logical JSON): pass; 227.8 MiB post-GC heap, 694.8 MiB current RSS, 841.0 MiB peak RSS.
  • 2,640 sessions × 384 KiB (990 MiB logical JSON): pass; 227.6 MiB post-GC heap, 689.7 MiB current RSS, 802.0 MiB peak RSS.
  • Both runs preserved exact session-node/window counts, entry_valid=1, and representative first/middle/last payload hashes.

Exact local commands:

"/opt/homebrew/Cellar/node/26.7.0/bin/node" "--max-old-space-size=512" "--trace-gc-nvp" "--import" "tsx" "/tmp/openclaw-126115-harness.ts" "run" "/tmp/openclaw-126115-baseline.4iPlkB" "/tmp/openclaw-126115-state-valid.0PBfIZ"
PATH=/opt/homebrew/opt/node@24/bin:$PATH bash /tmp/openclaw-126115-full-doctor-proof.sh
node scripts/run-vitest.mjs src/commands/doctor-auth-flat-profiles.test.ts src/commands/doctor-main-session-recovery.test.ts src/commands/doctor-session-canonical-keys.memory.test.ts src/commands/doctor-session-canonical-keys.race.test.ts src/commands/doctor-session-delivery-state.test.ts src/commands/doctor-session-incognito-key-repair.test.ts src/commands/doctor-session-sqlite.test.ts src/commands/doctor-session-state-providers.test.ts src/commands/doctor-state-integrity.order.test.ts src/commands/doctor-state-integrity.test.ts
changed_files=(${(f)"$(git diff --name-only origin/main...HEAD)"})
node scripts/check-changed.mjs -- "${changed_files[@]}"
git diff --check origin/main...HEAD
pnpm build
.claude/skills/autoreview/scripts/autoreview --mode branch --base origin/main --stream-engine-output

Post-rebase results: 205 focused assertions across 10 files passed; the broader implementation pass covered 331 tests. The complete changed-file gate passed core production/test typechecking, lint, formatting, dead-export, import-cycle, database-first, native-schema, and repository guards. Build passed before the conflict-free rebase, which changed no module/lazy/build boundary. After CI exposed a dynamically bundled test support file that Knip could not see, the support entry became a guarded static test import; the low-heap regression and exact deadcode:unused-files gate both pass. Fresh branch autoreview reported no accepted/actionable findings (patch is correct, confidence 0.98).

Production LOC is +1265/-972 (net +293). Tests/support are +725/-127 (net +598). The production growth establishes bounded scan/mutation ownership, compact concurrency decision tokens, and deterministic repair ordering while deleting the obsolete full-entry paths.

Known gap: the reporter's private corpus is unavailable. Linux Testbox allocation was blocked before execution because the local Blacksmith CLI was unauthenticated; no alternate provider or login was used. The built synthetic full-flow proof above exercised the real Doctor command at the reported 2,640-session scale. Exact-head hosted CI is attached to this SHA and remains the required native-prepare gate.

ClawSweeper handling: an exact-head review started at 2026-08-19 16:29:29 UTC, but its lease expired at 17:10:29 UTC without publishing a verdict, finding, or Rank-up moves:. There are therefore no published moves to apply or skip. Per the repository's late-publisher rule, the native scripts/pr guard remains authoritative; this state will be rechecked immediately before merge.

@steipete
steipete merged commit 61221c4 into main Aug 19, 2026
229 checks passed
@steipete
steipete deleted the steipete/amazing-tesla-2eee79 branch August 19, 2026 17:14
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@hannesrudolph

Copy link
Copy Markdown
Member

Canary follow-up: the authentic #126115 corpus still OOMs before this repair runs

Thanks for landing the bounded session-entry/canonical repair here. I tested the final PR head be8481ee2512b5d229d00f498669a4a7db9345e8 against the preserved recovered Krill canary corpus from #126115. The build passed, but the full Doctor flow still fails at the earlier transcript-media migration.

Authentic corpus measured at test time

  • agent database: 1,131,704,320 bytes
  • session_nodes: 2,648 rows / 4,421,208 bytes of entry_json
  • transcript_events: 162,289 rows / 837,304,772 bytes of event_json
  • largest transcript event: 1,437,235 bytes

No transcripts, credentials, configuration, or other private state are attached.

Exact test

NODE_OPTIONS=--max-old-space-size=2048 \
  node openclaw.mjs doctor \
  --repair --non-interactive --no-workspace-suggestions

Final-head result:

doctor_exit=1 elapsed_s=8 samples=32 peak_rss_mib=2147.6

<--- Last few GCs --->
Scavenge 2022.0 (2076.0) -> 2022.7 (2077.0) MB ... allocation failure
Scavenge 2022.8 (2077.0) -> 2021.7 (2099.5) MB ... allocation failure

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
...
v8::internal::JsonParser<unsigned short>::ParseJson(...)
Builtin_JsonParse(...)

This reproduces the original failure shape and approximately 2 GiB ceiling.

Why this is supplementary rather than a duplicate

This PR bounds the session-entry/canonical repair paths, which is valuable and covers the synthetic large-entry_json case described in its evidence. The recovered Krill database has only about 4.4 MB of session-entry JSON; its dominant corpus is about 837 MB of transcript-event JSON.

A V8 profile of the failing full Doctor run identified this earlier path:

autoMigrateLegacyState
  -> migrateLegacyMediaPersistence
  -> migrateAgentDatabase
  -> planTranscriptRows

That planner calls the eager SQLite query over every transcript_events.event_json row before entering its transaction. src/infra/state-migrations.media-persistence.ts is unchanged by this PR: its blob is a5f6a99bff9ab3681efca846845950115b801294 on both the PR base and merge commit 61221c4c20ec511ba239648a5f4f7998d5c35459.

PR #126265 is the companion fix for that remaining owner: #126265

It adds bounded transcript/trajectory migration batches plus the bounded session scan. On the same recovered canary and 2 GiB cap:

doctor_exit=0 elapsed_s=24 peak_rss_mib=903.2
Doctor complete.

Additional #126265 evidence:

  • generated 2,640-session/transcript regression fails on pre-fix main at a 256 MiB old-space cap and passes on the branch;
  • config validation passed with no warnings;
  • expected plugins loaded with zero errors;
  • Discord connected;
  • recovered-session and fresh-session turns passed;
  • Web UI and WebSocket 101 passed;
  • 20/20 ten-minute soak passed with zero runtime errors and zero restarts.

Recommendation: keep the session/canonical improvements landed here, but also land or port the bounded state-migrations.media-persistence.ts portion and regression from #126265. Since this PR closed #126115, the issue should remain tracked until the authentic transcript-heavy canary completes Doctor without a heap override.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 20, 2026
…law#126353)

* fix(doctor): bound large session-store repairs

Prevent post-core update finalization from retaining complete session JSON corpora. Move Doctor repair planning and rewrites onto ordered bounded SQLite owner scans with stale-decision revalidation and selective hydration.

Co-authored-by: Hannes Rudolph <[email protected]>

* test(doctor): expose memory helper to deadcode scan

---------

Co-authored-by: Hannes Rudolph <[email protected]>
steipete added a commit that referenced this pull request Oct 12, 2026
Doctor canonical-session repair rebuilt each accumulated candidate array for every appended row. One deep alias group bypasses the usefulness of the 64-group batch limit: the existing 12,001-candidate scale fixture causes the two grouping loops to copy 144,012,000 existing references before repair can finish. This change appends to function-owned arrays, preserving candidate order, database grouping, the first resolved database scope, SQL, transactions, and repair decisions. It changes two files (+16/-4); no new API, check, schema, or SQLite operation is introduced.

The two quadratic expressions originated in `61221c4c20ec` (#126353) and `fc4d5d744fad` (#123495). The observed scale failure on [the earlier repair candidate](https://github.com/openclaw/openclaw/actions/runs/38283393506/job/114926176837) was a child SIGTERM at its existing 60-second limit; the last recorded phase was repair entry. This establishes the failing flow and workload, not that grouping alone caused that timeout. No causal parent control or before/after timing benchmark is claimed.

Focused production-path proof:

| Test | Exact composed head | Result | Vitest / wrapper wall time |
| --- | --- | --- | --- |
| `pnpm test src/commands/doctor-session-canonical-keys.scale.test.ts --maxWorkers=1` | `7ac691f4a04689c9711192262ad0bc3c73b6ad92` | 1/1; case 66.300 s | 126.26 / 172.89 s |
| `pnpm test src/commands/doctor-session-canonical-keys.owner-repair.test.ts --maxWorkers=1` | `f1979f3b6f5ac9aa59a3f4c83dbe20b9ac49b535` | 4/4 | 234.79 / 526.36 s |

The unchanged scale test executes both edited loops through a real Node child under Doctor maintenance ownership and verifies that all 200,000 transcript events survive, one expected canonical node remains, and foreign keys are valid. The owner tests preserve required creation provenance, replace a stale owner with the selected winner, recover a stolen transcript window without losing history, and verify a repeat repair is a no-op. Both receipts ended at their original clean heads with no surviving processes. These are composed-head results; the composition also contained temporary phase diagnostics excluded from this change.

[Composed-head CI](https://github.com/openclaw/openclaw/actions/runs/38292637049) passed build, production and test types, all core lint stripes, source contracts, Knip, architecture/Madge, and database worker/dialect ratchets. The [published-driver update cell](https://github.com/openclaw/openclaw/actions/runs/38292637049/job/114965277486) executed and passed from published 2026.10.2 to candidate 2026.10.2 at `f1979f3b6f5a`: candidate checksum matched, update completed, readiness returned 200, and running version was verified. One Codex autoreview returned no findings. The publication preserves the newer main-key admission change. The two grouping bodies retain the reviewed and tested behavior; no standalone publication-head static run is represented as already complete.

The separate low-heap dry-run memory test remains unresolved: at `f1979f3b6f5a` it exceeded its existing 90-second case limit (90.277 s; Vitest 444.68 s / wrapper 557.96 s). Its child runs `apply:false`, so neither changed grouping loop executes. This is not a passing memory result or an inferred timeout root cause. The separate fixture-only commit `c92696a32a7bd33d7ca98be7f94f09f42d2acb8f` moves its unchanged minified/split bundle preparation to `beforeAll`; its runtime rerun is pending. That fixture keeps the existing 160 MiB heap, 60-second child and 90-second case limits.

This Doctor-only in-memory optimization does not remove SQLite reads, writes, or authority checks. No T1 reduction or warmed-turn SQL/request saving is claimed. Update and repair behavior remain unchanged; only group construction loses its quadratic copying cost.

Direct-main publication was refused by the repository ruleset; this emergency repair uses the authorized head-pinned PR squash fallback. Main is not yet established green.

Applicable newer static proof is also green at `8d087040fefe324e5ff7fa76faf497fadb542c08` in [CI run 38298120555](https://github.com/openclaw/openclaw/actions/runs/38298120555): production types, all core/general lint, source contracts, Knip/dependencies, architecture and baseline ratchets. The changed test graphs passed in core stripe 5 (`commands-doctor`, job 114974448774) and stripe 4 (`agents-sessions`, job 114974448893). The pending core-3 test stripe owns neither graph. These remain composed-head proofs with the integration limits stated above.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Doctor canonical-session repair rebuilt each accumulated candidate array for every appended row. One deep alias group bypasses the usefulness of the 64-group batch limit: the existing 12,001-candidate scale fixture causes the two grouping loops to copy 144,012,000 existing references before repair can finish. This change appends to function-owned arrays, preserving candidate order, database grouping, the first resolved database scope, SQL, transactions, and repair decisions. It changes two files (+16/-4); no new API, check, schema, or SQLite operation is introduced.

The two quadratic expressions originated in `fee9ee2148a3` (openclaw#126353) and `cd4f2480c2f5` (openclaw#123495). The observed scale failure on [the earlier repair candidate](https://github.com/openclaw/openclaw/actions/runs/38283393506/job/114926176837) was a child SIGTERM at its existing 60-second limit; the last recorded phase was repair entry. This establishes the failing flow and workload, not that grouping alone caused that timeout. No causal parent control or before/after timing benchmark is claimed.

Focused production-path proof:

| Test | Exact composed head | Result | Vitest / wrapper wall time |
| --- | --- | --- | --- |
| `pnpm test src/commands/doctor-session-canonical-keys.scale.test.ts --maxWorkers=1` | `7ac691f4a04689c9711192262ad0bc3c73b6ad92` | 1/1; case 66.300 s | 126.26 / 172.89 s |
| `pnpm test src/commands/doctor-session-canonical-keys.owner-repair.test.ts --maxWorkers=1` | `f1979f3b6f5ac9aa59a3f4c83dbe20b9ac49b535` | 4/4 | 234.79 / 526.36 s |

The unchanged scale test executes both edited loops through a real Node child under Doctor maintenance ownership and verifies that all 200,000 transcript events survive, one expected canonical node remains, and foreign keys are valid. The owner tests preserve required creation provenance, replace a stale owner with the selected winner, recover a stolen transcript window without losing history, and verify a repeat repair is a no-op. Both receipts ended at their original clean heads with no surviving processes. These are composed-head results; the composition also contained temporary phase diagnostics excluded from this change.

[Composed-head CI](https://github.com/openclaw/openclaw/actions/runs/38292637049) passed build, production and test types, all core lint stripes, source contracts, Knip, architecture/Madge, and database worker/dialect ratchets. The [published-driver update cell](https://github.com/openclaw/openclaw/actions/runs/38292637049/job/114965277486) executed and passed from published 2026.10.2 to candidate 2026.10.2 at `f1979f3b6f5a`: candidate checksum matched, update completed, readiness returned 200, and running version was verified. One Codex autoreview returned no findings. The publication preserves the newer main-key admission change. The two grouping bodies retain the reviewed and tested behavior; no standalone publication-head static run is represented as already complete.

The separate low-heap dry-run memory test remains unresolved: at `f1979f3b6f5a` it exceeded its existing 90-second case limit (90.277 s; Vitest 444.68 s / wrapper 557.96 s). Its child runs `apply:false`, so neither changed grouping loop executes. This is not a passing memory result or an inferred timeout root cause. The separate fixture-only commit `c92696a32a7bd33d7ca98be7f94f09f42d2acb8f` moves its unchanged minified/split bundle preparation to `beforeAll`; its runtime rerun is pending. That fixture keeps the existing 160 MiB heap, 60-second child and 90-second case limits.

This Doctor-only in-memory optimization does not remove SQLite reads, writes, or authority checks. No T1 reduction or warmed-turn SQL/request saving is claimed. Update and repair behavior remain unchanged; only group construction loses its quadratic copying cost.

Direct-main publication was refused by the repository ruleset; this emergency repair uses the authorized head-pinned PR squash fallback. Main is not yet established green.

Applicable newer static proof is also green at `8d087040fefe324e5ff7fa76faf497fadb542c08` in [CI run 38298120555](https://github.com/openclaw/openclaw/actions/runs/38298120555): production types, all core/general lint, source contracts, Knip/dependencies, architecture and baseline ratchets. The changed test graphs passed in core stripe 5 (`commands-doctor`, job 114974448774) and stripe 4 (`agents-sessions`, job 114974448893). The pending core-3 test stripe owns neither graph. These remain composed-head proofs with the integration limits stated above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: package-to-dev update Doctor OOMs on large recovered session state

2 participants