Skip to content

fix: recover renamed legacy session transcripts - #178146

Merged
steipete merged 1 commit into
mainfrom
upd/upd-l1709
Oct 20, 2026
Merged

steipete merged 1 commit into
mainfrom
upd/upd-l1709

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Fixes #177987

What Problem This Solves

Doctor leaves valid legacy conversation history out of SQLite when a transcript was renamed or copied and its header ID differs from its filename.

User Impact

Doctor imports that history under the header's session identity and records a warning. Original transcript bytes remain protected for recovery and restore. Files claiming the same identity remain separate in the protected archive; their paths are named in the conflict warning rather than combining their histories.

Why This Change Was Made

The migration reader confused a transcript's location with its identity. Keep the actual source path for reading, fingerprinting, archival, and restoration, and use the validated header for identity. Retained shared aliases and existing logical-owner checks remain unchanged. The new warning is informational both for Doctor exit status and retained plugin-source settlement.

The simplification removes the filename-equality rejection and reuses the existing discovery/import/archive owners. No schema, configuration, CLI option, or dependency changes. Production delta: +14/-9 (net +5); tests: +39/-11 (net +28); docs: +5/-1 (net +4). The small production increase records the mismatch and names conflicting originals.

Evidence

  • Isolated production Doctor command, using worktree-owned HOME and OPENCLAW_STATE_DIR: before the fix, import archived the renamed file but imported 0 sessions; after the fix, recover imported 1 session / 2 events with only transcript_filename_mismatch. Read-only SQLite inspection confirmed the header ID; the retained original was byte-for-byte unchanged. Doctor restore returned both original files with no conflicts; explicit validation verified 1 session / 2 events.
  • Red/green: with the four production files restored to base a8bc87f1c5b, both new regressions failed on importedEntries (0, expected 1). All four reviewed files were then restored byte-for-byte. Baseline run: 98.76s wall, 0.53s test time.
  • Focused discovery tests: 12/12 passed, including both renamed-file regressions and duplicate identity preservation. New cases took 14.1s and 15.0s. Total test time was 180.3s; file wall time was 807.0s (75% transform). The existing multi-stage archive recovery case took 52.5s; retained under the campaign's pre-existing slow-suite exception. All 46 additional direct/report-barrel consumer files passed: 397 tests across six test groups, in recorded argument order with one worker. Together with the focused file: 409 tests across 47 files. The consumer wrapper completed in 2994.6s; the command group accounted for 1509.7s (96% test execution).
  • Core and Doctor-test TypeScript checks passed. Direct oxlint, oxfmt, git diff --check, and Madge passed (0 import cycles).
  • The full source CLI wrapper refused runtime-artifact publication because it could not verify an offline Gateway. No host service was changed. The live proof instead called the production doctorCommand with its real maintenance lock and one-shot exit/finalization handling; this proves offline migration behavior, not package installation or CLI argument parsing.
  • The first Bun test attempt was interrupted before assertions after a 201-second cold runtime build. Node was selected through the supported test-runtime setting. The Node runtime build took 370 seconds on the loaded shared host; test time is reported separately above. The lint wrapper stalled preparing unrelated extension package artifacts; changed files passed direct oxlint instead.
  • Full check:changed / SQLite inventory was omitted under the campaign's local gate budget. Independent Codex review completed with a scoped-clean P0–P2 verdict and no actionable findings. Its initial temporary-directory preflight refusal was resolved using the OS-provided private temporary directory.
Local timing details

Existing slow cases on the loaded shared host, retained under the campaign exception:

  • src/commands/doctor-session-sqlite.discovery.test.ts — recovers a completed old archive once, preserves bytes, and does not resurrect user-deleted history: 52.50s.
  • src/gateway/session-startup-migration.test.ts — runStartupSessionMaintenanceForTest > admits the shared SQLite store before repair and preserves its history: 33.05s.
  • src/gateway/session-startup-migration.test.ts — runStartupSessionMaintenanceForTest > admits the scoped SQLite store before repair and preserves its history: 31.91s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > records held stores as advisories and completes independent repairs (unknown custom owner: false): 45.66s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > records held stores as advisories and completes independent repairs (unknown custom owner: true): 40.37s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > preserves deleted state (deleteFiles=false, registered=true, location=default): 61.36s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > preserves deleted state (deleteFiles=false, registered=false, location=default): 42.04s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > preserves deleted state (deleteFiles=false, registered=false, location=custom): 44.79s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts — Doctor with a deleted agent database > preserves deleted state (deleteFiles=true, registered=true, location=default): 35.20s.
  • src/commands/doctor-session-sqlite.deferred-plugin.test.ts — settles a retained source in the same Doctor after late plugin completion (unchanged source): 45.76s.
  • src/commands/doctor-session-sqlite.deferred-plugin.test.ts — settles a retained source in the same Doctor after late plugin completion (changed orphan): 38.52s.
  • src/commands/doctor-session-sqlite.deferred-plugin.test.ts — verifies canonical import and retains default originals until resolution without replay: 39.26s.
  • src/commands/doctor-session-sqlite.deferred-plugin.test.ts — verifies canonical import and retains configured-root originals until resolution without replay: 40.29s.
  • src/commands/doctor-config-preflight.container-upgrade.test.ts — container image replacement Doctor repair and startup readiness > preserves schema 19 at startup, then backs it up and repairs it through Doctor: 37.80s.
  • src/commands/doctor-session-sqlite.missing-retained-source.test.ts — import settles a missing retained primary only when its recorded bytes match canonical history: 46.33s.

