Skip to content

perf: speed up chat history preparation - #133635

Merged
steipete merged 1 commit into
mainfrom
codex/history-profile-third-pass
Aug 31, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/history-profile-third-pass

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Opening or scrolling back through long Control UI chats still spends avoidable Gateway time scanning ordinary messages for inbound metadata and heartbeat acknowledgement markup.

Follow-up to #133565, which increased history windows and optimized the initial projection path.

Why This Change Was Made

The metadata owner now checks literal provenance markers and delivery hints directly, using its whole-line regex only when Context: is present. Both metadata-stripping entry points share that detector. The heartbeat owner skips markup cleanup when the literal acknowledgement token is absent; the cleanup only inserts spaces or removes edge wrappers, so it cannot create that token.

This removes repeated scans at their shared owners, benefiting Gateway history, TUI formatting, and model replay. Production LOC: +12/-21 (net -9); tests: +0/-0. No new cache, configuration, storage, protocol, page-size, or rendering changes. The full-text and capped sanitization passes remain because TTS matching and deduplication need uncapped text.

User Impact

Chats open and older history loads with less Gateway processing. Existing metadata stripping, heartbeat suppression, displayed messages, initial 400-message windows, and older 1,000-message windows retain their behavior.

Release-note context: Chat history skips metadata-pattern and heartbeat-markup scans for ordinary messages, reducing Gateway work when opening chats and loading older history.

Evidence

Paired Node inspector measurements against baseline 6af76da58f4c469398eea9f03101c8d8fd349996 on the same macOS arm64 machine, Node 26.8.1, real isolated SQLite transcripts with 3,000 messages and 2,048 Markdown characters per message. Five warmup rounds and 30 measured rounds per scenario, with scenario order rotated. These medians measure history read/projection; they exclude setup, serialization, network, and browser painting.

Rich-history scenario Before After Reduction
Initial 400 22.056 ms 16.770 ms 24.0%
Initial 1,000 55.197 ms 41.764 ms 24.3%
Older 1,000, offset 1,000 14.479 ms 11.248 ms 22.3%

An independent earlier pair measured 15–17% less time for rich initial pages. Metadata-heavy pages improved about 9–10%; short-message differences were small and noisy on the busy host. The expanded rich CPU profile fell from 4,420.8 to 3,395.7 ms; metadata stripping and heartbeat markup cleanup accounted for 502.8 and 179.4 ms of sampled self time before this patch and disappear from the top frames afterward. No browser-paint improvement is claimed.

467 existing focused/integration tests passed: 358 local heartbeat, metadata, presentation, Gateway projection, TUI, and CLI replay tests, plus 109 clean Linux tests for provider-boundary cache stability and a real ephemeral Gateway's REST/SSE history flow. Blacksmith Testbox run 33342433086 completed with wrapper exit 0 and its lease was stopped; the backing Actions lifecycle may show cancellation after successful external cleanup.

600,000 deterministic old/new helper comparisons over 50,000 adversarial strings matched. All 15 page snapshots (8,100 messages) were deeply equal after normalizing only the source identifier derived from each fresh database's path and rewrite generation. Existing behavior tests plus paired profiling and differential checks were used instead of adding timing assertions or implementation-coupled tests. Temporary measurement harnesses are not part of the product diff.

Targeted formatting, lint, and strict typechecking of both edited modules passed. The broad local changed gate stopped at six pre-existing tslog declaration errors in src/logging/logger.ts; local integration setup also lacked shiki/wasm, so integration proof ran in the clean Linux Testbox. Named local follow-up: repair the shared dependency installation. Required Codex autoreview passed with no findings; exact-head CI run 33343149590 passed for 5a0f80701bf8bf8cb71f669392200106c0da982c. This satisfies ClawSweeper’s remaining CI request.

@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 size: XS maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 23:57
@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 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 8:04 PM ET / August 31, 2026, 00:04 UTC.

ClawSweeper review

What this changes

This PR speeds chat-history preparation by avoiding markup cleanup and metadata parsing when a message lacks the relevant heartbeat token or inbound-context sentinels.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open. The introduced owner-local fast paths preserve the existing marker, delivery-hint, and whole-line Context: contracts; no actionable defect was found. Exact-head hosted checks are still running.

Priority: P3
Reviewed head: 5a0f80701bf8bf8cb71f669392200106c0da982c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative implementation with preserved detection contracts and supplied runtime measurements; only exact-head CI remains pending.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless supplies real SQLite transcript and ephemeral-Gateway after-change measurements for the history-preparation path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless supplies real SQLite transcript and ephemeral-Gateway after-change measurements for the history-preparation path.
Evidence reviewed 5 items Introduced fast paths: The verified parent-to-head diff introduces the heartbeat early return and replaces the compiled metadata alternation with equivalent literal sentinel checks.
Metadata contract preserved: The detector still recognizes the provenance marker and every delivery hint by substring, while preserving the prior whole-line-only rule for the active-memory Context: header.
Existing contract coverage: Focused tests cover ordinary-text fast paths, marked context blocks, delivery hints, active-memory blocks, and lookalike Context: text.
Findings None None.
Security None None.

