Skip to content

perf(acp): reuse prepared replay ledger queries - #139982

Merged
steipete merged 1 commit into
mainfrom
codex/db-next-acp-perf-land
Sep 6, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/db-next-acp-perf-land

Conversation

@steipete

@steipete steipete commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Related: #139768

What Problem This Solves

ACP replay writes repeatedly rebuild the same queries and prepare native statements while appending events and enforcing the existing history limits. This adds avoidable work to every update.

Why This Change Was Made

Eleven fixed query shapes now retain their Kysely compilation per physical SQLite connection. Each invocation binds current session IDs, sequences, timestamps, metadata and payloads. Native statement retention, authorization, re-entry, size limits and invalidation remain owned by the existing bounded shared executor cache.

The raw runtime SQL in the affected append/trim operations is replaced with typed Kysely queries. The unchanged retention owner still enforces global counts, sequence gaps, session tie ordering and intermediate prompt-block eviction. No schema, configuration, cap, migration, or dependency changes are introduced.

An equivalent shared cache-admission shortcut also avoids UTF-8 scanning an obviously oversized string: when its UTF-16 code-unit length already exceeds the remaining byte budget, its UTF-8 representation cannot fit. Shorter strings still receive exact byte sizing. The cache admits exactly the same inputs as before.

User Impact

Warm ordinary appends use zero new native prepare calls and zero Kysely compilations instead of four and three respectively. Oversized payloads retain their existing uncached behavior and still require one native preparation. The trimming fixture drops from 840 native preparations to zero over 120 appends.

The first operation compiles all eleven shapes, and unchanged history-count scans can still dominate large histories. Local process-CPU samples before the shared sizing shortcut improved ordinary small writes by about 21–22% and byte trimming by about 15–23%; wall-clock samples were noisy. Final oversized-only comparisons put Node 24 roughly flat (+1.08% paired CPU) and Node 26 modestly faster (−4.25%). Both sides of those final oversized comparisons use the equivalent improved sizing helper. These are scoped local measurements, not uniform production latency claims.

Evidence

  • Before the repair, the warm-reuse regression observed 16 native preparations across four warmed appends. Its behavioral companions passed, isolating preparation overhead from data correctness.
  • The original reviewed five-file candidate passed 53 focused tests, the full changed-file gate and independent P0–P2 review. Cases cover fresh bindings, close/reopen with the same ledger object, authorizer invalidation, oversized-to-small transitions, shared-connection caps, sequence gaps, stable session ordering and prompt-block eviction.
  • Paired Node 24.20.0 and 26.8.1 benchmarks preserve every canonical row digest. The oversized-byte case also covers CJK text whose code-unit length fits while UTF-8 bytes exceed the cache limit.
  • Final integration on landed Unicode accounting repair fix(acp): keep Unicode replay within its byte budget #124476 passed 76 tests, including transaction/post-commit composition. The full changed-file gate passed in 395.3 s. Refreshed real ACP stdio/GatewayClient proof on Node 24/26 passed two restarts, below-cap exact replay and over-cap fallback using the current WebSocket loader. All four TypeScript files match the independently reviewed candidate byte-for-byte; the assertion baseline changes only by removal of its five obsolete casts.

Proof uses synthetic local SQLite and the real ACP stdio/GatewayClient against a local mock WebSocket Gateway; no production provider, user data or packaged-build performance is claimed.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Sep 6, 2026
@steipete
steipete marked this pull request as ready for review September 6, 2026 09:33
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Sep 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 5:39 AM ET / 09:39 UTC.

ClawSweeper review

What this changes

The PR reuses compiled SQLite queries when recording and trimming ACP replay history and avoids unnecessary byte counting for oversized cached-query inputs.

Merge readiness

✅ Ready for maintainer review

Keep open: this implements the accepted ACP performance work that current main still lacks. No actionable correctness or security defect was found in the introduced changes.

Priority: P2
Reviewed head: 9954fd4e1391dec6b938793548f763ab8107da70

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable optimization with useful regression coverage and no blocking defect identified.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied MEMBER association exempts this PR from the external-contributor proof gate. Its body reports SQLite benchmarks and ACP stdio/GatewayClient restart and retention checks against a mock Gateway; this review did not independently execute those runs, and the patch does not materially change authority.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied MEMBER association exempts this PR from the external-contributor proof gate. Its body reports SQLite benchmarks and ACP stdio/GatewayClient restart and retention checks against a mock Gateway; this review did not independently execute those runs, and the patch does not materially change authority.
Evidence reviewed 9 items Current main still performs repeated preparation: The fetched main revision rebuilds session queries and directly prepares append and retention statements; the proposed reuse is still absent.
Connection-owned query reuse: Eleven fixed query shapes use the existing prepared-query helper, with session values and limits supplied per invocation. Comparison with main preserves predicates, eviction ordering, byte accounting, and synchronous transaction boundaries.
Native statement lifecycle remains centralized: Prepared queries bind a new parameter array per invocation and use the shared executor. That executor invalidates statements on authorizer transitions and deserialization, bypasses caching while authorization is active, and protects synchronous re-entry. The new string-length check only rejects values whose UTF-8 bytes already cannot fit.
Findings None None.
Security None None.

