Skip to content

feat(sessions): automatically archive older transcripts - #145172

Merged
steipete merged 4 commits into
mainfrom
codex/session-cold-storage
Sep 11, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/session-cold-storage

Conversation

@steipete

@steipete steipete commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Related: #144232

Additional instructions

The branch is in openclaw/openclaw, so maintainers can edit it directly. GitHub’s fork-collaboration toggle applies only to cross-repository PRs.

What Problem This Solves

Older session transcripts keep agent databases large even when their sessions are rarely opened. Operators need automatic extraction, a visible account of the resulting storage, and a safe way to tune the policy without restarting the Gateway.

Why This Change Was Made

Adds opt-in cold storage owned by the existing Gateway maintenance lifecycle. At startup and once a minute, bounded workers move eligible inactive transcript windows into verified, immutable compressed JSONL files. SQLite retains their identity and archive metadata; opening history restores the exact serialized events and associated projections before use. Current and historical windows are eligible, with active work, recovery, pending inputs, and required history references protected.

The agent schema advances from 19 to 20 because older readers cannot safely interpret extracted event rows. The supported Doctor migration creates the new representation without rewriting existing transcripts; state schema remains 17. Supported full, SQLite, and Git backups embed verified compressed payloads in their snapshot databases, so restoration does not depend on the original archive directory.

The maintainer accepted this opt-in storage design and its operating boundaries: agent schema20, authoritative archive files, self-contained supported backups, pre-upgrade-backup rollback for older binaries, and the documented large-batch writer-queue latency. Database-only replicas must carry the archive files. The feature remains disabled by default.

User Impact

Settings → Agent Defaults → Session now shows hot/archived transcript counts, database and WAL sizes, archive file sizes, embedded archive bytes, per-agent details, and background maintenance status. Operators can enable archival, choose a positive day threshold, and start a background batch. Settings use the canonical config apply flow and take effect without a Gateway restart.

{
  session: {
    maintenance: {
      coldStorage: { enabled: true, afterDays: 30 },
    },
  },
}

Cold storage defaults off and has its own opt-in policy, independent of retention mode. Each pass is bounded to 128 transcripts and 64 MiB of restoration envelopes. Recently restored history stays hot for 24 hours in the current process. Text search reports excluded cold transcripts; bulk previews report archived history without restoring it. Chat/history access restores on demand, including when automatic extraction is disabled.

Archive files are authoritative history. Missing or damaged files produce explicit errors and preserve their metadata; they never become an empty conversation. Restore the matching backup to recover lost bytes. Files remain after rehydration to protect in-progress backups, so smaller working databases do not promise smaller total storage on every pass. Worker commit/reclamation joins the existing database writer queue and can delay other writes; one large copied-database batch held that queue for 11.3 seconds in local testing. Compression runs off the Gateway thread.

The docs cover configuration, eligibility, search/preview behavior, recovery, backups, physical reclamation, and upgrade/downgrade boundaries. Generated config inventory increases by exactly the three accepted cold-storage paths; test graph roots are rebalanced within the existing ceilings.

