Skip to content

perf(cron): reuse receipt transactions for agent availability - #156801

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-cron-receipt-guard-spawnsync-20260919
Sep 23, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-cron-receipt-guard-spawnsync-20260919

Conversation

@steipete

@steipete steipete commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Cron receipt availability checks can synchronously spawn a SQLite snapshot child while holding the shared-state write coordinator, blocking the Gateway event loop and other state writers.

User Impact

Receipt validation keeps the existing deletion, admission-refusal, and roster checks without paying for another database snapshot. No configuration, schema, retention, migration, or update behavior changes.

Why This Change Was Made

Receipt persistence and receipt-current checks now pass their existing transaction to the deletion owner. The shared current-authority reader also reuses the cached writer only inside its same-thread coordinated transaction, so lifecycle and worktree callbacks read the pending authoritative rows. Ordinary read-only/discovery reads keep committed-state isolation, and schema and maintenance checks remain in place. Admission refusals already belong to an in-memory owner and need no new database reader or cache.

Evidence

A synthetic measurement executes the real receipt beforeWrite hook in three shared-state write transactions. The original code fails the regression with three synchronous snapshot children and nine extra connection opens.

Three receipt guards Elapsed Child spawns Extra connections
Before 453.2 ms 3 9
After, implicit current-reader reuse 5.26 ms 0 0
After, supplied transaction 3.04 ms 0 0

These are focused samples, not a production latency projection. The supplied path removes about 99.3% of the measured transaction time.

Validation uses provider blacksmith-testbox, profile openclaw-check, lease tbx_01m381te2sf6j1dcsvf196e7cm (Testbox run).

  • Baseline: node scripts/run-vitest.mjs src/cron/store/run-receipt-store.test.ts -t 'checks receipt availability' --maxWorkers=1 — expected regression failure (3 spawns, 9 connections).
  • node scripts/check-changed.mjs --base faa6aa6243e — passed: core typecheck, all 25 test typecheck graphs, lint (zero warnings/errors), formatting, line limits, export checks, schema guards, and zero runtime import cycles. Remote command duration: 39m29s.
  • Final focused rerun — 268 tests passed across seven files, including the Gateway cron integration and receipt-settlement suites. The compound remote run verified the physical checkout and changed source hashes before testing, then completed in 2m16s. Commands: the three timed pnpm test invocations below, followed by node scripts/run-vitest.mjs src/state/openclaw-state-db-readonly.test.ts src/state/openclaw-state-db.runtime-fence.test.ts src/cron/service/run-receipt-settlement.test.ts src/gateway/server-cron.test.ts --maxWorkers=1.

Measured changed-test file costs on the same Testbox, using /usr/bin/time -p pnpm test <file> --maxWorkers=1: receipt store 40.45s wall (37 tests, including 24.2s cold worker preparation), lifecycle registry 14.26s (12 tests), read operations 10.23s (13 tests). The receipt suite needs real SQLite transactions and process instrumentation to catch this regression; cold worker compilation dominates its wall time. CI case-duration sums from the first run: receipt store 4.181s (37 cases), lifecycle registry 6.775s (12 cases), and read operations 0.949s (13 cases); these exclude setup/import overhead.

Independent review: no actionable P0–P2 findings after retaining explicit schema validation and extracting cached-handle reuse to stay within the line cap.

The first remote invocation lacked dependencies; a frozen-lockfile install on the same lease fixed the fixture. The first changed check also compared against the remote seed's older origin/main; subsequent checks use the lane's pinned starting commit faa6aa6243e.

Stable started cron.list/cron.status/page/get calls are verified to acquire no state write coordinator and dispatch no state worker mutation. Cold/stale store loading can still repair rows through loadCronJobsStoreWithConfigJobs, and an unstarted scheduler can write through recomputeUnownedCronSchedules; changing those repair contracts is not a one-line read routing fix and remains outside this lane.

The caller audit found no missed same-thread lifecycle migration: agent creation/team changes hold a config lock, cron add/update availability checks are outside native transactions, deletion completion already uses the supplied database, and generic worktree authority callbacks receive the central reader fix. Worker-thread admission callbacks keep their independent current-reader path because their writer handle belongs to another thread. No live Gateway deployment, production tail-latency measurement, or RSS comparison was performed. The Testbox lease was stopped after validation.

CI repair in the final change

The first PR CI run passed 143 jobs but failed checks-node-changed-extensions-bundle-18: Codex settlement cleanup hooks timed out after 180 seconds, and the workflow automatically retried its no-output stall. The CI merge incorporated newer main session-coordinator code from #156067 that had replaced native promise timers with global-timer backoff while retaining a native monotonic deadline. Switching a fixture from fake to real timers could strand accepted storage work on an abandoned fake retry timer.

The exact CI merge 989dd44c6e69a20eb33afb9f95b02d4bf5f9d63d and original 12-file/two-worker group reproduced the same cleanup timeout on Blacksmith Testbox tbx_01m388bbfqhe127xcdf7322xe1. Restoring native node:timers/promises backoff made all 107 tests pass on tbx_01m388rnvrjzvp29056mh61w5p in 100.89s; the first formerly failing case completed in 2.877s. Deadlines, cancellation, authority rechecks, and acquisition-only retries remain intact. The existing unit cases use a virtual sleep adapter so their timing and assertions remain deterministic; that file passed all nine tests in 2.30s wall (0.101s summed CI case time on the repaired head). Worker custody, receipt, and lifecycle siblings also passed (53 tests), followed by core typechecking. Final two-file lint passed with zero warnings/errors; the nine coordinator cases passed again. Fresh independent review found no actionable P0–P2 issues. A source-sync timeout occurred before one lint attempt; its transport retry succeeded. All Testbox leases are stopped. The final tree matches the tested CI-merge tree plus the reviewed timer repair.

Final CI: run 35934135123 passed on e9078ad020df319091ae39071f9bc7ab865dc3c0: 145 successful jobs, 15 skipped, zero failed. The previously failing extension bundle passed.

Carry the receipt transaction into deletion guards and reuse coordinated native transactions for current-authority reads. Preserve ordinary committed-row isolation and schema validation. Synthetic receipt guards dropped from 453.2 ms with three child spawns to 3.04 ms with none; 268 focused Testbox tests and the complete changed-file gate passed.
@clawsweeper

clawsweeper Bot commented Sep 23, 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 agents Agent runtime and tooling size: M labels Sep 23, 2026
@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 Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 6:10 PM ET / 22:10 UTC.

ClawSweeper review

What this changes

Cron receipt checks pass their SQLite transaction to the agent-deletion guard and let synchronous current-authority readers reuse a coordinated writer while ordinary reads retain committed-state isolation.

Merge readiness

✅ Ready for maintainer review

Current main still has the synchronous receipt-guard hotspot, so this PR remains useful. The reviewed patch has no supported blocking correctness finding.

Priority: P2
Reviewed head: 2de010c0c0369160bb44df39d500c6d55a298fad

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused patch has relevant transaction and rollback coverage plus reported direct SQLite measurements, with no supported blocking finding.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The member-authored PR is exempt from the contributor proof gate. Its body reports before/after Testbox measurements through the production receipt hook with real SQLite transactions; the linked logs were unavailable to this reviewer, and no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The member-authored PR is exempt from the contributor proof gate. Its body reports before/after Testbox measurements through the production receipt hook with real SQLite transactions; the linked logs were unavailable to this reviewer, and no stored-data contract changes.
Evidence reviewed 10 items Current-main hotspot: The receipt persistence hook calls the availability guard without its existing database transaction, leaving the deletion-journal reader to take a separate path.
Current-main reader behavior: The cached read path rejects a writer with an active transaction; the current-authority call therefore cannot reuse that transaction on main.
Transaction-local receipt guard: The introduced hook supplies its receipt transaction before the receipt ownership and job checks proceed.
Findings None None.
Security None None.

How this fits together

The Gateway’s cron scheduler checks an agent’s availability and a persisted run receipt before updating job state. Those checks use the shared SQLite state database and either allow the receipt transition or refuse it.

flowchart LR
  A[Cron run] --> B[Receipt transaction]
  B --> C[Agent availability check]
  D[Deletion journal] --> C
  E[Admission and roster] --> C
  C --> F{Available?}
  F -->|Yes| G[Receipt update]
  F -->|No| H[Refused transition]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +41, Tests +91, Docs +8. Total +140 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 9 76 35 +41
Tests 3 101 10 +91
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 185 45 +140

Review metrics

Metric Value Why it matters
Receipt guard measurement 3→0 child spawns; 9→0 extra connections The submitted Testbox measurement targets the transaction cost this PR is intended to remove.
Production and test delta production +76/−35 lines; tests +101/−10 lines Production growth extracts coordinated reader reuse, while the added tests cover receipt overhead and lifecycle rollback.

Technical review

Best possible solution:

Keep agent-deletion authority checks inside the owning receipt transaction and preserve committed-state isolation for discovery reads as remaining cron work moves through the existing SQLite worker owner.

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

Yes, the current-main receipt hook and separate reader path give a clear reproduction target, and the PR body reports a failing baseline through that hook. I did not execute current main in this read-only review.

Is this the best way to solve the issue?

Yes. Reusing the existing transaction addresses the nested read at its owner without adding a parallel authority cache; the patch also preserves ordinary read isolation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 764c9331a31b.

Labels

Label changes:

  • add P2: This is a bounded cron and shared-state performance repair with no demonstrated urgent user-facing outage.
  • 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. Not applicable: The member-authored PR is exempt from the contributor proof gate. Its body reports before/after Testbox measurements through the production receipt hook with real SQLite transactions; the linked logs were unavailable to this reviewer, and no stored-data contract changes.

Label justifications:

  • P2: This is a bounded cron and shared-state performance repair with no demonstrated urgent user-facing outage.
  • 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 member-authored PR is exempt from the contributor proof gate. Its body reports before/after Testbox measurements through the production receipt hook with real SQLite transactions; the linked logs were unavailable to this reviewer, and no stored-data contract changes.

Evidence

What I checked:

  • Current-main hotspot: The receipt persistence hook calls the availability guard without its existing database transaction, leaving the deletion-journal reader to take a separate path. (src/cron/service/run-receipts.ts:369, 764c9331a31b)
  • Current-main reader behavior: The cached read path rejects a writer with an active transaction; the current-authority call therefore cannot reuse that transaction on main. (src/state/openclaw-state-db-readonly.ts:287, 764c9331a31b)
  • Transaction-local receipt guard: The introduced hook supplies its receipt transaction before the receipt ownership and job checks proceed. (src/cron/service/run-receipts.ts:369, 2de010c0c036)
  • Reader isolation guard: Only a current-authority read in a coordinated active transaction may borrow the cached writer; ordinary reads continue to decline an in-transaction handle. (src/state/openclaw-state-db-readonly-reuse.ts:21, 2de010c0c036)
  • Pending-row and rollback coverage: The added lifecycle test checks pending provenance and deletion rows inside a transaction, then verifies authority is restored after rollback. (src/agents/agent-lifecycle-registry.test.ts:53, 2de010c0c036)
  • Submitted behavior evidence: The PR body reports a Testbox measurement through the production receipt hook and real SQLite transactions: three child spawns and nine extra connections before the change, zero of each afterward. It also reports focused test results and states that no live Gateway deployment was run.

Likely related people:

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

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.

Integrate the main revision exercised by this PR's CI merge and keep native
storage retries in the same clock domain as their monotonic deadlines.
Global fake timers could strand accepted worker work when a caller restored
real timers, leaving Codex settlement cleanup hooks blocked for 180 seconds.

The exact failing 12-file CI group reproduced on Testbox. Restoring native
promise timers passed all 107 cases; the first formerly blocked case settled
in 2.877 seconds. Coordinator budget, cancellation, authority, and worker
custody checks remain intact.
@steipete
steipete merged commit adf4aff into main Sep 23, 2026
226 checks passed
@steipete
steipete deleted the steipete/perf-micro-cron-receipt-guard-spawnsync-20260919 branch September 23, 2026 23:51
steipete added a commit that referenced this pull request Sep 24, 2026
JSON-escape mention sigils in optional attachment metadata so Codex does
not interpret filenames as skill or plugin requests. Preserve exact
decoded file identities and explicit mentions in the user's prompt.
Cover initial and steering preparation through the registered owner.

Merge current main including adf4aff from #156801. The prior CI run
reproduced settlement cleanup hangs when fake timers discarded the native
coordinator backoff; it was canceled after the failures were captured.
The owning repair keeps native storage waits independent of caller timers.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 24, 2026
…penclaw#156801)

Carry the receipt transaction into deletion guards and reuse coordinated native transactions for current-authority reads. Preserve ordinary committed-row isolation and schema validation. Synthetic receipt guards dropped from 453.2 ms with three child spawns to 3.04 ms with none; 268 focused Testbox tests and the complete changed-file gate passed.
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. 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