Files exceeding 120s of summed test time (excluding transformation/import):

  • src/acp/runtime/session-meta.legacy-migration.test.ts: 129.07s.
  • src/commands/doctor-session-sqlite.deferred-plugin.test.ts: 341.38s.
  • src/commands/doctor-session-sqlite.discovery.test.ts: 180.25s.
  • src/gateway/session-startup-migration.test.ts: 188.72s.
  • src/infra/state-migrations.retained-deleted-agent.test.ts: 298.32s.
Isolated live reproduction

Paths below are normalized: PROOF_ROOT was inside this worktree's .artifacts directory. Every invocation used HOME=$PROOF_ROOT/home, OPENCLAW_STATE_DIR=$PROOF_ROOT/state, and TMPDIR=$PROOF_ROOT/tmp. No operator state or running Gateway was used.

The synthetic state/agents/main/sessions/sessions.json contained {}. renamed.jsonl contained:

{"type": "session", "version": 3, "id": "original-id", "timestamp": "2026-04-15T00:00:00.000Z", "cwd": "/synthetic"}
{"type": "message", "id": "original-message", "parentId": null, "message": {"role": "user", "content": "renamedhistoryneedle"}}

The local doctor-live.mts harness invokes the production Doctor command, maintenance lock, and exit finalization without rebuilding/publishing runtime artifacts:

import { doctorCommand } from "../../src/commands/doctor.ts";
import { runCliWithExitFinalization } from "../../src/cli/one-shot-exit.ts";
import { closeOpenClawAgentDatabasesAsync } from "../../src/state/openclaw-agent-db.ts";
import { closeOpenClawStateDatabaseAsync } from "../../src/state/openclaw-state-db.ts";

const mode = process.argv[2];
if (mode !== "import" && mode !== "recover" && mode !== "validate" && mode !== "restore") {
  throw new Error("Expected import, recover, validate, or restore");
}
await runCliWithExitFinalization({
  run: () => doctorCommand(undefined, { sessionSqlite: mode, sessionSqliteAllAgents: !process.argv[3], sessionSqliteStore: process.argv[3], json: true }),
  onError: (error) => { console.error(error); process.exitCode = 1; },
  finalize: async () => {
    await closeOpenClawAgentDatabasesAsync();
    await closeOpenClawStateDatabaseAsync();
  },
});

Commands (with the isolated environment above):

node --import ./scripts/tsx.mjs "$PROOF_ROOT/doctor-live.mts" import
# Apply the fix, keeping the archive produced above.
node --import ./scripts/tsx.mjs "$PROOF_ROOT/doctor-live.mts" recover
node --import ./scripts/tsx.mjs "$PROOF_ROOT/doctor-live.mts" restore
node --import ./scripts/tsx.mjs "$PROOF_ROOT/doctor-live.mts" validate "$PROOF_ROOT/state/agents/main/sessions/sessions.json"

Import before the fix: importedEntries=0, historical_transcript_deferred with the filename/header error. Recovery with the fix: importedEntries=1, importedTranscriptEvents=2, transcript_filename_mismatch. Restore: two original files restored, no conflicts. Validation after restore: validatedEntries=1, validatedTranscriptEvents=2. The original JSONL's SHA-256 remained 44da730a621efd488d62ba9e01d86c5dc2acc5a449aef64905fea5f34c6a2838.

Use the validated transcript header for identity while preserving the actual
source path for import, archival, and restore. Record filename mismatches as
warnings, retain conflicting originals, and keep the warning nonblocking for
retained plugin-source settlement.

Fixes #177987
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations size: S labels Oct 20, 2026
@steipete
steipete marked this pull request as ready for review October 20, 2026 06:18
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T06:25:00.614502Z 427af27 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete
steipete merged commit fd566f2 into main Oct 20, 2026
196 of 200 checks passed
@steipete
steipete deleted the upd/upd-l1709 branch October 20, 2026 06:26
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…r session id (openclaw#178146)

Fixes openclaw#177987. Migration now uses the header session id for identity, preserves the original path and bytes, and warns on filename mismatch; conflicting histories that claim the same id stay deferred and protected.
RomneyDa added a commit that referenced this pull request Oct 26, 2026
…r session id (#178146)

Fixes #177987. Migration now uses the header session id for identity, preserves the original path and bytes, and warns on filename mismatch; conflicting histories that claim the same id stay deferred and protected.

(cherry picked from commit fd566f2)

Adapted for 2026.9.x: ported only the session-sqlite-migration-readers.ts
identity fix. The transcript_filename_mismatch warning, deferred-message path
list, and docs hunks touch doctor-session-sqlite-discovery.ts/types.ts, which a
parallel 9.35 port owns, so they are not included here. Renamed files now
import under their header identity without a warning. Regression tests
were rewritten on the 9.x discovery test helpers.
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 size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Session SQLite migration fails: transcript header filename mismatch

1 participant