Skip to content

perf(sessions): batch transcript index reconciliation - #173620

Merged
steipete merged 2 commits into
mainfrom
dbasync/indexrecon
Oct 16, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/indexrecon

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Transcript-index reconciliation spends hundreds of SQLite statements per maintenance chunk when an agent has thousands of session generations.

Related: #172985 and #172681.

User Impact

Background transcript-index maintenance uses fewer database commands while preserving immediate transcript-search freshness, bounded cleanup, and writer fairness. No schema migration, configuration change, or user action is required.

Why This Change Was Made

The existing writer-owned pending-session receipts already identify local changes. This change batches their classification and queue updates, and replaces per-session traversal commands with one bounded recursive index-seek query. It reuses the projection owner's readiness predicate, keeps the 128-session and 512-orphan-row budgets, and deletes the superseded per-session query loop.

A clean-status read no longer rereads the sibling-write revision afterward. Accepted edge case: a sibling write immediately after the read is observed through its receipt and the next maintenance pass. This is internal bookkeeping; search readiness and external-effect authority checks are unchanged.

The initial traversal and a sibling receipt still reconcile the owner state; subsequent local writes use the existing pending-session receipt path. No new generations, admission protocol, engine-specific search implementation, or durable bookkeeping store is added.

Evidence

  • Focused status tests: 10 existing cases passed, covering rollback/savepoints, writes behind the cursor, fairness under churn, sibling receipts, orphan bounds, and worker contention. The new bounded-batch regression also passed on the final source, including later transcript and classification writes.
  • Two Codex review rounds completed with no outstanding accepted finding. Hosted Codex review also completed without findings on the final head.
  • Indexed-query probe: all five candidate sources use covering-index searches; no persistent-table full scan. Classification uses the existing transcript, index-state, and unclassified-context indexes.
  • Type-aware core lint, formatting, and git diff --check pass. Exact-head CI passes, including production/test types, lint, Madge, source contracts, architecture guards, T1/dialect ratchets and changed Node tests. The required CI, dependency and security gates are green.
  • Explicit Knip export scans ran because ordinary PR CI omits that job. Script exports pass. Every production/full-tree finding matches the same file and export in scheduled main run 38832586414 at cedc5aeb4cc5; none is in the changed files. These are inherited under the campaign landing rule. All six alternating harness cells have completed.
  • Update/Doctor/schema/plugin-lifecycle cell and SDK API diff are not applicable: those contracts are unchanged.
Main-thread SQLite inventory Base Candidate
Reconciliation status worker 0 0
Shared transcript index module 6 6

The six shared-module sites remain for the supported synchronous SessionManager/SDK contract through December 31, 2026; their async API cutover is separate from this caller-only reconciliation change.

Synthetic reconciliation measurement Base Candidate
Cold production pass, all-thread statements 38,074 938
Cold direct owner, all-thread statements 38,074 937
Physical main b-tree row visits, scanstatus replay 60,049 50,720
TEMP b-tree row visits 221 221
Intermediate / virtual row visits 0 73,702
Writer chunks 73 73
Longest writer hold, ms (descriptive only) 273.76 9.89
Cold pass wall time, ms (descriptive only) 7,853.45 982.80
Cold / warm reconciliation MAIN statements 0 / 0 0 / 0
Clean repeat, all-thread statements 1 1
Reconciliation after an in-process append 13 12
Clean repeat after that reconciliation 1 1

Cold production reconciliation removes 97.54% of statements. The extra candidate production statement is a passive checkpoint outside the direct owner. Physical visits come from a separate read-only-main sqlite3_stmt_scanstatus replay; intermediate work is disclosed separately and is not a physical-table scan.

The synthetic fixture contains 4,763,052 transcript events, 9,329 nonempty generations, 8,564 logical sessions, 155,249 FTS rows and 84 aggregate planner-statistics rows. Database plus compressed reset is 7.80 GB. It models aggregate cardinalities and planner statistics, not the complete production payload-size distribution. No private rows or messages were copied. The fixture was deleted after measurement.

WAL bytes per independently committed assistant append (100 appends) Base Candidate
Total 125,866.0 125,783.6
FTS / shadow / ownership family 40,623.2 40,128.8
Index state 4,120.0 4,120.0
Active-event family 23,731.2 23,731.2

No append-WAL saving is claimed: small byte differences are consistent with UUID-related page splits. Actor statement counts remain 8 / 11 / 9 for metadata / assistant / tool appends. The standalone first-write driver has 8 lazy admission/watch MAIN statements on both versions; that is outside reconciliation and is not a warmed Gateway measurement.

Shared harness v3, three alternating pairs Base Candidate
First turn, causal SQL / requests / MAIN 228 [221–228] / 68 [64–69] / 0 [0–0] 227 [227–228] / 68 [68–68] / 0 [0–0]
First turn, raw SQL / requests 849 [817–1287] / 155 [152–155] 1002 [988–1003] / 161 [156–162]
Warm turns, causal SQL / requests / MAIN 75 [74–83] / 28 [27–31] / 0 [0–0] 75 [74–81] / 28 [27–30] / 0 [0–0]
Warm turns, raw SQL / requests / MAIN 75 [75–111] / 28 [27–35] / 0 [0–9] 75 [74–116] / 28 [27–35] / 0 [0–13]
Five-minute connected idle, SQL / requests / MAIN 102 [95–106] / 48 [45–49] / 0 [0–0] 103 [103–108] / 49 [47–51] / 0 [0–0]
Deferred warm work, SQL / requests / MAIN 0 [0–0] / 0 [0–0] / 0 [0–0] 0 [0–0] / 0 [0–0] / 0 [0–0]
Whole workload, SQL / requests 4598 [4597–4646] / 1158 [1155–1163] 4601 [4592–4618] / 1159 [1153–1160]
Warm index SQL / containing requests 13 [13–13] / 4 [4–4] 13 [13–13] / 4 [4–4]
Idle index SQL / containing requests 6 [6–6] / 5 [5–5] 6 [6–6] / 5 [5–5]
Idle memory SQL / containing requests 10 [10–10] / 4 [4–4] 10 [10–11] / 4 [4–5]

Values are median [min–max]. The order was M,C,M,C,M,C at baseline ffcb0a8cfa75f189abbbf425180907c797522767 and candidate 969ddfd51d3e96e112784d4a3c60b148b882fa38. Warm distributions pool 30 turns per version; other distributions contain three phase totals per version. Six complete runs passed, including foreground turns, RPCs, cron, child execution, compaction, restart and both shutdowns per run. Independent totals and request-ID joins agree with the shared analyzer; no failed SQL executions or prepares occurred.

Causal warm MAIN is zero throughout. Raw warm MAIN has occasional background lease-maintenance reads from openclaw-state-lease-store.ts; none belongs to the index owner. Index/memory request counts mean requests containing that family’s SQL, joined through the request ID and origin stack. A request may contain multiple families, so these counts are not additive.

Warm index operation, statements Base Candidate
Active-event inserts 3 [3–3] 3 [3–3]
Index-state writes 3 [3–3] 3 [3–3]
FTS maintenance 4 [4–4] 4 [4–4]
Reconciliation tracking 0 [0–0] 0 [0–0]

The remaining three index-related statements per warm turn are the latest active-boundary metadata read, visible-transcript statistics read, and transcript accounting snapshot read: one each on both versions. appendToIndex retains ten statements in three containing requests per warm turn on both versions.

Shared read family Warm base SQL / requests Warm candidate SQL / requests Workload base SQL / requests Workload candidate SQL / requests
Exact-entry facts 0 [0–0] / 0 [0–0] 0 [0–0] / 0 [0–0] 29 [28–29] / 29 [28–29] 29 [29–29] / 29 [29–29]
Actor hydration 0 [0–0] / 0 [0–0] 0 [0–0] / 0 [0–0] 6 [6–6] / 6 [6–6] 6 [6–6] / 6 [6–6]
Entry-cache snapshots 1 [1–1] / 1 [1–1] 1 [1–1] / 1 [1–1] 64 [62–65] / 51 [49–52] 63 [62–63] / 50 [49–50]
Row facts 2 [2–5] / 2 [2–4] 2 [2–4] / 2 [2–3] 84 [83–84] / 76 [75–76] 84 [83–84] / 76 [75–76]
Watermarks 0 [0–0] / 0 [0–0] 0 [0–0] / 0 [0–0] 4 [4–4] / 3 [3–3] 4 [4–4] / 3 [3–3]

Shared read families use explicitly recorded SQL signatures and source attribution for these v3 runs; their scope is not asserted identical to older census taxonomies.

Raw first-turn increases are startup redistribution, not added turn work. The agent-database schema owner emits exactly 142 statements across boot + connect + first turn in every run; 128 of those statements fall before the first-turn window in two baselines but inside it in every candidate. The agent-database owner and metadata totals are also unchanged across the combined window (14 and 8 statements respectively). Combined memory SQL is 409 in all six runs; combined index SQL is 51/52/52 on base and 51/52/51 on candidate. First-turn causal requests remain 68 at the median; the raw request difference is background submission timing.

Boot + connect + first turn Base SQL / requests Candidate SQL / requests
Pair 1 1832 / 268 1826 / 273
Pair 2 1838 / 271 1833 / 268
Pair 3 1836 / 276 1827 / 273

Whole-workload medians differ by +3 SQL (+0.065%) and +1 request (+0.086%); index and memory medians are unchanged at 354 and 499 statements. Idle medians differ by +1 SQL and +1 request from unchanged checkpoint/housekeeping timing. One candidate idle window includes one extra background loadMemorySourceFileState read, leaving its three-run median unchanged. All warm shared-read medians are unchanged; workload entry-cache snapshots fall from 64 to 63. No touched-owner regression is observed.

The six runs contain 84 successful foreground turns, 250 successful RPC records, six successful child runs and six successful cron runs. RPC record totals vary with successful cron.runs polling. The reported first-turn, warm-turn, boot and restart duration ratios stay below 1.5 (largest 1.362); observed pre-run host load ranges from 46.98 to 69.22 on 32 CPUs. These are count comparisons, not latency claims.

The host is heavily loaded. Fixture wall times and writer holds are descriptive; no latency improvement is claimed.

Scope follow-ups: the three per-turn index-state updates should be folded into the actor's existing append or turn-settlement transaction. FTS write amplification needs a separate measured change, beginning with engine-owned merge tuning or insert batching. Deferring FTS requires a durable backlog and a pending-search overlay to retain immediate freshness, so it is outside this no-schema change.

Change size: four files, +152/-53 lines, including regression coverage and storage documentation.

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T01:18:32.643273Z 969ddfd PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 16, 2026
@steipete steipete changed the title improve(sessions): reduce transcript index reconciliation work perf(sessions): batch transcript index reconciliation Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR batches transcript-index traversal, readiness classification, and pending-queue updates.

Example: Background maintenance encounters 96 dirty sessions named session-000 through session-095.

  • Before: Maintenance performs readiness checks and queue updates separately for each session.
  • After: Maintenance classifies and updates the sessions in batches while retaining the same dirty-session results.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch is coherent and exact-head CI is green; available evidence supports semantics more strongly than its performance benefit at scale.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied support covers SQLite owner tests and an indexed-query probe, while scale, writer-hold, WAL, and warm-turn measurements remain explicitly pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large session inventories make background transcript-index reconciliation issue hundreds of database commands per chunk.
Reason: The maintainer has selected this direction, and the focused change removes repeated work without expanding configuration, persistence, or public APIs.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-directed optimization preserves the existing reconciliation owner and bounds, adds distinct work absent from current main, and has no identified correctness defect.

Priority: P2
Reviewed head: 969ddfd51d3e96e112784d4a3c60b148b882fa38

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not include the pending production-scale and warm-turn comparisons or a recorded base-fail/head-pass run of the added regression.
Agent review details

How this fits together

The agent database's writer-owned maintenance worker consumes transcript changes and pending receipts, classifies projection readiness, removes bounded orphan rows, and returns sessions needing rebuild.

flowchart TD
  A[Transcript and projection writes] --> B[Transactional pending receipts]
  B --> C[Projection maintenance worker]
  D[Bounded session traversal] --> C
  C --> E[Shared readiness predicate]
  E --> F[Pending rebuild sessions]
  C --> G[Bounded orphan cleanup]
