Skip to content

perf: reduce repeated database work during Gateway startup - #174592

Merged
steipete merged 2 commits into
mainfrom
dbasync/bootmain4
Oct 16, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/bootmain4

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway startup and restart repeat database admission and lease bookkeeping even after the relevant owner has already established the facts.

User Impact

Startup performs fewer SQL statements while preserving Gateway exclusivity, runtime-pin recovery, and rollback custody. There is no configuration, schema, stored-format, or SDK change.

Why This Change Was Made

Completed runtime-pin migration reads its versioned receipt directly; actual pin access retains its schema and integrity admission. Fresh initialization uses the existing admitted native read and inserts the completion receipt only if absent. The copied-to-complete receipt and target-first commit ordering remain unchanged, including PostgreSQL's local, directly complete receipt.

Gateway lease acquisition retains the previous-owner liveness/refusal check and replaces delete/delete/insert with a conditional upsert. It reuses the state owner's transaction and publishes listening state with an owner-qualified update. The lease table, row, payload, and PostgreSQL advisory-lock contract are unchanged.

Staging-token creation trusts the private empty file it just created. Existing tokens still validate journal mode and the durable retirement marker; native transactions retain admission and retirement exclusion.

Removed checks and accepted edges:

  • Repeated pin-payload schema/integrity admission during completed migration: pin payload admission occurs when a pin is actually used; the stable receipt alone decides whether migration is complete.
  • Fresh initializer's second receipt read: ON CONFLICT DO NOTHING preserves any receipt already published by another initializer.
  • Nested lease savepoint and duplicate write admission: the existing state transaction owns admission; native bootstrap still opens its own transaction.
  • Listening publication's ordinary pre-read: an owner-qualified update refuses a replaced owner; the rare missing-start-identity path retains the read needed to preserve heartbeat repair.
  • Fresh staging-token journal/header probes: a private, unpublished, exclusively created empty file has the native default format.
  • Separate staging reader schema probe: the retained header read already establishes the reader's lock.

Quarantine header repetition is deferred: short-lived admission retires its facts on last close, so retaining those facts needs a lifecycle-owner change rather than another cache. Device pairing and schema changes are out of scope.

Evidence

Current head db8a3e28d21 is rebased without conflicts onto 3e55551264e, including the Windows helper packaging fix. Both reviewed commits are patch-identical after the rebase (git range-diff). Two Codex review rounds completed with no actionable findings.

Final-head CI 38968021545 passed all 55 selected jobs (26 skipped), including types, lint, source/export contracts, architecture/Madge and database ratchets. PostgreSQL conformance actually ran: 372 tests across 66 files passed, including all three maintenance-custody PostgreSQL cases, the corrected SQLite inspection expectation, nine Doctor migration cases and twelve port-recovery cases.

The published-driver update cell passed in one attempt: published 2026.10.4 to candidate db8a3e28d21, readiness HTTP 200, running version verified. The earlier missing-Windows-helper blocker is resolved. Package Acceptance's separate npm 12 installation succeeds but its installed-entry budget fails (47,789 > 47,500; below the shipped 50,000 updater cap). The same check failed on same-day main, 47,610 > 47,500, with the identical budget-checker blob. No exact current-base entry-count delta is claimed.

Three alternating shared-harness-v3 pairs completed in order M1,C1,M2,C2,M3,C3, base 3e55551264e versus candidate db8a3e28d21, through one ordinary proof slot. Every arm passed 14 turns and both shutdowns; Node 24.22.0, SQLite 3.54.0 and harness/native-library hashes stayed pinned. NODE_DISABLE_COMPILE_CACHE=1. Fixtures stayed below 5 GB and were removed after compaction. Counts only: no latency claim on the busy host (one-minute load snapshot 68.56 during M3).

Values are median [min–max]. Boot/restart/whole use three runs per side; warm rows pool 30 turns per side. SQL includes all threads and helper processes; MAIN is Gateway main-thread SQL.

