Skip to content

improve: speed up large history upgrades and Doctor checks - #133068

Merged
steipete merged 1 commit into
mainfrom
codex/migration-performance
Aug 30, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/migration-performance

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large stable-to-main upgrades spend unnecessary time importing transcript events and checking already healthy histories. Doctor opens SQLite twice per session across its header and label passes; the importer repeats session-root, generation and next-sequence setup for every event even inside one synchronous batch.

Why This Change Was Made

Doctor now owns one read-only connection per agent store and pass. Each session's iterators finish before the existing guarded repair transaction, so later reads see newly committed data. Detection still parses every required event, retains full snapshots for positive repairs, rejects concurrent changes and isolates malformed histories.

The transcript store owns a private cursor for the existing synchronous batch append. Root/generation setup and the first sequence lookup happen once; successful inserts advance the cursor. The importer streams its staged events through that same owner and records byte deduplication only after an insertion succeeds. Each attempted event still updates window recency before identity rejection. Single appends retain their existing callback behavior.

No schema, index, config, transaction boundary, locking, retention or recovery contract changes. Exact SQLite handoffs remain separate and preserve original bytes. Existing array-based fork/reset/recovery callers share the batch owner. Production delta is +42 lines; tests +58. The growth provides bounded streaming insertion feedback and private batch state, avoiding a second importer-specific write path or an escaping appender callback. Duplicate projection scheduling branches were folded into one common tail.

User Impact

Large upgrades and repeated Doctor checks complete faster with the same migration checks, archives, timestamps, duplicate handling and runtime history. No new setting or operator action is required.

Evidence

Focused reader benchmark, 20,000 sessions / 500,000 events, same canonical SQLite schema and data, three runs (median):

Pass Before After
Header detection 9.048 s 0.519 s
Label detection 9.349 s 1.293 s

These isolate the readers; they are not whole-upgrade timings. The label probe parses all events with a no-repair predicate, so it measures connection/query/parsing costs without the normalizer's extra work.

A real 10,001-event import executes 160,033 SQL operations before and 120,033 after. The 40,000 eliminated operations are repeated root/generation/sequence setup; all 10,001 window updates remain. Quiet, interleaved fresh-process measurements (three pairs per scenario, Node 26.8.1) show:

Real importer scenario Rows Before median After median Time reduction
Deep linear 10,001 1.785 s 1.425 s 20.2%
Wide 10,100 1.818 s 1.519 s 16.5%
Branched 10,200 2.471 s 2.042 s 17.4%

Every paired candidate run was faster; these are focused importer timings, not whole-upgrade timings.

Focused verification: 176 tests passed across seven files: importer, active/context projections, Doctor headers/labels, migration memory and the broader session accessor suite (including concurrent writers, reset/lifecycle and recovery). Coverage includes an append-abort rollback, source revalidation, mixed existing/duplicate/new events, exact bytes and timestamps, unchanged generation, final rejected-duplicate recency, later-session visibility, malformed histories, Unicode-escaped labels and shared stores. Existing batch and 100,000-event branched imports completed under a 256 MiB JavaScript heap with exact-byte, projection and rerun checks.

Matched Docker proof on the same Blacksmith Testbox (tbx_01m18cvvdk3kn4wsp9vpwab35v, holder run): published stable 2026.7.1-2 to baseline 5d07c11ccef2755ca569082b7c278f5eeb5bf67b, then that same baseline plus this exact reviewed patch. The full source diff SHA-256 was checked before packaging. Both runs passed with 20,000 sessions, 497,750 events, 10,000 cron jobs and 512 released SDK state records.

Docker measurement Before After
Complete lane, excluding package build 401 s 329 s
Update command 178.868 s 139.773 s
Repeated Doctor invocation 31 s 20 s
Gateway startup 8 s 8 s

