Skip to content

improve: reduce CPU overhead during session imports - #133689

Merged
steipete merged 1 commit into
mainfrom
codex/importer-performance-pass-eleven
Aug 31, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/importer-performance-pass-eleven

Conversation

@steipete

@steipete steipete commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133641

What Problem This Solves

Large session-history imports repeatedly rebuild and compile the same event-identity query, even though only the event ID changes within a session batch. This consumes CPU on top of the SQLite lookup itself.

Why This Change Was Made

Compile the existing identity lookup once per synchronous append batch through prepareSqliteQuerySync, binding fresh event IDs and reading current database rows on every call. Move the canonical identity reader into the existing transcript-read module and update its internal callers; there is no second query path or result cache.

User Impact

Lower CPU overhead for importing histories with event IDs. Duplicate detection, replay ownership, parent links, sequence numbers, opaque data and migration semantics stay unchanged. No schema, index, concurrency, configuration, dependency or public SDK change.

Evidence

  • All 236 focused tests pass across eight files: importer rollback/deduplication, generic append, context eligibility, session accessor, conformance, forks, message cuts and the prepared-query primitive. Command: node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-import.test.ts src/config/sessions/session-accessor.sqlite-transcript-store.test.ts src/config/sessions/session-transcript-context-eligibility.test.ts src/config/sessions/session-accessor.test.ts src/infra/kysely-sync.test.ts src/config/sessions/session-accessor.conformance.test.ts src/config/sessions/session-accessor.parent-fork.test.ts src/config/sessions/session-accessor.sqlite-message-cut.test.ts.
  • Scoped lint and formatting pass. The initial single-file implementation exceeded the transcript-store line limit; moving identity reads to their existing read owner resolved it without a suppression.
  • Independent Codex review of the final diff is scoped-clean through P3, confidence 0.95.
  • Production +43/-25 (net +18), including moved code and internal import changes; no test growth or new module. The added state holds one batch-local compiled query, with fresh bindings and no retained result rows. Existing behavior tests cover the stale-binding and stale-result risks.
  • Preliminary macOS Node 26 screening of 10,000-event full imports preserved exact stored-data digests. Both unprofiled pairs improved: CPU 1135.4 → 925.3 ms and 1002.4 → 896.8 ms. These are exploratory observations, not the final Linux performance claim.
  • Paired Linux full-import measurements and timed-region CPU profiles passed. Exact-head CI and packaged stable-upgrade proof also passed. Structural local changed checks passed through the core tsgo graph boundary, including three dead-export scans. Local core typecheck stopped on six pre-existing errors in unchanged src/logging/logger.ts; shared tslog lacks types/BaseLogger.d.ts. Shared dependencies were not modified; exact-head CI passed.

The private JSONL line-wrapper cleanup was also inspected, but not included: it removes a small allocation while this query compilation has a measured CPU cost. Doctor pre-count removal remains a separate error/report-ownership refactor.

Linux before/after imports

Candidate bd2175131d4c9e1f6c8cd450eab6c4d11ce9ba39; baseline 83b61257d6e328d904e7ed0c99ee50b661bbfe6d. Linux Node 24.19.0 / SQLite 3.53.3. Five alternating before/after pairs per shape, each in a fresh process. Fixtures and parity verification are outside the timer. These are complete file-to-SQLite imports.

Shape Before After Time reduction
single 9.3 ms 8.9 ms 3.7%
deep 5880.6 ms 5403.8 ms 8.1%
wide 646.4 ms 623.2 ms 3.6%
branch 997.7 ms 967.3 ms 3.0%
replay 163.4 ms 163.0 ms 0.3%
legacy-v1 636.8 ms 622.2 ms 2.3%
legacy-v2 603.0 ms 571.2 ms 5.3%
legacy-metadata-v1 367.9 ms 348.2 ms 5.3%
legacy-hooks-v2 532.4 ms 464.8 ms 12.7%

The clearest gains are 100,000-event deep histories (8.1% less wall time, 8.3% less CPU) and legacy hook histories (12.7% less wall time, 12.0% less CPU). Smaller multi-session/v1 cases were noisy; the table reports medians without claiming a uniform speedup. Already-imported replay is effectively neutral.

All 45 pairs preserve exact transcript JSON, identities, session windows, active positions, index state and FTS digests. SQL trace is identical: 100,034 calls across 34 shapes. Eight CPU profiles cover the timed import region; sampled Kysely self-time falls from 1387.5 to 1040.4 ms in the deep profile, consistent with removing repeated AST compilation. Profile sampling is supporting evidence, not the timing benchmark.

Deep-case median peak RSS is 492.7 → 492.9 MiB. The branch case is 371.8 → 395.6 MiB; no general memory reduction is claimed. All raw samples are retained.

The harness overrides every changed module reachable from the import entry point with its baseline source, leaving all other source/dependencies identical. Four changed modules are reachable; the checkpoint import-only change is not in that bundle and is covered by the passing checkpoint/branch tests. An initial harness assertion incorrectly required all five changed files to be reachable and stopped before timing; it now verifies the actual bundle inputs and records the unused file explicitly.

Raw results/profile archive SHA-256: cc83f499372d77b827a4ab5bd04a575ac960d1aff9f7ab749ee4f36061b33afb. Dedicated Testbox workflow; exact-head CI. The benchmark command exited 0 in 211 seconds.

Native review compared current main 5de1376b7f62: none of the five changed files differ from the benchmark baseline. Its newer retained-history optimization touches separate modules.

Packaged stable upgrade and landing gates

The existing published-upgrade-survivor Docker lane passed from stable 2026.7.1-2 to the candidate tarball; build info confirms exact commit bd2175131d4c9e1f6c8cd450eab6c4d11ce9ba39. It preserved 4,800 sessions, 1,227,946 events and 10,000 cron jobs. Automatic migration passed immediately after the update, before the standalone Doctor check. All survival assertions passed; eight Gateway history samples (600 messages across two agents) remained identical after restart. Repeat Doctor completed in 38 seconds within its 60-second budget. The lane took 505 seconds; build/package/test command took 779 seconds.

The test uses an explicit candidate tarball, manual Gateway restart and expected synthetic plugin-capability consent. It verifies automatic data migration, not unattended update-channel switching. The volume fixture uses v3 transcript headers; legacy-format performance is proved separately by the paired imports.

Docker proof archive SHA-256: a43f5670e25aac4d70511df27dd1d77b948cc0881c4a44b045b3185911b23942. The dedicated worker has been stopped after artifact collection.

Exact-head CI is green, and native preparation accepted the same tested commit without a rebase or additional push. The latest ClawSweeper review (2026-08-31 01:36 UTC) has no source correctness/security finding or rank-up moves; its incomplete-CI concern is resolved by the completed exact-head run and native gates. Maintainer handling proceeds under the requested performance-pass-and-land workflow.

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

clawsweeper Bot commented Aug 31, 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 31, 2026
@steipete
steipete marked this pull request as ready for review August 31, 2026 01:19
@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, 9:36 PM ET / August 31, 2026, 01:36 UTC.

ClawSweeper review

What this changes

The PR reuses compilation of the SQLite transcript-identity query within each synchronous session-import append batch while retaining fresh per-event reads.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for ordinary maintainer handling. The prepared reader is batch-local, rebinds each event ID, and still executes a fresh lookup after each append; no introduced correctness or security defect was found.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation is focused and source-consistent, with substantial supplied benchmark and parity evidence awaiting normal exact-head gate completion.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: This maintainer-associated internal performance PR is exempt from the external contributor proof gate; its body supplies before/after Linux import timings and storage-parity evidence for the changed batch append 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-associated internal performance PR is exempt from the external contributor proof gate; its body supplies before/after Linux import timings and storage-parity evidence for the changed batch append path.
Evidence reviewed 5 items Introduced batch reader: The introduced cursor retains a prepared identity-reader closure only for the append batch and invokes it for every event before deciding whether to skip a duplicate.
Prepared-query contract: The shared helper compiles once, maps bindings anew for each invocation, and executes the compiled query with those invocation-local parameters.
Import owner and existing coverage: The importer sends staged unseen events through the batch append owner, and its focused test covers repeated incoming identities plus a full idempotent rerun with the expected stored rows and identities.
Findings None None.
Security None None.

How this fits together

Session imports append historical events to an agent’s SQLite transcript store. Identity lookups decide whether an event is already present before the event, its parent relationship, and sequence metadata are written.

flowchart LR
A[Session history import] --> B[Transcript append batch]
B --> C[Prepared identity lookup]
C --> D{Event already stored?}
D -->|Yes| E[Skip duplicate]
D -->|No| F[Write event and identity]
F --> G[SQLite transcript store]
Loading

Decision needed

Question Recommendation
Should this maintainer-owned session-import CPU optimization merge after exact-head CI completes green? Merge after exact-head gates: Merge the current head once the final required checks confirm the demonstrated import parity and performance result.

Why: The protected maintainer label requires explicit maintainer handling even though the source review found no patch defect.

Before merge

  • Resolve merge risk (P1) - The supplied check rollup is incomplete and truncated, so normal exact-head CI and merge-gate verification remain necessary before landing.
  • Complete next step (P2) - This protected maintainer-associated PR has no mechanical repair to dispatch and should follow ordinary exact-head merge review.
Agent review details

Security

None.

PR surface

Source +18. Total +18 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 5 43 25 +18
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 5 43 25 +18

Review metrics

Metric Value Why it matters
Production vs test LOC production +18 net; tests 0 The net production growth is the batch-local prepared identity reader and its relocation; no behavior test was changed.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the batch-local prepared reader and land it after exact-head checks confirm the supplied import parity and performance evidence.
  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 batch-local prepared reader and land it after exact-head checks confirm the supplied import parity and performance evidence.

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

Not applicable: this is a performance optimization, not a report of broken behavior. The supplied before/after import evidence and source-level parity coverage are the relevant verification path.

Is this the best way to solve the issue?

Yes. Reusing compilation at the synchronous batch owner mirrors the existing prepared write/update cursor pattern while preserving fresh database reads for every identity check.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 67433ff43813.

Labels

Label justifications:

  • P3: This is a bounded internal CPU optimization with preserved import semantics and no new user-facing surface.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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-associated internal performance PR is exempt from the external contributor proof gate; its body supplies before/after Linux import timings and storage-parity evidence for the changed batch append 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)

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-31T01:26:18.229Z sha bd21751 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit fde8802 into main Aug 31, 2026
321 of 322 checks passed
@steipete
steipete deleted the codex/importer-performance-pass-eleven branch August 31, 2026 01:46
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
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: 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