Repository navigation
fix: PostgreSQL sessions fail to load model context when a transcript has an unpaired surrogate escape - #194591
Conversation
PostgreSQL rejects JSON-escaped unmatched surrogates (\ud800) and NUL when casting transcript event_json to jsonb (SQLSTATE 22P02), so model-context reads failed for rows SQLite reads fine. Route those rows through the same JavaScript projection owner SQLite uses for deep JSON instead of the native jsonb projection; stored rows stay byte-identical. Fixes openclaw#194517
|
🦞👀 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 Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 690febf138
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Codex review: needs maintainer review before merge. What this changesThis PR keeps PostgreSQL sessions readable when transcript JSON contains lone surrogate escapes or NUL, while preserving canonical transcript bytes. Example: A PostgreSQL session stores a tool result containing the escaped lone surrogate \ud83d, then receives another user turn.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a concrete PostgreSQL session failure that remains on current main; no actionable introduced defect was found, and the earlier cache finding is resolved. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherSession storage supplies transcript navigation, model context, chat history, and search; native SQL handles decodable rows, while existing JavaScript projectors handle exceptional JSON. flowchart TD
A[Transcript append] --> B[Canonical JSON storage]
A --> C[Derived search text]
B --> D[Native JSON validity guard]
D --> E[Native SQL projection]
D --> F[JavaScript projection]
E --> G[Model context and history]
F --> G
Technical reviewBest possible solution: Land the existing guarded-reader repair after the required checks pass, preserving canonical bytes and the shared projection owners. Do we have a high-confidence way to reproduce the issue? The pinned main source exposes the rejecting JSONB casts, and the report plus collaborator Gateway proof record the corresponding PostgreSQL failures; this read-only review ran no target code. Is this the best way to solve the issue? The repair addresses the native-decoding boundary using existing guards and JavaScript projectors, retains cached classification, and normalizes NUL only in derived search text. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9a26486062c8. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +123, Tests -4. Total +119 across 22 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed November 9, 2026, 3:14 AM ET / 08:14 UTC (Revision 5). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
PostgreSQL jsonb rejects escaped NUL and unpaired surrogate escapes that stored transcript JSON text may hold. Route every native read of stored transcript and session JSON through jsonNativeFieldsValid and decode the rows it rejects in JavaScript: model-context navigation (detached validation, reset kept tail, dependency fallback), run-input visibility, mirror run lookup, retained custom-data suffix reads and staging, and session-entry maintenance. Full-text index text replaces NUL with a space so a NUL-bearing message no longer aborts its append; stored rows keep their original bytes. Builds on ylcn91's model-context reader fix. Drops the test-line allocation and folds duplicated session test setup into shared helpers.
|
Proof on
Regression |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…unchanged The PostgreSQL-only dependency guard leaves SQLite's covered-fact plan as it was, parent repair of retained data goes back to its single native statement, and the mirror source marker compares without a conversion.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…e path Rows the native JSON guard rejects keep their custom data instead of being stripped in JavaScript, so suffix cleanup copies them byte for byte like SQLite's over-depth rows instead of reaching native parent repair.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
… has an unpaired surrogate escape (#194591) fix(sessions): read and index Postgres transcripts that contain escapes jsonb rejects Fixes #194517. On PostgreSQL, session transcript JSON that contains an escaped lone surrogate (for example \ud83d) or an escaped NUL cannot be cast to jsonb. Every follow-up turn in such a session failed with 22P02, and a user message containing NUL could not be stored at all, because the full-text index insert failed with 22021 and the message was dropped. SQLite accepts the same text. Every transcript and session-context read now routes stored JSON through the existing jsonNativeFieldsValid guard: rows Postgres can't cast are decoded in JavaScript instead. NUL is replaced by a space only in the derived full-text search text. There is no schema change, no migration, and no rewrite or stripping of stored rows. Covered: the model-context reader and its navigation cache, tree and reset-boundary navigation, detached-context validation, the reset kept-tail window, the active-context fallback, chat.history run-input visibility, the transcript mirror run lookup, retained custom-data reads, session-entry maintenance, and the full-text index on both engines. Evidence: built Gateway on node 24.22.1 in Docker with postgres:17 and a local fixture model provider, two runs per build, SQLite once each. On main, a follow-up turn after a tool result with a lone \ud83d or a user message with a lone \udc00 failed with 22P02; a user message with NUL was dropped (22021); an idle reset keeping a tail with \udc00 failed. With this change all of these complete, chat.history returns the messages with the characters kept, search finds the NUL message, existing rows are byte-identical, and the schema dumps are identical. Ordinary sessions and SQLite behave the same. Details: openclaw/openclaw#194591 (comment). Follow-ups not in this change: Doctor's session-entry rewrite, the SQLite-to-PostgreSQL port of stored NUL full-text rows, and an older IN () bug in readTranscriptMirrorFacts. Thanks @ylcn91 for the original fix and @reisball for the report. Co-authored-by: Ayaan Zaidi <[email protected]>
… has an unpaired surrogate escape (#194591) fix(sessions): read and index Postgres transcripts that contain escapes jsonb rejects Fixes #194517. On PostgreSQL, session transcript JSON that contains an escaped lone surrogate (for example \ud83d) or an escaped NUL cannot be cast to jsonb. Every follow-up turn in such a session failed with 22P02, and a user message containing NUL could not be stored at all, because the full-text index insert failed with 22021 and the message was dropped. SQLite accepts the same text. Every transcript and session-context read now routes stored JSON through the existing jsonNativeFieldsValid guard: rows Postgres can't cast are decoded in JavaScript instead. NUL is replaced by a space only in the derived full-text search text. There is no schema change, no migration, and no rewrite or stripping of stored rows. Covered: the model-context reader and its navigation cache, tree and reset-boundary navigation, detached-context validation, the reset kept-tail window, the active-context fallback, chat.history run-input visibility, the transcript mirror run lookup, retained custom-data reads, session-entry maintenance, and the full-text index on both engines. Evidence: built Gateway on node 24.22.1 in Docker with postgres:17 and a local fixture model provider, two runs per build, SQLite once each. On main, a follow-up turn after a tool result with a lone \ud83d or a user message with a lone \udc00 failed with 22P02; a user message with NUL was dropped (22021); an idle reset keeping a tail with \udc00 failed. With this change all of these complete, chat.history returns the messages with the characters kept, search finds the NUL message, existing rows are byte-identical, and the schema dumps are identical. Ordinary sessions and SQLite behave the same. Details: openclaw/openclaw#194591 (comment). Follow-ups not in this change: Doctor's session-entry rewrite, the SQLite-to-PostgreSQL port of stored NUL full-text rows, and an older IN () bug in readTranscriptMirrorFacts. Thanks @ylcn91 for the original fix and @reisball for the report. Co-authored-by: Ayaan Zaidi <[email protected]>
… has an unpaired surrogate escape (openclaw#194591) fix(sessions): read and index Postgres transcripts that contain escapes jsonb rejects Fixes openclaw#194517. On PostgreSQL, session transcript JSON that contains an escaped lone surrogate (for example \ud83d) or an escaped NUL cannot be cast to jsonb. Every follow-up turn in such a session failed with 22P02, and a user message containing NUL could not be stored at all, because the full-text index insert failed with 22021 and the message was dropped. SQLite accepts the same text. Every transcript and session-context read now routes stored JSON through the existing jsonNativeFieldsValid guard: rows Postgres can't cast are decoded in JavaScript instead. NUL is replaced by a space only in the derived full-text search text. There is no schema change, no migration, and no rewrite or stripping of stored rows. Covered: the model-context reader and its navigation cache, tree and reset-boundary navigation, detached-context validation, the reset kept-tail window, the active-context fallback, chat.history run-input visibility, the transcript mirror run lookup, retained custom-data reads, session-entry maintenance, and the full-text index on both engines. Evidence: built Gateway on node 24.22.1 in Docker with postgres:17 and a local fixture model provider, two runs per build, SQLite once each. On main, a follow-up turn after a tool result with a lone \ud83d or a user message with a lone \udc00 failed with 22P02; a user message with NUL was dropped (22021); an idle reset keeping a tail with \udc00 failed. With this change all of these complete, chat.history returns the messages with the characters kept, search finds the NUL message, existing rows are byte-identical, and the schema dumps are identical. Ordinary sessions and SQLite behave the same. Details: openclaw#194591 (comment). Follow-ups not in this change: Doctor's session-entry rewrite, the SQLite-to-PostgreSQL port of stored NUL full-text rows, and an older IN () bug in readTranscriptMirrorFacts. Thanks @ylcn91 for the original fix and @reisball for the report. Co-authored-by: Ayaan Zaidi <[email protected]>
Release adaptation: Keep the release SQLite planner helper private and omit agent-port-projections.ts, which does not exist on this release line. Preserve all baseline assertions by materializing four small test fixtures, and exercise lazy payload reads through the actual SQLite planner rather than a fake source. Allocate the exact 64 net test lines. No schema, config, or authority changes. Later same-path followups through 568d89f: 8633af9 (#194591) is the non-applicable PostgreSQL surrogate repair; b6ed907 (#193682) is the non-applicable schema41 hydration migration. Neither is a streaming prerequisite. Existing #195028 and #196277 repair contracts remain intact. Verified: baseline lazy-read regression fails; 32 focused tests pass across five suites, including compiled-worker publication and authority boundaries. Targeted types, lint, format, and whitespace checks pass. Fresh independent read-only review found no P0-P2 issues. (cherry picked from commit 7bc0ae7) Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Adapt c7bd622 (#186481) to the 2026.11.4 maintenance reader rather than importing paged/cold storage. Preserve canonical deep JSON, reuse the memory model-entry projector, and fence exceptional native decoding in existing navigation/read owners. Reclassify only false-invalid derived predicate fields at admission. Coupled reference: 8633af9 (#194591). Native PostgreSQL conformance is an adapter check; candidate agent/session storage is SQLite and this change does not enable PostgreSQL sessions. Original-author date: 2026-10-28T19:55:20+11:00. Primary ledger: hf-audit-c7bd622b950257867ee2a9588e6fbf02fef8a27f (high). Local preparation checkpoint only; final independent review remains required. Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Doksanbir <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Adapt the derived-search portion and native conformance evidence from 8633af9 (#194591), retaining canonical NUL and lone-surrogate escapes and the shared exceptional-row projector. The preceding coupled checkpoint owns the native decoding guard. Original-author date: 2026-11-09T11:37:39+03:00. Primary ledger: hf-main-8633af9341852740eb176d22840a46c521064a1b (high). The original PostgreSQL session incident is not production-reachable in this candidate (agent/session owner remains SQLite). No independent release-severity recommendation is made for this checkpoint. Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Closes #194517
What Problem This Solves
On PostgreSQL, a session whose transcript holds a JSON-escaped lone surrogate (for example a tool result or a user message with
\ud83dor\udc00alone) or an escaped NUL broke: the next turn failed withinvalid input syntax for type json(22P02), and a user message containing NUL could not be stored at all (22021, the whole append rolled back). SQLite handles the same transcripts.Why This Change Was Made
PostgreSQL stores each transcript event as its original JSON text.
jsonbrejects escaped NUL and unpaired surrogate escapes, whilejson, SQLite and JavaScript accept them. Several readers cast stored event text tojsonb, some behindjsonValid(), which checksjsonvalidity and so lets these rows through. Separately, the transcript full-text index wrote the message text into a PostgreSQLtextcolumn, which cannot hold 0x00.User Impact
PostgreSQL-backed sessions holding these characters keep working: turns complete, chat history shows the original text, search finds the message, and stored rows are not rewritten.
The fix
One guard owns "read stored transcript JSON natively on PostgreSQL": the existing
jsonNativeFieldsValid()(pg_input_is_valid(x, 'jsonb'), from #183560). Rows it rejects reach JavaScript unchanged and are decoded there.projectModelContextJson), keeps that classification across cached navigation pages, and moves tree and reset-boundary navigation onto the guard.projectModelContextNavigationSql(detached context validation, reset kept-tail window, dependency fallback): guarded, and the cast is fenced so bound writer inputs cannot be constant-folded past the guard.No schema change, no migration, no rewrite of stored rows, nothing stripped from the stored transcript.
Follow-ups, not in this PR: the Doctor session-entry rewrite still casts entries to
jsonb;readTranscriptMirrorFactswith an empty key list and asourceRunIdemitsIN ()on PostgreSQL (unrelated, pre-existing).Evidence
Built Gateway (node 24.22.1, Docker, PostgreSQL 17.11 official image, local fixture model provider), main twice, candidate twice, SQLite once each. Proof comment: #194591 (comment)
\ud83d, follow-up turn\udc00, follow-up turn\udc00firstKeptEntryId, follow-ups completeRegression:
session-transcript-portability.conformance.test.ts"reads, validates and indexes escapes JSONB rejects without rewriting rows" covers the model-context reads (full, bounded twice, async), detached validation, the active-context fallback, the retained-data suffix read, the mirror lookup, run-input visibility and full-text search on both engines. Main: SQLite passes, PostgreSQL fails (22021). This PR: both pass.Thanks to @ylcn91 for the fix and the cache-classification follow-up, and @reisball for the report and reproduction.