Skip to content

perf(sessions): keep agent-database transactions off the Gateway main thread - #163053

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-db-main-thread-holds-20260919
Oct 2, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-db-main-thread-holds-20260919

Conversation

@steipete

@steipete steipete commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Full-history recovery checkpoints, usage aggregation, and MCP App reconstruction can hold SQLite read transactions on the Gateway main thread and delay unrelated requests. This change sends those selectors through the existing admitted history worker and returns compact facts from one snapshot, including both MCP reconstruction passes. It adds prepared diagnostic context without extra queries or transcript payloads.

Schemas, stored bytes, retention, configuration, permissions, and update behavior are unchanged. Process-held incognito reads and shipped synchronous SDK contracts retain their existing owners. No summary cache or busy-worker synchronous fallback is introduced.

Why This Change Was Made

The branch was rebased onto main b21e522e2ad1, retaining only this lane's remaining changes. Main already provides the canonical restart-tombstone recovery worker and asynchronous custom-entry/message writes. Their overlapping branch implementations were removed during conflict resolution, preserving main's authority checks, FIFO admission, atomic recovery, and uncertain-outcome handling.

The failed mainRestartRecovery reference was private InternalSessionEntry.mainRestartRecovery, not a field to add to public SessionEntry. The redundant recovery kernel and registration are gone; the existing recovery worker owns that state. The benchmark preserves and restores typed native method descriptors and explicitly cancels its sampler. Its package command makes the executable discoverable to dependency analysis.

The original CI logs also identified a missing worker error-encoder import, a type import cycle through the sessions barrel, and tests using a worker thread where the host database broker requires the existing process-based test owner. These are repaired without changing performance semantics. The oversized spawn fixture's cache-TTL mock reader is moved into its existing mock helper.

Measurements

Historical performance evidence from this lane used Blacksmith Testbox, Node 24.19.0, baseline main 7cbaa6b36f15, 10,000 messages with 4 KiB payloads, and 2,000 other sessions. These are earlier before/after measurements, not a fresh comparison against the newer rebase base.

Operation Main-thread hold before → after Operation wall before → after Largest loop gap before → after
Recovery checkpoint 188.5 → 0 ms 189.3 → 95.5 ms 193.0 → 4.1 ms
Usage summary 170.8 → 0 ms 171.5 → 94.1 ms 179.1 → 0.7 ms
Tombstone recovery (now supplied by main) 1,815.6 → 0 ms 1,821.5 → 2,190.1 ms 1,823.0 → 4.5 ms
First custom append (now supplied by main) 5.9 → 0 ms 8.8 → 1,717.8 ms 8.8 → 6.9 ms

The original benchmark's wall time was 17.49 → 18.15 s and peak RSS 1,701,484 → 2,023,324 KiB. Moving blocking work does not promise lower write latency; the original tombstone wall time increased about 20%, and first append included cold worker startup. Reproduce via pnpm bench:agent-database-holds 10000 2000.

The earlier negative controls failed on native host-thread SQL for history, tombstone recovery, and custom messages. The history regression uses 1,204 messages and verifies checkpoint, usage, and MCP facts with no host transcript SQL. Existing runtime tests cover message publication, ancestry, rollback, and current authority. No live Gateway was changed.

Evidence

Blacksmith Testbox provider blacksmith-testbox, profile openclaw-check, lease tbx_01m3xhc9sejka6715p4rp4ht9n, workflow run https://github.com/openclaw/openclaw/actions/runs/36969110674.

The first lease installed dependencies and exposed two diagnostic-option type errors in the rebased candidate; those are repaired. A subsequent native full sync timed out before executing its payload, and that lease was stopped. Replacement lease tbx_01m3xhym6f83tkz5616ak0dd33 stayed queued from 05:38:48Z through the final 06:08:50Z status check on 2026-10-02. The first run hit the native 15-minute admission limit; after backoff, the retry remained queued through the 30-minute window. It never received a runner or workflow URL, and neither attempt executed its payload. Both task leases are stopped. No final passing remote result is claimed.

Independent Codex review passed with scoped-clean and no actionable P0/P1 findings for the staged candidate, including the unchanged recovery-owner contracts. The reviewer explicitly treated queued validation as unverified. The earlier CI run 36936592386 on 4058c9ec9c06 failed; its results are not current-head evidence. This prepared body is not a claim of publication.

Remaining work

The branch was rebased onto current main (merge base 9646ebea2497) and published as the exact head CI tests; the lane's final Testbox proof run was blocked by Testbox admission, so the hosted CI run on this head is the completion gate for the full changed-file checks. The Blacksmith Testbox measurements above are historical (taken on the pre-rebase head against the same owners) and are labeled as such. The check-test-types failure on the previous head (bench script forwarding into the overloaded native StatementSync methods) is fixed on this head.

@clawsweeper

clawsweeper Bot commented Oct 1, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 1, 2026
@steipete
steipete enabled auto-merge (squash) October 1, 2026 22:46
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 2, 2026, 2:36 AM ET / 06:36 UTC (Revision 3).

ClawSweeper review

What this changes

Moves full-history recovery, usage, and MCP App reconstruction into existing database workers, enables prepared custom-message appends, and adds transaction diagnostics and a benchmark.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR still addresses blocking transcript scans present on current main. No actionable introduced correctness or security defect was found, and the previous test-type concern is cleared by successful current-head checks.

Priority: P2
Reviewed head: 7c6d949f522f804a01aabbd9c864df1c98f53b50

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is coherent and source review found no blocking defect; historical performance evidence is useful, with a focused evidence-documentation follow-up remaining.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The supplied MEMBER classification exempts this internal PR from ordinary contributor proof. Historical Testbox measurements exercise the real recovery, usage, and append owners, but do not establish completion of validation for the rebased head. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied MEMBER classification exempts this internal PR from ordinary contributor proof. Historical Testbox measurements exercise the real recovery, usage, and append owners, but do not establish completion of validation for the rebased head. No stored-data contract changes require migration proof.
Evidence reviewed 10 items Pinned introduction reviewed: Reviewed the merge-base-to-head introduced changes, rather than endpoint drift or the stale test merge. The patch retains the existing history and writer owners, removes the host-facing transcript visitor, and adds typed summary requests.
Central work remains necessary: Fetched main still implements recovery checkpoints through the native transcript visitor and full usage aggregation through synchronous transcript-event visitation. The worker-summary cutover remains distinct from main's already-landed streaming-write and completion improvements.
Single-snapshot selection: Domain selectors load before snapshot acquisition. Both MCP reconstruction passes consume the same projection snapshot; durable requests use the admitted history worker, while incognito retains its process-held reader.
Findings None None.
Security None None.

How this fits together

OpenClaw stores session transcripts in per-agent SQLite databases. Gateway and agent callers read recovery, usage, and app-reconstruction facts from those transcripts; database workers perform the scans and return the selected results.

flowchart TD
  A[Gateway and agent requests] --> B[Transcript read owner]
  B --> C{Process-held incognito database?}
  C -->|Yes| D[Native snapshot reader]
  C -->|No| E[Admitted history worker]
  D --> F[Transcript selectors]
  E --> F
  F --> G[Recovery usage and app facts]
Loading

Before merge

  • Complete next step (P2) - Update the PR body with the published head, successful current-head type checks, standalone regression timings, and actual prompt-admission/cache-TTL validation results.
Agent review details

Security

None.

PR surface

Source +162, Tests +196, Docs +27, Config +1, Other +196. Total +582 across 46 files.

View PR surface stats
Area Files Added Removed Net
Source 26 507 345 +162
Tests 16 288 92 +196
Docs 1 29 2 +27
Config 1 1 0 +1
Generated 0 0 0 0
Other 2 197 1 +196
Total 46 1022 440 +582

Review metrics

Metric Value Why it matters
Production versus test growth Production net +162 LOC; tests/support net +196 LOC; benchmark +197 LOC Growth supports the worker cutover, compact selectors, diagnostics, and boundary coverage; the benchmark is separate from per-PR tests.

Technical review

Best possible solution:

Keep transcript selection and asynchronous appends with their existing admitted workers, preserving native incognito ownership and synchronous SDK contracts.

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

Yes, from source: current main's full recovery and usage selectors traverse native SQLite snapshots, and the supplied large-history benchmark provides a concrete trigger. This review did not execute it.

Is this the best way to solve the issue?

Yes. Reusing the admitted history worker and shared snapshot selectors avoids a competing database owner or summary cache while preserving existing contracts.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded performance improvement for large session histories, with no demonstrated urgent user-facing regression.
  • 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. Not applicable: The supplied MEMBER classification exempts this internal PR from ordinary contributor proof. Historical Testbox measurements exercise the real recovery, usage, and append owners, but do not establish completion of validation for the rebased head. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction reviewed: Reviewed the merge-base-to-head introduced changes, rather than endpoint drift or the stale test merge. The patch retains the existing history and writer owners, removes the host-facing transcript visitor, and adds typed summary requests. (src/gateway/session-transcript-readers.ts:155, 7c6d949f522f)
  • Central work remains necessary: Fetched main still implements recovery checkpoints through the native transcript visitor and full usage aggregation through synchronous transcript-event visitation. The worker-summary cutover remains distinct from main's already-landed streaming-write and completion improvements. (src/gateway/session-transcript-usage.ts:41, 25fbb38f16bd)
  • Single-snapshot selection: Domain selectors load before snapshot acquisition. Both MCP reconstruction passes consume the same projection snapshot; durable requests use the admitted history worker, while incognito retains its process-held reader. (src/gateway/session-transcript-read-kernel.ts:205, 7c6d949f522f)
  • Authority and storage contracts retained: Non-user preparation feeds the existing asynchronous append owner. That owner retains writer admission, identity assertions, commit guards, and committed-view adoption. No schema, configuration, retention, public SDK signature, or stored-format migration is introduced. (src/config/sessions/session-accessor.sqlite-transcript-message-append.ts:113, 7c6d949f522f)
  • Prior type concern cleared: The earlier head's check-test-types failed. At the reviewed head, check-test-types and all five core test-type checks completed successfully; no failure was returned by the inspected check-run pages. This clears the prior type-check follow-up without claiming the entire CI suite has completed. (scripts/bench-agent-database-holds.ts:62, 7c6d949f522f)
  • Historical performance evidence and remaining documentation: The captured body reports Blacksmith Testbox measurements using Node 24.19.0, 10,000 messages, and 2,000 other sessions: recovery and usage main-thread holds fell to zero. It correctly labels these measurements historical, but its Remaining work section incorrectly says the branch is unpublished and conflicting. Requested standalone regression costs and prompt-admission/cache-TTL results remain unrecorded.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: 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.

  • Record standalone regression timings and actual prompt-admission/cache-TTL validation results, and replace the body's obsolete unpublished/conflicting state.

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 (2 earlier review cycles)
  • reviewed 2026-10-01T22:46:34.202Z sha 4058c9e :: needs changes before merge. :: none
  • reviewed 2026-10-02T06:18:29.064Z sha 133554c :: needs changes before merge. :: none

… thread

Full-history recovery checkpoints, usage aggregation, MCP App reconstruction,
restart-tombstone recovery and runtime custom-message writes still reached the
agent database through native callback paths on the main thread, holding
transactions for seconds on large stores. Route them through the existing
database workers, keep tombstone recovery atomic through the canonical agent
writer, and add prepared session identifiers and event counts to the slow-hold
diagnostics.
@steipete
steipete force-pushed the steipete/perf-micro-agent-db-main-thread-holds-20260919 branch from 4058c9e to 133554c Compare October 2, 2026 06:12
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 2, 2026
@steipete
steipete merged commit b7cf8fa into main Oct 2, 2026
234 of 237 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-db-main-thread-holds-20260919 branch October 2, 2026 06:57
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…penclaw#163053)

* perf(sessions): keep agent-database transactions off the Gateway main thread

Full-history recovery checkpoints, usage aggregation, MCP App reconstruction,
restart-tombstone recovery and runtime custom-message writes still reached the
agent database through native callback paths on the main thread, holding
transactions for seconds on large stores. Route them through the existing
database workers, keep tombstone recovery atomic through the canonical agent
writer, and add prepared session identifiers and event counts to the slow-hold
diagnostics.

* fix(scripts): forward overloaded sqlite statement arguments in the agent-database holds bench
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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