Skip to content

improve(gateway): avoid full database copies during startup checks - #147635

Merged
VACInc merged 1 commit into
openclaw:mainfrom
VACInc:perf/startup-direct-checks-20260913
Sep 14, 2026
Merged

VACInc merged 1 commit into
openclaw:mainfrom
VACInc:perf/startup-direct-checks-20260913

Conversation

@VACInc

@VACInc VACInc commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

Avoid full agent-database copies for eligible Gateway startup checks while retaining both fresh integrity checks: initial admission and the reread under the migration lease.

What Problem This Solves

Gateway startup requests full migration readiness twice. Preflight excluded these requests from its existing direct-read child, so each admission copied the database family into a private snapshot before checking it. Large databases incurred repeated copying even when a read transaction was safe.

Root Cause

The preflight caller suppressed the existing direct-read owner when requireStartupMigrationReadiness was set. Startup readiness consequently took the snapshot path regardless of direct-read eligibility.

User Impact

Eligible DELETE databases and complete WAL/SHM families avoid two logical database copies. Both passes still perform fresh integrity, foreign-key, ownership, schema, and canonical-readiness checks; results are not cached across the migration lease.

Closed/incomplete WAL families, hot journals, source exclusions, and canonical mutation scopes retain private snapshots. A source-reader lease lasts through native close, and cancellation joins closure. Native error details and legacy migration error identity survive child IPC; foreign secondary-agent isolation remains ahead of failure handling.

Why This Change Was Made

Extend the existing schema-inspection child rather than add another startup owner. Its timeout includes the database family size, and its bounded 64 MiB connection cache serves index-page revisits. No config option, schema migration, retention change, or weakened integrity policy is introduced.

Evidence

Real behavior proof

The original preflight fails the DELETE and complete-WAL regression cases when there is no room for a full snapshot. The candidate admits those databases through the real preflight entry point. Additional coverage verifies fresh rejection after foreign-key damage between passes, concurrent WAL writes, corrupt foreign secondary-agent isolation, error transport, recovery fallbacks, and cancellation.

On a synthetic 136,060,928-byte DELETE database, two admissions per sample took a median 1,044.39 ms before / 736.88 ms after (one warmup, three alternating pairs). Snapshot requests fell 2 to 0, avoiding 272,121,856 logical copied bytes per pair. These are warm-cache fixture results, not production startup latency or physical disk-I/O telemetry.

Verification

  • 53 focused tests across five owner suites passed.
  • Selected changed-file checks passed, including typechecking, lint, and applicable guards.
  • Independent final-patch autoreview: no P0-P2 findings.
  • Full distributable build and package tarball integrity validation passed for commit b9c61f816d92252ae628d23f25e82217721d7452. Package SHA-256: bb31208c657900d9081090c8782cede38e7d9cb5d853e4fa624a22987cb5bed7.
  • Fresh-state packaged Gateway startup passed in a disposable network-isolated container: /healthz and /readyz both returned HTTP 200. The initial shell probe expected curl, which the runner lacks; Node fetch independently verified both endpoints before the container was stopped.
  • Published [email protected] updater to this exact packed candidate passed the canonical Docker sqlite-volume upgrade-survivor scenario. Automatic migration, Doctor idempotence, health/readiness, history RPC, and restarted-state survival passed.

Update behavior

The installed updater remains unchanged. Candidate startup selects the established direct-read or snapshot owner from current operator state; both migration admissions remain fresh. Recovery and integrity rejection behavior remains in place.

What was not tested

No live Gateway deployment or final large-production-state startup benchmark. Exact time savings and direct-read eligibility for every production startup family are not established. GitHub CI and ClawSweeper review are running for the published head.

Published-driver × candidate proof

The installed baseline updater performed the upgrade (candidateInstallMode: updater, updateOutcome: success). Automatic migration was asserted before a standalone Doctor pass. The scenario retained 4,800 sessions, 23,890 events, and 2,200 cron jobs and verified history RPC for eight conversations across two agents before and after restart.

node scripts/package-openclaw-for-docker.mjs --output-dir /tmp/startup-direct-package --output-name candidate.tgz
OPENCLAW_UPGRADE_SURVIVOR_PUBLISHED_BASELINE=1 \
[email protected] \
OPENCLAW_UPGRADE_SURVIVOR_SCENARIO=sqlite-volume \
OPENCLAW_CURRENT_PACKAGE_TGZ=/tmp/startup-direct-package/candidate.tgz \
  bash scripts/e2e/upgrade-survivor-docker.sh

Copied result:

SQLite volume idempotence doctor completed in 15s (budget 60s).
sqlite-volume Gateway RPC verified 8 conversations across 2 agents
Upgrade survivor Docker E2E passed [email protected] scenario=sqlite-volume candidate=2026.9.4 updateRestartMode=manual idempotence=15s startup=20s updateRestart=manuals healthz=1s readyz=1s status=1s.

This is synthetic compatibility proof, not a production performance comparison. The isolated run reused a runner built from the unchanged canonical scripts/e2e/Dockerfile bare target.

Maintainer regression proof

