Skip to content

improve: speed up legacy session transcript imports - #133496

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

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

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133446

What Problem This Solves

Large legacy-session upgrades spend time parsing modern-format JSONL histories twice inside the import reader and repeatedly constructing synthetic two-row files just to classify individual events.

Why This Change Was Made

The reader now stops planning at the first version-2-or-newer header: only version 1 needs original-row compaction targets before migration. Newer files enforce the same 100,000-distinct-target limit during streaming. Runtime loading and migration share a single-row classifier instead of rebuilding a temporary partition for every event.

Version-1/headerless planning, original-index links, header canonicalization, hook normalization, opaque-row preservation, file fingerprints, accepted-row deduplication, and canonical transaction boundaries remain intact. A malformed newer-file tail may reach the disposable staging spool before failing; all source reads and revalidation still finish before any canonical write. There are no schema, SQL, index, configuration, dependency, concurrency, retention, or durable data-format changes.

User Impact

Less parsing and allocation during session migration, with the same imported data and failure limits. Version-1 histories retain their required planning pass. In isolated Linux measurements, median complete JSONL-to-SQLite import time fell 7.8% for deep histories, 11.1% across many sessions, and 14.5% for repeat imports. Branching results varied between runs, so no reliable branching speedup is claimed.

Evidence

  • 53 focused tests passed: codec compatibility, SessionManager persistence, version-1 IDs/compaction links, import rollback/deduplication/exact handoff/source revalidation, eight reader boundary cases, and four actual Doctor import/revalidation cases.
  • New reader coverage protects versions 1/2/3/4, malformed and duplicate headers, recognized versus opaque custom hooks, unknown plugin payloads, malformed messages, target-limit rejection during prefix recovery, and strict/prefix handling of malformed tails.
  • Fresh full-priority Codex autoreview of the complete candidate found no actionable issues. Formatting, scoped lint, and completed changed guards pass. The local aggregate typecheck encounters six pre-existing shared-install tslog declaration errors in unchanged src/logging/logger.ts; the shared dependency tree was not modified. Clean exact-head CI passed, including the complete typechecks.
  • Isolated Linux Node 24 paired JSONL-to-SQLite benchmarks completed at 609db0dda18918d610df3b5f80a0032ddda3961a against 16421ec0b0b3f55d00b1ad1d65dff8774bcb1bdb. Packaged stable-upgrade proof passed on the same commit; details below.
  • Production: +44/-37 (net +7). Tests: +105. The remaining production lines preserve the existing target limit in the streaming pass while eliminating the redundant modern-format planning scan; both consumers reuse the same classifier and target validation remains in one helper.

Local commands: node scripts/run-vitest.mjs src/commands/doctor-session-sqlite-readers.test.ts src/config/sessions/session-accessor.sqlite-import.test.ts src/agents/sessions/session-manager-codec.test.ts src/agents/sessions/session-migrate-id-dedup.test.ts src/agents/sessions/session-manager.test.ts; node scripts/run-vitest.mjs src/commands/doctor-session-sqlite.test.ts --testNamePattern 'repairs legacy transcript|aborts import when|aborts a batch|imports and validates legacy'; node scripts/check-changed.mjs -- src/agents/sessions/session-manager-codec.ts src/commands/doctor-session-sqlite-readers.ts src/commands/doctor-session-sqlite-readers.test.ts.

Complete file-import measurements

Blacksmith Testbox run, Node 24.19.0 / SQLite 3.53.3. Five fresh processes per side per shape; pair order alternates. Both variants share all other source/dependencies and stable synthetic JSONL fixture paths, including version-1 ID derivation. Fixture generation and verification are outside the import timer.

Shape Before median After median Wall change CPU change
100k events, one history 6377.9 ms 5877.3 ms -7.8% -7.1%
100 sessions × 100 events 769.2 ms 683.8 ms -11.1% -6.9%
100 branching histories 1110.2 ms 1150.7 ms +3.6% +4.3%
10k existing events, repeat import 193.0 ms 165.0 ms -14.5% -20.0%
10k version-1 events 708.2 ms 693.4 ms -2.1% -3.3%
10k version-2 events 669.0 ms 624.0 ms -6.7% -5.8%

The initial branching result was 3.6% slower. An eight-pair follow-up with balanced starting order instead measured 4.4% faster wall time and 4.9% less CPU. These small movements are not consistent enough for a branching performance claim; neither result is hidden. Version-1 movement is also modest and retains the required full planning pass.

All 38 paired data digests match across exact transcript bytes, identities, window metadata, active positions, projection watermarks, and FTS. A separate 10k-event trace retains 100,034 SQL calls across the same 34 shapes. Separate before/after Node CPU profiles completed; timing samples were unprofiled.

ClawSweeper’s final-head review found no actionable code issues. Its rank-up request—confirm exact-head CI and inspect the latest review—is satisfied. The stored-data heuristic names the migration-reader path; this diff changes no schema, SQL, indexes, durable shape, or canonical write boundary. Data parity is verified above, and the packaged upgrade proof below passed.

Packaged upgrade and memory