How this fits together

The ACP bridge records prompts and agent updates in SQLite so clients can restore session history. Its replay ledger preserves ordered events within existing retention limits and falls back to transcript history when replay is incomplete.

flowchart LR
  A[Prompts and agent updates] --> B[ACP replay ledger]
  B --> C[Compiled queries with fresh values]
  C --> D[Shared SQLite statement cache]
  D --> E[Stored history and retention limits]
  E --> F{Complete replay available?}
  F -->|Yes| G[Ordered ACP replay]
  F -->|No| H[Transcript fallback]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +148, Tests +209, Other -1. Total +356 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 235 87 +148
Tests 2 217 8 +209
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 5 452 96 +356

Review metrics

Metric Value Why it matters
Production versus test growth Production +148 net lines; tests +209 net lines Production growth defines typed reusable queries; tests protect binding freshness, retention equivalence, and cache behavior.
Compilation tradeoff 11 query shapes compiled on first use Compilation moves to connection initialization; the PR reports zero new ACP preparations or compilations for warmed ordinary appends.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #139768
Summary: This PR implements the ACP portion of the canonical performance issue; transcript rewrite work remains separate.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep replay query compilation at the connection owner while preserving fresh bindings, shared statement invalidation, and existing retention semantics.

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

Not applicable as a correctness bug: source confirms repeated query construction on main, while the PR reports measured preparation overhead and preserved results.

Is this the best way to solve the issue?

Yes: using the existing prepared-query helper removes repeated work without adding a competing cache owner or changing durable replay semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against f66dc27b5bf7.

Labels

Label changes:

  • add P2: This is a bounded performance improvement to replay persistence with an explicitly accepted scope.
  • 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: The supplied MEMBER association exempts this PR from the external-contributor proof gate. Its body reports SQLite benchmarks and ACP stdio/GatewayClient restart and retention checks against a mock Gateway; this review did not independently execute those runs, and the patch does not materially change authority.

Label justifications:

  • P2: This is a bounded performance improvement to replay persistence with an explicitly accepted scope.
  • 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: The supplied MEMBER association exempts this PR from the external-contributor proof gate. Its body reports SQLite benchmarks and ACP stdio/GatewayClient restart and retention checks against a mock Gateway; this review did not independently execute those runs, and the patch does not materially change authority.

Evidence

What I checked:

  • Current main still performs repeated preparation: The fetched main revision rebuilds session queries and directly prepares append and retention statements; the proposed reuse is still absent. (src/acp/event-ledger.ts:68, f66dc27b5bf7)
  • Connection-owned query reuse: Eleven fixed query shapes use the existing prepared-query helper, with session values and limits supplied per invocation. Comparison with main preserves predicates, eviction ordering, byte accounting, and synchronous transaction boundaries. (src/acp/event-ledger.ts:51, 9954fd4e1391)
  • Native statement lifecycle remains centralized: Prepared queries bind a new parameter array per invocation and use the shared executor. That executor invalidates statements on authorizer transitions and deserialization, bypasses caching while authorization is active, and protects synchronous re-entry. The new string-length check only rejects values whose UTF-8 bytes already cannot fit. (src/infra/kysely-sync-cache-state.ts:130, 9954fd4e1391)
  • Focused regression coverage: The added tests inspect actual SQLite rows and replay results while checking warm query reuse, fresh Unicode bindings, reopening, denied inserts, oversized-to-small transitions, gapped sequences, shared-connection caps, and intermediate prompt eviction. Tests were inspected but not executed in this read-only review. (src/acp/event-ledger.prepared.test.ts:24, 9954fd4e1391)
  • Accepted scope and related work: The supplied discussion for Reduce repeated query compilation in transcript rewrites and ACP replay #139768 explicitly accepts fixed-query reuse while preserving transactions, payloads, limits, and ownership. The merged accounting repair fix(acp): keep Unicode replay within its byte budget #124476 is the prerequisite, not a replacement for this performance work. (c4822b82d55c)
  • Captured validation claims: The supplied complete PR body, under context sourceRevision 07c288799379b06cb70a44819c27fc3541ebcfdb3ade2127cdf9bb9e5c8c9217, reports 76 passing integration tests, preserved benchmark row digests, and real ACP stdio/GatewayClient runs against a local mock WebSocket Gateway on Node 24/26, including two restarts and below-cap replay versus over-cap fallback. These are contributor-reported results, not executions performed by this reviewer. (9954fd4e1391)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • coaiMax: 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.

@steipete
steipete merged commit 8e25799 into main Sep 6, 2026
252 checks passed
@steipete
steipete deleted the codex/db-next-acp-perf-land branch September 6, 2026 09:54
@steipete

steipete commented Sep 6, 2026

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 P2 Normal backlog priority with limited blast radius. 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