On the reviewed head b9c61f816d92252ae628d23f25e82217721d7452, temporarily reversing the five production-file changes made the four DELETE/WAL startup regressions fail with No space for a full agent database snapshot (4 failed, 5 passed). Restoring the reviewed production changes passed all 139 tests across nine suites:

node scripts/run-vitest.mjs src/state/openclaw-database-preflight src/infra/sqlite-schema-header.test.ts src/commands/doctor-config-preflight-startup.test.ts src/commands/doctor-config-preflight.state-migration.test.ts

The native-reader consistency and lease-through-close cases passed on success, read failure, close failure, and cancellation. Those lifetime cases predate this PR and are preservation proof. No source changes were needed.

ClawSweeper review

The latest review of this exact head reports no actionable findings or before-merge items. Its earlier build and upgrade-proof request is resolved by the published evidence above; nothing remains to apply or skip. Production-scale performance remains unmeasured.

Release-note context and credit

Gateway startup no longer copies every eligible agent database twice while checking migration readiness; large installations start, and finish updates, faster with the same integrity checks.

Thanks @VACInc (#147635).

@clawsweeper

clawsweeper Bot commented Sep 14, 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: M maintainer Maintainer-authored PR labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 9:42 PM ET / September 14, 2026, 01:42 UTC (Revision 3).

ClawSweeper review

What this changes

Gateway startup checks eligible agent databases directly in the existing read-only child process, avoiding full copies while preserving recovery snapshots and error details.

Merge readiness

✅ Ready for maintainer review

This remains a useful optimization absent from inspected main. The supplied exact-head startup and upgrade evidence resolves the earlier proof request, and no actionable introduced defects were found.

Priority: P2
Reviewed head: b9c61f816d92252ae628d23f25e82217721d7452

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with useful runtime and upgrade evidence and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied exact-head evidence exercises the changed preflight through a real SQLite benchmark and packaged Gateway startup, with published-updater upgrade and restart survival output; focused regressions supplement that proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Supplied exact-head evidence exercises the changed preflight through a real SQLite benchmark and packaged Gateway startup, with published-updater upgrade and restart survival output; focused regressions supplement that proof.
Evidence reviewed 7 items Introduced change and merge ownership: The pinned merge-base-to-head delta enables startup readiness in the existing inspection child. The test-merge commit has the recorded base and exact PR head as its two parents, and its preflight delta preserves this same change.
Still necessary on main: Inspected main still excludes requireStartupMigrationReadiness from direct inspection and prepares a private snapshot instead. No merged replacement was established. The latest-release source read could not complete because its local blob was unavailable; no shipped-fix claim is made.
Read consistency and recovery boundary: The existing reader pins one SQLite read transaction, declines empty files, rollback journals, and incomplete WAL families, and closes its native connection before returning. Source leases remain held when native close fails; the parent settles only on child close.
Findings None None.
Security None None.

How this fits together

Gateway startup inspects stored agent databases before admitting migrations. These checks validate ownership, integrity, and schema compatibility, then allow startup or report a refusal.

flowchart TD
  A[Startup admission] --> B[Agent database family]
  B --> C{Safe direct read?}
  C -->|Yes| D[Read-only child transaction]
  C -->|No| E[Private recovery snapshot]
  D --> F[Ownership and integrity checks]
  E --> F
  F --> G[Wait for native close]
  G --> H[Admit or report refusal]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +86, Tests +106, Docs +8. Total +200 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 5 103 17 +86
Tests 4 174 68 +106
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 286 86 +200

Review metrics

Metric Value Why it matters
Production versus test growth production +86 net lines; tests +106 net lines Production growth primarily preserves typed failures across the child-process boundary; tests cover freshness, recovery, and ownership behavior.

Technical review

Best possible solution:

Keep one readiness owner with fresh checks at both migration admissions and snapshots reserved for recovery or excluded sources.

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

Yes: current main explicitly forces full readiness onto the snapshot path, and supplied before/after regression results exercise that condition. This read-only review did not execute tests.

Is this the best way to solve the issue?

Yes: extending the established inspector avoids a competing implementation while retaining fresh validation, native-close settlement, and recovery fallbacks.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded startup-performance improvement for installations with large agent databases.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Supplied exact-head evidence exercises the changed preflight through a real SQLite benchmark and packaged Gateway startup, with published-updater upgrade and restart survival output; focused regressions supplement that proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Supplied exact-head evidence exercises the changed preflight through a real SQLite benchmark and packaged Gateway startup, with published-updater upgrade and restart survival output; focused regressions supplement that proof.

Evidence

What I checked:

  • Introduced change and merge ownership: The pinned merge-base-to-head delta enables startup readiness in the existing inspection child. The test-merge commit has the recorded base and exact PR head as its two parents, and its preflight delta preserves this same change. (src/state/openclaw-database-preflight.ts:594, 75ca585cdeb3)
  • Still necessary on main: Inspected main still excludes requireStartupMigrationReadiness from direct inspection and prepares a private snapshot instead. No merged replacement was established. The latest-release source read could not complete because its local blob was unavailable; no shipped-fix claim is made. (src/state/openclaw-database-preflight.ts:595, a7344f3d0355)
  • Read consistency and recovery boundary: The existing reader pins one SQLite read transaction, declines empty files, rollback journals, and incomplete WAL families, and closes its native connection before returning. Source leases remain held when native close fails; the parent settles only on child close. (src/infra/sqlite-readonly-inspection.ts:12, b9c61f816d92)
  • Preserved admission and failure semantics: The inspector still runs full integrity and canonical-version checks. Structured failures retain ownership metadata so the parent applies existing secondary-agent isolation before throwing; regression coverage exercises fresh corruption rejection and legacy migration-error identity. (src/state/openclaw-agent-schema-inspection.ts:59, b9c61f816d92)
  • Exact-head behavior and upgrade evidence: The supplied complete PR body at captured sourceRevision 252b34e4382e98d4df380ed6da4970f07fd9067599106466f6d5b6241c1df1f4 reports packaged fresh-state health/readiness HTTP 200 and a published [email protected] updater-to-candidate sqlite-volume run preserving history across restart. Copied output reports eight conversations across two agents verified. The real-preflight synthetic benchmark reports two snapshot requests reduced to zero; production-scale latency remains unmeasured. These are supplied observations, not reviewer-executed tests. (b9c61f816d92)
  • Review continuity: The previous completed review covered this same head and retained no findings. The body now documents the earlier build/upgrade request as resolved and reports four regressions failing when the production changes were reversed, followed by 139 passing tests after restoration. (b9c61f816d92)

Likely related people:

  • Vito Cappello: Raw commit 0f74803 adds src/state/openclaw-agent-schema-inspection.ts:58 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0f748036332e; files: src/state/openclaw-agent-schema-inspection.ts)
  • Peter Steinberger: 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-14T01:08:25.142Z sha b9c61f8 :: blocked before merge. :: none
  • reviewed 2026-09-14T01:23:34.152Z sha b9c61f8 :: needs maintainer review before merge. :: none

