Repository navigation
fix(doctor): session SQLite import drops Codex assistant messages from legacy transcripts - #140296
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 7:24 AM ET / 11:24 UTC (Revision 8). ClawSweeper reviewWhat this changesDoctor postpones legacy transcript metadata writes until its SQLite scan finishes, preserving assistant messages during import and adding regression coverage. Merge readiness✅ Ready for maintainer review Keep open: this is a focused, proven fix for silent transcript loss that remains present on current main and v2026.9.3. No actionable introduced defect was found, and the related draft explicitly defers to this contributor fix. Priority: P0 Review scores
Verification
How this fits togetherDoctor imports older session files into OpenClaw’s SQLite conversation store. A temporary staging database normalizes transcript metadata and removes genuine replays before the resulting history reaches the agent’s database. flowchart LR
A[Legacy session files] --> B[Doctor import]
B --> C[Temporary transcript staging]
C --> D[Scan and identify genuine replays]
D --> E[Apply deferred metadata updates]
E --> F[Agent SQLite history]
F --> G[Conversation context]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +29, Tests +97. Total +126 across 3 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Preserve every distinct event during first import through deferred staging writes, while treating reconstruction of already-damaged active history as a separate recovery repair. Do we have a high-confidence way to reproduce the issue? Yes: the six-event legacy transcript and real CLI before/after trace identify a precise reproduction, and current main retains the responsible cursor mutation. This review verified source without executing the reproduction. Is this the best way to solve the issue? Yes: deferring writes in the existing temporary staging owner fixes the cursor hazard while preserving normalization and genuine replay deduplication. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against a1b4f6f91724. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
82fbc57 to
33837db
Compare
…m legacy transcripts The legacy transcript repair normalized Codex provider metadata by updating the staged rows table while iterating it from an open cursor. node:sqlite re-delivers an updated row, and the identical-replay guard then treated the second delivery as a duplicate and deleted the only copy, so every Codex assistant message except the last one was lost on import. Stash normalized bytes in a scratch table inside the disposable spool and apply them after the scan; the replay guard reads the stashed bytes first so real duplicates still deduplicate.
The import spool already keeps per-repair scratch sets in tree_sets, so the rows whose Codex provider metadata needs normalizing are recorded there and rewritten after the scan instead of through a new spool table. Readers that need the normalized form before the rewrite (the replay guard and the final rewrite itself) normalize the stored bytes on the way out.
33837db to
3fa839c
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
…m legacy transcripts (openclaw#140296) Fixes openclaw#140100. Preserve legacy assistant events during Doctor SQLite import by deferring provider-metadata rewrites until the staging cursor is exhausted. Keep byte-exact replay checks against normalized prior rows and reuse the existing per-repair scratch set; no persistent schema or archive policy changes. The importer and Doctor regressions cover nonterminal assistant rows. Existing exact-head CI and the contributor's Linux CLI proof show all six events preserved in order instead of four. Fresh maintainer review found no actionable issue. Recovery into an already-partial destination still does not restore its original physical order or active-history projection; that limitation remains explicit in the PR evidence. Co-authored-by: Yalçın Doksanbir <[email protected]>
Closes #140100
What Problem This Solves
Fixes an issue where users running
openclaw doctor --session-sqlite importon a legacysessions.json+ transcript JSONL store would lose every assistant message the agent had produced on the Codex runtime (message.provider: "codex"), except the last one in the file, while user messages, tool results, and assistant messages from other providers imported normally. The receipt still reported the import as complete,validateandinspectstayed green, and the archived JSONL was classified as generic unknown history, so operators migrated with half a conversation and nothing pointed at the gap.Why This Change Was Made
The legacy repair pass normalizes Codex provider metadata while streaming the staged transcript rows from a SQLite cursor, and it wrote the normalized bytes back into the same table it was iterating.
node:sqlitere-delivers an updated row from an open cursor, and the identical-replay guard then saw the second delivery as a duplicate of itself and scheduled the only copy of that row for deletion. The provider check is only the trigger; there was never an intended exclusion. The rows whose bytes need normalizing are now recorded in the spool's existing per-repair scratch set (tree_sets, the samediskSetthe repair already uses for repeated and reset rows) and rewritten after the scan completes, so the cursor never observes a rewrite. Until that rewrite the stored bytes are still legacy, so the replay guard normalizes a recorded row on the way out before comparing, and genuine duplicates of a normalized row still deduplicate. The spool is a private temp database that is discarded after every import; no persistent store or schema changes, and no new table.Data-model compatibility
No persisted table changes, and no
CREATE TABLE,ALTER TABLE, or new column anywhere: the scratch bookkeeping uses the spool's existingtree_setstable insidetranscripts.sqlite, a private temp database thatwithSqliteSessionImportStagecreates for one import in a private temp directory and removes infinally; nothing else opens it. The agent database (agents/<id>/agent/openclaw-agent.sqlite), migration-run manifest, archive layout,restore, andvalidateare untouched:git diff --stat ce174871076..3fa839c8810issession-accessor.sqlite-import-stage.ts(+32/-3) plus two test files. Verified against an existing database in the recovery run below: an agent database written by themainbuild accepts the fixed importer with no migration, and the byte-exact seen-set dedupe matched the rows the older build had written. No upgrade step; downgrade remains the existingrestoreflow.User Impact
openclaw doctor --session-sqlite importnow imports every Codex-runtime assistant message from a legacy transcript, in order, with the provider metadata normalized as before. Operators who already migrated on an affected version still have the complete transcript insession-sqlite-import-archive/;restorefollowed byvalidateon this build reports the missing rows, and a re-runimportappends them to the SQLite transcript (see the recovery run below for what that does and does not restore). Other providers and non-legacy stores are unaffected.Evidence
Root cause reproduced directly against
node:sqliteon Node v24.18.0: iteratingSELECT ... FROM rows ORDER BY seqand updating the current row'sevent_jsoninside the loop delivers each updated row twice (1:codex 1:openai 2:openai 3:codex 3:openai ...).Regression tests fail on
mainand pass on this branch. Both use a six-row transcript where the Codex assistant replies are not the last row, which is the shape the existing coverage happened not to exercise:src/config/sessions/session-accessor.sqlite-import.test.ts"keeps legacy Codex assistant rows that precede later transcript rows during repair". Onmain:src/commands/doctor-session-sqlite.test.ts"imports every legacy Codex assistant message, not only the last one" (realrunDoctorSessionSqliteimport against a legacy store on disk). Onmain:On this branch both pass and
loadTranscriptEventsSyncreturns all six ids withprovider: "openai"on the normalized replies.node scripts/check-changed.mjs: passed (exit 0). Codex autoreview (gpt-6-astra, high): no actionable findings, "patch is correct (0.98)".Follow-up (not in this PR): the pre-archive event count check at
src/commands/doctor-session-sqlite.tscompares SQLite against the post-repair spool count rather than the source JSONL line count, so a repair that drops rows can certify itself. Worth a separate fix.Revision 33837db2f08
Answers the two red lanes on
82fbc57e81d: thecheck-test-types-core-2TS18046 ('event' is of type 'unknown') by asserting the stored rows withexpect.objectContainingin one pass instead of narrowing opaqueTranscriptEventrows, andchecks-node-compact-small-2(thepublicmemory scenario seeds 100,000toolResultevents with nomessage.provider, so the new normalization path is a no-op there). CI on this head is green, includingchecks-node-compact-small-2.Real CLI proof on
33837db2f08Environment: Linux devbox, Node v24.18.0, no Gateway running, isolated
OPENCLAW_STATE_DIRandOPENCLAW_CONFIG_PATH({}) per run. Two built checkouts:mainatdbf7b06342d(before the fix) and this branch at33837db2f08(dist/.buildstampchecked before each run). The legacy store is the shape from the issue, written by hand:agents/main/sessions/sessions.jsonwith oneagent:main:mainentry pointing atsession-1.jsonl, and a six-line transcript (sessionheader,user-1,reply-1[codex],user-2,reply-2[codex],user-3; the two Codex replies are not the last row.)Rows are read back with
sqlite3 -readonly <state>/agents/main/agent/openclaw-agent.sqliteasseq | id | role | providerfromtranscript_events. Temp paths are shortened to<state>.Before the fix (
mainbuilddbf7b06342d), first import into an empty destinationBoth Codex replies are gone, the receipt reports no issue, the legacy files are archived, and
validateselects nothing afterwards. The archived JSONL still holds all six lines.After the fix (this branch, build
33837db2f08), first import into an empty destinationAll six rows import in file order; the Codex replies carry the same normalized
provider/apibytes the legacy normalizer produced before this change.session_transcript_active_eventslists five active messages (event_seq 1..5).Recovery into an already-partial SQLite destination (one state directory, both builds)
This is the situation of an operator who already migrated on an affected version. Step 1 ran the
mainbuild, steps 2-4 ran this branch's build.What this shows, and what it does not:
restorereturns the archived JSONL andsessions.jsonto their original paths (documented downgrade path, unchanged by this PR), andvalidateon the fixed build now names the gap instead of staying green.importtakes the existing-destination path (session-accessor.sqlite-import.ts,readTranscriptEventsbranch): the seen-set matched the four rows already in SQLite byte for byte and appended only the two missing Codex replies. Nothing is duplicated and nothing existing is rewritten.session_transcript_active_eventsthen lists three active messages (event_seq 1, 2, 5) instead of five, so the active-branch projection of a recovered session does not match a fresh import. Restoring original order for an already-migrated session needs a separate repair; the User Impact wording above has been narrowed accordingly.Revision 3fa839c
Rebased onto
main(ce174871076) and reworked the deferral so the fix adds no table. The previous head stashed the normalized bytes in a newnormalizedtable inside the spool; the review flagged thatCREATE TABLEas a stored-data-model change even though the spool is disposable. The repair now records the affected row numbers in the spool's existingtree_setsscratch set and rewrites those rows after the scan, normalizing a recorded row on read when the replay guard compares against it. Same fix, same regression tests, one table fewer.Re-verified on this head, Linux, Node v24.18.0:
session-accessor.sqlite-import.test.ts14 passed,doctor-session-sqlite.test.ts230 passed (2 skipped),tsgocore lane clean,oxfmtclean.Real CLI proof on
3fa839c8810Same setup as the earlier proof: isolated
OPENCLAW_STATE_DIRandOPENCLAW_CONFIG_PATH({}), the six-line legacy store from the issue (sessionheader,user-1,reply-1[codex],user-2,reply-2[codex],user-3), built checkouts withdist/.buildstampchecked before each run:mainatdbf7b06342d(before the fix) and this branch at3fa839c8810. Rows read back withsqlite3 -readonlyasseq | id | role | provider.Before the fix (
mainbuilddbf7b06342d), first import into an empty destinationSame loss as before: both Codex replies are gone and the receipt reports no issue.
After the fix (this branch, build
3fa839c8810), first import into an empty destinationAll six rows import in file order with the normalized
provider/apibytes, exactly as on the previous head.Recovery into an already-partial SQLite destination (one state directory, both builds)
Identical to the recovery run on the previous head: an agent database written by the
mainbuild accepts the reworked importer with no migration, the seen-set matches the four existing rows byte for byte, only the two missing replies are appended, and the recovery-order limitation described above is unchanged.