Evidence

  • Real copied-database migration, extraction, and restoration: exact event, identity, window, and node preservation; archive hash/envelope verification; SQLite quick and foreign-key checks. No production Gateway or database was modified.

  • Concurrent-reader regression: the old split marker/payload read returned missing history when a second SQLite connection archived between queries. The test fails before the fix and passes with a single read snapshot. Synchronous writes against cold history reject without mutation.

  • Focused migration/persistence, reader/writer, eligibility, backup, search/usage, agent/CLI/SDK resume, Gateway lifecycle/RPC/config, and UI tests. Representative completed runs: 174 migration/persistence tests, 387 resume/API tests, 120 Gateway lifecycle tests, 49 final Gateway routing/history tests, 40 user-turn persistence tests, 6 backup tests, 16 usage tests, and 9 Settings component plus 3 browser E2E tests. These are separate suite receipts, not an aggregated unique test count.

  • Independent review findings were checked against source and behavior; the reader snapshot race and historical-window eligibility were fixed. Bulk preview restoration was deliberately excluded to avoid menu prewarming refilling the database, with a clear macOS archived-history message.

  • Production and macOS builds passed. Schema/config guards, unused-export checks, UI i18n, CSS lint, and runtime import-cycle checks passed. Documentation validation checked 13,448 links with zero broken links. Full repository TypeScript checks passed. TypeScript lint findings were fixed and the corrected files passed scoped rechecks; no suppressions or budget increases were added.

  • Supported Doctor CLI: agent schema 19 → 20, both version markers updated, original events/identities/windows/nodes/watermarks unchanged, and integrity/foreign-key checks passed.

  • Live isolated Gateway: 30-day and 7-day thresholds selected the expected histories; configuration enable/age/disable changes preserved the Gateway process and connection. Run now acknowledged in 32 ms and 1.2 ms before completion; concurrent message writes succeeded. Database size fell from 67.87 MB to 42.78 MB with three cold transcripts. Exact restoration, explicit missing-file failure with metadata retained, and recovery after replacing the file passed. The 115 health probes measured 27.9 ms p95 and 223.7 ms maximum; these are synthetic local observations, not a throughput guarantee.

  • Automatic startup on the committed code: with the 7-day policy enabled before launch, the Gateway archived three old transcripts and kept two recent transcripts hot. The harness called only storage status and health, never Run now. Both isolated Gateway processes shut down cleanly.

Follow-up validation and repairs

Cold history now restores before channel context, latest-assistant reads, reset, fork/rewind, branch inspection/switching, and parent-session forks. Missing-file failures preserve logical session/history state; existing-child no-ops do not read an unnecessary parent archive. Legacy schema14/17 preflight no longer requires the schema20 table before migration creates it, while current-schema validation remains strict. Steering waits for the initial projection and received notifications before committing its transcript prefix. Native protocol bindings were regenerated.

Linux Blacksmith Testbox runs passed the reader, historical-migration, process-census, config-hint, Swift-protocol and SQLite-guard groups, and all 19 final steering cases. A clean frozen dependency install passed 125 reader/lifecycle/migration/Doctor tests across 11 files. Earlier lifecycle coverage passed 86 distinct cases, including 21 cold success/missing-file/skip cases, with red proof against the original owners. These are separate suite receipts, not an aggregated unique count.

The packaged Linux campaign used the genuine published [email protected] updater and old source writers. A forced process termination at the schema-20 WAL synchronization boundary rolled back coherently to schema 19 with all eight canonical table hashes unchanged. Immediate recovery correctly refused the still-valid maintenance lease; after observing its natural expiry, supported update repair and two real artifact updates passed with schema 20 and unchanged data. The docs describe this recovery delay.

The same installed candidate archived 257 old events through live policy configuration and the scheduled worker. Verified backup refused a missing archive. A schema-neutral package update legitimately preserved the missing reference; history access still failed explicitly. Replacing the archive, verified backup, another real package update, exact restoration of all eight original tables, and one appended message passed. Update receipts include canary, package swap, and Doctor steps, so repeated artifact updates were not already-current no-ops.

The campaign also repaired two validation gaps: synthetic update fixtures now update only the content-inventory entries they change, and native capability checks skip mutable startup. The latter returned exact JSON without touching pristine or unreadable state in six built-CLI probes; registered CLI/preAction tests passed. A CI account-picker failure reproduced a focused More action becoming Manage during refresh; keyed rows fix it, with 13 browser E2E and 58 sibling tests passing. Independent review found no remaining actionable P0–P2 findings in these repairs.

The final package at a2dab0421d8 passed both maintained published-release upgrade lanes: managed restart in 372 seconds and populated SQLite upgrade in 399 seconds, using auto-auth restart mode. Blacksmith Testbox run. This exercises real Gateway processes through the maintained systemctl fixture; it is not a native systemd-daemon or power-loss certification. Exact-head CI passed. All cold-storage implementation files match the separately verified crash/cold-file candidate.

Before and after

Synthetic Control UI fixtures; displayed counts are illustrative, not production data.

Before: session settings without storage controls

After: storage inventory and automatic archival settings

@clawsweeper

clawsweeper Bot commented Sep 11, 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 app: macos App: macos app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling plugin: workboard size: XL maintainer Maintainer-authored PR labels Sep 11, 2026
@steipete
steipete marked this pull request as ready for review September 11, 2026 19:01
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 11, 2026, 7:24 PM ET / 23:24 UTC (Revision 5).

ClawSweeper review

What this changes

Adds opt-in compressed transcript archival, automatic restoration, portable backups, and Settings controls, with follow-up updater and account-picker repairs.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/state/openclaw-agent-schema.sql. Prefer a design that avoids changing persisted SQLite tables. Migration or upgrade compatibility proof is recorded, but maintainers should still confirm that the schema change is necessary.

Merge readiness

⛔ Blocked before merge - 4 items remain

This remains a distinct, maintainer-owned feature absent from current main. The earlier reader findings appear addressed, and no additional blocking code defect was identified.

Priority: P2
Reviewed head: a2dab0421d8ba4215e4bb86e8d84e0359a92c933

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Substantial runtime evidence and addressed reader regressions support a good patch assessment, with final-package upgrade validation still outstanding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded isolated Gateway and published-updater runs exercise the production archive, restoration, backup, and migration owners with preserved history and explicit failure recovery; inspected screenshots establish Settings presentation. Final-package upgrade completion remains a separate follow-up.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded isolated Gateway and published-updater runs exercise the production archive, restoration, backup, and migration owners with preserved history and explicit failure recovery; inspected screenshots establish Settings presentation. Final-package upgrade completion remains a separate follow-up.
Evidence reviewed 13 items Pinned patch and clean checkout: Reviewed the merge-base-to-head introduction rather than endpoint drift. The checkout matches the pinned original head; git diff --check passed and git status remained clean.
Still necessary on main: Fetched main still declares agent schema 19 and has no session-cold-storage.ts implementation. The supplied latest release also declares schema 19.
Latest release boundary: The supplied v2026.9.4 release revision uses agent schema 19; this PR's schema-20 feature is not established as shipped.
Findings None None.
Security None None.

How this fits together

OpenClaw stores conversation history in per-agent SQLite databases. Gateway maintenance moves inactive history into verified archive files, while history readers restore it and supported backups capture its contents.

flowchart TD
  A[Saved archival policy] --> B[Gateway maintenance]
  C[SQLite conversation history] --> B
  B --> D{Inactive and unprotected?}
  D -->|Yes| E[Verified compressed archives]
  E --> F[History restoration]
  F --> C
  E --> G[Portable backups]
  C --> G
Loading

Before merge

  • Resolve merge risk (P1) - Agent migration advances to schema 20 even with archival disabled; older binaries require a matching pre-upgrade backup. Final-package managed-restart and populated-database upgrade results remain pending.
  • Resolve merge risk (P1) - Once enabled, database-only replicas are incomplete without referenced cold files; operators must use supported self-contained backups or retain those files.
  • Complete next step (P2) - Record successful final-package managed-restart and populated SQLite upgrade results before merge.
  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Configuration and protocol surface 2 configurable leaves, 2 administrator RPCs, agent schema 19 → 20 Extraction defaults off, but the schema migration applies independently of that setting.
Production versus test growth Production/tooling net +2,986 lines; tests/test support net +3,423 lines The stated production growth supports archive ownership, restoration, backup portability, and Settings; documentation and metadata are excluded.

Stored data model

Persistent data-model change detected: database schema: src/state/openclaw-agent-schema.sql, serialized state: ui/src/i18n/locales/en-settings.ts, serialized state: ui/src/pages/config/settings-targets.ts, unknown-data-model-change: ui/src/i18n/locales/en-settings.ts, unknown-truncated-pull-files. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Complete the existing upgrade campaign (recommended)
    Record final-package managed-restart and populated SQLite upgrade results while preserving the accepted backup and downgrade boundaries.

Technical review

Best possible solution:

