Repository navigation
improve: speed up session projection indexing with less code - #133802
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 31, 2026, 3:02 AM ET / 07:02 UTC. ClawSweeper reviewWhat this changesThis 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 Merge readinessKeep 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 Review scores
Verification
How this fits togetherSession 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]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -17, Tests +43, Other +19. Total +45 across 5 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
0637c25 to
405de2e
Compare
|
Merged via squash.
|
…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
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:
Scoped type-aware lint and formatting passed:
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-existingLogger.attachTransport/settingserrors in unchangedsrc/logging/logger.ts; this worktree's shared dependency tree lackstslog/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.
Linux performance and data parity
Blacksmith Testbox run 33358682180, Node 24.19.0 / SQLite 3.53.3, benchmark revision
0637c2537a71dd5c84d5e06974b7088542f5f3ddversus baselineee036be7796396868bfa4851210e66c17bb2a25c. 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.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.1exposed four concrete harness defects during real packaged runs. The repairs are confined to test setup and capability detection:dmPolicy/allowFromthere while preserving the historical spelling for older baselines, including v2026.2.1. Matrix's separate nested-DM contract is unchanged.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:
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:
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.mjsselects 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.