How this fits together

Gateway history projection sanitizes stored chat text before it reaches the Control UI, TUI, and model replay. The changed functions detect internal metadata and heartbeat acknowledgements so ordinary messages can bypass unnecessary parsing.

flowchart LR
  A[Stored chat messages] --> B[Gateway history projection]
  B --> C[Inbound metadata detection]
  B --> D[Heartbeat acknowledgement cleanup]
  C --> E[Sanitized history]
  D --> E
  E --> F[Control UI, TUI, and model replay]
Loading

Before merge

  • Resolve merge risk (P1) - Exact-head hosted checks were still in progress in the supplied status rollup; merge should wait for the required checks to finish green.
  • Complete next step (P2) - No repair lane is needed because the source review found no concrete introduced defect; this PR needs normal exact-head CI completion.
Agent review details

Security

None.

PR surface

Source -9. Total -9 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 2 12 21 -9
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 12 21 -9

Review metrics

Metric Value Why it matters
Production versus test delta production +12/-21 (net -9), tests 0 The optimization removes more production code than it adds and does not expand public, config, storage, or protocol surface.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the shared-owner fast paths and land after exact-head CI confirms the existing sanitization and heartbeat contracts.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Retain the shared-owner fast paths and land after exact-head CI confirms the existing sanitization and heartbeat contracts.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this PR optimizes existing history preparation rather than reporting a failure. Its supplied body includes before/after real-transcript and ephemeral-Gateway measurements.

Is this the best way to solve the issue?

Yes. The change keeps the parsing and stripping owners intact while making their no-sentinel paths cheaper; it does not add a competing cache or behavior path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0b392310b92d.

Labels

Label changes:

  • add P3: This is a small, behavior-preserving performance improvement rather than a user-visible regression or safety fix.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless supplies real SQLite transcript and ephemeral-Gateway after-change measurements for the history-preparation path.

Label justifications:

  • P3: This is a small, behavior-preserving performance improvement rather than a user-visible regression or safety fix.
  • 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: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless supplies real SQLite transcript and ephemeral-Gateway after-change measurements for the history-preparation path.

Evidence

What I checked:

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Wait for required exact-head hosted checks to complete successfully before merge.

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.

@steipete steipete self-assigned this Aug 31, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The shared-owner fast paths are reviewed and ready for native landing. Exact-head CI run 33343149590 is green for 5a0f80701bf8bf8cb71f669392200106c0da982c, completing ClawSweeper’s only rank-up move. Production +12/-21 (net -9); no test or public-contract expansion. Both helpers are byte-identical after the mechanical rebase.

The Node profile showed ordinary messages repeatedly entering inbound-metadata regex matching and heartbeat markup cleanup. The canonical detector and token-absence check remove that work while retaining marked metadata, wrapped heartbeat tokens, timestamp handling, and the uncapped TTS/deduplication boundary. Rich initial 400-message preparation improved 22.056 → 16.770 ms; older 1,000-message preparation improved 14.479 → 11.248 ms. These are Gateway preparation timings, not browser-paint timings.

467 focused/integration tests passed. All 600,000 differential helper comparisons matched, as did 15 real SQLite page snapshots (8,100 messages) after normalizing only each fresh database's source identifier. The clean Linux ephemeral-Gateway REST/SSE and replay-boundary proof is run 33342433086, wrapper exit 0, lease stopped. Fresh Codex autoreview and ClawSweeper found no actionable source defect.

Executed focused commands
node scripts/run-vitest.mjs src/auto-reply/heartbeat.test.ts src/auto-reply/heartbeat-filter.test.ts src/auto-reply/reply/strip-inbound-meta.test.ts src/auto-reply/reply/agent-runner-presentation.test.ts src/gateway/chat-display-projection.test.ts src/gateway/chat-display-projection.media.test.ts src/gateway/chat-display-projection.tool-result.test.ts src/gateway/chat-display-projection.forwarded.test.ts src/agents/cli-runner.helpers.test.ts src/tui/tui-formatters.test.ts
node scripts/crabbox-wrapper.mjs run --timing-json -- node scripts/run-vitest.mjs src/gateway/sessions-history-http.test.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/auto-reply/heartbeat.ts src/auto-reply/reply/strip-inbound-meta.ts
node scripts/run-tsgo.mjs -p .artifacts/control-ui-e2e/history-window-perf/tsconfig.third.json
git diff --check

The scoped typecheck inherits the repository's core compiler options and aliases. The broad local check stopped at pre-existing shared-install tslog errors; Linux integration proof and hosted PR CI cover the submitted source without changing those declarations.

@steipete
steipete merged commit afac389 into main Aug 31, 2026
313 checks passed
@steipete
steipete deleted the codex/history-profile-third-pass branch August 31, 2026 00:17
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: XS 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