Skip to content

improve: speed up session projection indexing with less code - #133802

Merged
steipete merged 6 commits into
mainfrom
codex/importer-performance-pass-thirteen
Aug 31, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/importer-performance-pass-thirteen

Conversation

@steipete

@steipete steipete commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large session imports still rebuild the same search/history query builders for every event after the preceding importer optimizations. This adds avoidable CPU work as histories grow.

Related: #133742 (streamline importer streaming and identity writes), #133403 (update existing transcript watermarks directly).

Why This Change Was Made

The transcript projection owner now prepares its FTS insert, active-history insert, and watermark writer once per synchronous append batch. The same insert factories serve full projection rebuilds. Moving forward indexing into its batch owner also removes repeated database/session arguments and duplicated row types.

The first watermark write still upserts; subsequent batch writes still update. Branch selection, dirty-state transitions, timestamps, write ordering, and synchronous transaction ownership are unchanged. No schema, index definition, retention, configuration, dependency, or persistence-semantic change.

Production LOC: +104 / -121, net -17. Upgrade harness: +63 / -44, net +19. Regression tests: +167 / -124, net +43, including table reformatting. Total: +45 across five files. The importer shrinks; harness growth repairs reproduced setup/coverage defects, and the tests protect those contracts. No new parser, raw-SQL path, or cache owner.

User Impact

Imports and history-index rebuilds spend less CPU building identical SQL queries. Existing session data and search/history results remain unchanged. On Linux, 100,000-event imports improve from 4,950.4 ms to 3,841.9 ms (22.4%), with 24.2% less CPU. Wide and branching histories improve about 19%; replay is approximately unchanged.

Evidence

  • 338 tests passed in 10 files, including importer idempotence/source revalidation, session conformance, append/replacement, branch forks and cuts, eligibility/reconcile recovery, projection behavior, and Kysely binding/cache contracts:

    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 src/config/sessions/session-transcript-projection-rebuild.test.ts src/commands/doctor-session-sqlite.test.ts
  • Scoped type-aware lint and formatting passed:

    node scripts/run-oxlint.mjs --type-aware --tsconfig config/tsconfig/oxlint.core.json src/config/sessions/session-transcript-index.ts
    node_modules/.bin/oxfmt --check src/config/sessions/session-transcript-index.ts
  • Independent Codex autoreview: scoped-clean through P3, including a fresh post-rebase pass supplied with the complete projection owner, import caller, shared executor, and binding/cache tests (confidence 0.96). Repeated markers, fresh values, error reporting, authorizers, and re-entry isolation checked.

  • node scripts/check-changed.mjs: structural gates, all three Knip scans, and core graph boundary passed. Local core typecheck remains blocked by six pre-existing Logger.attachTransport/settings errors in unchanged src/logging/logger.ts; this worktree's shared dependency tree lacks tslog/types/BaseLogger.d.ts. Shared dependencies were not modified. Exact-head hosted checks are required before landing.

  • Exploratory 20,000-event baseline/candidate runs preserved the full stored-data digest; local wall times were contended and are not used as a speed claim.

  • Both unchanged 256 MiB heap stress tests passed on Linux (batch 15.955s; deep 19.602s), bringing focused coverage to 340 passing tests across 11 files. The local wide case passed, but the deep case hit its unchanged 180-second timeout while its child was observed in uninterruptible wait with about 21 seconds of CPU consumed. The failure did not reproduce on clean Linux; neither test nor timeout changed.

    node scripts/run-vitest.mjs src/commands/doctor-session-sqlite.memory.test.ts

Linux performance and data parity

Blacksmith Testbox run 33358682180, Node 24.19.0 / SQLite 3.53.3, benchmark revision 0637c2537a71dd5c84d5e06974b7088542f5f3dd versus baseline ee036be7796396868bfa4851210e66c17bb2a25c. The benchmark overrides only the changed projection owner; build metadata verifies that it is loaded, and all other sources/dependencies are identical. Fresh processes, alternating order, five pairs per shape. Fixture generation and parity checks are outside the import timer.

Shape Baseline median Candidate median Less time Less CPU
single 8.9 ms 8.5 ms 4.5% 4.7%
deep 4950.4 ms 3841.9 ms 22.4% 24.2%
wide 545.0 ms 441.2 ms 19.1% 16.0%
branch 927.5 ms 752.2 ms 18.9% 17.0%
replay 162.8 ms 162.5 ms 0.2% 7.4%
legacy-v1 534.2 ms 447.1 ms 16.3% 17.6%
legacy-v2 480.2 ms 372.9 ms 22.3% 22.5%
legacy-metadata-v1 262.1 ms 181.4 ms 30.8% 27.7%
legacy-hooks-v2 401.4 ms 312.5 ms 22.1% 17.1%

All 45 pairs have identical hashes of transcript JSON/timestamps, identities, session windows, active positions/eligibility, index state, and FTS rows. All five deep-history pairs favor the candidate. The SQL trace retains exactly 100,034 calls across 34 shapes with no count differences, so the improvement removes query construction rather than storage work or validation.

Eight import-region Node CPU profiles cover deep, wide, legacy-v1, and legacy-hooks-v2 before/after. Deep Kysely self samples fall from 773.7 ms to zero sampled time (not a claim of literally zero setup cost); wide falls 93.4 → 25.8 ms, legacy-v1 76.7 → 1.1 ms, hooks 52.4 → 1.1 ms. This supports the query-compilation attribution; headline timings come from unprofiled runs.

Peak RSS is mixed: deep median 479.8 → 444.4 MiB, but legacy-v2 374.7 → 404.6 MiB and hooks 380.0 → 390.8 MiB. No general memory-reduction claim. Both bounded-heap suites pass.

Local proof artifacts: .artifacts/migration-cpu-profile/round13/ (harness, results, source hashes, commands, traces, eight profiles). Collected archive SHA-256: d17cfe5e354041a2449a71183e1fbe562ef011d11d626b081e3a444edf20b9e2.

Packaged upgrade and fixture compatibility

The first build hit an existing Control UI CSS budget failure (54,809 bytes versus the unchanged 54,784-byte limit). The branch consumes the already-landed #133787 repair through a mechanical rebase onto c2d1c256665119d7f441a4fe90cf3c29149983fd. No authored CSS change or budget bypass. The importer is byte-identical to the benchmarked revision; its surrounding session/importer, Kysely and agent-state owners did not change in the rebase. A fresh independent review and 38 repeated focused tests passed.

Latest stable 2026.8.1 exposed four concrete harness defects during real packaged runs. The repairs are confined to test setup and capability detection:

  • Modern config writes stamp explicit fleet ownership and reject the fixture's legacy default marker. The recipe removes it only for modern baselines; older releases keep the migration specimen and its ownership meaning.
  • Modern strict Discord CLI input rejects nested DM policy fields. The recipe uses canonical dmPolicy/allowFrom there while preserving the historical spelling for older baselines, including v2026.2.1. Matrix's separate nested-DM contract is unchanged.
  • Volume fixtures mixed the oldest shared-session layout with per-agent JSON. Latest stable leaves the original three sessions in the shared file during setup; candidate Doctor then merges and normalizes the volume store before SQLite archival. The volume seed now authors all sessions in per-agent JSON with canonical keys and matching transcript paths. Other scenarios keep the oldest shared-store specimen. This fixes the producer and leaves every baseline, SQLite and archive assertion unchanged.
  • Modern packages publish the dedicated plugin-state-store runtime without declarations. The former declaration-only check silently skipped 512 plugin rows. The harness now selects that explicit runtime export; older packages retain their typed Doctor contract, and broken declared imports/constructors still fail.

Real published-CLI negative controls reproduce the setup errors. All 13 adapted config commands pass. The extended seed test fails before the producer repair and passes after, verifying both layouts, exact keys, transcript paths and absence of the other store. Both new SDK fault cases fail before and pass after. All 48 upgrade assertion tests and 14 recipe tests pass, bringing distinct focused coverage to 402 passing cases, plus 38 post-rebase repeats. Scoped lint and formatting pass. Independent reviews through P3 found no actionable defects.

The corrected fixture also passes a complete small migration through the actual published 2026.8.1 CLI: 20 volume sessions, 90 events, 10 cron jobs and 512 plugin rows in schema 15, with every archive assertion intact. The previous large candidate run verified all canonical session/event, cron and plugin rows before revealing the seed/archive mismatch; it is recorded as failed, not counted as full upgrade success.

The full Docker upgrade passed on worker 33364788103, built from 8253ae205f6708391be1829d46e5e5912b790cb4: 4,800 sessions, 1,227,946 events, 10,000 cron jobs and 512 plugin rows. Automatic migration is asserted immediately after update and before standalone Doctor. All SQLite contents, original archive checks, pairing ownership and workspace data pass. Eight Gateway history samples (600 messages across two agents) match exactly after restart. Idempotence Doctor takes 42s against the unchanged 60s budget; startup 12s, health/readiness/status each 1s. The upgrade lane takes 551s; full build/run 955s. Collected proof archive SHA-256: 8565d0c9ba32f3264c5537452c47c5a7667324d3aff2a50b2e6f9b0ae09113e3.

Reproduction:

OPENCLAW_TESTBOX=1 OPENCLAW_TESTBOX_REMOTE_RUN=1 OPENCLAW_DOCKER_ALL_LANES=published-upgrade-survivor OPENCLAW_DOCKER_ALL_LOG_DIR=.artifacts/docker-tests/migration-round13-deep OPENCLAW_UPGRADE_SURVIVOR_BASELINE_SPECS=2026.8.1 OPENCLAW_UPGRADE_SURVIVOR_SCENARIOS=sqlite-volume OPENCLAW_UPGRADE_SURVIVOR_VOLUME_SESSIONS=4800 OPENCLAW_UPGRADE_SURVIVOR_VOLUME_EVENTS_PER_SESSION=257 OPENCLAW_UPGRADE_SURVIVOR_VOLUME_CRON_JOBS=10000 node scripts/test-docker-all.mjs

Limits: explicit candidate tarball, manual Gateway restart, and expected synthetic-plugin capability consent recovery. This proves automatic data migration during the package update, not unattended release-channel switching. Candidate identity guards and all budgets remain intact. All six task-owned Testbox leases are stopped.

Named follow-ups outside this importer/fixture change:

  • The generic cached Docker rerun-command generator omits the source SHA/version/hash tuple required by its registry validator. Supplying it correctly rejects dirty synchronized source identity; this proof uses a fresh committed build.
  • The published Discord reader normalizes shipped nested DM aliases, while strict CLI schema input rejects them first. Fresh modern setup uses canonical input; older upgrade coverage is preserved.

Final head: e7b7fe776e30d037431e2588145b5a9cd28716a5. Its only delta from the successful Docker build is a two-line test assertion/import fixing three TypeScript narrowing errors reported by hosted CI. The package and every harness file are byte-identical. Both affected test cases pass; review is clean through P3 (confidence 0.99). Exact-head CI 33366135987 is green, including test typechecking. The Docker proof is intentionally reused across this test-only change, rather than claiming the earlier build has the newer SHA.

Latest ClawSweeper review reviewed this exact head at 07:02 UTC and found no actionable code defects. Its wait-for-green Rank-up move is satisfied. The automated SQLite-table warning is a false positive: sqlite-volume-shared-state.mjs selects an existing published SDK factory to seed synthetic test rows; there is no DDL, table definition, schema, index, retention, concurrency or production persistence-semantic change. The runtime SQL trace is unchanged.

@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: M maintainer Maintainer-authored PR labels Aug 31, 2026
@steipete
steipete marked this pull request as ready for review August 31, 2026 04:55
@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 31, 2026, 3:02 AM ET / 07:02 UTC.

ClawSweeper review

What this changes

This PR prepares session transcript FTS, active-history, and watermark SQLite writes once per synchronous append batch, and updates upgrade-survivor fixtures for published baseline layouts.

Warning

SQLite table change

This PR modifies persisted SQLite tables in scripts/e2e/lib/upgrade-survivor/sqlite-volume-shared-state.mjs. Prefer a design that avoids changing persisted SQLite tables. Migration or upgrade compatibility proof is recorded, but maintainers should still confirm that the schema change is necessary.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this maintainer-owned PR open. Its central prepared-query optimization is not on current main, the introduced implementation preserves the existing synchronous batch ownership, and no concrete correctness or security defect was found; exact-head hosted checks are still running.

Priority: P3
Reviewed head: e7b7fe776e30d037431e2588145b5a9cd28716a5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative runtime refactor with strong captured validation and no supported correctness finding; hosted checks still need to finish on the exact head.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable to the contributor-proof gate because this is a maintainer-authored PR; the captured body nevertheless reports packaged Docker upgrade evidence for the session-storage path.
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 the contributor-proof gate because this is a maintainer-authored PR; the captured body nevertheless reports packaged Docker upgrade evidence for the session-storage path.
Evidence reviewed 6 items Introduced runtime change: The exact PR-introduced commit replaces per-event query construction with lazily retained prepared FTS, active-history, and update-watermark writers inside the synchronous appender.
Current-main comparison: Current main still uses the prior apply-forward path that builds its writes for each event, so the central optimization is not already implemented there.
Caller ownership: The transcript-store cursor creates one appender for the import batch, establishing the lifetime in which the PR retains the prepared writers.
Findings None None.
Security None None.

How this fits together

Session imports append transcript events and maintain SQLite search, active-history, and watermark projections in the same transaction. History and search readers consume those projections after import or a rebuild.

flowchart LR
  A[Transcript events] --> B[SQLite import transaction]
  B --> C[Projection appender]
  C --> D[Prepared statement bindings]
  D --> E[Full-text search index]
  D --> F[Active history]
  D --> G[Projection watermark]
Loading

Before merge

  • Resolve merge risk (P1) - The exact PR head still has an incomplete hosted-check rollup; do not merge until its required checks finish green.
  • Complete next step (P2) - No actionable repair was found; this maintainer-owned PR only needs its exact-head checks to complete before normal merge handling.
Agent review details

Security

None.

PR surface

Source -17, Tests +43, Other +19. Total +45 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 1 104 121 -17
Tests 1 167 124 +43
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 63 44 +19
Total 5 334 289 +45

Review metrics

Metric Value Why it matters
Production versus test delta production −17; upgrade test-support +19; regression tests +43 The runtime refactor is net-negative; added lines are confined to baseline-fixture compatibility and its coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: scripts/e2e/lib/upgrade-survivor/assertions.mjs, migration/backfill/repair: scripts/e2e/lib/upgrade-survivor/config-recipe.mts, migration/backfill/repair: scripts/e2e/lib/upgrade-survivor/sqlite-volume-shared-state.mjs, serialized state: scripts/e2e/lib/upgrade-survivor/config-recipe.mts, unknown-data-model-change: scripts/e2e/lib/upgrade-survivor/config-recipe.mts, unknown-data-model-change: scripts/e2e/lib/upgrade-survivor/sqlite-volume-shared-state.mjs. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Retain the owner-local prepared-query refactor and merge after exact-head hosted checks are green.
  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 owner-local prepared-query refactor and merge after exact-head hosted checks are green.

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

Not applicable: this is a performance refactor rather than a reported broken behavior. The captured PR evidence includes benchmark and packaged-upgrade results, but this read-only review did not rerun them.

Is this the best way to solve the issue?

Yes. Reusing the existing synchronous prepared-query helper in the appender’s batch lifetime removes repeated construction without adding a cache, schema change, or parallel write path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 366834c85cf4.

Labels

Label justifications:

  • P3: This is a bounded internal performance improvement without a reported user-facing regression.
  • 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 the contributor-proof gate because this is a maintainer-authored PR; the captured body nevertheless reports packaged Docker upgrade evidence for the session-storage path.

Evidence

What I checked:

  • Introduced runtime change: The exact PR-introduced commit replaces per-event query construction with lazily retained prepared FTS, active-history, and update-watermark writers inside the synchronous appender. (src/config/sessions/session-transcript-index.ts:312, 405de2e84b66)
  • Current-main comparison: Current main still uses the prior apply-forward path that builds its writes for each event, so the central optimization is not already implemented there. (src/config/sessions/session-transcript-index.ts:254, 366834c85cf4)
  • Caller ownership: The transcript-store cursor creates one appender for the import batch, establishing the lifetime in which the PR retains the prepared writers. (src/config/sessions/session-accessor.sqlite-transcript-store.ts:165, e7b7fe776e30)
  • Binding contract and sibling coverage: The existing synchronous helper compiles once and maps fresh parameter values for every invocation; its tests cover repeated bindings and synchronous callback re-entry, while session active-event tests cover dirty/rebuild projection outcomes. (src/infra/kysely-sync.ts:273, e7b7fe776e30)
  • History and routing: Recent merged session-index and import optimizations are attributed to steipete, making that account the strongest routing candidate for this owner surface. (src/config/sessions/session-transcript-index.ts:254, 3988315e8ce4)
  • Captured behavior evidence: The reviewed PR body reports a packaged Docker upgrade preserving SQLite state and Gateway history, plus focused projection and upgrade-fixture coverage; the contributor proof gate is exempt because the PR is maintainer-authored. (8253ae205f67)

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 the required hosted checks on e7b7fe7 to complete green before merging.

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 (6 earlier review cycles)
  • reviewed 2026-08-31T05:07:51.148Z sha 0637c2537a71dd5c84d5e06974b7088542f5f3dd :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T05:16:43.328Z sha 405de2e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T05:40:45.184Z sha 3165ac3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T06:02:28.485Z sha 36bae97 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T06:22:05.532Z sha b28bdcc :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T06:42:18.163Z sha 8253ae2 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/importer-performance-pass-thirteen branch from 0637c25 to 405de2e Compare August 31, 2026 05:09
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Aug 31, 2026
@steipete
steipete merged commit 12f2f9c into main Aug 31, 2026
242 checks passed
@steipete
steipete deleted the codex/importer-performance-pass-thirteen branch August 31, 2026 07:21
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 1, 2026
…w#133802)

* perf(sessions): reuse transcript projection writers per batch

* test(migration): adapt modern baseline agent ownership

* test(migration): canonicalize modern baseline Discord setup

* test(migration): verify modern baseline volume and plugin state

* test(migration): seed volume sessions at their import boundary

* test(migration): narrow seeded rows before transcript checks
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. scripts Repository scripts 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