Repository navigation
perf(history): reuse prepared display and session facts - #133316
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 10:41 AM ET / 14:41 UTC. ClawSweeper reviewWhat this changesThis PR reuses per-operation transcript, profile-display, CLI-import, and decoded-session facts to reduce repeated history-read work without changing stored formats or public configuration. Merge readinessNo blocking defect was identified in this maintainer-authored performance refactor. It should remain open while the one remaining exact-head CI shard completes. Priority: P3 Review scores
Verification
How this fits togetherGateway history reads project stored transcript events into chat-history and live session-message responses, while companion context reads a bounded transcript tail for an agent run. The refactor keeps display and session facts local to each read operation before those responses reach clients or context preparation. flowchart LR
A[Stored transcript events] --> B[Gateway history reader]
C[Session entry rows] --> B
D[CLI transcript imports] --> B
B --> E[Prepared display and session facts]
E --> F[Chat history responses]
E --> G[Companion context]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +50, Tests +77. Total +127 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the per-operation fact ownership and bounded-tail projection, then land after exact-head CI confirms the refactor on the current merge result. Do we have a high-confidence way to reproduce the issue? Not applicable: this PR refactors existing history-read behavior rather than addressing a separately reported failure; focused regression coverage exercises its changed paths. Is this the best way to solve the issue? Yes: keeping cached display facts within each response and retaining fresh-versus-borrowed session ownership at the storage boundary is the narrowest maintainable approach found. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against aea8ee845ccf. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Merged via squash.
|
CLI backends persist each assistant turn twice: once as the synthetic `api: "cli"` aggregate whose text is the turn's text blocks joined, and again as the native blocks the Claude CLI transcript import brings back. Those are two shapes of the same turn, so per-message equality can never pair them and the turn renders twice (openclaw#123792). The merge owner now groups imported assistant messages into turns and pairs each turn with the persisted aggregate that duplicates it. Within one text and producer the two sides are matched in timestamp order: the aggregate is written once the turn completes, so the earliest turn that finished no more than the dedupe window before an aggregate owns it. Pairing is one-to-one, so two genuinely repeated replies with identical text are only both suppressed when the import actually holds both turns. An unmatched aggregate is retained, which keeps the durable fallback for an incomplete or trimmed import. `api: "cli"` alone is not unique to the aggregate — ordinary CLI assistant replies are persisted the same way. The producer stamps `idempotencyKey: "cli-assistant:<runId>"` and the transcript append spreads it onto the stored message, so that key is the discriminator; every other `api: "cli"` record is retained. Blocks of a turn that replaced an aggregate are flagged, because such a block is then the only surviving copy of its text and weak role/text dedupe must not discard it as well. A one-for-one replacement leaves the message count unchanged, so the resolver reports an import by identity rather than by length. Grouping needs every imported row prepared before the merge loop, which only pays for itself when a local aggregate could actually be covered. A session without one keeps the lazy, skip-on-identity path from openclaw#133316 untouched. `prepareComparableMessage` derives the turn facts from the single read it already makes of each field, so the added pass reads no raw property twice, and `resolveImportedExternalIdentityKey` reaches the same metadata through `asOptionalRecord` instead of four unchecked type assertions. Co-authored-by: Ayaan Zaidi <[email protected]> Co-Authored-By: Claude Opus 5 <[email protected]>
History preparation repeatedly rediscovered the same visibility, profile, position, import, and session facts. Companion context also normalized and redacted rows that its existing tail limit would discard. This refactor carries prepared facts through the owning operation and removes copies only where the producer already returns fresh objects.
The eight measured changes share the history-read boundary:
No schema, migration, protocol, config/default, public API, dependency, persistent cache, or authorization change. Production is +238/−189 = +49 lines; tests are +146/−68 = +78. The added production structure owns bounded per-operation facts and explicit projection types. Removed paths include redundant full-row preparation, repeated search/copy work, and duplicate companion error classification. The final companion reversal allocates at most 40 references. Release workflow owns the changelog.
Correctness includes the complete owners, callers, sibling display/live paths, canonical SQLite stores, existing tests, and client transcript contracts. The final integrated proof uses 35 complete owners per variant, all 17 changed production owners, 336 strict source bindings, and 70 copied files. It passes 1,378 display/CLI/UI comparisons, 628 session scenarios with 3,127 comparisons and 152 isolation checks, and 37 actual-SQLite companion scenarios with 156 comparisons, including complete first-ask results and prompts. Subcounts overlap and are not added into a larger claim. Synthetic external CLI artifacts use the real loader/parser; mocked provider acquisition is explicitly separate from live proof.
Canonical verification: all 1,150 tests across 35 files passed on the final base, including upstream first-insert/writer-fence and internal-session cleanup coverage. The profile regression failed before the change at three reads instead of one; the companion regression failed at 128 redactions instead of 40. Both passed after the owner changes. Independent source review and the refreshed managed P0–P3 review are clean. The full changed gate and build pass.
The broader run initially exposed an incomplete wholesale test mock: it omitted the newly canonical projector export and caused a 23-test cascade. The fixture now retains real facade exports and its original scalar override; no product guard or assertion was weakened. Lint also caught an in-place reversal and a profile test file over the line limit. The reversal uses
toReversed(), and two equivalent ETag tests are parameterized, preserving byte/MIME cases and testing both within one millisecond. All failed attempts remain in local evidence.After main advanced, the branch was rebased once and the full proof was refreshed. The new first-insert lease owner, write-result copies, synchronous post-commit bookkeeping, idempotency ownership, and transcript-write fences are preserved. The final benchmark compares main
48b0857ewith candidate37f216f9; earlier receipts remain attached to their original source bytes.CI then found a typed raw SQL expression outside the allowed Kysely boundary. The shared avatar-presence selection now uses the typed
avatar IS NOT NULLexpression. Kysely and SQLite source, the existing NULL/empty-BLOB cases and all three consumers confirm identical 0/1 semantics. No guard exception or cast was added. The Kysely guard, all 1,150 canonical tests (68.03 seconds), the full changed gate (271.34 seconds) and a fresh managed P0–P3 review pass. The corrected build passes in 151.19 seconds. All final proof, timings and live checks below use the corrected source. This refines an existing mechanism, not another performance count.Four quiet fresh processes cover 193 workload shapes in opposite owner/workload orders, with three warmups and five alternating measured samples retained. Complete output equality is checked before timing. Independent reduction and a separate parent recalculation agree on all 772 medians. Representative complete paths are below; values are milliseconds per invocation.
These measure complete local owners with real SQLite, not Gateway RPC, browser paint, cold startup, or provider latency. First-ask timing substitutes only the existing model-selection/run seams. Large avatar/text fixtures are scaling controls. No ablation gains are multiplied and no per-variant memory claim is made. The unweighted matrix has 122 rows faster in both orders, 18 slower, and 53 mixed; that is not a production traffic average or a statistical-significance claim.
Costs remain visible: the no-avatar 30-row fresh-profile history/UI path is +2.3%/+3.4%; the 30-row image merge alone is +2.3%/+1.0%, while its full display/UI composition improves 29–41%; empty companion first-ask is +4.8%/+1.6%. The retained 128 KiB full-store control is +10.8%/+10.8% (32/30 µs). The large default-list-copy control is mixed, −8.1%/+57.5% (−14/+56 µs), and ordinary 30-row UI composition is −0.5%/+9.0%. Required borrowed/cached copies remain. No cost is attributed to GC, JIT, the SQL correction or another cause without evidence.
Every row slower in both orders is retained here; positive percentages mean slower. Both signs for all other rows remain in local raw evidence.
profile-null-false-1/full-row-controlprofile-null-false-30/fresh-profile-readonly/sqlite-history-uiprofile-null-true-1/warm-handle/deltaprofile-32768-false-1/full-row-controlprofile-524288-false-1/fresh-profile-readonly/deltaprofile-524288-false-30/warm-handle/sqlite-history-uiprofile-524288-true-30/fresh-profile-readonly/sqlite-history-uiplain-0/warm-handle/deltaplain-1/fresh-profile-readonly/deltaplain-30/fresh-profile-readonly/deltaCLI-image-forward-1/mergeCLI-image-forward-30/mergefull-store-control-131072companion-reader-user-30x32companion-reader-mixed-30x2000companion-reader-sparse-128x2000companion-reader-user-0x32first-ask-user-0x32The first historical timing attempt failed its output precondition because missing fixture timestamps used the UI wall clock. The failed receipt remains; fixtures now have explicit positive timestamps. No clock mock or weaker equality was used in the final runs.
Live verification at
37f216f95a49a87765e5b5eeb6e8945a26477a04passed against the actual build: five real OpenAI turns, two web fetches, 107 assertions, and 35 successful proof RPCs. Full and cursorchat.history/chat.startupresponses remained consistent across two canonical avatar writes from another process, and authenticated avatar HTTP reads returned the exact new bytes/ETags. Stored transcript rows stayed byte-identical. Two real companion asks correctly used the selected session and recalled the preceding companion question. The real Claude loader/parser/merge processed a synthetic native-format file; this is not a claim that a native CLI process ran. A fresh connection also recovered history during an actual web tool call, with session/status/anchor checks preserved. The task Gateway stopped cleanly; its process group is confirmed dead and both Node CPU profiles are retained.The first live companion attempt correctly rejected the task fixture's disjoint tool allowlists before calling the provider. A separate task-only launcher added the two session-read tools already permitted by the companion; read/exec/write remain unavailable. The entire live helper then passed. The original failure and profiles are retained; no product guard or operator configuration changed.
The latest ClawSweeper source review found no introduced defect and asked for exact-head CI completion. Its serialized-state heuristic is addressed by the unchanged storage/schema/write formats, retained write-owned copies, existing upgrade/reader tests, and byte-identical stored transcript checks; this read-only refactor requires no migration. The user-authorized maintainer review is complete. Exact-head CI remains the landing gate.