Skip to content

improve(sessions): reduce database work for transcript batch appends - #174817

Merged
steipete merged 2 commits into
mainfrom
dbasync/batchappend
Oct 17, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/batchappend

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Transcript imports and batched appends update session recency and the projection watermark for every event, even though the batch already owns those intermediate facts.

User Impact

Batched transcript writes perform fewer database statements while preserving event bytes, identity deduplication, rewrite generations, recency, and search/index state. There is no schema, configuration, SDK, durability, or transaction-ordering change.

Why This Change Was Made

The append cursor now retains the final attempted recency and flushes it through the existing final mutation write. The index appender retains its watermark and flushes once per batch; standalone appends still settle immediately. Caught iterator failures settle the accepted prefix without advancing the batch mutation fence; escaping failures retain transaction rollback. Rejected identities still affect recency without advancing that fence. Replacement batches also settle their accepted prefix on error.

Removed work and accepted edges:

  • Per-event recency writes: intermediate database recency is not published during the synchronous batch; the final attempted timestamp is persisted before returning or propagating an iterator error.
  • Per-event projection-watermark writes: intermediate SQL watermark rows are not visible to reentrant mutation inside the owned batch; the cursor and actor retain the current projection until settlement.
  • Dirty-projection reread: the appender uses its already-owned watermark instead of rereading it. Mutating the same session outside this synchronous cursor is unsupported.

The two final mutation SQL shapes remain necessary for actor/non-actor publication. Generation ensure already performs no SQL when the actor owns the generation; the offline path retains its ensure because it has no retained generation. Identity lookup remains: immediate payload foreign keys and cold-history/idempotency behavior require separate parity proof before an insert-first redesign.

The touched kernels retain 20 static T1 call sites (state 13, store 1, index 6), unchanged in the exact base/head census. Their released synchronous native SessionManager contract lasts through December 31, 2026, and cannot be removed by moving shared helpers or relabeling them as worker-only. This uses the task's compatibility/owner-redesign escape hatch. Gateway MAIN is measured separately below.

Evidence

  • Focused batch regression: 3 passed (deduplication, rejected attempt, rewrite generation, accepted-prefix settlement and rollback).
  • Projection/FTS owner tests: 9 passed on the integrated head (identity mapping, deletion/rollback, large suffix replacement, reconciliation, interrupted rebuilds, and active-branch projection).
  • Actor/non-actor timestamp tests: 2 passed, including rejected identities and degraded compaction.
  • Codex review: both rounds found no actionable P0–P2 findings. The later integration preserved the production behavior, narrowed a type-only helper dependency to fix a Madge cycle, and migrated the fixture change to the test file renamed on main.
  • Type-aware changed-file lint, formatting and diff checks passed. Final-head CI 38981854378 passed all selected tests, types, lint, contracts, PostgreSQL conformance, and T1/dialect ratchets. Madge reports zero cycles after removing the whole-cursor type dependency that caused the initial CI failure. The changed batch/projection files passed 3/3 and 9/9 in CI. Security review also passed. Knip was not selected by CI; both exact-head local scans passed with zero findings (production and full-tree exports). No SDK API diff or published-driver update cell applies.

Measurements

Three alternating shared-v3 pairs completed in order M1,C1,M2,C2,M3,C3 on base ece4639ff9306103c9773e6fff1c53b79bdb19ff and candidate e56b2cf677e152f359e2a110479fce4d97a32209. Node 24.22.0 / SQLite 3.54.0; compile cache disabled. Every arm passed workload, source/runtime identity, cleanup, calibration, and causal coverage checks. Independent raw recounts matched the shared analyzer; zero failed native SQL calls. Headline brackets span the three per-arm medians; pooled brackets span all 30 turns per side.

Scope Base SQL Candidate SQL Base requests Candidate requests Base MAIN Candidate MAIN
Warm causal 67 [67–67] 67 [67–67] 22 [22–22] 22 [22–22] 0 [0–0] 0 [0–0]
Warm raw window 67.5 [67–68] 67.5 [67–67.5] 22 [22–22] 22 [22–22] 0 [0–0] 0 [0–0]
Warm causal, pooled 30 67 [67–68] 67 [67–68] 22 [22–23] 22 [22–23] 0 [0–0] 0 [0–0]
Warm raw, pooled 30 67.5 [67–85] 67 [67–106] 22 [22–25] 22 [22–28] 0 [0–9] 0 [0–13]
Whole raw workload 3816 [3802–3848] 3794 [3785–3801] 991 [991–993] 983 [983–991] 206 [206–206] 207 [206–207]

Warm non-regression holds for both causal and raw-window medians. Every arm has causal mean 67.1 SQL / 22.1 requests / 0 MAIN. The standard single-event turn does not exercise the bulk-append savings: its transcript-index/state/store totals remain 100/50/90 SQL per ten warm turns. appendToIndex → appendEvent is a function rename, not a −40/+40 SQL change. All captured owner-operation counts are unchanged in the standard workload after combining that rename.

Raw-window tails include background lease/plugin-index work. Thirteen MAIN lease checks move between first-turn and early warm windows; they appear on both sides and are not turn-caused. The whole-workload MAIN median 206→207 is one extra PRAGMA busy_timeout during initial boot in C2/C3 (openNativeStateDatabase → setSqliteBusyTimeout, startup preflight). Normalizing the timeout value, all other whole-run MAIN SQL shapes have identical counts across all six arms. The affected boot/state files are unchanged. This is not a warm MAIN increase or a transcript-owned statement. Whole raw SQL/request changes include background phase redistribution; no whole-workload savings claim is made.

Shared-family attribution also shows no warm increase: row-facts direct reads are 2 SQL/1 request per turn, with 3 SQL/1 request when counting each full associated request. Captured warm exact-entry, actor hydration, entry-cache snapshot and watermark families are zero on both sides. These are observed-frame counts, not claims that the logical operations never occur. Whole-run row-fact captures vary 132 [131–135]→135 [133–135] statements while associated request medians stay 58; the warm family remains identical. Families overlap and are not summed.

Phase (raw, except named causal) Base SQL Candidate SQL Base requests Candidate requests Base MAIN Candidate MAIN
01.boot 392 [380–398] 382 [381–383] 92 [87–92] 89 [87–89] 92 [92–92] 93 [92–93]
02.first-turn causal 190 [186–190] 188 [188–188] 58 [58–58] 58 [58–58] 0 [0–0] 0 [0–0]
04.second-session causal 465 [464–466] 465 [464–466] 129 [129–129] 129 [129–129] 0 [0–0] 0 [0–0]
06.cron 282 [278–305] 279 [275–282] 74 [73–77] 73 [73–74] 0 [0–0] 0 [0–0]
07.compaction 155 [152–158] 155 [151–171] 28 [25–30] 28 [25–32] 0 [0–0] 0 [0–0]
07.idle-settle 258 [8–260] 128 [101–247] 29 [7–31] 25 [13–30] 0 [0–0] 0 [0–0]
07.idle-connected 119 [119–376] 250 [117–284] 43 [42–72] 50 [43–65] 0 [0–0] 0 [0–0]
09.restart-boot 411 [397–433] 408 [400–416] 100 [98–112] 98 [94–104] 83 [83–83] 83 [83–83]
10.restart-first-turn causal 149 [149–149] 149 [149–149] 47 [47–47] 47 [47–47] 0 [0–0] 0 [0–0]

SQLite microbenchmarks use one instrumented run per side and verify persisted event, recency and index state. Offline owner calls do not measure Gateway requests or PostgreSQL network round trips. Every micro fixture was removed. Wall observations below are diagnostic only: the host was busy (load roughly 46–90), so there is no latency/speedup claim.

Shape Base append SQL Candidate append SQL Saved SQL Base/candidate append wall ms Base/candidate transaction wall ms
1k-20 8,250 6,350 1,900 159.5 / 349.3 363.7 / 494.5
1k-500 8,010 6,014 1,996 135.8 / 647.6 158.9 / 832.0
10k-20 82,500 63,500 19,000 2055.6 / 2112.3 12709.6 / 5678.1
10k-500 80,100 60,140 19,960 1428.6 / 2503.5 2202.0 / 2563.0
pgstress-shape 289,800 218,520 71,280 5340.6 / 5916.6 23440.7 / 10442.2

The 36k-event shape is 300 short sessions ×20 plus one long session receiving 60 successive ×500-event batches. It saves 71,280 append statements (24.6%). Per-operation counts:

36k append operation Base Candidate
Recency-only UPDATE 35,640 0
Projection-watermark UPDATE 36,000 360
Final mutation UPDATE 360 360
All session-window writes 36,360 720
Generation ensure 360 360
Identity SELECT / identity write 36,000 / 36,000 36,000 / 36,000
Payload INSERT / active-event INSERT 36,000 / 36,000 36,000 / 36,000
FTS writes 72,000 72,000

Production diff: +141/−78 (net +63), plus tests/docs. The growth provides one explicit batch-settlement lifecycle and preserves the existing partial-iterator contract; no cache, handshake, or new state owner is introduced.

@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-16T23:33:45.193541Z e56b2cf New commits
ℹ️ 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: M labels Oct 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels 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 settles transcript recency and projection watermarks once per batch instead of writing them for every event.

Example: Append messages one and two, then reject duplicate attempts with timestamps 25 and 40.

  • Before: Each attempt updates session recency, and each accepted event writes its projection watermark.
  • After: The batch settles both metadata records once, retains three messages including the existing root, and preserves final recency 40.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and has meaningful storage-boundary coverage, but supplied evidence does not yet establish measured production-path performance.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers real-SQLite owner tests and CI, while performance measurements remain pending and no latency improvement is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Transcript imports and batched writes perform repeated database metadata work for intermediate facts already owned by the batch.
Reason: The existing feature owner proposes a focused reduction in database work and explicitly records the intermediate-visibility tradeoff without changing configuration or public contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored optimization contains useful work absent from current main, and review found no actionable correctness or security defects.

Priority: P2
Reviewed head: e56b2cf677e152f359e2a110479fce4d97a32209

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped-entry-point batch trace or demonstrated base-fail/head-pass run accompanies the new tests; campaign measurements are explicitly pending.
Agent review details

How this fits together

The session transcript storage owner receives events from imports and session mutations, writes canonical events and identities, and maintains active-history and search projections within the caller's transaction.

flowchart TD
  A[Imports and session mutations] --> B[Transcript batch owner]
  B --> C[Event and identity writes]
  B --> D[Transaction local cursor]
  D --> E[Projection and recency settlement]
  C --> F[Caller transaction commit or rollback]
  E --> F
Loading

Technical review

Best possible solution:

Retain the existing transaction owner and merge the focused batch-settlement optimization when its required CI completes successfully.

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

Current-main source directly shows repeated recency and watermark writes inside a synchronous batch; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change removes redundant writes at their existing owner, updates every internal appender caller, and preserves standalone settlement without adding another state authority.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8d9c36de833a.

Provenance checked

  • Transaction-local transcript projection cursor keeps the original intent (348ad76: Reuse projection facts within a synchronous batch whose source cannot mutate the destination session.)
  • Prepared projection writers changes intended behavior with a stated reason (12f2f9c: Prepare FTS, active-history, and watermark writers once per batch while preserving projection semantics.)
  • Entry-cache preservation receipts keeps the original intent (84beaf6: Preserve unchanged session metadata through transcript-owner write receipts instead of a separate cache mutation tracker.)
  • Maintenance replacement mutation helper keeps the original intent (8aa6763: Invalidate stale transcript projections after repair while preserving historical session recency.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

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

PR surface

Source +63, Tests +162, Docs +8. Total +233 across 7 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 141 78 +63
Tests 2 163 1 +162
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 312 79 +233

Review metrics

Metric Value Why it matters
Production versus test LOC Production +141/-78; tests +163/-1 Production growth supplies explicit batch settlement and preserves partial-iterator behavior; tests exercise persisted results and the statement reduction.

Labels

Label changes:

  • add P2: This is a bounded database-work improvement for transcript imports and batch writes, with no demonstrated urgent user-facing failure.
  • 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 bounded database-work improvement for transcript imports and batch writes, with no demonstrated urgent user-facing failure.
  • 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.

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 16, 2026, 7:47 PM ET / 23:47 UTC.

@steipete
steipete merged commit 629b1cd into main Oct 17, 2026
148 of 149 checks passed
@steipete
steipete deleted the dbasync/batchappend branch October 17, 2026 00:13
@steipete

Copy link
Copy Markdown
Contributor Author

Final post-merge measurement: all three alternating shared-v3 pairs passed.

Three alternating shared-v3 pairs completed in order M1,C1,M2,C2,M3,C3 on base ece4639ff9306103c9773e6fff1c53b79bdb19ff and candidate e56b2cf677e152f359e2a110479fce4d97a32209. Node 24.22.0 / SQLite 3.54.0; compile cache disabled. Every arm passed workload, source/runtime identity, cleanup, calibration, and causal coverage checks. Independent raw recounts matched the shared analyzer; zero failed native SQL calls. Headline brackets span the three per-arm medians; pooled brackets span all 30 turns per side.

Scope Base SQL Candidate SQL Base requests Candidate requests Base MAIN Candidate MAIN
Warm causal 67 [67–67] 67 [67–67] 22 [22–22] 22 [22–22] 0 [0–0] 0 [0–0]
Warm raw window 67.5 [67–68] 67.5 [67–67.5] 22 [22–22] 22 [22–22] 0 [0–0] 0 [0–0]
Warm causal, pooled 30 67 [67–68] 67 [67–68] 22 [22–23] 22 [22–23] 0 [0–0] 0 [0–0]
Warm raw, pooled 30 67.5 [67–85] 67 [67–106] 22 [22–25] 22 [22–28] 0 [0–9] 0 [0–13]
Whole raw workload 3816 [3802–3848] 3794 [3785–3801] 991 [991–993] 983 [983–991] 206 [206–206] 207 [206–207]

Warm non-regression holds for both causal and raw-window medians. Every arm has causal mean 67.1 SQL / 22.1 requests / 0 MAIN. The standard single-event turn does not exercise the bulk-append savings: its transcript-index/state/store totals remain 100/50/90 SQL per ten warm turns. appendToIndex → appendEvent is a function rename, not a −40/+40 SQL change. All captured owner-operation counts are unchanged in the standard workload after combining that rename.

Raw-window tails include background lease/plugin-index work. Thirteen MAIN lease checks move between first-turn and early warm windows; they appear on both sides and are not turn-caused. The whole-workload MAIN median 206→207 is one extra PRAGMA busy_timeout during initial boot in C2/C3 (openNativeStateDatabase → setSqliteBusyTimeout, startup preflight). Normalizing the timeout value, all other whole-run MAIN SQL shapes have identical counts across all six arms. The affected boot/state files are unchanged. This is not a warm MAIN increase or a transcript-owned statement. Whole raw SQL/request changes include background phase redistribution; no whole-workload savings claim is made.

Shared-family attribution also shows no warm increase: row-facts direct reads are 2 SQL/1 request per turn, with 3 SQL/1 request when counting each full associated request. Captured warm exact-entry, actor hydration, entry-cache snapshot and watermark families are zero on both sides. These are observed-frame counts, not claims that the logical operations never occur. Whole-run row-fact captures vary 132 [131–135]→135 [133–135] statements while associated request medians stay 58; the warm family remains identical. Families overlap and are not summed.

Phase (raw, except named causal) Base SQL Candidate SQL Base requests Candidate requests Base MAIN Candidate MAIN
01.boot 392 [380–398] 382 [381–383] 92 [87–92] 89 [87–89] 92 [92–92] 93 [92–93]
02.first-turn causal 190 [186–190] 188 [188–188] 58 [58–58] 58 [58–58] 0 [0–0] 0 [0–0]
04.second-session causal 465 [464–466] 465 [464–466] 129 [129–129] 129 [129–129] 0 [0–0] 0 [0–0]
06.cron 282 [278–305] 279 [275–282] 74 [73–77] 73 [73–74] 0 [0–0] 0 [0–0]
07.compaction 155 [152–158] 155 [151–171] 28 [25–30] 28 [25–32] 0 [0–0] 0 [0–0]
07.idle-settle 258 [8–260] 128 [101–247] 29 [7–31] 25 [13–30] 0 [0–0] 0 [0–0]
07.idle-connected 119 [119–376] 250 [117–284] 43 [42–72] 50 [43–65] 0 [0–0] 0 [0–0]
09.restart-boot 411 [397–433] 408 [400–416] 100 [98–112] 98 [94–104] 83 [83–83] 83 [83–83]
10.restart-first-turn causal 149 [149–149] 149 [149–149] 47 [47–47] 47 [47–47] 0 [0–0] 0 [0–0]

SQLite microbenchmarks use one instrumented run per side and verify persisted event, recency and index state. Offline owner calls do not measure Gateway requests or PostgreSQL network round trips. Every micro fixture was removed. Wall observations below are diagnostic only: the host was busy (load roughly 46–90), so there is no latency/speedup claim.

Shape Base append SQL Candidate append SQL Saved SQL Base/candidate append wall ms Base/candidate transaction wall ms
1k-20 8,250 6,350 1,900 159.5 / 349.3 363.7 / 494.5
1k-500 8,010 6,014 1,996 135.8 / 647.6 158.9 / 832.0
10k-20 82,500 63,500 19,000 2055.6 / 2112.3 12709.6 / 5678.1
10k-500 80,100 60,140 19,960 1428.6 / 2503.5 2202.0 / 2563.0
pgstress-shape 289,800 218,520 71,280 5340.6 / 5916.6 23440.7 / 10442.2

The 36k-event shape is 300 short sessions ×20 plus one long session receiving 60 successive ×500-event batches. It saves 71,280 append statements (24.6%). Per-operation counts:

36k append operation Base Candidate
Recency-only UPDATE 35,640 0
Projection-watermark UPDATE 36,000 360
Final mutation UPDATE 360 360
All session-window writes 36,360 720
Generation ensure 360 360
Identity SELECT / identity write 36,000 / 36,000 36,000 / 36,000
Payload INSERT / active-event INSERT 36,000 / 36,000 36,000 / 36,000
FTS writes 72,000 72,000

Measured head: e56b2cf677e152f359e2a110479fce4d97a32209; squash: 629b1cdfe2e484138dd294342073bc7297ce23a9. The patch IDs match and the squash is on main. Touched-area T1 remains 20→20, under the documented native synchronous compatibility exception; global T1 187→187, T1-compat 10→10, dialect growth 0. CI, security, both Knip scans, and two Codex reviews passed.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
Reduce transcript batch append writes by settling session recency and projection watermarks once per batch. Preserve identity deduplication, rewrite generations, caught partial-iterator settlement, transaction rollback, and actor/non-actor mutation publication.

Keep standalone append settlement immediate and retain the existing native SessionManager compatibility contract. No schema or durability change.
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant