Skip to content

fix(sessions): manual compaction deletes transcript history while claiming it was archived - #111122

Merged
jalehman merged 2 commits into
openclaw:mainfrom
yetval:fix/sessions-compact-transcript-backup
Jul 22, 2026
Merged

jalehman merged 2 commits into
openclaw:mainfrom
yetval:fix/sessions-compact-transcript-backup

Conversation

@yetval

@yetval yetval commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Related: #98236

What Problem This Solves

Fixes an issue where users running openclaw sessions compact <key> --max-lines N would permanently lose the trimmed part of their conversation history while the CLI told them it had been archived. Since the SQLite storage flip (#98236, commit 0a8e360), the manual compaction path deletes the trimmed transcript rows without writing any backup, then returns an archived value that is a fabricated marker string (sqlite:<agent>:<session>:<store>.bak.<timestamp>) pointing at nothing. The CLI prints Archived transcript: <marker>, so users believe the full history is recoverable when it is gone. Before the flip, manual compaction renamed the live JSONL transcript to a real .bak.<timestamp> file before writing the trimmed replacement, so the full pre-compaction history was always recoverable.

Why This Change Was Made

The fix restores the pre-flip safety contract at the SQLite transcript writer boundary: before any rows are deleted, the complete pre-compaction transcript is exported to a real, durable archive file, and archived now returns that file's actual path. The archive reuses the existing session archive writer that the reset/delete lifecycle flows already use (exclusive create, 0o600, fsync file and directory, atomic rename, optional zstd), with the artifact named <sessionId>.jsonl.bak.<timestamp>[.zst] in the same per-agent sessions archive directory. The .bak shape is already recognized by the archive artifact classifiers, so cleanup and disk-budget treat it exactly like reset/delete archives. The backup is written outside any SQLite transaction; the destructive replacement then revalidates the row snapshot inside the write transaction and aborts while retaining the durable backup if the transcript changed after the snapshot, so concurrently appended rows can never be deleted. If backup creation fails, compaction aborts with an error and every original row stays in place. Active-run and lifecycle fencing in the sessions.compact RPC is unchanged.

User Impact

openclaw sessions compact <key> --max-lines N is safe again: the printed Archived transcript: path is a real file containing every pre-compaction transcript event in order, recoverable with the same tooling that reads reset/delete archives. If the backup cannot be written, compaction fails without deleting anything instead of silently destroying history.

Evidence

Live before/after against a real gateway and the real CLI, identical inputs. For each phase: fresh isolated OPENCLAW_STATE_DIR, a session seeded with 7 transcript events (session header plus messages important message 1..6) through the production accessor, gateway started from the built dist (node openclaw.mjs gateway --port <port>), then node openclaw.mjs sessions compact main --max-lines 3 --url ws://127.0.0.1:<port> --token .... Nothing was mocked.

Before, on pristine main 62c5a8b:

$ openclaw sessions compact main --max-lines 3
Compacted session agent:main:main (kept 3 lines).
Archived transcript: sqlite:main:aaaaaaaa-...:<state>/agents/main/sessions/sessions.json.bak.2026-07-19T01-52-43.722Z

authoritative transcript rows now: 3
sessions dir unreadable: ENOENT
backup artifacts in agents/main/sessions: []
claimed archive path exists: false

Four transcript events were deleted, the printed "archive" is a marker string, the archive directory was never created, and no backup exists anywhere. The trimmed history is unrecoverable.

After, this patch:

$ openclaw sessions compact main --max-lines 3
Compacted session agent:main:main (kept 3 lines).
Archived transcript: <state>/agents/main/sessions/aaaaaaaa-...jsonl.bak.2026-07-19T02-00-59.389Z.zst

authoritative transcript rows now: 3
backup artifacts in agents/main/sessions: ["aaaaaaaa-...jsonl.bak.2026-07-19T02-00-59.389Z.zst"]
backup aaaaaaaa-...jsonl.bak.2026-07-19T02-00-59.389Z.zst: 7 events, first=session, contents include: 6 messages
claimed archive path exists: true

The printed path is a real file (mode 0600), and decompressing it yields all 7 pre-compaction events in order, including the 4 trimmed ones, parsed back through the shared archive reader.

Validation on the changed surface (all green locally):

  • node scripts/run-vitest.mjs src/config/sessions/session-accessor.test.ts src/commands/sessions-compact.test.ts (72 + 10 passed)
  • node scripts/run-vitest.mjs src/gateway/server.sessions.compaction.test.ts (21 passed)
  • node scripts/run-vitest.mjs src/config/sessions/session-accessor.conformance.test.ts src/config/sessions/transcript.test.ts src/config/sessions/artifacts.test.ts (123 passed)
  • node scripts/run-tsgo.mjs -p tsconfig.core.json and -p test/tsconfig/tsconfig.core.test.json clean
  • node scripts/run-oxlint.mjs and oxfmt --check clean on all changed files; git diff --check clean

Control red: with only the four production files reverted to main, the updated trim test plus the two new tests fail in session-accessor.test.ts (3 failed) and the updated gateway archive test fails in server.sessions.compaction.test.ts (1 failed); with the patch they all pass.

New regression coverage:

  • accessor: trim writes a .bak artifact holding every original event, parseable via the archive reader; backup-write failure (archive directory path occupied by a file) leaves all rows untouched and errors; a row appended after the backup snapshot aborts the replacement with a conflict error, deletes nothing, and preserves the durable backup.
  • gateway RPC: sessions.compact with maxLines returns an archived path that exists on disk and contains all 500 seeded pre-compaction events.
  • CLI: the printed Archived transcript: line is exactly the RPC's archived path.

Not tested live: Bun runtime (plain JSONL archive fallback path, exercised by the shared writer used unchanged by reset/delete flows) and Windows.

Siblings: session reset and delete flows already archive through the same writer and are unchanged. sessions.compact without --max-lines (LLM summarization) rewrites via compaction checkpoints, not row deletion, and is unaffected.

@yetval
yetval marked this pull request as ready for review July 19, 2026 02:03
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime commands Command implementations size: M labels Jul 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 19, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 10:15 PM ET / July 19, 2026, 02:15 UTC.

Summary
The PR archives the complete SQLite transcript before sessions compact --max-lines deletes rows, then returns the actual archive path through the gateway and CLI.

PR surface: Source +31, Tests +120. Total +151 across 7 files.

Reproducibility: no. independent current-main run was possible in this review because the read-only command backend failed before repository inspection. The PR nevertheless provides a concrete reproduction using a real gateway, CLI, isolated state directory, and authoritative transcript-row checks.

Review metrics: none identified.

Stored data model
Persistent data-model change detected: serialized state: src/commands/sessions-compact.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-archive.ts, serialized state: src/config/sessions/session-accessor.sqlite-transcript-write.ts, serialized state: src/config/sessions/session-accessor.test.ts, serialized state: src/config/sessions/session-accessor.transcript.ts, serialized state: src/gateway/server.sessions.compaction.test.ts, and 3 more. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🐚 platinum hermit
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Complete a direct source review of the shared archive writer, artifact cleanup, and SQLite revalidation path before merge.

Risk before merge

  • [P1] The patch changes a destructive session-state path and replaces an externally returned synthetic archive marker with a real on-disk artifact; a direct source review should confirm archive cleanup, retention, and concurrent-write semantics across the shared lifecycle writer before merge.
  • [P1] The PR body reports Node live proof and focused tests, but does not show equivalent live Bun or Windows behavior; the shared archive writer may cover them, but that contract was not independently verified here.

Maintainer options:

  1. Verify shared archive lifecycle integration (recommended)
    Before merge, confirm the new bak archive reason is retained, discoverable, and cleaned up under the same contract as reset/delete archives.
  2. Accept the corrected archive contract
    Merge with the intentional change from a nonexistent SQLite marker to a real recoverable archive path if maintainers confirm no supported caller relies on the fabricated marker.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Review the shared archive writer, artifact classification, cleanup, and concurrent transcript-write revalidation paths; preserve the focused regression tests.

Next step before merge

  • [P2] No discrete patch defect was established, but a human or fresh automated pass must inspect the shared archive and SQLite write paths before merge because this review environment could not read the checkout.

Security
Cleared: The proposed diff is confined to session archive, transcript replacement, CLI output assertions, and tests; it adds no dependency, workflow, permission, secret, or supply-chain surface.

Review details

Best possible solution:

Keep the archive-before-delete repair focused at the SQLite transcript writer boundary, then complete direct review of the shared archive lifecycle and transactional revalidation before merging.

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

No independent current-main run was possible in this review because the read-only command backend failed before repository inspection. The PR nevertheless provides a concrete reproduction using a real gateway, CLI, isolated state directory, and authoritative transcript-row checks.

Is this the best way to solve the issue?

Unclear pending direct source review. Reusing the existing durable archive writer and revalidating the snapshot inside the destructive transaction appears to be the narrowest maintainable fix, provided its archive lifecycle contract matches reset/delete behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ead8f691eacf.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes a redacted real gateway-and-CLI before/after transcript showing the prior nonexistent marker and the patched existing, parseable archive artifact.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes a redacted real gateway-and-CLI before/after transcript showing the prior nonexistent marker and the patched existing, parseable archive artifact.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Manual compaction can permanently remove user conversation history while reporting that it was archived.
  • merge-risk: 🚨 compatibility: The externally reported archived value changes from a synthetic SQLite marker to a filesystem archive path.
  • merge-risk: 🚨 session-state: The patch modifies the backup, validation, and deletion sequence for persisted transcript rows.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes a redacted real gateway-and-CLI before/after transcript showing the prior nonexistent marker and the patched existing, parseable archive artifact.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes a redacted real gateway-and-CLI before/after transcript showing the prior nonexistent marker and the patched existing, parseable archive artifact.
Evidence reviewed

PR surface:

Source +31, Tests +120. Total +151 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 4 68 37 +31
Tests 3 123 3 +120
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 191 40 +151

What I checked:

  • Reported regression and after-fix behavior: The PR body supplies a concrete real-gateway and real-CLI before/after run: current behavior reduces authoritative rows while returning a nonexistent sqlite: marker, whereas the patch returns an existing .jsonl.bak... archive that parses to all pre-compaction events. (src/config/sessions/session-accessor.transcript.ts:233, cb5018a551db)
  • Focused regression coverage: The proposed branch adds accessor, gateway RPC, and CLI assertions for an existing archive path, complete archived content, archive-write failure without deletion, and concurrent-append conflict handling. (src/config/sessions/session-accessor.test.ts:2249, cb5018a551db)
  • Likely regression provenance: The related SQLite storage flip was merged as commit 0a8e3604ba24de4791d3505b7a442e8017276dd0; its stated architecture made SQLite authoritative while preserving archive-before-delete lifecycle behavior, matching the boundary this PR repairs. (src/config/sessions/session-accessor.sqlite-transcript-write.ts:143, 0a8e3604ba24)
  • Review-environment limitation: The first read-only repository command failed in the sandbox before opening files, so current-main source, scoped guides, maintainer notes, and git history could not be independently inspected in this review cycle.

Likely related people:

  • jalehman: Authored the merged SQLite sessions/transcripts storage flip that introduced the affected runtime boundary and archive lifecycle expectations. (role: storage-flip author and likely adjacent owner; confidence: medium; commits: 0a8e3604ba24; files: src/config/sessions/session-accessor.sqlite-transcript-write.ts, src/config/sessions/session-accessor.transcript.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-19T02:06:10.896Z sha e0b5415d1a7905ca84ad722f686417c1f378acca :: needs real behavior proof before merge. :: none

@yetval
yetval force-pushed the fix/sessions-compact-transcript-backup branch from e0b5415 to cb5018a Compare July 19, 2026 02:11
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 19, 2026
@jalehman jalehman self-assigned this Jul 21, 2026
@jalehman
jalehman force-pushed the fix/sessions-compact-transcript-backup branch 2 times, most recently from 1701687 to d0f53eb Compare July 21, 2026 23:46
yetval and others added 2 commits July 21, 2026 16:48
…eletes rows

openclaw sessions compact <key> --max-lines N deleted the trimmed SQLite
transcript rows without writing any backup, then returned an archived value
that was a fabricated marker string pointing at nothing, so the CLI told
users their history was archived when it was permanently gone. Regression
from the SQLite storage flip (openclaw#98236): the previous flat-file path renamed
the live transcript to a real .bak.<timestamp> file before replacing it.

The manual compact trim now exports the complete pre-compaction transcript
through the shared durable session archive writer (exclusive create, 0o600,
fsync, atomic rename, optional zstd) as
<sessionId>.jsonl.bak.<timestamp>[.zst] in the per-agent sessions archive
directory before any rows are deleted, and archived returns that real path.
The backup is written outside the SQLite transaction; the destructive
replacement revalidates the row snapshot inside the write transaction and
aborts, removing the fresh backup, if the transcript changed after the
snapshot. Backup failure aborts compaction with every original row intact.
@jalehman
jalehman force-pushed the fix/sessions-compact-transcript-backup branch from d0f53eb to 537c39e Compare July 21, 2026 23:48
@yetval

yetval commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-run

@clawsweeper

clawsweeper Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(sessions): manual compaction deletes transcript history while claiming it was archived This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@jalehman

Copy link
Copy Markdown
Contributor

Maintainer landing note: the exact-head ClawSweeper artifact for 537c39ead1f07a0f1ddd568526726c1d3d227360 reports zero findings. Its rank-up move asks for archive, conflict, and archive-lifecycle validation on the clean merge result.

I am not rebasing again solely for behind-main drift: this exact head has 83 successful checks with zero failures or pending jobs, including the session accessor/transcript/SQLite proof lanes and the full Node matrix; OPENCLAW_TESTBOX=1 scripts/pr prepare-run 111122 passed its hosted exact-or-recent-parent gate; GitHub reports the PR mergeable; and the current-main changes since 73d2b27a11c have no overlap with any of the seven PR paths. This satisfies the requested proof without another patch-identical force-push/review cycle.

@jalehman
jalehman merged commit db16117 into openclaw:main Jul 22, 2026
117 checks passed
@jalehman

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 22, 2026
…iming it was archived (openclaw#111122)

* fix(sessions): archive the full transcript before manual compaction deletes rows

openclaw sessions compact <key> --max-lines N deleted the trimmed SQLite
transcript rows without writing any backup, then returned an archived value
that was a fabricated marker string pointing at nothing, so the CLI told
users their history was archived when it was permanently gone. Regression
from the SQLite storage flip (openclaw#98236): the previous flat-file path renamed
the live transcript to a real .bak.<timestamp> file before replacing it.

The manual compact trim now exports the complete pre-compaction transcript
through the shared durable session archive writer (exclusive create, 0o600,
fsync, atomic rename, optional zstd) as
<sessionId>.jsonl.bak.<timestamp>[.zst] in the per-agent sessions archive
directory before any rows are deleted, and archived returns that real path.
The backup is written outside the SQLite transaction; the destructive
replacement revalidates the row snapshot inside the write transaction and
aborts, removing the fresh backup, if the transcript changed after the
snapshot. Backup failure aborts compaction with every original row intact.

* fix: preserve reused compaction archives on conflict

---------

Co-authored-by: Josh Lehman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

2 participants