Repository navigation
fix(sessions): migrate long histories without exhausting heap - #131276
Conversation
Stage transcript payloads and deduplication in private temporary SQLite storage before the existing atomic import. Rebuild projections from navigation metadata and stream payload reads rather than retaining entire histories. Preserve exact handoffs, source validation, and archive recovery.\n\nFixes #127468.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 11:51 PM ET / August 28, 2026, 03:51 UTC. ClawSweeper reviewWhat this changesMigrates large legacy JSONL session histories through a temporary SQLite staging store so Doctor can import them without retaining whole transcript batches in heap. Warning SQLite table change This PR modifies persisted SQLite tables in Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readinessThe PR remains necessary and its introduced disk-backed staging path is coherent; no introduced correctness defect was found. Merge review should still reconcile the overlapping session-store PR and refresh exact-head/main validation before landing. Priority: P1 Review scores
Verification
How this fits togetherDoctor moves legacy session transcripts into OpenClaw’s canonical per-agent SQLite store before Gateway resumes using that history. The change replaces in-memory import preparation and healthy-history scans with bounded, disk-backed or streamed processing. flowchart LR
A[Legacy JSONL transcripts] --> B[Doctor migration reader]
B --> C[Temporary SQLite staging]
C --> D[Source fingerprint check]
D --> E[Canonical SQLite transaction]
E --> F[Gateway session history]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +455, Tests +501, Docs +12, Other +3. Total +971 across 26 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Land one canonical bounded import path after reconciling it with the shared-session-store work and proving the rebased head preserves migration, integrity, and restart behavior. Do we have a high-confidence way to reproduce the issue? No independent current-head execution was run in this read-only checkout, but the former whole-history preparation and the new constrained-heap regression harness make the failing path source-reproducible with high confidence. Is this the best way to solve the issue? Yes, subject to the overlap validation: staging before the synchronous canonical transaction keeps filesystem work out of the write lock while avoiding JavaScript retention of full transcript batches. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against eda219c4c21b. LabelsLabel changes:
Label justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Stream unchanged header and label detection while retaining exact snapshots and atomic guards for positive repairs. Reuse one import-finalize operation for handle closure, schema maintenance, and automatic incremental vacuum. Keep full integrity checks, NONE-mode conversion, and explicit full compaction. Verified constrained-heap regressions, real historical upgrades, complete long-history Docker cases, process interruption, source mutation, and temporary-volume exhaustion.
|
Land-ready review for The root cause was payload retention at the import/projection and healthy-Doctor owners, not JSONL read chunk size. The canonical path now uses private disposable disk staging and exact disk-backed deduplication, streams selected projection payloads and healthy checks, and preserves source revalidation before the atomic canonical transaction. Automatic cleanup avoids unnecessary full repacking while retaining integrity/FK checks, NONE conversion, and explicit full compaction. Both storage decisions were approved before implementation. The temporary tables are not a canonical schema change. Production net +146 is justified by that planning boundary; tests/support net +810. Smaller batches do not bound one long transcript, and source reads inside the canonical transaction would violate the ownership contract. All final package/fault proof is complete: six Docker cases, 649 sessions, 1,132,000 transcript events plus 960 artifacts, and 2.93 GB of source data; actual stable schema-v1 stores; 256 MiB full Doctor; between-batch SIGKILL/recovery; source mutation; updater-finalization SIGKILL/repair; and real 64 MiB tmpfs exhaustion/retry. Exact content, metadata, identity, projections, source/archive bytes, integrity/FKs, idempotence and real Gateway history passed. Largest first Doctor: 569.658 → 290.431 seconds; entire package update: 668.41 → 379.40 seconds under equal quotas on separate Testboxes. Final package/fault environment, provider blacksmith-testbox, lease The genuine stable → exact-dev clone/build test also completed. The published stable updater installed this head and migrated all 192,000 events, but returned exit 1 during its known replaced-module finalization bug. Before recovery, the installed full head and every data/archive invariant were independently verified. Actual Latest ClawSweeper exact-head review found no introduced correctness/security defect. Its remaining shared-store overlap/rank-up item is resolved by landing order: the physical-store/logical-agent repair is still OPEN and unmerged at Current-main reconciliation was refreshed: Focused results remain 125 import/projection/ownership passes (two existing platform skips), 62 sibling passes, and 133 final Doctor passes; local build and changed gates passed. Individual records and positive header/label repairs retain documented memory limits; incremental cleanup retains partly filled pages. The earlier 30-second ClawSweeper probe did not observe suite completion, whereas complete Linux logs do. No workloads, heap caps, timeouts, integrity checks, or exact-content assertions were weakened. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
…aw#131276) * fix(sessions): bound legacy transcript import memory Stage transcript payloads and deduplication in private temporary SQLite storage before the existing atomic import. Rebuild projections from navigation metadata and stream payload reads rather than retaining entire histories. Preserve exact handoffs, source validation, and archive recovery.\n\nFixes openclaw#127468. * build: register doctor transcript staging SQL boundary * perf(doctor): bound healthy history checks and import cleanup Stream unchanged header and label detection while retaining exact snapshots and atomic guards for positive repairs. Reuse one import-finalize operation for handle closure, schema maintenance, and automatic incremental vacuum. Keep full integrity checks, NONE-mode conversion, and explicit full compaction. Verified constrained-heap regressions, real historical upgrades, complete long-history Docker cases, process interruption, source mutation, and temporary-volume exhaustion.
|
Follow-up #146597 has merged. It builds on this PR's incremental-vacuum import-finalization path by skipping redundant cleanup and the second integrity scan for already-compact databases with zero free pages and no WAL. It retains initial validation and leaves explicit compaction and pending-cleanup behavior unchanged. This is an additional optimization; it does not replace this PR's bounded-memory migration work. |
Closes #127468.
What Problem This Solves
Operators upgrading many long transcripts—or one very long transcript—could exhaust the JavaScript heap before Doctor committed their import. Chunked JSONL reading did not help: the import owner retained every parsed transcript in a 256-session batch, then kept complete payload strings for deduplication and projection rebuilding. Even after importing successfully, healthy header and label checks could materialize the entire history again.
Large imports also paid for full-file SQLite repacking during automatic cleanup. In the profiled 256,000-event case, maintenance/compaction consumed about 66 of 164 seconds while full repacking reclaimed only 1.2% of the database.
Why This Change Was Made
The canonical import path now stages payloads and exact-byte deduplication in a private, disposable SQLite database. Readers and deferred source-fingerprint validators finish before the existing atomic batch transaction. Projection rebuilding retains navigation metadata, streams selected payloads, and uses a linear ancestor walk. The old whole-payload arrays/set and duplicate projection-building path are removed.
Healthy header detection reads the first ordered stored row, including nonzero sequences. Label detection streams through the existing normalizer. Actual repairs retain their full exact snapshots, malformed-sibling checks, ownership/binding checks, and atomic mutation guards. Automatic import finalization consolidates the former close/migrate booleans and incrementally vacuums databases that already support auto-vacuum. NONE-mode conversion and explicit session/shared compaction still run full
VACUUM; full integrity and foreign-key checks, busy-checkpoint refusal, quarantine handling, and permissions remain intact.Both storage decisions were explicitly approved before implementation. No canonical schema/version, runtime fallback, configuration option, dependency, or archive/restore contract is added or changed. Temporary-volume space and retaining partially filled pages are the documented tradeoffs. The final large corpus uses about 1.18% more database space than full repacking.
Production LOC: +460/-314 (net +146). Tests/test support: +921/-111 (net +810). Docs: +12. Guard/ratchet tooling: net +3, including an exact shrink-only assertion-baseline update. Production growth owns private disk staging, exact disk-backed deduplication, streamed projections, and bounded no-op detection. Smaller batches would not bound one long transcript; reading files inside the write transaction would violate its contract; deleting integrity checks would weaken the approved repair.
Regression provenance is clear for the allocations: batch materialization came from the large-session batching change, commit 1a821db04926, on 2026-08-17 (code author, PR author, and merger: @steipete). Whole-history label snapshots came with plain inbound-context labels, commit d7627d6f4cc4, on 2026-07-27 (code/PR author and merger: @jesse-merhi); header snapshots came with missing-header repair, commit 8aa67634ca03, on 2026-07-28 (code/PR author and merger: @galiniliev). Those repair behaviors remain; their healthy-path payload retention does not.
User Impact
Long histories can migrate without retaining a whole batch's payloads in the JavaScript heap. Session IDs, ordered content, active branches, exact SQLite handoff bytes, timestamps, ownership, source-change rejection, and recovery archives remain protected. Staging never becomes a second runtime store and is never resumed after interruption.
A JSON record must still fit in memory. Huge histories that genuinely need header or label mutation still use the existing full-snapshot repair contract. Healthy label scans remain linear. This PR does not claim globally bounded memory for every Doctor operation or provider execution.
AI-assisted implementation and verification. No release or package publication is requested.
Evidence
Source identity and focused proof
Final head:
e3887beb8da8099b316633a32c2937ccd706b91a. Candidate package SHA-256:f912864d7aa27c7f77acb83e74bb493be5ed45a21c5640305e5d64dea1e6956a(58,991,509 bytes). The package builder checked all 16 changed/new performance files before and after building; after commit, every tested file was matched against its Git blob at this head. Package inventory/import integrity checks passed.Both original import regressions aborted before the fix with exit 134 under a 256 MiB JavaScript heap: 256 transcripts × 64 roughly 32 KiB tool-result events, and one 100,000-event roughly 4 KiB transcript. The same limits passed after the repair on Linux Node 24.19.0 in 24.5 s and 24.9 s, including exact hashes, active projections, archives, and repeat import. That run passed 125 focused tests with 2 existing platform skips; another 62 ownership, handoff, race/ledger/startup, reconciliation, search, and Doctor sibling tests passed locally.
The healthy-header/label regressions separately failed before inside SQLite
.all()on a 320 MiB transcript, after seeding outside the constrained child. Both now pass under the unchanged 256 MiB/30-second child limits with exact raw JSON/sequence/timestamp digests. The final four-file Doctor run passed 133 tests, including real SQLite NONE/FULL/INCREMENTAL cleanup, explicit session/shared repacking, Unicode-escaped labels, malformed siblings, snapshot races, recency, ownership, and FTS behavior.Local
pnpm build, the full changed-file gate, Kysely guard, typechecks, lint, architecture checks, and whitespace checks passed. No ineffective dynamic-import warning was emitted. Fresh isolated Codex autoreview of the performance diff and then the complete branch reported no accepted/actionable findings at its default P0-only threshold; reviews did not execute tests. The full-branch review confidence was 0.93.Actual installed-package Docker matrix
Latest stable was resolved and rechecked as [email protected], with registry integrity
sha512-ycF3yPcbjN6bUPeaUx6Mh6vze1hQWoD3CT/wWcmD7a8xaHHHRUaAlaq+lFxMHf1ssEgODVAwjlzYqp2twkYZ7g==. Each case installed that actual package and ranopenclaw update --tag file:<candidate.tgz> --yes --no-restart --json.All six final cases pass full ordered event-content/identity checks, complete expected session entries, active-branch projections, exact original/archive byte hashes, SQLite integrity/foreign keys, repeated-Doctor idempotence, real Gateway readiness,
sessions.list, and visiblechat.historymarkers. Inactive branch markers stay absent. Combined: 649 sessions, 1,132,000 transcript events, 960 additional artifact events, and 2,927,466,266 source bytes, rerun on the final candidate.Before/after use Node 24.19.0/npm 11.17.0 and the same four-CPU/12 GiB container limits on separate Testboxes. These are observed runs, not a universal speedup claim; small cases include installation/startup noise. The largest complete update dropped from 668.41 to 379.40 seconds. Full update peak RSS includes npm installation and is not migration-only memory.
The actual installed full Doctor previously aborted at 256 MiB on the already-current 100,000-event history. It now completes in 11.43 s at that heap limit, peak RSS 464,088 KiB, with exact idempotence. Without the heap cap, that case's peak RSS fell from 1,478,276 to 517,720 KiB.
An additional historical-store case used the actual stable
setup --baselineandmemory status --jsonto create shared and per-agent schema-v1, auto-vacuum NONE databases. With 100,000 events/243,257,894 source bytes, the package update completed in 74.63 s (first Doctor 33.476 s). Existing migrations produced shared schema 13 and agent schema 17, with the agent database converted to incremental auto-vacuum. Full integrity/FKs, exact content/archives, 256 MiB full Doctor (11.60 s), idempotence, and real Gateway history passed. This PR does not change those schema versions.Provider: blacksmith-testbox, final package/fault lease
tbx_01m12x62e689qkwxh01y210a1n, environment run, now explicitly stopped. First-candidate comparison used the earlier Testbox environment. No operator state, host home, service bus, or provider/channel credentials were mounted into the app containers. This is Testbox-hosted Docker proof, not direct AWS Crabbox or authenticated provider proof.Fault and recovery boundaries
openclaw update repair --yes --jsoncompleted in 24.97 s with unchanged full data/archive hashes; another Doctor and real Gateway history passed.Genuine dev-channel update and remaining gates
Separately, the literal published-stable → moving-dev command was exercised against GitHub, selecting
e68aa7b5ff9c0605d37bcd48cde008e2a49d5c4a. It installed dev and migrated all 192,000 events/463,905,309 source bytes, but the old stable updater then failed loading a replaced module during finalization. Freshopenclaw update repair --yes --jsoncompleted in 32.16 s with unchanged verified data and archives. The fresh-process install-switch fix already exists on main in 4ee399c714d6; this PR does not rewrite or claim to fix the already-published stable binary.The second genuine stable → dev clone/build/update used a fresh Git directory and the supported internal target-ref hook pinned to this exact PR head. It also returned exit 1 after 863.02 s with the same released-updater finalization error. Before recovery, the installed Git revision was independently verified as
e3887beb8da8099b316633a32c2937ccd706b91a, and all 192 sessions/192,000 events/463,807,965 source bytes plus archives passed the complete oracle. Actualopenclaw update repair --yes --jsonthen succeeded in 49.40 s, with unchanged data/archive hashes. The newly installed CLI's subsequentopenclaw update --channel dev --yes --jsonsucceeded in 403.83 s, retaining the same pinned head. Another full Doctor passed in 31.13 s, and real Gateway readiness, session listing, and history passed for all three agents. The model selection was verified in both actual catalogs; no provider call was made.That sequence proves candidate installation, migration, recovery, and a successful subsequent update—not a clean first hop from the old released updater. Git clone/build/check time is separate from migration timing; no Git checkout or build was faked. Provider blacksmith-testbox, lease
tbx_01m1317mzdz5z8rffggtbhf8d5, exact-dev environment run, now explicitly stopped.Exact-head CI run 33134954706 completed with
openclaw/ci-gateSUCCESS. The native watcher endedGREENafter excluding superseded/cancelled contexts. A separate source review against frozen main075487ad7755b5902f25af03f0d2fecbc7708cacfound no new interaction defect in the upstream history/checkpoint/provenance changes: added arguments are optional and the canonical writers/schema owners are unchanged. That assessment is source-based, not a separately executed combined-tree suite.The corpus uses stable V3 transcripts. Provider execution, native external-harness transcripts, binary media, and host-power-loss recovery are not claimed. Overall logical digests include source mutation metadata and are compared within each state directory; per-state content/metadata/archive oracles remain exact. Early harness setup/probe errors were corrected without weakening those oracles. The earlier ClawSweeper live probe stopped after 30 seconds waiting for a test-name string and did not observe a terminal suite result; the complete focused executions above are the test evidence. Its requested deep/interruption recovery evidence is now included here.
Exact permanent regression commands:
The local host was heavily contended during early import-memory runs; one timed out and two diagnostic repeats were stopped. Unchanged tests passed on isolated Linux without larger heaps/timeouts. Subsequent complete local Doctor tests, changed gates, and build passed. Synthetic corpus tooling and raw proof remain campaign artifacts, not product runtime or committed transcripts.