Retain the accepted opt-in storage design, exact restoration, and portable backups with completed final-package upgrade validation.

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

Not applicable to the feature request; the recorded isolated Gateway campaign exercises archival and restoration, and this read-only review did not execute tests.

Is this the best way to solve the issue?

Yes: the patch extends the existing session and maintenance owners, preserves serialized history, and documents the accepted storage tradeoffs; final-package upgrade validation remains unfinished.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2efa249c405b.

Labels

Label justifications:

  • P2: This is an opt-in storage improvement with meaningful upgrade requirements, without evidence of an urgent existing-user outage.
  • merge-risk: 🚨 compatibility: Schema 20 prevents older readers from reopening upgraded databases, and enabled archival changes what database-only backups must retain.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded isolated Gateway and published-updater runs exercise the production archive, restoration, backup, and migration owners with preserved history and explicit failure recovery; inspected screenshots establish Settings presentation. Final-package upgrade completion remains a separate follow-up.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded isolated Gateway and published-updater runs exercise the production archive, restoration, backup, and migration owners with preserved history and explicit failure recovery; inspected screenshots establish Settings presentation. Final-package upgrade completion remains a separate follow-up.

Evidence

What I checked:

  • Pinned patch and clean checkout: Reviewed the merge-base-to-head introduction rather than endpoint drift. The checkout matches the pinned original head; git diff --check passed and git status remained clean. (a2dab0421d8b)
  • Still necessary on main: Fetched main still declares agent schema 19 and has no session-cold-storage.ts implementation. The supplied latest release also declares schema 19. (package.json:7, 2efa249c405b)
  • Latest release boundary: The supplied v2026.9.4 release revision uses agent schema 19; this PR's schema-20 feature is not established as shipped. (src/state/openclaw-agent-db-contract.ts:24, 3a9d69db306c)
  • Related work is distinct: fix(sessions): speed up database cleanup and find transcript archives consistently #144232 is verified merged. Its supplied discussion explicitly excludes file-only cold storage, new configuration, and schema migration, so it does not supersede this feature. (d748e5d93d8d)
  • Archive and restoration invariants: The worker publishes and verifies compressed contents before removing hot events, rechecks protection and the prepared snapshot inside the transaction, and restores events and projections before removing the cold descriptor. (src/config/sessions/session-cold-storage-worker.ts, a2dab0421d8b)
  • Prior reader findings addressed: Core recent-history and latest-assistant readers now use the restore-aware owner, as do SDK latest-text reads. The registered channel-preparation regression checks that prior conversation context survives archival. The previous reviewed SHA could not be loaded for a historical comparison; no late finding is asserted. (src/plugin-sdk/session-transcript-runtime.read-fence.test.ts:136, a2dab0421d8b)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record completed final-package managed-restart and populated SQLite upgrade results, preserving the existing crash/recovery and cold-file evidence.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-11T19:09:42.200Z sha b2c1bcf :: blocked before merge. :: [P1] Restore cold transcripts before assembling channel history | [P2] Preserve cold-history support in asynchronous latest-text APIs
  • reviewed 2026-09-11T21:48:52.652Z sha b10e15f :: blocked before merge. :: none
  • reviewed 2026-09-11T22:08:49.157Z sha c6d9bf6 :: blocked before merge. :: none
  • reviewed 2026-09-11T23:15:47.956Z sha 07a6cbe :: blocked before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added app: android App: android commands Command implementations extensions: codex labels Sep 11, 2026
@steipete
steipete force-pushed the codex/session-cold-storage branch from c94e0c2 to b10e15f Compare September 11, 2026 21:41
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 11, 2026
Add opt-in worker maintenance, live storage settings, and exact restoration from compressed JSONL archives. Advance the agent schema to 20 and embed verified cold payloads in supported backups.
Restore archived history before channel context, latest-text reads, reset and fork operations. Preserve legacy schema migration preflight and steering transcript order; regenerate native protocol bindings and repair the Windows cleanup fault fixture.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: android App: android app: macos App: macos app: web-ui App: web-ui cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: codex gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: workboard proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant