Skip to content

improve: speed up legacy imports and transcript replacement - #133546

Merged
steipete merged 2 commits into
mainfrom
codex/importer-performance-pass-eight
Aug 30, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/importer-performance-pass-eight

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133496

What Problem This Solves

Legacy session imports and transcript replacements repeatedly rebuild the same Kysely insert query. Batch imports also rebuild the same window-recency update for every event. This spends CPU on query construction after SQLite statement caching has already removed most prepare work.

Why This Change Was Made

Compile these fixed query shapes once per synchronous batch and bind fresh values for each execution. A small typed preparation helper uses Kysely's bound-value expressions and compiler ordering, then delegates to the existing synchronous executor. It does not introduce another native statement cache or bypass cache admission, authorizer invalidation, re-entry handling, error reporting, or cleanup. Transcript append and replacement share one insert builder.

The SQL, write order, timestamps, JSON normalization, duplicate handling, idempotency ownership, projections, and transaction boundaries are unchanged. There are no schema, index, configuration, dependency, retention, concurrency, or durable-format changes.

User Impact

Less query-building work during legacy imports and transcript replacement. Isolated Linux median complete file-to-SQLite import time fell 6.8% for deep histories, 4.7% across many sessions, 6.8% for v1 files, and 18.1% for v2 files. Branching, replay, and tiny-import changes were modest; no material gain is claimed for those controls. The packaged stable upgrade and final-head CI both passed after a metadata-only assertion-baseline correction.

Evidence

  • 99 focused tests passed across synchronous Kysely execution, legacy import rollback/deduplication/source validation, active-branch projections, accessor conformance, and context eligibility/replacement. One existing 100k-message concurrent-rebuild test was excluded from the local run; the large importer/package proof runs on isolated Linux.
  • New coverage exercises changing null/blob/bigint/Unicode/injection-like values, repeated bindings mixed with literal parameters, and synchronous callback re-entry without corrupting outer bindings.
  • Full-priority independent Codex autoreview found no actionable findings. Formatting and completed structural guards pass. The local aggregate gate stops at six pre-existing tslog declaration errors in unchanged src/logging/logger.ts; the shared install lacks types/BaseLogger.d.ts and was not modified. Clean exact-head CI subsequently passed, including type checks.
  • Three exploratory local before/after 10k imports had identical full persisted-data digests and lower CPU in every pair. Isolated Linux timing, CPU profiles, SQL traces, and a packaged stable upgrade gate landing.
  • Production +77/-56 (net +21); tests +49. The added preparation seam preserves typed Kysely construction without hard-coded SQL or positional binding assumptions. The duplicate append/replacement insert builder is removed, and all execution safeguards remain owned by the existing executor. Nearby normalization now uses the existing canonical non-array record guard instead of repeated checks and casts.

Focused command: node scripts/run-vitest.mjs src/infra/kysely-sync.test.ts src/config/sessions/session-accessor.sqlite-import.test.ts src/config/sessions/session-accessor.sqlite-active-events.test.ts src/config/sessions/session-accessor.conformance.test.ts src/config/sessions/session-transcript-context-eligibility.test.ts --testNamePattern '^(?!.*100k-message)'.

Separate follow-up opportunities: Doctor's preliminary transcript-count scan still reparses rows before staging, and the JSONL reader still assembles temporary fragment arrays for complete lines. These are outside this query-construction change.

Isolated Linux measurements

Blacksmith Testbox run, Node 24.19.0 / SQLite 3.53.3, exact candidate 1c410b2575f7b05f96e884558bdd0614685e4c2b. Only the two production owners are overridden for the baseline from e60b4ec5260f91c4969654aa9dee5c4d5396f089; all other source and dependencies are identical. Five fresh processes per side per shape, alternating pair order. Fixture creation and digest verification are outside the timer; stable fixture paths preserve v1 ID derivation.

Shape Before median After median Wall change CPU change
One event 8.4 ms 8.1 ms -2.8% -2.0%
100k events, one history 6080.5 ms 5665.7 ms -6.8% -5.8%
100 sessions × 100 events 707.3 ms 674.0 ms -4.7% -1.7%
100 branching histories 996.9 ms 967.8 ms -2.9% -2.9%
10k existing events, repeat import 156.2 ms 154.4 ms -1.1% -0.4%
10k version-1 events 662.1 ms 617.4 ms -6.8% -6.3%
10k version-2 events 731.9 ms 599.6 ms -18.1% -25.7%

All 35 paired digests match across exact transcript bytes, identities, window metadata, active positions, projection watermarks, and FTS. The separate 10k-event trace retains 100,034 SQL calls across the same 34 shapes. Before/after Node CPU profiles completed separately from the unprofiled timing samples. All samples, including outliers, remain in the evidence; small movements in controls should not be treated as reliable speedups.

Packaged upgrade and final-head scope

