Skip to content

perf(sessions): yield during SQLite entry write contention - #160801

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-thread-sqlite-busy-wait-20260919
Sep 29, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-thread-sqlite-busy-wait-20260919

Conversation

@steipete

@steipete steipete commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-entry patches can stall unrelated Gateway requests while SQLite synchronously waits for another connection's write transaction.

User Impact

The Gateway can service its event loop while an entry patch waits for SQLite admission. The existing admission deadline remains in place, so a sufficiently long competing transaction can still make the patch fail. No configuration, schema, durability, or update migration changes.

Why This Change Was Made

Ordinary and lifecycle-target entry patches use the existing asynchronous BEGIN-admission primitive, with a zero native busy timeout through commit. Only a failed BEGIN IMMEDIATE may retry. The existing session writer queue retains FIFO order through publication. Each attempt retains and rechecks its original connection; the admitted transaction revalidates prepared rows and current caller authority. Admitted writes and publications never replay.

The helper is explicitly registered with the synchronous-callback source guard. Retired async-transaction APIs remain banned. A Slack Stop-owner fixture now awaits its competing real session write at the existing async routing boundary; its previous assumption about updater/commit timing failed under the yielding path. All Stop-ownership assertions remain unchanged, and Slack production code is unchanged.

The change adds 71 net core production lines and one guard-registration line. Transcript snapshot writes, other synchronous lifecycle writes, and synchronous entry reads remain outside this cutover.

Evidence

A real second SQLite connection holds the agent-store write lock; the caller's next event-loop turn releases it. The measurement caps native waiting at 250 ms to bound the negative control:

Measurement Before After
Event-loop release callback delay 262.19 ms 0.94 ms
Focused case, including fixture setup 447 ms, failed 206 ms, passed

All remote proof used blacksmith-testbox, profile openclaw-check:

  • tbx_01m3n3bsyannhvrmc7nyhwv48y (run): pinned source/file hashes; held-lock comparison; 58 session tests and 29 transaction tests passed. Core typecheck, formatting, line-cap/assertion guards, and dependency checks passed.
  • tbx_01m3n535ya5p3za673w066n515 (run): changed-test typecheck (agents-sessions), targeted lint, schema/storage guards, import-cycle and unused-export checks passed.
  • tbx_01m3n7m0zbbt6e8d69w5qrqh18 (run): 46 focused session/guard tests passed after the CI corrections, the actual SQLite transaction-boundary check passed, and its negative control failed before registering the synchronous callback. The original 32-file Slack group reproduced the CI failure; the corrected group passed 3 times (1,013 tests each), followed by 20 clean standalone runs of the 34-test Slack file.

Focused commands use node scripts/run-vitest.mjs with the entry revalidation, entry admission, environment-capture, and SQLite transaction test files; guard proof uses pnpm lint:tmp:sqlite-transaction-boundary and test/scripts/check-sqlite-transaction-boundary.test.ts. Slack group replay preserves the CI selection and concurrency through scripts/ci-run-node-test-shard.mts.

Measured costs with pnpm test <file> --maxWorkers=1: entry revalidation 40.25 s wall / 37 tests (cold compiler dominates; test execution about 4 s); environment capture 6.32 s / 4 tests; guard 1.47 s / 5 tests; Slack agent events 30.70 s cold and 11.46–15.59 s warm / 34 tests. Native contention proof needs real connections and uses an event-loop barrier rather than sleeps or timing assertions.

The aggregate changed check on the pinned base stops on the inherited environment-name budget violation (477/476), fixed on current main by #160756. The remaining selected checks were run separately; no budget was changed. Initial CI also timed out in the unchanged shared-state worktree recovery case recovers clean CRLF from worktree-autocrlf, missing=true. Its original two-plan Node replay passed all 58 files / 974 tests; the timeout's cause remains unresolved and no fix is claimed for it.

Independent Codex autoreview is scoped-clean with no actionable P0–P2 findings, including the guard correction and Slack fixture ordering. No production load campaign or live Gateway mutation was performed.

Final CI passed on 6770dfb0b4abed12b93f76c88ffed70e482794ed: run 36504259471, 21 min 36 s workflow wall time. All task-owned Testbox leases are stopped.

Rollback-journal compatibility follow-up: #160887 removes the redundant timeout override so BEGIN keeps yielding while admitted writes and COMMIT retain the original bounded wait. It includes a red/green native reader-contention proof.

