Skip to content

refactor(storage): reduce SQLite bookkeeping per turn - #169173

Merged
steipete merged 5 commits into
mainfrom
dbasync/smallfold
Oct 11, 2026
Merged

steipete merged 5 commits into
mainfrom
dbasync/smallfold

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Ordinary chat turns repeat activity snapshot setup, read connection policy already owned in process, issue empty audit expiry deletes, and write a transcript window twice.

User Impact

Reduces SQLite work per turn without changing transcript bytes, audit retention, lock-wait policy, permissions, schemas, or update behavior.

Why This Change Was Made

  • Activity metadata, ancestry, watermark, and bounded pages now share one native snapshot. That production change was also supplied by upstream perf(sessions): reuse transcript projection facts within reads #169201 during validation; this PR retains its one-snapshot/post-write regression.
  • Retain busy timeout at the connection owner, route memory-worker changes through its existing private SDK facade, and skip unchanged assignments.
  • Retain the audit writer's next expiry; update it for earlier inserts and invalidate it on rollback or maintenance.
  • Fold known-existing transcript window recency into the final mutation-watermark update. Duplicates still touch recency, and compaction preserves an intervening entry writer's timestamp.

Removed ordinary-path work and accepted edges:

  • Activity final snapshot comparison and two duplicate transaction envelopes: writes after snapshot admission appear in the next recap.
  • Busy-timeout read-before-override and equal assignments: all managed policy changes use the owner; foreign raw SQL policy changes are unsupported. Matching scopes preserve intentional policy changes inside the operation.
  • No-op audit expiry deletion: the single writer retains the earliest expiry; maintenance and rollback invalidate the fact, and external concurrent writers are unsupported.
  • Known-existing transcript root touch: the actor/batch keeps the root alive for the synchronous transaction; duplicates retain their recency-only update.

No new freshness probes, generations, or admission handshakes.

Main-thread inventory and escape hatch

Activity, audit, and timeout-owner sites: T1 0 → 0. The shared transcript files retain 15 classified T1 sites; 8 are in changed functions. One actor-guarded update is worker-only. The other 7 changed-function sites also serve the released synchronous SessionManager persistence API, which guarantees commit before return. Moving those requires its SDK owner redesign, so this PR uses the requested escape hatch and preserves that contract. The ordinary Gateway turn remains on its existing actor/worker path. No T1 call added.

Evidence

Codex autoreview: scoped clean, no actionable P0–P2 findings (round 1); the timeout correction is clean at P0/P1 in round 2. Focused Testbox proof: 220 tests passed in 12 files, five shards, 137.59s runner wall time. Covers activity post-write reads, audit expiry/rollback, timeout nested overrides/reopen, transcript actor/batch timestamp semantics and dedupe, entry revalidation, WAL/deadlines, memory publication, and SDK runtime guardrails.

Three alternating pairs, M1,C1,M2,C2,M3,C3, ran on one AWS worker using the unchanged shared workload (SHA-256 1de5109a7b89eaf8c10ef943bde724a89bd44772b7d70419bd344caf18d92cd1). Baseline ebdc7d54c0842d96c4bb2fb2bb4be4758f07f255; measured production head ba8c1993aa0edccb396b8d07a3d979d1477f53b7. The test relocation retained identical production inputs. The later conflict-only merge to b292f4cf100a69b5159ad25d25d975b117074e36 integrates main at 6e7d21ec8310351584b27926d8cbb09e0585cd49; the one conflict preserves main’s projection-owned watermark. Per the conflict-only proof policy, these measurements are reused and describe the original four-item implementation, not a fresh measurement against the later main baseline.

Warmed per turn, median [min–max] Base Candidate
All-thread statements 336.7 [335.5–342.0] 321.5 [316.5–322.8]
Logical worker requests 89.3 [88.9–89.5] 88.3 [87.3–88.7]
Gateway MAIN statements 0 [0–0] 0 [0–0]

Observed warmed reduction: 15.2 statements (4.5%) and 1.0 requests (1.1%). Changed-owner requests are unchanged; background variation accounts for the remaining request reduction. Warmed duration ratio C/M: 0.994.

Changed operation Requests/turn, base → head Statements/turn, base → head
Activity summary source 1 → 1 14 → 8
Audit writer process 2 → 2 14 → 10
Actor acceptInput 2 → 2 16 → 15
Actor appendTranscriptEvent 2 → 2 23 → 21

The original four-item implementation accounts for 13 deterministic statements removed per warmed turn. Activity’s 6-statement saving is now also on main through #169201; the remaining PR contributes 7 deterministic statements (2 timeout reads, 2 empty expiry deletes, 3 transcript-root UPSERTs), with unchanged owner request counts. Within them, busy-timeout reads are 2 → 0, empty audit expiry DELETEs 2 → 0, and transcript root UPSERTs 3 → 0. The remaining observed reduction is background variation.

First-turn statements decrease 1203 → 1189, while first-turn requests vary 192 → 199 as unchanged memory/session projection work moves between phases. Following RAW TURN INCREASE, one extra pair M4,C4 checked the complete workload: statements 9799 → 9533, requests 1730 → 1721. Across all four pairs, complete-workload medians are 9830 → 9542.5 statements and 1725 → 1718.5 requests; warmed medians are 336.1 → 321.6 statements and 89.15 → 88.5 requests. No new request class appears in the changed owners. All eight workloads succeed; their two expected lock-admission failures are identical (connect and shutdown). Census has no missing context rows or duplicate sends; the same two startup send/receive observations lack target linkage in every run.

Static proof: core, core-test, extension, and extension-test typechecks passed before the conflict-only merge. On final head b292f4cf100a69b5159ad25d25d975b117074e36, type-aware core/extension lint, formatting, export collisions, SDK surface, Madge (0 runtime cycles), and T1/dialect ratchets pass. T1 is 612 → 612 raw / 610 → 610 normalized against the merged base. The SDK API diff passed with no public API changes before the merge; the conflict resolution introduced no SDK change. The final-head activity/transcript suite passes 69 tests in 4 files, 124.23s runner. Earlier unchanged-owner proof (220 focused tests, 21 timeout/update-contention tests, 52 mocked-SDK tests) is reused.

Knip exception: final head and exact main baseline 6e7d21ec8310351584b27926d8cbb09e0585cd49 report the identical 41 UI unused-export findings, keyed by scan, file, and symbol; zero added or removed findings, and none of those files differs in this PR. The earlier subagent-store finding is absent after integrating main. The final required CI gates are green (run 38157182225).
No published-driver update cell: update, Doctor, schema/migrations, plugin loading, and service lifecycle are unchanged.

Final diff LOC: production +145/−56, tests +308/−4, docs +14/−0 (13 files). Release-note context: internal SQLite turn-overhead reduction; no migration or operator action.

CI found an update-contention regression in the first head: restoring a matching timeout scope overwrote the mutation’s intentional 5000 ms policy. Fixed by restoring only when the wrapper changed policy on entry. Existing regression plus timeout tests: 21/21 pass (47.15s runner).

Native landing initialization refused twice because the trusted tooling checkout could not resolve @openclaw/proc-safe, including after frozen dependency restoration. Per the authorized relaxed workflow, use the exact-head REST squash fallback after proof gates pass.

Pre-merge-head CI’s remaining failure was inherited: ui/src/e2e/chat-flow.navigation-presentation.e2e.test.ts:921, “keeps derived sidebar titles and accessible state after session patch refreshes”, expects link "Readable planning title" but receives link "Unread Readable planning title". The same assertion fails on main run 38147604740, job 114494370832. This PR changes no UI code. Pre-merge-head evidence. The earlier production-identical head also hit the terminal-canvas timeout independently seen in that main job. These are prior-head CI observations; final-head required CI is green. The static Knip exception above remains inherited.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core plugin: file-transfer size: L labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reduces repeated SQLite snapshot setup, timeout assignments, audit pruning, and transcript-window writes during chat turns.

Example: A warmed chat turn reads an Activity recap and persists audit and transcript events.

  • Before: The reported workload executes 336.7 SQLite statements per turn.
  • After: The reported workload executes 321.5 statements per turn, including 13 deterministic removals in the changed owners.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and supported by paired production-workload results and meaningful storage-contract tests; required landing validation remains incomplete.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied paired Gateway workloads exercise Activity reads, audit persistence, and actor transcript writes, with owner-attributed SQL reductions and successful results; tree evidence confirms the measured production code matches the reviewed head, while the inspected screenshots belong to another PR.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary chat turns perform avoidable SQLite bookkeeping.
Reason: The owner-directed change demonstrates a bounded reduction in database work while preserving data, retention, lock policy, and existing persistence contracts.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it delivers a useful, owner-directed storage optimization that current main lacks, with no actionable correctness finding; landing remains gated by incomplete required checks.

Priority: P2
Reviewed head: 932a4cde9a569304a55da118480e60c1237dc223

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway chat events enter the session and audit writers, while Activity reads bounded transcript snapshots; these existing workers consume connection policy and return committed facts or recap source data.

flowchart TD
  Chat[Chat turn] --> Gateway[Gateway]
  Gateway --> Sessions[Session writer]
  Gateway --> Activity[Activity reader]
  Gateway --> Audit[Audit writer]
  Sessions --> SQLite[SQLite databases]
  Activity --> SQLite
  Audit --> SQLite
Loading

Technical review

Best possible solution:

Land the existing-owner optimization once the required storage and SDK validation is satisfied through the applicable inherited-failure landing path.

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

Current-main source shows the redundant operations, and the supplied paired workloads quantify them against the candidate; this read-only review ran no target code or tests.

Is this the best way to solve the issue?

The patch uses existing transaction, writer, and disposal owners, removes superseded work, and preserves the documented synchronous compatibility path without introducing another storage owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Reviewed introduction: The review uses the pinned merge-base-to-head changes; a tree comparison shows the final commit changes only test files relative to the measured production head. (932a4cde9a56)
  • Still necessary on main: The changed production owners have no tree changes between the merge base and fetched main, so main retains the redundant operations this PR removes. (fcf234a0713c)
  • Connection-policy lifecycle: Timeout facts are invalidated through the existing native-disposal callback; matching scopes preserve intentional policy changes, while scopes that changed policy restore it. (src/infra/sqlite-busy-timeout.ts:78, 932a4cde9a56)
  • Retention contract preserved: The audit owner tracks earlier inserted expiries, retains the strict cutoff and bounded deletion policy, and drops retained facts after rollback or maintenance. (src/audit/audit-event-store.ts:585, 932a4cde9a56)
  • Transcript semantics preserved: Rejected identities still update attempt recency without advancing mutation watermarks; successful appends combine writes, and degraded compaction preserves the entry writer's timestamp. (src/config/sessions/session-accessor.sqlite-transcript-store.ts:172, 932a4cde9a56)
  • Completed performance evidence: The complete PR body reports four alternating Gateway workload pairs, attributes 13 deterministic statement removals, and records successful workloads with matching expected lock failures; this addresses the prior measurement request. (932a4cde9a56)

PR surface

Source +88, Tests +304, Docs +14. Total +406 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 7 206 118 +88
Tests 5 308 4 +304
Docs 2 14 0 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 528 122 +406

Review metrics

Metric Value Why it matters
Production versus tests Production +206/−118; tests +308/−4 Production growth retains lifecycle-owned timeout and expiry facts; tests protect timestamp, deduplication, rollback, snapshot, and connection-lifecycle contracts.
Attributed SQLite reduction 13 deterministic statements removed per warmed turn The reported owner-level measurements distinguish patch savings from background variation and make no latency improvement claim.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded performance improvement without an established urgent user-facing regression.
  • merge-risk: 🚨 compatibility: The worker SDK facade adds a timeout setter and documents managed policy-write expectations; owner direction is present, existing exports remain, and the bundled memory caller moves with it.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-11T15:24:18.638Z sha ba8c199 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T15:52:40.907Z sha 932a4cd :: needs changes before merge. :: none

Reviewed October 11, 2026, 12:17 PM ET / 16:17 UTC (Revision 3).

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete
steipete merged commit 6e4d1d5 into main Oct 11, 2026
138 checks passed
@steipete
steipete deleted the dbasync/smallfold branch October 11, 2026 17:05
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
Retain connection-owned busy-timeout policy, skip empty audit expiry deletes
until due, and fold known transcript-root recency into watermark writes.
These remove seven deterministic SQLite statements per warmed turn.

The original four-item measurement reduced warmed all-thread statements from
336.7 to 321.5 and requests from 89.3 to 88.3. Its six-statement activity snapshot
saving also landed upstream in openclaw#169201; retain that path and its regression.
Gateway MAIN remains zero. Preserve the released synchronous SessionManager
contract under the documented T1 escape hatch. No schema or retention change.

Final-head activity/transcript proof: 69 tests. Type-aware lint, T1/dialect
ratchets, export collisions, SDK surface, and cycles pass; required CI is green.
Knip reports the same 41 UI findings on the final head and its main baseline,
with no changed finding files. SDK API diff reports no public API changes.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream 0bc7491..408a1f3 (53 commits, including
openclaw#169164 cold session/memory SQL off the Gateway main thread, openclaw#169173
per-turn SQLite bookkeeping, openclaw#169207 coalesced tool-result actor
admissions, openclaw#169238 inter-session envelope bytes, openclaw#168989 ACP replies).

Conflict:
- plugin-sdk-surface-report.mts: upstream budgets 3673/2134; ours stays
  +11/+4 on top (3684/2138).

Drag removed against upstream:
- plugin-sdk-surface-report.mts: dropped the "+1: createSessionHeaderLink"
  budget comments; upstream added them in openclaw#158742 and retired them in
  openclaw#165334, and no such export exists any more.
- normalize-reply.ts: restored upstream's blank line before
  bindNormalizeReplyTransformOwner (formatting-only overlay noise).

Auto-merged files that carry continuation overlay (normalize-reply,
sqlite-entry-store, user-turn-transcript, baselines, vitest paths) keep
the overlay byte-for-byte. Worker access inventory regenerated.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[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 extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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