Skip to content

fix(cli): stop cloning the state database for Gateway RPC commands - #190761

Merged
steipete merged 2 commits into
mainfrom
codex/cli-skip-state-db-snapshot
Nov 2, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/cli-skip-state-db-snapshot

Conversation

@steipete

@steipete steipete commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Related: #178730 (separate snapshot-exit cleanup; unchanged here).

What Problem This Solves

RPC-only CLI commands clone the whole shared state database during startup when a Gateway has held its lock for more than five minutes and plugin source captures exist. On a reported btrfs installation, an 11.8 GB database with about 555,000 extents made these repeated reflinks expensive enough to stall unrelated writers, including Gateway WAL commits.

User Impact

Commands such as openclaw team-reports list --period day --json can check the live Gateway's readiness without copying its state database. No configuration, schema, retention, permission, or CLI contract changes are required. Artifact-preserving inspection and Doctor schema repair retain private snapshots.

Why This Change Was Made

The lease reader now uses the existing synchronous native current-read path for its bounded lease lookup when hasVerifiedLiveSqliteOwner verifies the exact database's recorded process identity. It retains the existing schema/admission checks and synchronous reader cleanup. PostgreSQL, artifact-preserving scopes, and explicit schema-maintenance admission keep their existing paths. This is the existing native path used by synchronous lifecycle guards, rather than a new transport or cache.

The trigger chain is:

  1. src/cli/program/preaction.ts:174 → src/cli/command-execution-startup.ts:60 → src/cli/program/config-guard.ts:140 runs startup preflight before the RPC action.
  2. src/commands/startup-config-preflight.ts:113-118 → src/commands/startup-plugin-source-captures.ts:36-58 attempts capture cleanup under the existing Doctor maintenance lock.
  3. src/commands/doctor-sqlite-maintenance-lock.ts:168 → src/infra/gateway-lock.ts:561 reports live-owner contention through captureStalledGatewayStartup.
  4. src/infra/gateway-startup-owner.ts:30-53 checks the five-minute startup budget, then reads the current owner lease to distinguish a listening Gateway from a stalled startup.
  5. src/infra/gateway-owner-lease.ts:211-225 previously supplied no native-read permission. src/state/openclaw-state-db-readonly.ts:669-680 consequently called prepareSqliteReadOnlyLocationSync; src/infra/sqlite-snapshot-source.ts:381-400 → src/infra/sqlite-readonly-worker.ts:539 spawned the full-database sync copy.

The actual command action only uses Gateway RPC (extensions/team-reports/src/cli.ts:12-16,43-65). Auth-profile reads and plugin metadata inspection were not the remaining copy trigger.

git log -S startupPhase and git log -S listeningAt both identify f84a3aa (#171678): readiness deliberately lives in the existing owner lease. startupPhase: "starting" distinguishes modern holders from legacy leases; the payload schema only accepts that literal (src/infra/gateway-lock-payload.ts:192). markListening updates the lease, not that marker (src/infra/gateway-lock.ts:663-671, src/infra/gateway-owner-lease.ts:350-370). The marker cannot prove listening, and changing its producer would duplicate the existing readiness owner.

Snapshot history explains the retained boundary: 31d7030 (#141451) added artifact-preserving reads because even read-only SQLite opens can create WAL sidecars; 73ace5d (#148834) keeps schema maintenance on fresh private readers. Those reasons still apply to Doctor and artifact inspection, so those paths remain. A short live lease lookup needs current committed readiness, not preserved source artifacts or a long-lived WAL reader. The existing native exception comes from 6c1e166 (#163496).

Capture cleanup still attempts its existing lock. A separate early live-owner skip would repeat ownership policy and would not fix other current lease readers; lock contention now performs the bounded read.

Owners this process cannot verify keep the old snapshot read. hasVerifiedLiveSqliteOwner throws GatewayLockNamespaceError when the lock payload's process namespace is missing, null or from another host, for example a payload from an older Gateway during an upgrade, or a CLI in another container that shares the state directory. The lease reader treats that as "not verified" instead of failing, so restart, stop, update and recovery callers behave as before for those owners (src/infra/gateway-owner-lease.ts, hasVerifiedLiveStateOwner). src/infra/gateway-state-owner.test.ts covers the missing, null and foreign namespace cases: without the fallback all three throw GatewayLockNamespaceError; with it they pass. The test-line allocation rises from 89 to 94 for those five lines.

Evidence

Acceptance rule: three successful RPC-only commands against each isolated dev Gateway, with capture presence and a real lock older than five minutes, must create zero snapshot staging directories and spawn zero read-only sync children on head. Only synthetic state and loopback ports were used; no live installation or real data was accessed.

The new subprocess regression seeds real SQLite state, publishes a real process owner and listening lease, and supplies a lock timestamp older than five minutes. A different process calls the real captureStalledGatewayStartup seam and counts snapshot allocations and child spawns.

pnpm test src/daemon/gateway-startup-recovery.test.ts --maxWorkers=1 -t 'without copying shared state'
Base 3012cdd6fa46 (origin/main at task start): exit 1
  expected: { stalled: false, syncSpawns: 0, snapshotDirectories: 0 }
  received: { stalled: false, syncSpawns: 1, snapshotDirectories: 1 }
Head: full owning suite exit 0, 4 passed

The current origin/main lease-reader method was also checked and still matches the failing base method.

Real end-to-end command, three times per build:

pnpm openclaw team-reports list --period day --json
Build Successful commands sync children Staging directories created
Base 3012cdd, Gateway age >5 minutes 3/3 3 6
Head 4351c85, Gateway age >5 minutes 3/3 0 0

Each command exited 0 and returned {"periods":[]}. The final head Gateway was ready at 17:11:41 and its three RPC connections occurred at 17:17:05, 17:17:08, and 17:17:11 (local proof timestamps). After committing, the isolated Gateway was rebuilt/restarted before aging it again for the exact-head measurement.

Counts include nested snapshot staging; they measure creation even when cleanup later removes the directory. A preload observes child_process and staging allocation, and the Gateway logs confirm the real CLI RPC connections. Before the five-minute threshold, the base also produced zero copies, explaining the initial missed reproduction.

Focused verification: 161 tests passed, with one Windows-only process test skipped on macOS. This includes owner lease (45), startup recovery (4), capture cleanup (11), Doctor maintenance lock (23), CLI Gateway diagnostics process tests (2), existing interruption/reclamation tests (3), Gateway lock (24), and restart/stop/process/handoff/update consumers (49). Also passed production core typecheck, services test typecheck, targeted type-aware lint, format, git diff --check, and the staged test-line ratchet (6,385,097 lines).

pr-simplify retained one owner change: production +13/-1 lines, one 89-line subprocess regression, four documentation lines, and a one-line allocation record. The regression needs a separate reader process because an in-process cached database handle bypasses the defect. Its exact 89-line allocation avoids deleting unrelated proof or raising the shared baseline.

Codex autoreview: local candidate clean through P2; committed branch review uses --engine codex --mode branch --base origin/main --max-priority P2 with frozen source context. Final status: scoped-clean, no accepted/actionable P0–P2 findings on 4351c85513114916c412bb5d5cc03dc76c86eb50.

Snapshot leak findings

Normal preparation failures already discard partial payloads (src/infra/sqlite-readonly-location-cleanup.ts:485-517), and the synchronous source owner removes its staging directory on a thrown preparation error (src/infra/sqlite-snapshot-source.ts:381-400). A .partial name marks preparation before publication (src/infra/sqlite-readonly-location.ts:319, sqlite-readonly-location-cleanup.ts:519-545); hard interruption can prevent those cleanup paths. Existing SIGKILL/SIGTERM subprocess tests reproduce abandoned data and successfully reclaim it.

The normal one-shot exit gap is already owned by #178730: src/cli/runtime-cleanup.ts:156-172 lacks its proposed async snapshot finalizer, while the synchronous exit hook cannot retire retained async owners (src/infra/sqlite-readonly-location-cleanup.ts:210-225,300-306). Leave that fix to its PR.

Dead-owner reclamation already runs through idle Gateway maintenance every 15 minutes (src/gateway/server-startup-finish.ts:666-682) with a 15-minute grace and 512 MiB budget, allowing one oversized directory per pass (src/infra/sqlite-snapshot-staging.ts:36-37,83-111). Frequent multi-GB interrupted copies can outpace that owner. Filenames and absent open handles alone cannot establish which exit path caused each production leftover or whether reclamation was deferred/refused. No independent cleanup defect was proven, so this PR removes the repeated copy trigger and adds no speculative cleanup policy.

@clawsweeper

clawsweeper Bot commented Nov 2, 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 Nov 2, 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-11-02T01:36:06.055569Z 0e5ff21 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 docs Improvements or additions to documentation gateway Gateway runtime size: S labels Nov 2, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 2, 2026
The native owner-lease read added for live owners called hasVerifiedLiveSqliteOwner eagerly. For a lock payload whose process namespace cannot be verified (missing, null or foreign host), that throws GatewayLockNamespaceError, so lifecycle callers such as restart, stop and update would fail where they previously read the lease through a snapshot. Treat an unverifiable owner as not verified and keep the snapshot read.
@clawsweeper

clawsweeper Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR lets synchronous Gateway lease checks read verified live SQLite state without copying the database.

Example: Run openclaw team-reports list --period day --json with plugin captures present and a listening Gateway older than five minutes.

  • Before: Three successful commands spawned three snapshot children and created six staging directories.
  • After: Three successful commands returned the same result with zero snapshot children and zero staging directories.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with production-entry-point proof and no discrete findings; the required update/restart CI failure still needs attribution.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR records exact-head isolated Gateway runs through the real team-reports CLI with synthetic state, plugin captures, and a lock older than five minutes: three successful RPC commands produced zero snapshot children or staging directories, compared with three children and six directories on base.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: RPC-only CLI commands can copy a large live database during startup and stall unrelated database writers.
Reason: The source and before/after command evidence support a concrete performance defect, and the maintainer-authored direction preserves existing public behavior.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a verified source path that still copies live state on main, with convincing CLI evidence and no actionable code findings; required CI remains unresolved.

Priority: P2
Reviewed head: 4351c85513114916c412bb5d5cc03dc76c86eb50

Before merge

None.

Findings

None.

Agent review details

How this fits together

CLI startup cleanup encounters Gateway ownership contention and reads the owner lease to distinguish a listening Gateway from stalled startup; the shared-state reader supplies that committed lease.

flowchart TD
  A[CLI command startup] --> B[Plugin capture cleanup]
  B --> C[Gateway lock contention]
  C --> D[Current owner lease reader]
  D --> E[Verified live SQLite read]
  D --> F[Preserved snapshot paths]
  E --> G[Listening or stalled result]
  F --> G
Loading

Technical review

Best possible solution:

Retain this focused lease-reader change while preserving Doctor snapshots and the separate CLI snapshot-finalization repair.

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

The source establishes the five-minute contention-to-snapshot path, and the supplied base/head subprocess and real CLI results exercise it; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch fixes the allocation at the existing lease-reader owner, retains current-read semantics, and avoids duplicating readiness or cleanup policy in callers.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Current lease reads during lifecycle checks keeps the original intent (418018b: Doctor maintenance must inspect current ownership rather than inherit a discovery snapshot before stopping a managed Gateway.)
  • Private snapshot selection changes intended behavior with a stated reason (31d7030: Read-only admission must preserve source artifacts, including WAL absence; this PR explicitly retains artifact-preserving and repair snapshots while allowing a bounded live-owner lookup.)
  • Listener readiness ownership keeps the original intent (f84a3aa: A fresh worker heartbeat does not establish completed startup, so the existing lease records listener readiness separately.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The introduced diff changes only native-read selection, one subprocess regression, its test allocation, and the database documentation. (src/infra/gateway-owner-lease.ts:217, 4351c8551311)
  • Current main retains the copy trigger: Current main still calls the current-read helper without native-read permission; that helper selects snapshot preparation for SQLite when no reusable handle exists. (src/infra/gateway-owner-lease.ts:209, 18e52ca69eae)
  • Existing guards remain authoritative: The native exception requires the exact database's verified live process owner and excludes PostgreSQL, artifact-preserving reads, and explicit schema-maintenance admission; the existing connection owner retains schema checks and cleanup. (src/state/openclaw-state-db-readonly.ts:646, 4351c8551311)
  • Shipped CLI behavior evidence: The full PR body records isolated base and exact-head Gateway runs with capture presence and locks older than five minutes: all commands succeeded, while snapshot children fell from three to zero and staging allocations from six to zero. (4351c8551311)
  • Required CI failure remains unattributed: The failing checks-node-changed-3 annotations report update/restart outcome assertion failures. Neither a matching base failure nor a patch-caused defect was established. Full job logs redirect to a host blocked by the review environment. (src/cli/update-cli/update-command-service.integration.test.ts:593, 4351c8551311)
  • Readiness provenance: The earlier readiness repair deliberately stores listener readiness in the owner lease and revalidates process identity before termination; this PR preserves that design. (src/infra/gateway-startup-owner.ts:44, f84a3aafa3b7)

Likely related people:

  • Peter Steinberger: Raw commit 1edc42c adds src/infra/gateway-owner-lease.ts:212 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1edc42ce552b; files: src/infra/gateway-owner-lease.ts)
  • Dallin Romney: Raw commit 418018b adds src/infra/gateway-owner-lease.ts:77 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 418018b67ff8; files: src/infra/gateway-owner-lease.ts)
  • vladimirkrdzic: Raw commit 1f8e152 adds src/infra/gateway-owner-lease.ts:75 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 1f8e15282c74; files: src/infra/gateway-owner-lease.ts)

PR surface

Source +12, Tests +89, Docs +4, Other +1. Total +106 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 13 1 +12
Tests 1 89 0 +89
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 4 107 1 +106

Review metrics

Metric Value Why it matters
Production versus regression growth Production +13/-1 lines; regression tests +89 lines The small owner change reuses existing native-read machinery; the separate reader process is necessary because a cached in-process handle bypasses the failing path.

Labels

Label changes:

  • add P2: Avoidable full-database copies can create substantial I/O pressure, but the demonstrated trigger requires capture presence and an older live Gateway.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Avoidable full-database copies can create substantial I/O pressure, but the demonstrated trigger requires capture presence and an older live Gateway.
  • 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.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

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

  • Determine whether the failing update/restart assertions reproduce on the pinned base before assigning any repair to this PR.

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 November 1, 2026, 8:31 PM ET / November 2, 2026, 01:31 UTC.

@steipete
steipete merged commit 34c5e91 into main Nov 2, 2026
56 of 57 checks passed
@steipete
steipete deleted the codex/cli-skip-state-db-snapshot branch November 2, 2026 01:35
RomneyDa added a commit that referenced this pull request Nov 2, 2026
…190761)

Every `openclaw` CLI startup on a host with a running Gateway copied the whole state database to read one owner-lease row. Startup preflight cleans plugin source captures under the Doctor maintenance lock. When the Gateway holds that lock and has been up past the five-minute startup budget, `captureStalledGatewayStartup` reads the current owner lease to see whether the Gateway is listening. That read had no native-read permission, so it went through `prepareSqliteReadOnlyLocationSync` and a full read-only `sync` copy.

On a production host with an 11.8 GB state database split into about 555k btrfs extents, each such copy ran for over a minute and generated terabytes of btrfs metadata reservation requests. That fed filesystem-wide stalls which held unrelated writers, including the Gateway's own WAL commits, for up to 60 s.

The owner-lease reader now uses the existing native current-read path when the exact database has a verified live SQLite owner. PostgreSQL, schema-maintenance admission and artifact-preserving reads keep their existing paths. Owners this process cannot verify (missing, null or foreign process namespace) keep the snapshot read instead of failing.

Proof:
- A subprocess regression with a real state database and an overdue listening owner shows one `sync` spawn and one staging directory on base, and none on head.
- Isolated Gateway end to end: three RPC commands, 3 copies on base, 0 on head.
- Missing, null and foreign namespace owners fall back without throwing `GatewayLockNamespaceError`.

(cherry picked from commit 34c5e91)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
…penclaw#190761)

Every `openclaw` CLI startup on a host with a running Gateway copied the whole state database to read one owner-lease row. Startup preflight cleans plugin source captures under the Doctor maintenance lock. When the Gateway holds that lock and has been up past the five-minute startup budget, `captureStalledGatewayStartup` reads the current owner lease to see whether the Gateway is listening. That read had no native-read permission, so it went through `prepareSqliteReadOnlyLocationSync` and a full read-only `sync` copy.

On a production host with an 11.8 GB state database split into about 555k btrfs extents, each such copy ran for over a minute and generated terabytes of btrfs metadata reservation requests. That fed filesystem-wide stalls which held unrelated writers, including the Gateway's own WAL commits, for up to 60 s.

The owner-lease reader now uses the existing native current-read path when the exact database has a verified live SQLite owner. PostgreSQL, schema-maintenance admission and artifact-preserving reads keep their existing paths. Owners this process cannot verify (missing, null or foreign process namespace) keep the snapshot read instead of failing.

Proof:
- A subprocess regression with a real state database and an overdue listening owner shows one `sync` spawn and one staging directory on base, and none on head.
- Isolated Gateway end to end: three RPC commands, 3 copies on base, 0 on head.
- Missing, null and foreign namespace owners fall back without throwing `GatewayLockNamespaceError`.
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 gateway Gateway runtime 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: S 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