Phase Base SQL / requests / MAIN Candidate SQL / requests / MAIN
Fresh boot 397 [383–398] / 92 [89–94] / 92 [92–92] 343 [339–363] / 93 [92–105] / 64 [63–64]
Restart boot 423 [392–436] / 104 [98–119] / 82 [82–82] 367 [367–380] / 98 [98–103] / 66 [66–66]
Warm raw 69 [67–109] / 22.5 [22–29] / 0 [0–13] 70 [67–93] / 23 [22–29] / 0 [0–9]
Warm causal 68.5 [67–73] / 22.5 [22–24] / 0 [0–0] 68.5 [67–73] / 22.5 [22–24] / 0 [0–0]
Whole workload 3888 [3885–3888] / 1021 [1021–1022] / 205 [205–205] 3794 [3782–3801] / 1022 [1014–1027] / 157 [156–157]

Warm non-regression: every paired causal warm operation group matches exactly: 688 SQL / 226 requests / 0 MAIN per ten-turn arm, with 619 normalized SQL groups and 182 request groups. Shared-family per-turn SQL/request medians are unchanged: exact-entry 0/0, actor hydration 0/0, entry-cache snapshots 0/0, row facts 2/2, watermark reads 0/0. Raw warm medians rise by 1 SQL and 0.5 requests because plugin startup, checkpoint, catalog and quarantine background work lands in different windows. The same plugin lifecycle operation executes exactly 13 MAIN statements in every whole workload; its warm-window allocation is 4→13, 4→13, and 13→4 across the three pairs. None of the four edited owners adds causal warm work.

The disjoint union of the four edited owner cohorts falls 264 [264–265] → 171 [171–171] SQL, with 17 [17–18] → 17 [17–17] requests and 102 → 53 MAIN across the whole workload. Whole raw request median 1021→1022 and fresh-boot request median 92→93 come from work outside those edited-owner cohorts; no request increase is attributed to the change. The baseline's extra snapshot request occurs only in M3. The overall 94-SQL median saving and the deterministic 93-SQL owner saving are reported separately.

Per-owner whole-workload SQL / request medians (overlapping stack cohorts; do not add):

Owner Base Candidate SQL / request delta
Runtime-pin migration 43 / 0 14 / 0 −29 / 0
Gateway owner lease 47 / 2 33 / 2 −14 / 0
Staging custody 165 / 12 101 / 12 −64 / 0
Snapshot capture 28 / 7 23 / 7 −5 / 0
Quarantine (unchanged/deferred) 144 / 47 145 / 47 +1 / 0

The complete disjoint MAIN ledger below reconciles every fresh/restart statement in all six arms with zero unclassified groups. The targets below 50 fresh / 40 restart MAIN are not reached. Quarantine still costs 16 restart MAIN statements and requires lifecycle-owner work; device migration remains untouched. Candidate cold-open deadlines caused one extra timeout-reset statement in C1/C2, absent in C3.

Complete boot MAIN owner ledger (median [min–max])
Owner Fresh base → candidate Restart base → candidate
ACP startup metadata migration readiness 0 [0–0] → 0 [0–0] 1 [1–1] → 1 [1–1]
Daemon runtime-pin migration 14 [14–14] → 13 [13–13] 10 [10–10] → 1 [1–1]
Device desktop pairing migration 8 [8–8] → 8 [8–8] 7 [7–7] → 7 [7–7]
Gateway owner lease acquire and payload update 15 [15–15] → 9 [9–9] 16 [16–16] → 12 [12–12]
Historical webhook migration evidence and completion marker 8 [8–8] → 8 [8–8] 1 [1–1] → 1 [1–1]
Persisted quarantine admission 0 [0–0] → 0 [0–0] 16 [16–16] → 16 [16–16]
Preflight admission and inventory 9 [9–9] → 9 [9–9] 9 [9–9] → 9 [9–9]
Registry listing admission and rows 2 [2–2] → 2 [2–2] 2 [2–2] → 2 [2–2]
SQLite runtime capability probes 3 [3–3] → 3 [3–3] 3 [3–3] → 3 [3–3]
Session startup migration readiness 0 [0–0] → 0 [0–0] 3 [3–3] → 3 [3–3]
Snapshot schema and header capture 5 [5–5] → 0 [0–0] 0 [0–0] → 0 [0–0]
Staging-token lock and custody 18 [18–18] → 1 [1–1] 4 [4–4] → 1 [1–1]
State cold open and WAL setup 10 [10–10] → 11 [10–11] 10 [10–10] → 10 [10–10]

Changed-file formatting, type-aware lint and git diff --check pass. The focused owner tests cover interrupted migration and SIGKILL recovery, stale/live-owner refusal, competing Gateway acquisition and staging retirement. The final-head local run passed all 69 tests across five owner files; the additional staging SIGKILL recovery case also passed. CI passes the changed tests.

Change size: 10 files, +292/−80 lines (production +115/−74; tests +165/−6; inventory classification +12). No schema, SDK, dependency or persisted lease contract changes. The new inventory entry classifies only conditional lease acquisition as the existing synchronous process-lock exception; heartbeat renewal remains worker-owned. The native inventory reports owned-area T1 0 → 0, global T1 197 → 197, and T1-compat 10 → 10. Owned T2 changes 1 → 2 because the new conditional-acquire primitive is classified as the existing synchronous lock exception. The exact-base worker and dialect ratchets pass; changed-file engine-maintenance dialect matches fall 7 → 5. The final boot MAIN owner ledger is included above. The generated inventory Markdown refresh requested by the automated P2 review remains a follow-up.

Standalone Knip completed every scope: script exports pass; production has one and full-tree has six inherited findings, all matching the same rule/path/symbol on scheduled main. The finding-source blobs are identical on base, candidate and observed main. There are no candidate-only findings; this is an inherited-only failed scan, not a clean scan. Both inherited failures have been routed to the main-failure owners.

@clawsweeper

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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-16T21:17:34.557180Z db8a3e2 New commits
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts size: M labels Oct 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9f98ad8025

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1004 to +1008
"src/infra/gateway-owner-lease.ts",
[
{
tier: "T2",
operations: ["acquireGatewayOwnerLease"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Regenerate the worker-access inventory

This classification changes the generator output because the target source adds an executeSqliteQueryTakeFirstSync call under acquireGatewayOwnerLease, but docs/reference/database-schemas/worker-access-inventory.md still reports 2,312 calls and contains no T2 row for gateway-owner-lease.ts. Consequently, pnpm db:worker-inventory:check will report the committed artifact as stale and the published audit undercounts synchronous startup database access; regenerate and commit the inventory with this change.

AGENTS.md reference: scripts/AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

@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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR reduces repeated migration-receipt checks, Gateway lease statements, and staging-token probes during startup.

Example: A Gateway restarts with a completed version-1 runtime-pin migration receipt.

  • Before: Checking migration completion also admits the pin store’s schema and integrity.
  • After: Completion reads the receipt directly; actual pin access retains full admission.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful scope and coherent ownership, but mandatory upgrade evidence remains pending and two concrete integration repairs are required.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Gateway starts and restarts perform avoidable database work after the relevant ownership and migration facts are already established.
Reason: The feature-history owner directs this bounded optimization, and source inspection supports the redundant-work reductions without new user settings.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this useful, maintainer-directed optimization open; the generated inventory is stale and CI confirms an outdated maintenance-test expectation.

Priority: P2
Reviewed head: 9f98ad80259ab9985ad690d1229bd9f52a4a8155

Before merge

  • Update the maintenance conformance expectation for the removed probes (P2) - The maintenance inspection path now omits PRAGMA busy_timeout=0 and SELECT rootpage FROM sqlite_schema LIMIT 1, but maintenance-custody.conformance.test.ts:264 still expects both. The exact-head checks-node-changed-compact-small-6 job fails on that mismatch. Update the expected trace to match the intended optimization while retaining the remaining inspection and custody assertions.
  • Regenerate the committed worker-access inventory (P2) - The new classification and lease-acquisition primitive change the generator output, but docs/reference/database-schemas/worker-access-inventory.md remains unchanged and lacks the Gateway lease row. The generator compares its complete rendered output against that artifact, so db:worker-inventory:check will reject it. Regenerate and commit the artifact using the existing generator.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Update the maintenance conformance expectation for the removed probes — src/infra/sqlite-staging-token.ts:132-134
  • [P2] Regenerate the committed worker-access inventory — scripts/database-worker-inventory.mjs:1003-1009

Tests

  • Missing end-to-end proof: No latest-stable upgrade/restart result or base-fails/head-passes result for the new regressions is supplied.
Agent review details

How this fits together

Gateway startup uses shared-state leases for process ownership, a daemon-owned SQLite store for runtime intent, and SQLite staging tokens for temporary-copy custody.

flowchart TD
  A[Gateway startup] --> B[Physical state custody]
  B --> C[Gateway owner lease]
  C --> D[Worker heartbeat]
  A --> E[Runtime pin migration receipt]
  E --> F[Daemon service intent store]
  A --> G[Staging token custody]
Loading

Technical review

Best possible solution:

Retain the focused optimization, repair its generated artifact and test expectation, and establish upgrade compatibility.

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

Current-main source shows repeated pin-store admission, nested lease transaction work, and staging probes; CI independently demonstrates the introduced maintenance-test failure.

Is this the best way to solve the issue?

The optimization fits the existing owners and documented admission policy without adding a cache or changing persisted formats, but its integration repairs remain necessary.

Full review comments:

  • [P2] Update the maintenance conformance expectation for the removed probes — src/infra/sqlite-staging-token.ts:132-134
    The maintenance inspection path now omits PRAGMA busy_timeout=0 and SELECT rootpage FROM sqlite_schema LIMIT 1, but maintenance-custody.conformance.test.ts:264 still expects both. The exact-head checks-node-changed-compact-small-6 job fails on that mismatch. Update the expected trace to match the intended optimization while retaining the remaining inspection and custody assertions.
    Confidence: 1
  • [P2] Regenerate the committed worker-access inventory — scripts/database-worker-inventory.mjs:1003-1009
    The new classification and lease-acquisition primitive change the generator output, but docs/reference/database-schemas/worker-access-inventory.md remains unchanged and lacks the Gateway lease row. The generator compares its complete rendered output against that artifact, so db:worker-inventory:check will reject it. Regenerate and commit the artifact using the existing generator.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Runtime-pin receipt admission changes intended behavior with a stated reason (b87a1ab: The daemon-owned store separated local runtime intent from shared state and preserved exact copy/retire recovery; this PR explicitly defers payload admission until actual pin access.)
  • Gateway lease acquisition and listening publication keeps the original intent (perf(gateway): avoid copying state during startup lock admission #169097: Startup admission must preserve physical custody, independently refuse live or unverifiable owners, and await heartbeat readiness; those contracts remain in the inspected callers and transaction owners.)
  • Staging-token custody and retirement keeps the original intent (b25f3d8: Recovery must reclaim disposable payload under exclusive custody while preserving active readers and durable retirement; this PR retains those native transactions and existing-token checks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm db:worker-inventory:check
  • pnpm test src/infra/database-engine/maintenance-custody.conformance.test.ts src/infra/sqlite-staging-token.test.ts --maxWorkers=1
  • pnpm test src/infra/gateway-owner-lease.test.ts src/infra/state-migrations.daemon-runtime-pins.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b87a1ab adds src/daemon/runtime-pin-store.ts:101 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b87a1abdad51; files: src/daemon/runtime-pin-store.ts)
  • Vincent Koc: Raw commit b25f3d8 adds src/infra/sqlite-staging-token.ts:89 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b25f3d82963c; files: src/infra/sqlite-staging-token.ts)
  • darkamenosa: Raw commit 9843b93 adds src/daemon/runtime-pin-state.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 9843b937e354; files: src/daemon/runtime-pin-state.ts)

PR surface

Source +41, Tests +161, Other +12. Total +214 across 9 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 115 74 +41
Tests 3 165 4 +161
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 12 0 +12
Total 9 292 78 +214

Review metrics

Metric Value Why it matters
Production versus test changes Production +115/-74; tests +165/-4 Production growth separates receipt reading from payload admission; test growth covers persisted receipts, crash recovery, reader custody, and competing acquisition.

Labels

Label changes:

  • add P2: This is a bounded startup performance improvement with mechanical integration defects and no established urgent runtime regression.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a bounded startup performance improvement with mechanical integration defects and no established urgent runtime regression.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 16, 2026, 3:48 PM ET / 19:48 UTC.

@steipete
steipete merged commit bb8e463 into main Oct 16, 2026
157 of 158 checks passed
@steipete
steipete deleted the dbasync/bootmain4 branch October 16, 2026 23:58
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…174592)

* perf: reduce repeated database work during Gateway startup

* test: update maintenance custody statement expectations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: M 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