Loading

Technical review

Best possible solution:

Retain batching within the existing projection owner while preserving readiness, traversal progress, and bounded cleanup.

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

Current main visibly performs traversal, readiness, and pending-queue commands per session; source establishes the repeated work, but no performance benchmark was run during this read-only review.

Is this the best way to solve the issue?

Batching at the existing writer owner addresses repeated command overhead directly and reuses the canonical readiness predicate without adding persistent state or another maintenance path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5ae65452e5a0.

Provenance checked

  • Bounded traversal and transactional pending queue keeps the original intent (359eb9c: Avoid unbounded global projection-status scans while retaining rollback-safe pending facts, writer fairness, and bounded orphan cleanup.)
  • Shared projection readiness query keeps the original intent (a10773f: Consolidate readiness reads with the transcript owner and provide the same predicate to compound readers.)
  • Sibling-write revision observation changes intended behavior with a stated reason (1d76f57: Use Gateway-owned write receipts instead of repeated SQLite freshness probes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 359eb9c adds src/config/sessions/session-transcript-index-status.worker.ts:197 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 359eb9c88f67; files: src/config/sessions/session-transcript-index-status.worker.ts)

PR surface

Source +56, Tests +40, Docs +3. Total +99 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 105 49 +56
Tests 1 40 0 +40
Docs 1 7 4 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 152 53 +99

Review metrics

Metric Value Why it matters
Production versus test LOC Production +105/-49; tests +40/-0 The production growth implements bounded batch queries and queue updates while removing the superseded per-session loop; the test protects statement cost and readiness results.

Labels

Label changes:

  • add P2: This is a focused background-maintenance performance improvement for agents with large session inventories.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a focused background-maintenance performance improvement for agents with large session inventories.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Complete the declared base-versus-candidate measurements to confirm lower command cost without longer writer holds or deferred-work regressions.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 15, 2026, 9:30 PM ET / October 16, 2026, 01:30 UTC.

@steipete
steipete merged commit 2fabcd4 into main Oct 16, 2026
130 checks passed
@steipete
steipete deleted the dbasync/indexrecon branch October 16, 2026 01:37
vincentkoc added a commit that referenced this pull request Oct 16, 2026
* commit '56c315156f4542f197a2b7f727681ba3f41c21b5': (23 commits)
  fix(ui): remove stale Lit cleanup from model catalog tests
  refactor(tests): consolidate iMessage discovery checks (#173624)
  fix(auto-reply): retire older collect cancellation after admission
  fix(memory): avoid rebuilding initially empty indexes after restart (#173622)
  fix(test): preserve subprocess runtime identity (#173446)
  perf(sessions): batch transcript index reconciliation (#173620)
  fix(gateway): share GitHub options preparation during reconnects (#173589)
  perf(control-ui): open the composer model picker without list-wide work (#173275)
  fix: finish compile-cache cleanup after short CLI commands exit (#173603)
  refactor(ui): finish native shell rendering (#171554)
  fix: preserve standalone CLI profiles and settle Doctor shutdown (#173154)
  refactor: centralize agent memory host typing (#173619)
  fix: camera fallback picker opens away from the attachment button (#173618)
  refactor: deduplicate existing CI runner routing with YAML anchors (#172670)
  fix(ai): preserve multiline Google replies and report malformed streams (#173612)
  refactor(tests): remove duplicate speech policy test (#173606)
  refactor(ui): simplify page rendering and derivations (#173608)
  fix(release): Linux channel promotion fails after a withdrawn Windows companion (#173615)
  fix(update): wait for native Gateway ownership before restarting (#173588)
  test(sessions): admit schema probe fixture writes behind maintenance
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
Batch transcript-index traversal, readiness classification and receipt updates inside the existing writer owner. Preserve 128-session and 512-orphan bounds, immediate search freshness and incremental receipt invalidation. Remove the redundant clean-status sibling-revision reread; a later sibling write is handled by its receipt and the next maintenance pass.

A 4.76-million-event synthetic fixture reduces cold reconciliation from 38,074 to 938 SQL statements with zero MAIN SQL and unchanged append WAL costs. Exact-head CI and two Codex review rounds pass. Knip findings match scheduled main run 38832586414. The shared synchronous SDK index sites remain under their existing compatibility contract.
vincentkoc added a commit that referenced this pull request Oct 16, 2026
* fix(ci): share the iOS screenshot build

* fix(ci): preserve the screenshot artifact container on download

* merge: integrate main for iOS screenshot workflow conflicts

* style(ci): format the combined screenshot evidence changes

* docs(ci): name the combined screenshot capture

* fix(ios): expose screenshot simulator creation errors

* Merge main at 56c3151 to include the UI test cleanup fix

* commit '56c315156f4542f197a2b7f727681ba3f41c21b5': (23 commits)
  fix(ui): remove stale Lit cleanup from model catalog tests
  refactor(tests): consolidate iMessage discovery checks (#173624)
  fix(auto-reply): retire older collect cancellation after admission
  fix(memory): avoid rebuilding initially empty indexes after restart (#173622)
  fix(test): preserve subprocess runtime identity (#173446)
  perf(sessions): batch transcript index reconciliation (#173620)
  fix(gateway): share GitHub options preparation during reconnects (#173589)
  perf(control-ui): open the composer model picker without list-wide work (#173275)
  fix: finish compile-cache cleanup after short CLI commands exit (#173603)
  refactor(ui): finish native shell rendering (#171554)
  fix: preserve standalone CLI profiles and settle Doctor shutdown (#173154)
  refactor: centralize agent memory host typing (#173619)
  fix: camera fallback picker opens away from the attachment button (#173618)
  refactor: deduplicate existing CI runner routing with YAML anchors (#172670)
  fix(ai): preserve multiline Google replies and report malformed streams (#173612)
  refactor(tests): remove duplicate speech policy test (#173606)
  refactor(ui): simplify page rendering and derivations (#173608)
  fix(release): Linux channel promotion fails after a withdrawn Windows companion (#173615)
  fix(update): wait for native Gateway ownership before restarting (#173588)
  test(sessions): admit schema probe fixture writes behind maintenance
  ...

Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
* fix(ci): share the iOS screenshot build

* fix(ci): preserve the screenshot artifact container on download

* merge: integrate main for iOS screenshot workflow conflicts

* style(ci): format the combined screenshot evidence changes

* docs(ci): name the combined screenshot capture

* fix(ios): expose screenshot simulator creation errors

* Merge main at a11e38b to include the UI test cleanup fix

* commit 'a11e38b8bb1eb58aaf392a0eab458dbb47aad30f': (23 commits)
  fix(ui): remove stale Lit cleanup from model catalog tests
  refactor(tests): consolidate iMessage discovery checks (openclaw#173624)
  fix(auto-reply): retire older collect cancellation after admission
  fix(memory): avoid rebuilding initially empty indexes after restart (openclaw#173622)
  fix(test): preserve subprocess runtime identity (openclaw#173446)
  perf(sessions): batch transcript index reconciliation (openclaw#173620)
  fix(gateway): share GitHub options preparation during reconnects (openclaw#173589)
  perf(control-ui): open the composer model picker without list-wide work (openclaw#173275)
  fix: finish compile-cache cleanup after short CLI commands exit (openclaw#173603)
  refactor(ui): finish native shell rendering (openclaw#171554)
  fix: preserve standalone CLI profiles and settle Doctor shutdown (openclaw#173154)
  refactor: centralize agent memory host typing (openclaw#173619)
  fix: camera fallback picker opens away from the attachment button (openclaw#173618)
  refactor: deduplicate existing CI runner routing with YAML anchors (openclaw#172670)
  fix(ai): preserve multiline Google replies and report malformed streams (openclaw#173612)
  refactor(tests): remove duplicate speech policy test (openclaw#173606)
  refactor(ui): simplify page rendering and derivations (openclaw#173608)
  fix(release): Linux channel promotion fails after a withdrawn Windows companion (openclaw#173615)
  fix(update): wait for native Gateway ownership before restarting (openclaw#173588)
  test(sessions): admit schema probe fixture writes behind maintenance
  ...

Co-authored-by: Vincent Koc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant