Skip to content

perf(sessions): batch transcript persistence writes - #175193

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

steipete merged 2 commits into
mainfrom
dbasync/batchappend2

Conversation

@steipete

@steipete steipete commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Transcript imports and prepared append batches still issue one identity lookup and three inserts for every event, despite already sharing one owner transaction.

User Impact

This reduces transcript persistence work while preserving event order, duplicate rejection, message-key ownership, search projections, and accepted-prefix behavior when an import iterator fails. No schema migration or user action is required.

Why This Change Was Made

Prepared arrays resolve identity and message-key conflicts once, then write payloads, identities, and active projection rows in groups of at most 64 rows or 1 MiB of pending payloads. Streaming imports retain per-row acceptance feedback and batch accepted writes. The same bounded inserters serve scalar and batch writes.

Scalar appends without complete actor facts fold the identity lookup into the payload insert. Identity-first INSERT ... ON CONFLICT cannot preserve the current immediate identity-to-payload foreign key without a schema change; the conditional payload insert keeps that constraint and only publishes actor/index facts after acceptance. Payloads precede identities and active rows. Existing per-event search writes and transaction/commit boundaries remain.

Removed repeated checks and accepted edges:

  • Prepared arrays reuse their initial conflict facts throughout the synchronous owner operation; an array that invokes an out-of-contract destination mutation through a getter is unsupported.
  • Scalar identity rejection shares the payload insert; malformed duplicate payloads can now fail serialization before their existing identity is rejected. Canonical valid events retain duplicate behavior.
  • Streaming imports retain identity lookups because their next(accepted) contract requires a decision before reading the next input.

Evidence

Focused regressions cover three bounded insert groups, contiguous sequences after rejected identities, later in-process writes, all three message-key modes across a flush with persisted and buffered owners, and iterator prefix commit versus rollback. Formatting, basic lint, diff checks, and the line-cap ratchet pass. Both isolated Codex review rounds are complete: the first was clean; the second found only already-corrected index-snapshot type errors, resolved in the committed working tree, with no additional P0–P2 defects. Initial CI exposed bounded-array type annotations and a metadata-read test spy counting lazy write compilation; both are corrected. Corrected-head CI run 39008355548 confirms 100 passing tests across nine focused owner files, both core type-aware lint stripes, source contracts, export collisions, Madge, and the line/T1/dialect ratchets. The merge-ref T1 ratchet is 182→182 (deprecated compatibility sites 10→10). All selected type checks also passed. The local import suite adds 12 passing cases, bringing focused owner coverage to 112 tests. Canonical Knip reports 8 production and 6 full-tree unused-export findings, with no script findings; every finding matches scheduled main run 39006528379 in unchanged files, and this inherited exception is recorded with the main repair owner. The owner microbenchmark, frozen-revision T1 census, and all three alternating Gateway measurement pairs are complete below. All six arms passed with unchanged runtime receipts, complete turn coverage, zero native SQL/prepare errors, and no remaining fixture children. Independent raw recounts agree with the shared harness. No latency claim is made.

PostgreSQL conformance exceeded its 30-minute job limit after four test failures, leaving the aggregate CI gate red. The retained-root 300-second timeout also occurs on scheduled main run 39006528379. A bounded PostgreSQL 17/pgvector replay of the other three failures passes all three cases on both frozen base and candidate: both Git-backup cases and Matrix partial-publication recovery. Those original CI failures remain unreproduced; the passing replay is not a claimed fix. Both isolated clusters were stopped and removed. The final Doctor pgvector case and the extension PostgreSQL groups did not complete in CI, so this is not a full PostgreSQL conformance pass.

Landing uses the authorized relaxed policy after correcting the initial small type/lint/test-spy defects: all changed-owner and static gates are passing or exactly attributed to main, two review rounds are complete, and the focused failed-case PostgreSQL replay passes on both revisions. The inherited Knip exception and incomplete PostgreSQL CI coverage remain explicit. An initial local import attempt stopped before a verdict when the scratch-size sampler encountered a disappearing temporary cache file; its task-only correction preserved the same limits, and the resumed import test passed.

Measurement Base Candidate
Causal warmed all-thread statements, pooled 30 turns 62 [62–63] 62 [62–63]
Causal warmed requests, pooled 30 turns 18 [18–19] 18 [18–19]
Causal warmed MAIN statements, pooled 30 turns 0 [0–0] 0 [0–0]
Raw warmed all-thread statements, pooled 30 turns 62 [62–81] 62 [62–82]
Raw warmed requests, pooled 30 turns 18 [18–23] 18 [18–24]
Raw warmed MAIN statements, pooled 30 turns 0 [0–9] 0 [0–9]
Whole workload statements, three runs 3560 [3552–3586] 3573 [3557–3598]
Whole workload requests, three runs 922 [917–928] 923 [916–932]
Whole workload MAIN statements, three runs 150 [150–150] 149 [149–150]
Transcript owner T1 sites (same eight-file scope) 34 34
Whole-repository inventory T1 sites 186 186

Three unchanged-harness pairs ran in M,C,M,C,M,C order. Tables report median [min–max]. The median of the three raw warmed arm medians is 62 [62–62.5] → 62 [62–63] statements, 18 [18–18] requests on both sides, and zero MAIN. Causal arm medians are exactly 62 statements / 18 requests / 0 MAIN in every arm. Pooled raw MAIN outliers are background lease-expiry reads from deferred plugin startup maintenance (runGatewayPostReadyStartupMaintenance → withPluginLifecycleLease → assertOperationOwned → readOpenClawStateLeaseExpiry), outside transcript owners. Some bounded stacks end at plugin registry refresh; the outermost captured stacks show deferred post-ready startup maintenance. Raw warm MAIN totals are M1/C1/M2/C2/M3/C3 = 13/0/13/13/0/0; the affected arms have nine reads in turn 1 and four in turn 2. Causal turn MAIN remains zero throughout.

Raw phase counts across the three runs:

Phase Base SQL Candidate SQL Base requests Candidate requests Base MAIN Candidate MAIN
01.boot 333 [332–333] 333 [333–333] 89 [88–89] 89 [89–89] 63 [63–63] 63 [63–63]
01.connect 260 [70–266] 224 [49–256] 31 [22–33] 21 [20–27] 0 [0–0] 0 [0–0]
02.first-turn 335 [314–501] 398 [347–545] 97 [97–101] 105 [103–114] 0 [0–13] 13 [0–13]
04.second-session 508 [506–511] 505 [502–509] 134 [134–135] 134 [133–135] 0 [0–0] 0 [0–0]
05.control-plane 7 [7–7] 7 [7–8] 1 [1–1] 1 [1–1] 0 [0–0] 0 [0–0]
06.cron 276 [276–277] 279 [277–280] 73 [73–73] 74 [73–74] 0 [0–0] 0 [0–0]
07.compaction 156 [155–156] 153 [153–154] 28 [28–30] 28 [28–28] 0 [0–0] 0 [0–0]
07.idle-connected 143 [142–143] 143 [141–280] 50 [49–50] 51 [50–67] 0 [0–0] 0 [0–0]
07.idle-settle 237 [236–237] 237 [100–239] 27 [27–28] 27 [10–27] 0 [0–0] 0 [0–0]
08.shutdown 26 [26–26] 26 [26–26] 6 [6–6] 6 [6–6] 7 [7–7] 7 [7–7]
09.restart-boot 346 [346–361] 352 [342–352] 103 [102–107] 103 [103–104] 60 [60–60] 59 [59–60]
09.restart-connect 54 [35–62] 57 [48–69] 21 [19–22] 22 [20–28] 0 [0–0] 0 [0–0]
10.restart-first-turn 215 [209–232] 209 [187–240] 70 [68–70] 69 [61–70] 0 [0–0] 0 [0–0]
11.restart-shutdown 30 [26–31] 26 [26–26] 7 [6–8] 6 [6–6] 7 [7–7] 7 [7–7]

The standard workload mostly uses scalar appends: payload/identity/active INSERT statements remain 67/67/63 in every arm. The standalone identity/cold-state lookup falls 3→0 in every pair, one each in first-turn, second-session, and compaction windows. All SELECT/WITH statements mentioning the identity table fall 74/74/73→71/71/70. Across the touched owner modules, observed statements fall 528→525 per complete run and 48→47 in the raw first-turn window; the ten warmed turns remain 250→250. Distinct linked request IDs across these touched owners remain 105→105 per complete run, 9→9 in first-turn, and 50→50 across the ten warmed turns; these are deduplicated unions, not sums of overlapping per-operation request counts. Batched inserts therefore show their main gain in the larger owner workloads below.

Whole-run medians rise by 13 statements and one request, while raw and causal warmed medians do not rise. The touched owner statement counts decrease; the aggregate increase is outside the changed owner operations. No whole-workload saving is claimed. Exact-entry, hydration, row-facts, entry-cache, and watermark families have no captured warm reads/associated requests on either side; the compact report retains cold-family counts and observed source stacks.

Offline SQLite append microbenchmark (setup and enclosing transaction statements excluded):

Workload Base append statements Candidate append statements
1,000 events, 20-event sessions 6,350 2,550
1,000 events, 500-event sessions 6,014 2,064
10,000 events, 20-event sessions 63,500 25,500
10,000 events, 500-event sessions 60,140 20,640
36,000 events: 300 short sessions plus 60 × 500-event long-session batches 218,520 77,220

The 36,000-event workload saves 141,300 statements (64.7%). Identity reads fall from 36,000 to 360, and each payload/identity/active insert class falls from 36,000 to 780. Per-event FTS writes remain 72,000. All five cases verify payloads, identities, active/FTS rows, index state, and recency; zero failed native calls. These are offline SQLite counts, not PostgreSQL round trips or Gateway requests.

The frozen-revision inventory is distinct from the CI merge-ref ratchet above: the identical eight-file scope remains 34 T1 sites in five files; whole-repository T1 remains 186 in 89 files, with compatibility sites separately unchanged at 10. Prepared-query factories and returned executor calls are outside the canonical primitive census.

The shared transcript kernels retain released synchronous SDK callers; this change does not claim T1-zero or reclassify them as worker-only. Gateway MAIN and requests are reported independently from the offline owner microbenchmark above. No wall-time claim on the shared host. No update cell or SDK API diff applies to this transcript-only change.

Candidate: 40141fba5e1583dacdc517b0210b017ac2d25641; measurement base: 6d578912da668b3011720ac91997669b6383db5a. Scope: ten files, +707/−175 lines (production +507/−168; tests +189/−0; docs +11/−7). Batch lifecycle and exact-row writes are extracted into one sibling to keep the existing store under its line cap. Builds and SQL fixtures are isolated from live Gateway state.

@clawsweeper

clawsweeper Bot commented Oct 17, 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 17, 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-17T06:04:59.413949Z 40141fb 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: L labels Oct 17, 2026
@steipete steipete changed the title improve(sessions): batch transcript persistence writes perf(sessions): batch transcript persistence writes Oct 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature 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:feature Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR batches transcript payload, identity, and active-history inserts while preserving the existing transaction owner.

Example: Import a transcript containing 130 unique messages.

  • Before: All 130 messages are retained using individual payload, identity, and active-history inserts.
  • After: The same ordered messages are retained using three insert groups for each table.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and supported by meaningful owner-level coverage; supplied evidence does not yet establish production performance gains.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence exercises real persistence owners in process, while shipped-entry-point measurements remain 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 transcript imports and prepared append batches perform avoidable database work for each event.
Reason: The area owner's direction is established by this maintainer-authored PR, and the source plus focused tests support a concrete reduction in persistence statements without new user-facing controls.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR provides a distinct persistence optimization with no actionable introduced defect found; PostgreSQL conformance remains pending.

Priority: P2
Reviewed head: 40141fba5e1583dacdc517b0210b017ac2d25641

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not exercise transcript import or prepared appends through a shipped entry point.
Agent review details

How this fits together

Session imports and prepared append operations enter the synchronous transcript transaction owner, which persists canonical events and updates identity, history, and search projections for subsequent reads.

flowchart TD
  A[Imports and prepared appends] --> B[Transcript transaction owner]
  B --> C[Identity and key resolution]
  C --> D[Bounded payload inserts]
  D --> E[Identity and active history inserts]
  B --> F[Search projection writes]
  E --> G[History and search readers]
  F --> G
Loading

Technical review

Best possible solution:

Retain bounded batching within the existing transcript owner and preserve its identity, projection, and transaction contracts.

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

This is a performance improvement rather than a reported functional defect; the prior source establishes per-event inserts, and no target code was executed during this read-only review.

Is this the best way to solve the issue?

The implementation places batching in the existing persistence owner, shares inserters with scalar paths, and preserves streaming acceptance feedback without adding a competing store or schema.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8457e29a4d01.

Provenance checked

  • Batch settlement and transcript ownership keeps the original intent (629b1cd: Settle recency and projection watermarks once while retaining accepted-prefix behavior and enclosing transaction rollback.)
  • Shared projection inserters keeps the original intent (12f2f9c: Reuse prepared projection writers across synchronous batches and rebuilds without changing branch selection or transaction ownership.)
  • Payload representation keeps the original intent (c659113: Compact physical payloads while preserving logical transcript bytes and searchable content; the supplied provenance and available base blob establish this contract.)
  • Scalar identity rejection changes intended behavior with a stated reason (improve(sessions): reduce database work for transcript batch appends #174817: Separate identity lookup was retained until an alternative preserved immediate foreign keys and cold-history behavior; this PR explains the conditional payload insert and its malformed-duplicate tradeoff.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3d385d4 adds src/config/sessions/session-accessor.sqlite-transcript-store.ts:315 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3d385d4f7423; files: src/config/sessions/session-accessor.sqlite-transcript-store.ts)
  • Dallin Romney: Raw commit 3c9a40a adds src/config/sessions/session-transcript-index.ts:311 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 3c9a40aae8da; files: src/config/sessions/session-transcript-index.ts)

PR surface

Source +339, Tests +189, Docs +4. Total +532 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 507 168 +339
Tests 2 189 0 +189
Docs 1 11 7 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 707 175 +532

Review metrics

Metric Value Why it matters
Production versus test changes Production +507/-168; tests +189/-0 Production growth supplies shared bounded inserters and transaction-local conflict tracking; tests cover persisted results and the statement-reduction contract.

Labels

Label changes:

  • add P2: This is a normal-priority transcript persistence optimization without an established 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 normal-priority transcript persistence optimization without an established 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.

Rank-up moves

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

  • Publish comparable base/candidate measurements for the affected batch sizes and warmed Gateway workload.

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 17, 2026, 2:29 AM ET / 06:29 UTC.

@steipete
steipete merged commit 0ba3926 into main Oct 17, 2026
170 of 174 checks passed
@steipete
steipete deleted the dbasync/batchappend2 branch October 17, 2026 07:50
steipete added a commit that referenced this pull request Oct 17, 2026
The fault worker delegated iteration with yield*, which does not close the
native iterator when next() throws. Its completed wrapper then hid the
native return() from Kysely cleanup. On Node 24.19 the cached statement
reported the old injected error on its next use after faults were disabled.

Explicitly close the native iterator before restoring the TEMP triggers.
Production queue and database behavior is unchanged. Preserve every
committed-prefix, pending-input and exactly-once assertion.

The scalar INSERT ... RETURNING path added by #175193 exposed this latent
fixture defect. #174897 did not remove a required predecessor, and #175295
is not the cause. Reproduced the same failure on hourly ab37bc6 and
current main 9c12710 using CI's Node 24.19.0; Node 24.22 used all()
and passed without the change.

Focused full-file proof: 5/5 pass in normal order with --maxWorkers=1,
28.45 s Vitest / 49.62 s command wall. Independent P2 review is clean.
All 22 affected consumer files pass: 337 tests using Node 24.19 and
--maxWorkers=1. The other 21 files take 509.14 s wall across five native
configs. Owning test-helper types, boundary lint, syntax, formatting and
whitespace checks pass. Root-test type-aware lint reports the same
pre-existing no-map-spread violation at this file's unchanged line 22 on
both base and candidate; no new diagnostic or suppression is introduced.
No CI dispatch or rerun.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
Batch transcript payload, identity, and active-event writes in bounded groups. Prepared arrays resolve conflict facts once; scalar appends fold identity rejection into the payload insert while preserving immediate foreign-key ordering.

Preserve iterator acceptance feedback, duplicate and message-key ownership semantics, committed-prefix behavior, and existing search projections. Add regressions for rejected identities, chunk boundaries, and in-process write visibility.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
The fault worker delegated iteration with yield*, which does not close the
native iterator when next() throws. Its completed wrapper then hid the
native return() from Kysely cleanup. On Node 24.19 the cached statement
reported the old injected error on its next use after faults were disabled.

Explicitly close the native iterator before restoring the TEMP triggers.
Production queue and database behavior is unchanged. Preserve every
committed-prefix, pending-input and exactly-once assertion.

The scalar INSERT ... RETURNING path added by openclaw#175193 exposed this latent
fixture defect. openclaw#174897 did not remove a required predecessor, and openclaw#175295
is not the cause. Reproduced the same failure on hourly ea5c031 and
current main 6b9b192 using CI's Node 24.19.0; Node 24.22 used all()
and passed without the change.

Focused full-file proof: 5/5 pass in normal order with --maxWorkers=1,
28.45 s Vitest / 49.62 s command wall. Independent P2 review is clean.
All 22 affected consumer files pass: 337 tests using Node 24.19 and
--maxWorkers=1. The other 21 files take 509.14 s wall across five native
configs. Owning test-helper types, boundary lint, syntax, formatting and
whitespace checks pass. Root-test type-aware lint reports the same
pre-existing no-map-spread violation at this file's unchanged line 22 on
both base and candidate; no new diagnostic or suppression is introduced.
No CI dispatch or rerun.
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: L 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