Keep the Gateway event loop responsive while session-entry patches wait for another SQLite writer. Reuse begin-only asynchronous admission with zero native busy waiting, retaining FIFO ordering, connection custody, commit revalidation, and non-replay of admitted writes. No schema or configuration changes.
@clawsweeper

clawsweeper Bot commented Sep 28, 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 size: S labels Sep 28, 2026
@steipete
steipete enabled auto-merge (squash) September 28, 2026 23:50
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 8:48 PM ET / September 29, 2026, 00:48 UTC (Revision 2).

ClawSweeper review

What this changes

Session-entry patches yield while waiting for a SQLite write lock, with regression tests, a transaction guard update, a Slack test-fixture adjustment, and database-access documentation.

Merge readiness

⛔ Blocked before merge - 4 items remain

Current main still makes session-entry patches wait synchronously for a SQLite writer, so this PR remains useful. A supported rollback-journal case can now fail at commit under read contention, which blocks merge.

Priority: P2
Reviewed head: 6770dfb0b4abed12b93f76c88ffed70e482794ed

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The contention proof is strong, but a supported journaling mode has an unresolved commit regression.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body reports before-and-after Testbox output from the production session patch entry point with a real second SQLite connection holding the write lock; the after-fix callback ran promptly and the patch committed. That proves yielding admission, while rollback-journal commit compatibility remains an independent merge blocker. No stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body reports before-and-after Testbox output from the production session patch entry point with a real second SQLite connection holding the write lock; the after-fix callback ran promptly and the patch committed. That proves yielding admission, while rollback-journal commit compatibility remains an independent merge blocker. No stored-data contract changes.
Evidence reviewed 8 items Current main still uses synchronous entry writes: The current-main session patch path calls runOpenClawAgentWriteTransaction after preparing the patch; the proposed yielding helper is absent there.
Introduced zero-timeout commit path: The new admission wrapper retains a zero native busy timeout around the synchronous transaction, including COMMIT.
Supported rollback-journal storage: OpenClaw selects rollback journaling for NFS, SMB, virtiofs, and 9p mounts.
Findings 1 actionable finding [P1] Preserve bounded COMMIT waiting on rollback journals
Security None None.

How this fits together

Gateway and channel activity updates session entries in an agent’s SQLite database. The session writer queue orders those updates, and committed changes are published to session state.

flowchart LR
  A[Session patch request] --> B[Session writer queue]
  B --> D[SQLite write admission]
  C[Competing SQLite connection] --> D
  D --> E[Revalidate rows and authority]
  E --> F[Commit entry change]
  F --> G[Publish session state]
Loading

Before merge

  • Preserve bounded COMMIT waiting on rollback journals (P1) - OpenClaw supports rollback journaling on NFS, SMB, virtiofs, and 9p. A concurrent reader can allow BEGIN IMMEDIATE but block COMMIT; this new zero busy timeout then throws SQLITE_BUSY, and the transaction helper cannot retry after admission. The former path allowed up to five seconds for that reader to finish. Preserve rollback-journal commit behavior and cover it with a two-connection session-patch regression.
  • Resolve merge risk (P1) - On supported rollback-journal storage, an active reader can make COMMIT return SQLITE_BUSY immediately, rolling back a session-entry patch that previously had a bounded chance to finish.
  • Resolve merge risk (P1) - The reported two-connection proof covers write-lock admission but does not establish upgrade-safe commit behavior with a concurrent reader in rollback-journal mode.
  • Complete next step (P2) - Repair rollback-journal COMMIT contention and demonstrate the existing session patch succeeds after a concurrent reader releases its lock before merge.

Findings

  • [P1] Preserve bounded COMMIT waiting on rollback journals — src/state/openclaw-agent-db-transaction.ts:61-64
Agent review details

Security

None.

PR surface

Source +71, Tests +89, Docs +10, Other +1. Total +171 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 2 74 3 +71
Tests 4 95 6 +89
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 8 180 9 +171

Review metrics

Metric Value Why it matters
Production and test growth production +71 lines, tests +89 lines The production growth supports retained connection and commit checks; the new tests cover admission and authority, but omit rollback-journal commit contention.

Merge-risk options

Maintainer options:

  1. Preserve rollback-journal commits (recommended)
    Repair the rollback-journal commit path and demonstrate that a reader releasing its lock allows the session patch to commit, while BEGIN admission still yields.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Preserve the existing bounded COMMIT wait for rollback-journal agent databases without replaying an admitted write. Add a real two-connection rollback-journal reader-contention regression through the session-entry patch path, and retain the existing yielding BEGIN proof.

Technical review

Best possible solution:

Keep yielding for BEGIN admission while preserving the existing bounded commit behavior on rollback-journal storage, then prove both journal modes with real connections through the session patch path.

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

Yes. The old write path and the reported two-connection Testbox comparison provide a high-confidence contention scenario, although this read-only review did not execute it locally.

Is this the best way to solve the issue?

No, not yet. Yielding at BEGIN addresses the event-loop stall, but the zero timeout through COMMIT needs a rollback-journal compatibility repair.

Full review comments:

  • [P1] Preserve bounded COMMIT waiting on rollback journals — src/state/openclaw-agent-db-transaction.ts:61-64
    OpenClaw supports rollback journaling on NFS, SMB, virtiofs, and 9p. A concurrent reader can allow BEGIN IMMEDIATE but block COMMIT; this new zero busy timeout then throws SQLITE_BUSY, and the transaction helper cannot retry after admission. The former path allowed up to five seconds for that reader to finish. Preserve rollback-journal commit behavior and cover it with a two-connection session-patch regression.
    Confidence: 0.92

Overall correctness: patch is incorrect
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4f993f287f3f.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The changed commit timeout can make existing rollback-journal session writes fail when a reader holds a lock.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body reports before-and-after Testbox output from the production session patch entry point with a real second SQLite connection holding the write lock; the after-fix callback ran promptly and the patch committed. That proves yielding admission, while rollback-journal commit compatibility remains an independent merge blocker. No stored-data contract changes.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement with a compatibility defect affecting supported rollback-journal installations.
  • merge-risk: 🚨 compatibility: The changed commit timeout can make existing rollback-journal session writes fail when a reader holds a lock.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body reports before-and-after Testbox output from the production session patch entry point with a real second SQLite connection holding the write lock; the after-fix callback ran promptly and the patch committed. That proves yielding admission, while rollback-journal commit compatibility remains an independent merge blocker. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports before-and-after Testbox output from the production session patch entry point with a real second SQLite connection holding the write lock; the after-fix callback ran promptly and the patch committed. That proves yielding admission, while rollback-journal commit compatibility remains an independent merge blocker. No stored-data contract changes.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-entry-revalidation.test.ts src/infra/sqlite-transaction.test.ts.
  • [P1] pnpm lint:tmp:sqlite-transaction-boundary.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RoboClaw: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Prove a session patch commits after a concurrent rollback-journal reader releases its lock, while retaining the existing yielding-admission result.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-28T23:55:27.689Z sha 14f9a5f :: needs maintainer review before merge. :: none

Name yielding admission separately from retired async-transaction APIs and register its synchronous callback with the source guard. Make the Slack Stop-owner fixture await its competing committed session write instead of depending on updater microtask ordering.
@openclaw-barnacle openclaw-barnacle Bot added channel: slack Channel integration: slack scripts Repository scripts labels Sep 29, 2026
@clawsweeper clawsweeper Bot added 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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. labels Sep 29, 2026
@steipete
steipete merged commit 5d60562 into main Sep 29, 2026
222 of 226 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-thread-sqlite-busy-wait-20260919 branch September 29, 2026 01:03
steipete added a commit that referenced this pull request Sep 29, 2026
Follow up #160801. Keep BEGIN admission yielding while restoring the original native timeout before the synchronous write and COMMIT, so session patches retain their bounded chance to commit after a rollback-journal reader finishes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…160801)

* perf(sessions): yield during SQLite entry write contention

Keep the Gateway event loop responsive while session-entry patches wait for another SQLite writer. Reuse begin-only asynchronous admission with zero native busy waiting, retaining FIFO ordering, connection custody, commit revalidation, and non-replay of admitted writes. No schema or configuration changes.

* fix(sessions): enforce synchronous callbacks during yielding admission

Name yielding admission separately from retired async-transaction APIs and register its synchronous callback with the source guard. Make the Slack Stop-owner fixture await its competing committed session write instead of depending on updater microtask ordering.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
Follow up openclaw#160801. Keep BEGIN admission yielding while restoring the original native timeout before the synchronous write and COMMIT, so session patches retain their bounded chance to commit after a rollback-journal reader finishes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: slack Channel integration: slack docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant