Skip to content

perf(knowledge): release database locks during Git checkpoints - #184789

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-knowledge-ingest-tx-20260919
Oct 26, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-knowledge-ingest-tx-20260919

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Knowledge Git checkpoints held an IMMEDIATE SQLite write transaction while running Git subprocesses and filesystem work. Even an empty checkpoint queue acquired a write transaction. Slow transaction logs could not distinguish this work from publication, observation, or attachments.

User Impact

Knowledge keeps its operational database writer free during Git checkpoints. Exact content, search behavior, publication atomicity, checkpoint order, and crash recovery are unchanged. No schema, configuration, retention, or migration changes.

Why This Change Was Made

The storage worker already serializes operations, and the durable Git checkpoint ref already makes replay idempotent. Drain one retained batch at a time outside the transaction, then acknowledge its job and publication receipt together in a short transaction after checking current access. Reuse prepared statements and derive the publication-token lookup once per synchronous drain instead of once per job. Empty drains do no transactional work. Label attachment, acceptance, publication/recovery, observation, and Git settlement transactions.

The plugin has no embedding stage. Record preparation already runs in the storage worker; keyword reconciliation is incremental and search-driven. Atomic publication batches remain capped at 25 items / 1 MiB. Filesystem validation in acceptance/publication/observation remains intact. The new labels will distinguish residual slow work there; this PR does not claim that every previously unlabeled slow transaction was Git.

Runtime production delta: +12 lines across the three storage modules. Growth preserves atomic per-job acknowledgement and current-authority checks after removing the encompassing transaction. There is no new long-lived cache or compatibility path. The separate benchmark is tooling, with an exact Knip entry; the shared performance README is unchanged.

Evidence

Acceptance: remove the database writer hold during real Git work, eliminate empty-drain transactions, preserve exact stored Git blobs and receipts, and reduce owner CPU/allocation without a demonstrated adverse result. Synthetic owner benchmark on macOS/Node 26.12.1, baseline e0b550b0ababbf011ec2aaee40c00a228070562a, 2,000 archived jobs and publication receipts. Five timing runs per arm; two separate allocation runs per arm. Each invocation is a small single-process run; no live service load was started.

Workload / metric Base Candidate
2,000 empty drains: write transactions 2,000 0
Empty drains: mean CPU 2,739 ms 2,535 ms (−7.5%)
Empty drains: mean wall time 2,653 ms 2,472 ms
Empty drains: sampled allocation / call 117,689 B 82,307 B (−30.1%)
10 checkpoints × 25 documents: mean CPU 336 ms 298 ms (−11.4%)
Checkpoints: sampled allocation / job 4.64 MB 2.68 MB (−42.3%)
Checkpoints: total write-lock hold 1,642 ms 14.4 ms (−99.1%)
Checkpoints: mean wall time 1,658 ms 1,717 ms (+3.6%; noisy)

CPU excludes Git children; allocation includes collected JavaScript objects, not native SQLite/Git memory. Every run verifies all 250 document blob hashes and all checkpoint receipts. Timing median/range: empty drains 2,557 [2,489–2,974] → 2,473 [2,291–2,692] ms; checkpoints 1,634 [1,511–1,831] → 1,842 [1,439–1,947] ms. Host one-minute load per timing arm: base 25.6/20.4/19.3/18.1/17.2; candidate 24.5/24.2/19.6/18.7/17.6. No latency-tail claim from these small samples. Maximum checkpoint transaction per timing run: base 1607/1815/1676/1617/1494 ms; candidate 3.73/3.59/2.68/6.93/1.98 ms (one vs ten transactions per run).

GC was collected in two additional untraced AB/BA pairs after fixing the benchmark's observer queue drain. Empty drains: 7 → 5 collections per run, paired mean total 8.88 → 8.46 ms per 2,000 calls; maxima base 1.79/1.43 ms, candidate 1.96/3.98 ms. Checkpoint drains: one collection (1.65/1.77 ms) → zero. These tiny counts are context only. Those extra checkpoint timing windows were highly variable: base 2.15/7.09 s, candidate 3.19/1.93 s; none were discarded. The earlier timing/allocation results remain valid, but their original GC fields were not used.

Mean post-operation RSS: empty 295.6 → 290.0 MiB; queued 303.3 → 292.2 MiB. Transient heap: empty 89.4 → 76.3 MiB; queued 70.7 → 75.8 MiB with fewer collections. These are owner-process observations, not retained Gateway heap measurements.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/knowledge-git-transactions.ts; use --sample separately for allocation. The script header documents baseline source selection and workload options.

Validation:

  • Hosted CI run 40357604946: success on 7d7740ca093a1f98a0471d953f0135bf5d923d43; required openclaw/ci-gate checks passed. No CI reruns.
  • Extended the existing exact-content Git test with a second-connection write probe during checkpointing: fails on base with database is locked, passes on candidate.
  • Added revoked-access-after-Git recovery coverage; authorized retry reuses the same commit.
  • git-history.test.ts, publication.test.ts, and ingestion.test.ts: 46 passed, final runner exit 0, 96.6 s wall time. These include process death, FIFO catch-up, filesystem conflicts, immutable sources, and scope isolation. An earlier run passed assertions but was rejected because source changed before runner verification; only the frozen rerun is counted.
  • Changed-file format and lint; pnpm tsgo:extensions; git diff --check: passed.
  • Independent subagent review (autoreview route unavailable): clean P0–P2. The configured autoreview provider did not match the operator configuration; no configuration was changed.

Gaps: owner proof follows the scoped fast-path protocol; no ten-minute whole-Gateway stress or live ingest mutation. The reported main-thread heap increase remains unattributed: full parsed catalogs/plans live in the storage worker, and this change does not establish a Gateway heap-retention fix. Hosted CI supplies broad validation. The standalone unused-file analysis was not run under the local compute limit; the benchmark has an exact Knip entry.

Keep Git outside write transactions, settle each checkpoint and receipt atomically, and reuse per-drain request facts and statements. Label ingest transaction owners while preserving publication and recovery semantics.
@clawsweeper

clawsweeper Bot commented Oct 26, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts plugin: knowledge size: M labels Oct 26, 2026
@steipete
steipete marked this pull request as ready for review October 26, 2026 16:16
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T16:19:37.077722Z 7d7740c Draft marked ready
ℹ️ 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.

@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 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR runs Knowledge Git checkpoints outside SQLite write transactions and atomically records each checkpoint result afterward.

Example: Knowledge drains 10 queued checkpoints containing 25 documents each.

  • Before: Git subprocesses hold the database writer; the reported benchmark measured 1,642 ms of total write-lock hold.
  • After: Only checkpoint acknowledgement holds the writer; the reported benchmark measured 14.4 ms while preserving all 250 document blobs and receipts.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-consistent, with useful owner-level measurements and regression coverage; evidence remains at the storage harness boundary.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its reported macOS/Node benchmark exercises StorageBase with real SQLite and Git and verifies exact blobs and receipts, while focused tests cover lock availability, replay, and revoked acknowledgement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Knowledge checkpoints unnecessarily reserve the operational database writer while running local Git and filesystem work.
Reason: The maintainer-authored direction removes measured writer hold while retaining publication semantics and existing recovery owners; the stated scope makes no Gateway latency or heap-retention promise.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: current main still holds the SQLite writer during Git checkpoints, and this focused change removes that hold without a definite introduced defect.

Priority: P2
Reviewed head: 7d7740ca093a1f98a0471d953f0135bf5d923d43

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence exercises the storage owner with real SQLite and Git rather than the shipped Gateway; the PR explicitly reports that limitation.
Agent review details

How this fits together

Knowledge's serialized storage worker publishes vault content, queues exact snapshots in SQLite, sends those snapshots to local Git, and records checkpoint results in publication receipts.

flowchart TD
  A[Knowledge operation] --> B[Serialized storage worker]
  B --> C[Publication and SQLite outbox]
  C --> D[Ordered checkpoint drain]
  D --> E[Local Git checkpoint]
  E --> F[Atomic job and receipt settlement]
Loading

Technical review

Best possible solution:

Keep Git work in the existing serialized storage owner and use short atomic transactions solely to settle each job and its receipt.

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

Current-main source directly shows Git subprocess work inside an IMMEDIATE transaction, and the PR reports a second-connection writer probe failing on the base and passing on the candidate; this review ran no target code.

Is this the best way to solve the issue?

The change addresses the lock's owning boundary with the existing worker, outbox, and idempotent Git refs; the added benchmark and two distinct regression checks are proportionate to the transaction change.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Knowledge checkpoint transactions and receipts changes intended behavior with a stated reason (65ad180: The bundling commit imported Knowledge and converted transaction handling to SDK helpers while preserving ordered exact snapshots and replay; no inspected history establishes a requirement to hold SQLite's writer during Git.)
  • Storage transaction labels keeps the original intent (65ad180: The existing StorageBase transaction helper centralized SDK-managed transactions; adding diagnostic labels keeps that owner and its callers intact.)
  • Knip standalone command registration keeps the original intent (523df35: The earlier change retained path-executed commands at repositoryScriptEntries; this PR registers its benchmark at the same owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 65ad180 adds extensions/knowledge/src/storage-host.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 65ad18005286; files: extensions/knowledge/src/storage-host.ts)

PR surface

Source +12, Tests +39, Docs +2, Other +298. Total +351 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 51 39 +12
Tests 1 40 1 +39
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 2 298 0 +298
Total 7 392 41 +351

Review metrics

Metric Value Why it matters
Runtime production versus regression-test growth Runtime production +12 net lines; regression tests +39 net lines The storage growth preserves atomic per-job settlement and access checks; the tests protect writer availability and acknowledgement recovery after revocation.

Labels

Label changes:

  • add P2: This removes unnecessary database writer contention in an optional memory plugin without evidence of an urgent user-facing outage.
  • 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 removes unnecessary database writer contention in an optional memory plugin without evidence of an urgent user-facing outage.
  • 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 26, 2026, 12:33 PM ET / 16:33 UTC.

@steipete
steipete merged commit bd90ea5 into main Oct 26, 2026
218 of 221 checks passed
@steipete
steipete deleted the steipete/perf-micro-knowledge-ingest-tx-20260919 branch October 26, 2026 16:45
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…law#184789)

Keep Git outside write transactions, settle each checkpoint and receipt atomically, and reuse per-drain request facts and statements. Label ingest transaction owners while preserving publication and recovery semantics.
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. plugin: knowledge rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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