Packaged Docker upgrade from stable 2026.7.1-2 to the exact candidate 609db0dda18918d610df3b5f80a0032ddda3961a 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 39 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 Testbox command exited successfully in 13m15s. Proof and CPU profiles were collected and checksum-verified, then the worker was stopped.

Median process peak RSS (KiB), before → after: deep 551,500 → 523,824; wide 405,404 → 405,716; branching 414,112 → 414,436; replay 455,672 → 401,376; v1 400,968 → 404,048; v2 409,064 → 397,180. These are process peaks, not isolated importer allocations; no universal memory-reduction claim is made.

@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 commands Command implementations agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete steipete self-assigned this Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 20:11
@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 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, 4:25 PM ET / 20:25 UTC.

ClawSweeper review

What this changes

The branch avoids a redundant planning pass for version-2-and-newer legacy JSONL session imports and reuses a per-row classifier between Doctor import and runtime loading.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

No introduced correctness defect was found. This PR remains open because it is maintainer-authored and carries the protected maintainer label; current main does not contain the optimization, and final merge-gate status still needs maintainer confirmation.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch cleanly preserves the existing versioned import boundary and adds focused coverage; final landing still requires exact-head gate confirmation.
Proof confidence 🌊 off-meta tidepool Not applicable: The PR is maintainer-authored, so the external-contributor proof gate does not apply; its supplied benchmark and focused import evidence are supplemental.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The PR is maintainer-authored, so the external-contributor proof gate does not apply; its supplied benchmark and focused import evidence are supplemental.
Evidence reviewed 6 items Shared classification preserves the runtime rule: The extracted classifier performs the same legacy-hook normalization and recognized-entry test used by runtime partitioning; the partitioner now delegates to it.
Importer retains the versioned compaction boundary: The import reader preplans only version 1, where migration resolves original row indexes; version 2 and later enforce the existing distinct-target limit while streaming before rows reach the import consumer.
Caller keeps staging separate from canonical writes: Doctor supplies the transcript reader to the import operation after malformed-source classification and fingerprint capture; import tests verify rollback and staging cleanup on failure.
Findings None None.
Security None None.

How this fits together

Doctor reads legacy JSONL session transcripts, normalizes recognized rows, preserves opaque rows, and stages them for SQLite import. Runtime session loading uses the same codec rules to distinguish valid session entries from opaque persisted data.

flowchart LR
  A[Legacy JSONL transcript] --> B[Import planning]
  B --> C[Shared row classification]
  C --> D[Versioned migration]
  D --> E[SQLite staging and commit]
  F[Runtime session loader] --> C
Loading

Decision needed

Question Recommendation
Should this protected maintainer PR be landed once the exact-head checks and prior ClawSweeper rank-up requirements are confirmed? Confirm gates and land: Confirm the complete exact-head check rollup and prior rank-up state, then proceed with normal maintainer landing.

Why: Repository policy keeps maintainer-authored and maintainer-labeled items out of automated closure; the available source review finds no code blocker, but the final gate evidence is incomplete.

Before merge

  • Resolve merge risk (P1) - Exact-head merge readiness cannot be independently confirmed from the supplied truncated check rollup and omitted detailed text of the latest ClawSweeper rank-up comment.
  • Complete next step (P2) - A maintainer must resolve the protected-item landing gate and confirm the incomplete exact-head evidence; no mechanical repair is indicated.
Agent review details

Security

None.

PR surface

Source +7, Tests +105. Total +112 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 44 37 +7
Tests 1 105 0 +105
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 149 37 +112

Review metrics

Metric Value Why it matters
Production versus test delta production +7 net; tests +105 The small production increase extracts one shared classifier and retains the target-limit check while adding focused version and malformed-input coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-sqlite-readers.ts, unknown-data-model-change: src/commands/doctor-session-sqlite-readers.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the single shared classifier and version-specific planning boundary, then land only after a maintainer confirms the exact-head required checks and prior rank-up state.
  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 single shared classifier and version-specific planning boundary, then land only after a maintainer confirms the exact-head required checks and prior rank-up state.

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

Not applicable: this PR is a performance optimization rather than a report of a current failing behavior. The affected versioned import path is source-traceable and has focused coverage.

Is this the best way to solve the issue?

Yes. The migration code only needs precomputed future row targets for version 1; extracting the existing row-classification rule avoids the prior synthetic two-row partition allocation without adding a parallel import policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P3: This is a bounded performance improvement to a legacy import path, with no demonstrated 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: The PR is maintainer-authored, so the external-contributor proof gate does not apply; its supplied benchmark and focused import evidence are supplemental.

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)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm the complete exact-head CI rollup and the latest ClawSweeper rank-up requirements before merge.

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-30T20:18:55.566Z sha 609db0d :: needs maintainer review before merge. :: none

@steipete
steipete merged commit c2e2484 into main Aug 30, 2026
335 of 336 checks passed
@steipete
steipete deleted the codex/importer-performance-pass-seven branch August 30, 2026 20:38
@steipete

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

agents Agent runtime and tooling commands Command implementations 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