Skip to content

fix(sessions): speed up database cleanup and find transcript archives consistently - #144232

Merged
steipete merged 2 commits into
mainfrom
codex/session-transcript-cleanup
Sep 11, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/session-transcript-cleanup

Conversation

@steipete

@steipete steipete commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes #144212

What Problem This Solves

Fixes an issue where users cleaning large session databases would wait through repeated whole-database validation for individual historical transcripts. Explicit SQLite store selectors could also measure or prune the wrong artifact directory, missing archives and prompt blobs while counting SQLite shared-memory files.

Why This Change Was Made

Local CLI cleanup now reuses its admitted database connection through the existing in-process reclamation path. Gateway and background cleanup retain Workers, and the existing transaction, snapshot, admission, retention, and per-candidate disk checks remain. Archive staging batches small UTF-8 JSONL writes, and successful archive INSERTs skip redundant blob rereads while preserving conflict verification.

A shared directory resolver aligns measurement, pruning, preview exclusions, and archive publication for equivalent legacy and SQLite selectors. Selected SQLite SHM files are excluded from budget totals. Documentation clarifies archive storage, copied-state validation, and Doctor's explicit agent selector.

User Impact

Local cleanup avoids a full integrity scan for every historical victim and consistently finds the owning session artifacts. Existing session protection and retention behavior is preserved. This PR does not add file-only cold storage, new configuration, or a schema migration.

Evidence

  • 92 focused archive, historical cleanup, CLI, and artifact tests pass on the rebased branch. The final 21-test archive-worker run also passes, including the added native custom-directory publication regression. Regressions were demonstrated failing before their fixes.
  • Native Gateway live proof using isolated synthetic state: sessions.cleanup reclaimed exactly one historical window, retained the current session, and reduced measured storage from 2,732,032 to 667,648 bytes. The current transcript remained byte-identical and visible through sessions.preview; SQLite integrity and foreign-key checks passed.
  • All 50 HTTP health probes during the live exercise succeeded (local p95 6.9 ms, maximum 72.2 ms). The task-owned Gateway was shut down afterward.
  • Offline cleanup and Doctor compaction were also verified on an isolated large SQLite snapshot. Retained transcript hashes and logical-session metadata matched the untouched baseline; protected history correctly prevented further cleanup when no eligible victims remained.
  • A synthetic 50,000-row staging benchmark produced identical output while reducing file writes from 100,000 to 190. Median staging-only time fell from 287.7 ms to 17.1 ms; this is not an end-to-end speed claim.
  • Full changed-file checks, targeted final lint/formatting, and the documentation link/anchor audit pass (13,535 internal links; zero broken links). Final independent review is clean at P0–P2.

Stored-data compatibility

No migration is required: this PR leaves the agent/state DDL and schema versions (19/17), archive names, encoding, decoder, and reclamation transaction format unchanged. The serialized-state flag reflects a writer implementation change, not a stored-format change.

Fresh cross-version proof compared the exact pre-change and PR-head staging, zstd encoding, persistence, and decoder implementations using 1,803 synthetic rows (675,176 JSONL bytes), including Unicode, escaping, preserved whitespace, and a row larger than 64 KiB. Both writers produced identical plaintext and compressed hashes (5,154 compressed bytes). All four old/new writer-reader combinations passed plain-file, compressed-file, and SQLite-blob round trips; duplicate writes were accepted and conflicting same-generation blobs rejected in both versions.

The existing exact-byte archive-worker and conflict rollback tests remain regression coverage. Earlier native Gateway and copied-database validation also preserved retained transcript bytes and session metadata. The separate file-only archival/schema proposal is not included in this PR.

@clawsweeper

clawsweeper Bot commented Sep 10, 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 gateway Gateway runtime commands Command implementations size: M maintainer Maintainer-authored PR labels Sep 10, 2026
@steipete
steipete marked this pull request as ready for review September 10, 2026 17:24
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 11, 2026, 11:30 AM ET / 15:30 UTC (Revision 3).

ClawSweeper review

What this changes

Speeds up local session cleanup, makes SQLite and legacy selectors locate the same transcript artifacts, and documents safe cleanup on copied databases.

Merge readiness

⛔ Blocked before merge - 1 item remains

The PR remains useful on the pinned main revision, and no blocking defect was found. The verified test merge resolves the previous conflict concern; the supplied storage and runtime evidence supports proceeding through normal merge gates.

Priority: P2
Reviewed head: e49a09117964fe53f057b6f7f9492b193aa8f212

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with relevant runtime and compatibility evidence and no identified blocking correctness issue.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured evidence covers native Gateway cleanup, offline cleanup and Doctor on copied SQLite state, and old/new archive writer-reader round trips, with retained transcript bytes and metadata preserved; focused tests supplement those runtime observations.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured evidence covers native Gateway cleanup, offline cleanup and Doctor on copied SQLite state, and old/new archive writer-reader round trips, with retained transcript bytes and metadata preserved; focused tests supplement those runtime observations.
Evidence reviewed 9 items Pinned introduction and conflict resolution: Reviewed the merge-base-to-head changes. Raw test-merge records identify main 21a5c18 followed by head e49a091 as its parents; its result contains the intended cleanup changes. The previous conflict-only blocker therefore no longer applies.
Current main still exhibits the reported mechanism: Pinned main inventories dirname(storePath), which selects agent/ for an explicit canonical SQLite selector instead of sibling sessions/. Its historical cleanup also still passes forceInProcess: false for each candidate. No merged replacement is established by the supplied context.
Local optimization preserves the transaction owner: The local runner selects the existing in-process path. Both execution modes call reclaimSqliteSessionInTransaction, retaining current protection, reference, and snapshot checks. Gateway sessions.cleanup supplies no reclamation override and retains Worker execution.
Findings None None.
Security None None.

How this fits together

Session maintenance applies retention settings to OpenClaw’s conversation databases and transcript artifacts. It measures disk usage, protects retained conversations, and archives or removes eligible history.

flowchart TD
  A[CLI cleanup] --> C[Session maintenance]
  B[Gateway cleanup] --> C
  C --> D[Measure database and artifacts]
  D --> E[Check retention and protection]
  E --> F[Existing reclamation transaction]
  F --> G[Canonical archive and derived file]
  G --> H[Remeasure and report]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +37, Tests +166, Docs +77. Total +280 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 9 64 27 +37
Tests 5 183 17 +166
Docs 4 91 14 +77
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 338 58 +280

Review metrics

Metric Value Why it matters
Production versus test growth Production net +37 lines; tests net +166 lines Production growth supports bounded write buffering and shared directory resolution, with regression coverage for selector equivalence and both reclamation modes.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.sqlite-archive.worker.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #144212
Summary: This PR is the candidate fix for the linked cleanup defect; the broader Worker-reuse proposal overlaps only part of the performance work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one archive-directory resolver and the existing reclamation transaction, with connection reuse limited to local cleanup and unchanged retention and archive formats.

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

Yes, from source: explicit SQLite selectors scan the wrong directory on pinned main, and local historical cleanup selects a fresh reclamation Worker per candidate. This review did not execute a reproduction.

Is this the best way to solve the issue?

Yes. The patch reuses existing transaction machinery and consolidates artifact-directory selection without adding a competing retention policy or stored format.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 21a5c1830211.

Labels

Label justifications:

  • P2: Repairs a bounded maintenance-performance and artifact-accounting defect without an established urgent runtime outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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): The captured evidence covers native Gateway cleanup, offline cleanup and Doctor on copied SQLite state, and old/new archive writer-reader round trips, with retained transcript bytes and metadata preserved; focused tests supplement those runtime observations.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured evidence covers native Gateway cleanup, offline cleanup and Doctor on copied SQLite state, and old/new archive writer-reader round trips, with retained transcript bytes and metadata preserved; focused tests supplement those runtime observations.

Evidence

What I checked:

  • Pinned introduction and conflict resolution: Reviewed the merge-base-to-head changes. Raw test-merge records identify main 21a5c18 followed by head e49a091 as its parents; its result contains the intended cleanup changes. The previous conflict-only blocker therefore no longer applies. (abe9e1d7e1c6)
  • Current main still exhibits the reported mechanism: Pinned main inventories dirname(storePath), which selects agent/ for an explicit canonical SQLite selector instead of sibling sessions/. Its historical cleanup also still passes forceInProcess: false for each candidate. No merged replacement is established by the supplied context. (src/config/sessions/disk-budget-files.ts:79, 21a5c1830211)
  • Local optimization preserves the transaction owner: The local runner selects the existing in-process path. Both execution modes call reclaimSqliteSessionInTransaction, retaining current protection, reference, and snapshot checks. Gateway sessions.cleanup supplies no reclamation override and retains Worker execution. (src/config/sessions/session-accessor.sqlite-reclamation.ts:410, e49a09117964)
  • Archive bytes and conflict handling: Staging preserves ordered event_json strings and newline delimiters while buffering small writes. Successful inserts use the repository SQLite adapter’s BigInt affected-row count; conflicting inserts still compare the persisted payload and metadata. No schema, decoder, or archive encoding change appears in the introduced diff. (src/config/sessions/session-accessor.sqlite-archive-store.ts:63, e49a09117964)
  • Focused regression coverage: Inspected selector-equivalence measurement and pruning tests, the native custom-directory archive test, mixed Unicode and oversized-row byte checks, and historical eviction cases covering both execution modes. Existing rollback, stale-snapshot, protected-history, and pending-publication coverage remains intact. (src/config/sessions/session-accessor.sqlite-archive.worker.test.ts:296, e49a09117964)
  • Recorded runtime and compatibility proof: The captured PR body reports native sessions.cleanup reducing physical usage from 2,732,032 to 667,648 bytes while preserving the current transcript and passing integrity checks; copied-database CLI cleanup and Doctor checks preserved retained hashes and metadata. It also reports all four old/new writer-reader combinations passing with identical archive hashes across 1,803 synthetic rows. These are supplied observations, not executions performed during this review.

Likely related people:

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

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 (2 earlier review cycles)
  • reviewed 2026-09-10T17:32:51.611Z sha d751a16 :: blocked before merge. :: none
  • reviewed 2026-09-11T15:21:07.446Z sha d751a16 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 11, 2026
@steipete
steipete force-pushed the codex/session-transcript-cleanup branch from d751a16 to e49a091 Compare September 11, 2026 15:23
@steipete
steipete merged commit d748e5d into main Sep 11, 2026
176 checks passed
@steipete
steipete deleted the codex/session-transcript-cleanup branch September 11, 2026 15:47
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 12, 2026
… consistently (openclaw#144232)

* fix(sessions): speed up local cleanup and resolve archive paths consistently

* test(sessions): verify custom archive directory ownership
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

Session cleanup repeatedly validates large databases and miscounts archive storage

1 participant