The complete lane used 18% less time; the update command used 22% less, and repeated Doctor used 35% less. These are one paired end-to-end run, not a universal latency guarantee. Automatic migration is asserted before any standalone Doctor or fixture capability consent. Full row checks run five times, including after repeated Doctor and restart. Eight real Gateway session/history samples (144 messages) retain identical hashes across all four before/after/restart probes. Integrity, archives, pairing/workspace data and budgets are unchanged. Fixture plugin capability consent remains explicit; this does not claim background stable-to-main channel switching.

Reproduction uses OPENCLAW_DOCKER_ALL_LANES=published-upgrade-survivor, OPENCLAW_UPGRADE_SURVIVOR_BASELINE_SPECS=2026.7.1-2, OPENCLAW_UPGRADE_SURVIVOR_SCENARIOS=sqlite-volume, and volume knobs SESSIONS=20000, EVENTS_PER_SESSION=25, CRON_JOBS=10000 under the OPENCLAW_UPGRADE_SURVIVOR_VOLUME_ prefix with node scripts/test-docker-all.mjs.

Committed-head deep Docker proof also passed: 4,800 sessions / 1,227,946 events / 10,000 cron jobs / 512 released SDK records in 562 seconds, with five exhaustive row checks. Repeated Doctor took 40 seconds (unchanged 60-second budget), startup 11 seconds. Eight Gateway samples (600 messages, bounded to the normal history page size) retained identical hashes across restart; API probe times were 6.619 and 6.745 seconds. The packed build-info commit is exactly c6ebf69c94eb4415f5a2120fb92567456e203acc. Blacksmith Testbox tbx_01m18ebmqmzkjdxfbxfw3hwap8, holder run; same Docker command with volume settings 4800/257/10000. Both Testbox leases were stopped after evidence capture. Exact-head hosted CI completed successfully on c6ebf69c94eb4415f5a2120fb92567456e203acc, including all production/test types, tests and required CI gate.

Local production typecheck and repository guards passed. The aggregate test typecheck encountered the pre-existing shared dependency mismatch in ui/vite.config.ts (installed pako lacks the expected declarations); no dependency workaround was added. Fresh hosted CI subsequently passed the production and test typechecks and aggregate CI gate on the PR head.

After the final scheduling simplification, the 22 importer/active-projection tests and a fresh review passed again.

Independent Codex autoreview: no accepted/actionable P0 findings. This is a P0-scoped review, not a broader correctness certificate.

Separate follow-up: branch-heavy FTS rebuilds still scan their unindexed session field. This change does not alter index design or claim to resolve #119884's planner-statistics report. Existing native stable auth-credential retention work in #129689 also remains outside this change.

ClawSweeper review and Rank-up moves addressed: the declared committed-head million-event upgrade and exact-head hosted CI both passed. The review found no actionable correctness/security issue; maintainer-requested landing proceeds with the existing schema and persistence contracts unchanged.

@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 size: M maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 04:20
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. 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, 12:27 AM ET / 04:27 UTC.

ClawSweeper review

What this changes

This PR reuses one read-only SQLite connection per Doctor pass and batches transcript imports to avoid repeated setup during large history upgrades.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open. This member-authored, maintainer-labeled PR remains necessary: current main still performs the repeated per-event and per-session work the branch removes, and no introduced correctness defect was found in the transcript-state paths reviewed.

Priority: P2
Reviewed head: c6ebf69c94eb4415f5a2120fb92567456e203acc

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has coherent owner-boundary design and focused invariant coverage, with the declared exact-head high-volume validation still appropriate before merge.
Proof confidence 🌊 off-meta tidepool Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its body nevertheless supplies a linked released-baseline Docker upgrade run covering persisted rows, repeated Doctor, restart, and Gateway history samples.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its body nevertheless supplies a linked released-baseline Docker upgrade run covering persisted rows, repeated Doctor, restart, and Gateway history samples.
Evidence reviewed 6 items Introduced batch owner preserves write invariants: The shared cursor initializes the transcript root and generation once, updates window recency for every attempted event, advances sequence only after insertion, and schedules one final projection reconciliation.
Importer only marks source bytes after successful append: The generator receives insertion feedback before recording its staging deduplication entry, retaining the prior retry and rollback behavior.
Focused regression coverage: The updated importer test covers append abort rollback, exact bytes, identity deduplication, rejected-duplicate recency, generation stability, and rerun idempotence; the Doctor test covers observing a later committed session during an earlier repair.
Findings None None.
Security None None.

How this fits together

Doctor scans agent SQLite transcript histories for repairs, while the session importer writes recovered history into the canonical agent database. Both paths feed the persisted transcript and derived session projections.

flowchart LR
  A[Legacy session history] --> B[Doctor transcript scan]
  B --> C[Read-only SQLite connection]
  C --> D[Guarded repair transaction]
  A --> E[SQLite session importer]
  E --> F[Batch transcript append]
  D --> G[Canonical transcript store]
  F --> G
  G --> H[Session projections]
Loading

Before merge

  • Resolve merge risk (P1) - The batch path changes persisted transcript sequencing, identities, recency, and projection scheduling during upgrades; complete the PR's declared exact-head high-volume and hosted-CI validation before merging.
  • Complete next step (P2) - No concrete repair is needed; complete normal exact-head validation before merge.
Agent review details

Security

None.

PR surface

Source +42, Tests +58. Total +100 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 6 157 115 +42
Tests 2 70 12 +58
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 227 127 +100

Review metrics

Metric Value Why it matters
Production vs test delta production +42, tests +58 The production growth is confined to one canonical streaming batch owner; the tests add rollback, deduplication, recency, and interleaved-repair coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-sqlite-transcript-readers.ts, migration/backfill/repair: src/commands/doctor-session-transcript-headers.ts, migration/backfill/repair: src/commands/doctor-session-transcript-labels.ts, serialized state: src/config/sessions/session-accessor.sqlite-import.ts, unknown-data-model-change: src/commands/doctor-session-sqlite-transcript-readers.ts, unknown-data-model-change: src/commands/doctor-session-transcript-labels.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Complete exact-head upgrade validation (recommended)
    Run the declared high-volume released-baseline scenario and allow the exact-head hosted checks to finish before merging the changed persistent-state path.

Technical review

Best possible solution:

Land the single transcript-store-owned batch path after exact-head upgrade proof confirms preserved rows, identities, projections, and rerun behavior on a released baseline.

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

Not applicable: this is a performance refactor, with the PR body supplying benchmark and released-baseline upgrade evidence rather than a discrete failing report.

Is this the best way to solve the issue?

Yes. Moving the batching cursor into the transcript-store owner avoids a parallel importer-specific append implementation while preserving the existing single-append behavior and state invariants.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded performance and upgrade-safety improvement to session persistence paths.
  • add merge-risk: 🚨 compatibility: Doctor and importer changes run against existing agent SQLite stores during upgrade and repair flows.
  • add merge-risk: 🚨 session-state: The batch path controls persisted transcript event order, deduplication, recency, and derived projections.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This repository-member PR is exempt from the external-contributor proof gate; its body nevertheless supplies a linked released-baseline Docker upgrade run covering persisted rows, repeated Doctor, restart, and Gateway history samples.

Label justifications:

  • P2: This is a bounded performance and upgrade-safety improvement to session persistence paths.
  • merge-risk: 🚨 compatibility: Doctor and importer changes run against existing agent SQLite stores during upgrade and repair flows.
  • merge-risk: 🚨 session-state: The batch path controls persisted transcript event order, deduplication, recency, and derived projections.
  • 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: This repository-member PR is exempt from the external-contributor proof gate; its body nevertheless supplies a linked released-baseline Docker upgrade run covering persisted rows, repeated Doctor, restart, and Gateway history samples.

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.

  • Complete the declared 1.2-million-event released-baseline run and exact-head hosted CI 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.

@steipete
steipete merged commit 65beb1e into main Aug 30, 2026
314 of 315 checks passed
@steipete
steipete deleted the codex/migration-performance branch August 30, 2026 04:37
@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

commands Command implementations maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

Agent/session DB migration doesn't ANALYZE → stale planner stats → 15s session ops + 30-57s event-loop starvation on large stores

1 participant