Repository navigation
fix(cli): stop cloning the state database for Gateway RPC commands - #190761
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
|
Codex review: needs maintainer review before merge. What this changesThis PR lets synchronous Gateway lease checks read verified live SQLite state without copying the database. Example: Run
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCLI 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
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +12, Tests +89, Docs +4, Other +1. Total +106 across 4 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 1, 2026, 8:31 PM ET / November 2, 2026, 01:31 UTC. |
…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]>
…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`.
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 --jsoncan 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
hasVerifiedLiveSqliteOwnerverifies 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:
src/cli/program/preaction.ts:174→src/cli/command-execution-startup.ts:60→src/cli/program/config-guard.ts:140runs startup preflight before the RPC action.src/commands/startup-config-preflight.ts:113-118→src/commands/startup-plugin-source-captures.ts:36-58attempts capture cleanup under the existing Doctor maintenance lock.src/commands/doctor-sqlite-maintenance-lock.ts:168→src/infra/gateway-lock.ts:561reports live-owner contention throughcaptureStalledGatewayStartup.src/infra/gateway-startup-owner.ts:30-53checks the five-minute startup budget, then reads the current owner lease to distinguish a listening Gateway from a stalled startup.src/infra/gateway-owner-lease.ts:211-225previously supplied no native-read permission.src/state/openclaw-state-db-readonly.ts:669-680consequently calledprepareSqliteReadOnlyLocationSync;src/infra/sqlite-snapshot-source.ts:381-400→src/infra/sqlite-readonly-worker.ts:539spawned the full-databasesynccopy.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 startupPhaseandgit log -S listeningAtboth 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).markListeningupdates 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.
hasVerifiedLiveSqliteOwnerthrowsGatewayLockNamespaceErrorwhen 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.tscovers the missing, null and foreign namespace cases: without the fallback all three throwGatewayLockNamespaceError; 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
syncchildren 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
captureStalledGatewayStartupseam and counts snapshot allocations and child spawns.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:
syncchildrenEach 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_processand 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-simplifyretained 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 P2with frozen source context. Final status:scoped-clean, no accepted/actionable P0–P2 findings on4351c85513114916c412bb5d5cc03dc76c86eb50.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.partialname 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-172lacks 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.