@VACInc

VACInc commented Sep 14, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

The body now includes the completed exact-head build, package integrity, fresh-state startup, and published 2026.9.3 updater × candidate sqlite-volume proof for b9c61f816d92252ae628d23f25e82217721d7452. Automatic migration, preserved history, Doctor idempotence, health/readiness, and post-restart history all passed. Fresh-state packaged startup also returned HTTP 200 from healthz and readyz in an isolated container.

CI separately hit a three-second CLI fixture timeout in an unchanged test (execute.executable-invocation.test.ts); both cases passed locally on this exact head, including the failing case in 309 ms. The CI run is still active, and GitHub currently refuses its individual job rerun. No startup code changes were needed.

@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Sep 14, 2026
@VACInc
VACInc merged commit 3cfc0ad into openclaw:main Sep 14, 2026
416 of 418 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
steipete added a commit that referenced this pull request Sep 17, 2026
Fleet database admission repeatedly started a schema-inspection process for every agent after #147635 enabled the heavier reader during Gateway startup. Reuse one reader in each of the existing two scheduler slots while preserving fresh reads, integrity and ownership checks, private-snapshot recovery, cancellation, and joined cleanup. Bootstrap tracing now records substeps, durations, repeated calls, and fleet counts.

In the isolated 200-agent repeat boots, schema readers fall from 200 to two and database admission falls from 44.38s to 15.93s and 8.11s. Whole-startup timings remain variable; these measurements do not establish installed-updater compatibility or the reporter's 632-agent readiness target. No schema, configuration, backup, or rollback contract changes.

Related: #148529, #149538. Thanks to @609NFT for the per-build fleet measurements and repeat-boot target.

Validation: 41 focused tests, changed-file checks, build, scoped-clean Codex review, and isolated Gateway boots reaching readiness and exiting cleanly. Exact-head CI run 35177837447 is green for cb599c7. The published-driver upgrade proof and 632-agent whole-startup target remain explicit proof gaps under the maintainer disposition in the PR body.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 18, 2026
)

Fleet database admission repeatedly started a schema-inspection process for every agent after openclaw#147635 enabled the heavier reader during Gateway startup. Reuse one reader in each of the existing two scheduler slots while preserving fresh reads, integrity and ownership checks, private-snapshot recovery, cancellation, and joined cleanup. Bootstrap tracing now records substeps, durations, repeated calls, and fleet counts.

In the isolated 200-agent repeat boots, schema readers fall from 200 to two and database admission falls from 44.38s to 15.93s and 8.11s. Whole-startup timings remain variable; these measurements do not establish installed-updater compatibility or the reporter's 632-agent readiness target. No schema, configuration, backup, or rollback contract changes.

Related: openclaw#148529, openclaw#149538. Thanks to @609NFT for the per-build fleet measurements and repeat-boot target.

Validation: 41 focused tests, changed-file checks, build, scoped-clean Codex review, and isolated Gateway boots reaching readiness and exiting cleanly. Exact-head CI run 35177837447 is green for cb599c7. The published-driver upgrade proof and 632-agent whole-startup target remain explicit proof gaps under the maintainer disposition in the PR body.
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 maintainer Maintainer-authored PR 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. 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