The packaged Docker upgrade from stable 2026.7.1-2 passed with 4,800 synthetic sessions, 1,227,946 events, and 10,000 cron jobs. Five full-state assertions passed, including automatic migration immediately after update and before standalone Doctor. Eight Gateway history samples across two agents returned 600 messages identically after restart. Repeat Doctor completed in 37 seconds against the unchanged 60-second budget; startup took 11 seconds, and health/readiness/status probes each took 1 second. The scenario uses an explicit candidate tarball, manual Gateway restart, and expected synthetic-plugin capability consent; it does not claim unattended update-channel switching. The command exited successfully in 13m14s; proof and CPU profiles were collected and checksum-verified, then the worker was stopped.

The package and benchmarks ran at 1c410b2575f7b05f96e884558bdd0614685e4c2b. Final head f29c696bfbd0fe91ea475768bc73fcf0b223b31a differs only in config/assertion-safety-baseline.txt (7 → 2), recording the five removed casts. All production and test file hashes are identical. The baseline file is absent from the package inventory, so that correction does not change the tested runtime. The first CI run correctly caught the stale allowance; its exact ratchet passes after the correction, and independent review of that one-line change is clean. Final-head CI completed successfully at f29c696bfbd0fe91ea475768bc73fcf0b223b31a.

Dependency contract and review disposition

ClawSweeper’s final-head review, refreshed at 2026-08-30 21:41 UTC and personally read before landing, found no concrete code defect, but could not inspect the pinned dependency in its environment. I directly inspected installed Kysely 0.29.5 and independently fetched the versioned upstream compiler: compileQuery copies the ordered parameter array; visitValue forwards bound values unchanged; addParameter appends the original value. A separate final-head executable probe confirmed marker identity, repeated marker ordering, and literal preservation in the installed version. The new SQLite tests also execute these bindings and nested callbacks, and all 35 complete import pairs match stored data. This resolves the dependency-inspection gap. I read the latest completed comment and its rank-up list; its exact-head CI request is now satisfied by the successful final run. The dependency contract is verified and accepted on that evidence; all requested rank-up work is addressed, with no skips.

Median process peak RSS (KiB), before → after: single 353,788 → 353,916; deep 512,860 → 512,636; wide 399,612 → 405,784; branch 406,024 → 405,228; replay 395,208 → 400,816; legacy-v1 406,332 → 402,048; legacy-v2 527,984 → 396,640. These are process peaks, not isolated importer allocations; no universal memory reduction is claimed.

@steipete steipete self-assigned this Aug 30, 2026
@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: S maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 21:10
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. 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, 5:41 PM ET / 21:41 UTC.

ClawSweeper review

What this changes

The PR compiles fixed Kysely query shapes once per transcript import or replacement batch and supplies fresh values for each SQLite write.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored, protected PR open. The introduced batch-local binding path preserves the existing SQLite executor and transcript ordering; no concrete patch defect was found, but exact-head CI and a dependency-contract check remain the appropriate merge gates.

Priority: P3
Reviewed head: f29c696bfbd0fe91ea475768bc73fcf0b223b31a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch and focused tests are coherent, but independent inspection of the exact Kysely compiler contract was unavailable in this review environment.
Proof confidence 🌊 off-meta tidepool Not applicable: This is an internal transactional performance change and the supplied repository state identifies the author as a MEMBER; the PR's Testbox upgrade and parity results are supplemental evidence, not a contributor-proof requirement.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is an internal transactional performance change and the supplied repository state identifies the author as a MEMBER; the PR's Testbox upgrade and parity results are supplemental evidence, not a contributor-proof requirement.
Evidence reviewed 7 items Prepared binding implementation: The new helper compiles a Kysely query once, replaces only locally generated parameter markers with fresh invocation values, and routes execution through the existing synchronous executor.
Transcript owner boundary: Import batches retain cursor-local prepared insert and recency-update functions; replacement retains one local insert function while existing sequence, identity, mutation, and index work remains in order.
Caller and callee coverage: Legacy import invokes the batch append after staging and source validation, while public replacement holds the established synchronous write transaction and writer fence before calling the replacement owner.
Findings None None.
Security None None.

How this fits together

Legacy session import and transcript replacement write normalized events into an agent-local SQLite store. Those rows drive session recency, transcript indexes, and later history reads.

flowchart LR
A[Legacy session import] --> C[Transcript write batch]
B[Transcript replacement] --> C
C --> D[Prepared query bindings]
D --> E[SQLite transcript events]
E --> F[Transcript indexes and history]
Loading

Decision needed

Question Recommendation
After exact-head CI completes, should this generic Kysely binding seam be accepted based on the version-specific compiler evidence in the PR? Verify and accept the binding contract: Confirm the supplied Kysely 0.29.5 compiler evidence and merge once exact-head CI is green.

Why: The source review found no defect, but the review environment could not independently inspect the pinned dependency implementation that the helper relies on.

Before merge

  • Resolve merge risk (P1) - The helper depends on Kysely 0.29.5 retaining compiler parameter identity and order; local dependency source was unavailable, so a maintainer should verify the supplied version-specific proof before merge.
  • Complete next step (P2) - The protected maintainer PR has no mechanical repair finding; it awaits exact-head CI and maintainer acceptance of the dependency-contract evidence.
Agent review details

Security

None.

PR surface

Source +21, Tests +49, Other 0. Total +70 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 77 56 +21
Tests 1 49 0 +49
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 4 127 57 +70

Review metrics

Metric Value Why it matters
Production versus test delta production +21, tests +49 The net production growth is a generic typed binding seam offset by duplicated transcript-write removal; the added tests cover its binding and re-entry invariants.

Merge-risk options

Maintainer options:

  1. Verify the pinned compiler contract (recommended)
    Before merge, confirm Kysely 0.29.5 preserves the compiled parameter ordering and marker identity relied on by the helper, then require green exact-head CI.
  2. Pause pending independent dependency access
    Keep the PR open if no maintainer can validate the version-specific Kysely behavior from source or an equivalent executable probe.

Technical review

Best possible solution:

Keep the single canonical synchronous executor and land the batch-local preparation seam after exact-head CI and Kysely 0.29.5 contract evidence are accepted.

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

Not applicable: this PR is an internal performance refactor rather than a report of failing user behavior; its relevant checks are binding parity and transcript-write invariants.

Is this the best way to solve the issue?

Yes. Reusing the existing synchronous executor with fresh batch-local bindings is cleaner than a second native cache or handwritten positional SQL, and it removes duplicated insert construction.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 00b64b81c407.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P3: This is a bounded internal performance improvement with no demonstrated user-visible behavior change.
  • merge-risk: 🚨 other: Correctness depends on a pinned third-party compiler parameter contract that this environment could not independently inspect.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is an internal transactional performance change and the supplied repository state identifies the author as a MEMBER; the PR's Testbox upgrade and parity results are supplemental evidence, not a contributor-proof requirement.

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)
  • Vito Cappello: 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.

  • Complete exact-head CI and have a maintainer verify the supplied Kysely 0.29.5 compiler-contract evidence.

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-30T21:22:45.267Z sha 1c410b2 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 30, 2026
@steipete
steipete merged commit e585660 into main Aug 30, 2026
257 checks passed
@steipete
steipete deleted the codex/importer-performance-pass-eight branch August 30, 2026 21:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Aug 30, 2026
* origin/main: (55 commits)
  test: include v2026.8.1 release navigation (#133581)
  fix: stop cloud work before unrelated provider inspection finishes (#133476)
  fix(e2e): keep delete fixture target-compatible (#133526)
  fix(release): detect optional target E2E capability (#133525)
  fix(package): publish readable dist inventory (#133549)
  docs: add complete v2026.8.1 maintainer change index (#133585)
  fix(browser): preserve contextless worker and iframe sessions (#133571)
  fix(voice): discover configured provider candidates (#133507)
  refactor(ui): simplify chat rendering and lifecycle state (#133567)
  test: reduce maturity fixture cleanup time (#133566)
  improve: speed up legacy imports and transcript replacement (#133546)
  docs: add draft v2026.8.1 release notes (#133557)
  test: guard multi-project Vitest cache ownership (#133554)
  fix(memory): clarify default agent scope in command help (#133560)
  fix(clawdock): keep credentials out of diagnostic output (#133547)
  refactor(ui): avoid redundant presence work in avatar lists (#133548)
  fix(agents): recognize internal requester completion replies (#133543)
  fix: prevent duplicate queued user messages in chat clients (#133542)
  chore(ui): refresh control ui locales (#133544)
  fix(beam): restart delivery when the receiver changes (#133533)
  ...
vincentkoc added a commit to shojikumaru/openclaw that referenced this pull request Aug 30, 2026
…cked-delivery

* origin/main:
  test: include v2026.8.1 release navigation (openclaw#133581)
  fix: stop cloud work before unrelated provider inspection finishes (openclaw#133476)
  fix(e2e): keep delete fixture target-compatible (openclaw#133526)
  fix(release): detect optional target E2E capability (openclaw#133525)
  fix(package): publish readable dist inventory (openclaw#133549)
  docs: add complete v2026.8.1 maintainer change index (openclaw#133585)
  fix(browser): preserve contextless worker and iframe sessions (openclaw#133571)
  fix(voice): discover configured provider candidates (openclaw#133507)
  refactor(ui): simplify chat rendering and lifecycle state (openclaw#133567)
  test: reduce maturity fixture cleanup time (openclaw#133566)
  improve: speed up legacy imports and transcript replacement (openclaw#133546)
  docs: add draft v2026.8.1 release notes (openclaw#133557)
  test: guard multi-project Vitest cache ownership (openclaw#133554)
  fix(memory): clarify default agent scope in command help (openclaw#133560)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
…#133546)

* perf(sessions): reuse compiled transcript write queries

* chore(sessions): shrink assertion allowance after guard cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S 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