Skip to content

perf(history): reuse prepared display and session facts - #133316

Merged
steipete merged 2 commits into
mainfrom
codex/perf50-history-preparation
Aug 30, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf50-history-preparation

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Prepare visibility facts once per row and inspect the next row only for heartbeat handling.
  • Select the profile display columns without materializing avatar blobs; retain full profile reads for their existing consumers.
  • Resolve a repeated sender once within a delta response. A later request performs a fresh lookup, and scalar/live projection retains its current behavior.
  • Capture transcript positions and nested-activity facts once, preserving selector invocation order, mutable-iterator behavior, stable barriers, and output identities.
  • Replace repeated CLI image-row searches and splices with per-key remaining capacity.
  • Check exact external CLI identity before text preparation, without consuming image capacity for a discarded identity duplicate.
  • Remove redundant copies of fresh decoded session entries; retain copies of cached, borrowed, and write-owned objects. Target-only resolution uses the existing list projection without changing database open policy.
  • Select the bounded visible companion tail before normalization/redaction, preserving scan limits, partial-message budgeting, chronological output, and abort/generation fences.

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 48b0857e with candidate 37f216f9; 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 NULL expression. 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.

Path Original F/R Candidate F/R
30-row repeated-profile delta, no avatar 1.154 / 1.146 0.585 / 0.523
Same delta, 512 KiB avatar 2.156 / 2.129 0.607 / 0.611
CLI exact identities, 300 local + 300 imported rows through display/UI 17.192 / 18.423 10.091 / 10.864
CLI image matches, 300 + 300 rows through display/UI 18.964 / 17.952 11.674 / 11.128
Fresh decoded entry, 4 KiB prompt fields, warm handle 0.064 / 0.064 0.057 / 0.060
Target lookup, 128 KiB prompt fields 0.248 / 0.280 0.118 / 0.117
SQLite companion reader, mixed 300-row short-text fixture 0.978 / 0.963 0.715 / 0.730
Complete first-ask preparation, mixed 300-row long-text fixture 26.367 / 26.631 9.334 / 9.440

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.

Workload Change F / R
profile-null-false-1/full-row-control +1.00% / +1.20%
profile-null-false-30/fresh-profile-readonly/sqlite-history-ui +2.25% / +3.43%
profile-null-true-1/warm-handle/delta +7.85% / +0.85%
profile-32768-false-1/full-row-control +1.37% / +3.81%
profile-524288-false-1/fresh-profile-readonly/delta +3.32% / +11.10%
profile-524288-false-30/warm-handle/sqlite-history-ui +0.81% / +0.07%
profile-524288-true-30/fresh-profile-readonly/sqlite-history-ui +1.40% / +0.56%
plain-0/warm-handle/delta +2.09% / +1.62%
plain-1/fresh-profile-readonly/delta +3.58% / +3.72%
plain-30/fresh-profile-readonly/delta +3.93% / +0.91%
CLI-image-forward-1/merge +0.33% / +3.57%
CLI-image-forward-30/merge +2.28% / +1.02%
full-store-control-131072 +10.82% / +10.79%
companion-reader-user-30x32 +0.41% / +0.32%
companion-reader-mixed-30x2000 +2.40% / +3.47%
companion-reader-sparse-128x2000 +0.22% / +1.92%
companion-reader-user-0x32 +1.87% / +6.60%
first-ask-user-0x32 +4.84% / +1.62%

The 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 37f216f95a49a87765e5b5eeb6e8945a26477a04 passed against the actual build: five real OpenAI turns, two web fetches, 107 assertions, and 35 successful proof RPCs. Full and cursor chat.history/chat.startup responses 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.

@clawsweeper

clawsweeper Bot commented Aug 30, 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 gateway Gateway runtime size: L maintainer Maintainer-authored PR labels Aug 30, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 10:41 AM ET / 14:41 UTC.

ClawSweeper review

What this changes

This 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 readiness

⚠️ Ready for maintainer review - 2 items remain

No 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
Reviewed head: 37f216f95a49a87765e5b5eeb6e8945a26477a04

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has coherent owner-local caching and targeted regression coverage, with no concrete correctness or security finding found in review.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable to this MEMBER-authored PR; the supplied body records an actual Gateway verification, while this read-only review independently traced the changed history, session, and companion owners and notes pending exact-head CI.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable to this MEMBER-authored PR; the supplied body records an actual Gateway verification, while this read-only review independently traced the changed history, session, and companion owners and notes pending exact-head CI.
Evidence reviewed 6 items Introduced runtime path: The delta reader creates one profile-display projector before iterating events and passes it through each message projection, so repeated profile senders share one lookup only within that response.
Display-cache behavior: The projector caches only resolved display facts by sender ID; the cursor regression test verifies one lookup for three delta rows and a refreshed avatar URL on the next request.
Fresh session-entry ownership: Exact SQLite reads decode a new entry object before returning it, while cached list views retain their separately documented borrowed-read behavior; removing these redundant clones does not expose a cached mutable object.
Findings None None.
Security None None.

How this fits together

Gateway 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]
Loading

Before merge

  • Resolve merge risk (P1) - One exact-head CI shard was still in progress in the supplied check state; merge should wait for required checks to finish successfully.
  • Complete next step (P2) - No mechanical repair is indicated; wait for the remaining exact-head CI result.
Agent review details

Security

None.

PR surface

Source +50, Tests +77. Total +127 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 18 242 192 +50
Tests 4 142 65 +77
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 384 257 +127

Review metrics

Metric Value Why it matters
Production vs test LOC production +238/-189 (net +49); tests/test-support +146/-68 (net +78) The production growth is localized to explicit per-operation fact ownership while replacing repeated scans, clones, and full-row display reads.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.entry.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the per-operation fact ownership and bounded-tail projection, then land after exact-head CI confirms the refactor on the current merge result.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best 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.

Labels

Label justifications:

  • P3: This is a bounded performance refactor with no identified user-facing regression or security concern.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable to this MEMBER-authored PR; the supplied body records an actual Gateway verification, while this read-only review independently traced the changed history, session, and companion owners and notes pending exact-head CI.

Evidence

What I checked:

Likely related people:

  • unknown: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-30T14:14:30.863Z sha 569b767 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit a22f9d8 into main Aug 30, 2026
241 checks passed
@steipete
steipete deleted the codex/perf50-history-preparation branch August 30, 2026 14:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
)

* perf(history): reuse prepared display and session facts

* refactor(state): express avatar presence through Kysely
spunzon pushed a commit to spunzon/openclaw that referenced this pull request Sep 3, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

1 participant