Skip to content

fix: avoid copying live state during read-only inspection - #202608

Merged
steipete merged 2 commits into
mainfrom
codex/state-read-no-live-copy
Nov 20, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/state-read-no-live-copy

Conversation

@steipete

@steipete steipete commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Running openclaw plugins update better-prompt --dry-run beside a live Gateway took 192 seconds against a 30.2 GB shared state database. In about 150 seconds, its snapshot child read 104.5 GB and wrote 107.2 GB (about 3.5 whole-file copies). Concurrent session commits stalled for 26.1 and 12.3 seconds, and the write-reservation queue reached 22.6 seconds.

User Impact

Ordinary read-only inspection of a shared state database with a verified live owner now reads directly through a read-only connection, avoiding whole-file staging. This covers deferred plugin migrations and the shared-state reads used by config, templates, plugins, and Doctor. Offline inspection and unverifiable owner identities keep artifact-preserving private copies and its existing sidecar/lock guarantees.

Why This Change Was Made

At base dacf5604e469, src/state/openclaw-state-db-readonly.ts:273 selected a private copy for every ordinary artifact-preserving shared-state read without checking the live owner. The shared decision now uses the existing exact-database owner verification before selecting a copy, covering synchronous, awaited, async, and reusable-image paths.

The existing metadata live-read path in src/state/openclaw-state-read-operation.ts:329 now remains independent of the private-copy decision. That preserves its fresh schema-version rejection when a live writer advances the header; it still reads directly without staging.

Explicit frozen inspection scopes remain unchanged. In particular, openclaw update status (src/cli/update-cli/status.ts:126, contract in src/state/openclaw-state-inspection-snapshot.ts:7) still prepares one private image. Follow-up: a live-owned source could provide that frozen image through one transaction on a direct read-only connection, using WAL snapshot isolation instead of copying files. No copy-effect refusal or new transport option is introduced here.

The reported 1,222 empty sqlite-* namespace roots remain a follow-up: src/infra/sqlite-private-directory.ts:79 creates them and src/infra/sqlite-snapshot-reclamation.ts:77 skips namespace entries. Removing an empty root can race an allocator that has already resolved it but has not called mkdtemp; safely changing that lifecycle exceeds this bounded repair.

Release-note context: CLI inspection beside a live Gateway avoids copying the entire shared state database while retaining offline artifact preservation.

Evidence

The real deferred-migration reader runs against a database with a verified local SQLite owner. Ordinary reads prepare zero snapshots across sync, awaited, async, and reuse paths; an explicit frozen scope still prepares exactly one. Existing offline preservation tests remain covered. The new regression shares its fixture with the existing concurrent online-backup proof, and redundant availability/callback setup is folded together to keep net test lines nonpositive.

Red on base dacf5604e46997f146e58b2f088bb3d3340b89fc (final regression, original production reader):

pnpm test src/state/openclaw-state-db-readonly.source-identity.test.ts --maxWorkers=1 -t 'reads live-owned state directly'
Expected preparation counts: [0, 0, 0, 0]
Received preparation counts: [1, 1, 2, 1]
Test Files  1 failed (1)
Tests       1 failed | 2 skipped (3)

Green with the fix (same regression plus its touched owner suite):

Test Files  2 passed (2)
Tests       17 passed (17)

The four counters cover sync, async, awaited, and retained-async preparation entry points; delegated preparation calls overlap and are not distinct-copy counts. The frozen-scope assertion expects [0, 0, 0, 1] after the zero-preparation reads.

  • Reader/connection siblings, config snapshots, and update-status snapshot consumer: 14 files, 129 tests passed.
  • Deferred-migration, templates, and plugin-update integration consumers: 91 passed initially; one plugin-update case hit a macOS Bun SQLite-library probe SIGTRAP. That exact case passed under the repository-supported Node test runtime (1 passed, 36 skipped). Passing replay does not repair the Bun probe; CI remains the broad proof.
  • Final touched tests and the final red replay used OPENCLAW_VITEST_RUNTIME=node.
  • pnpm tsgo:core, the targeted state-logging test typecheck, targeted oxlint, pnpm format:check -- <four touched paths>, and git diff --check passed.
  • Net test lines: −1 (109 added, 110 removed). Production reader: 20 added, 25 removed; scope options move unchanged to the existing read-types owner to stay within the lint line budget.
  • Independent $autoreview completed scoped-clean with no actionable P2-or-higher findings.
  • Initial CI run 44779074317 exposed a real metadata consumer regression: its newer-schema assertion resolved instead of rejecting. Reproduced only that failed case locally; the bounded read-operation guard repair preserves the existing fresh metadata path. Only the failed metadata case was rerun after repair: 1 passed, 14 skipped. A second failed shard exposed seven Doctor cases whose predecessor file records omit process-start identity; the copy decision now treats that typed unknown-verification result as unverified and keeps the existing private-copy behavior. It never authorizes a direct read from an unknown identity. The failed-case replay passes all 8 selected cases (14 unrelated cases skipped). Follow-up autoreview caught a copy-permission assertion ordered before verification; that finding is fixed, and final autoreview is scoped-clean at P2. Replacement CI will verify the exact repair head.
  • No production host or Gateway was contacted; proof uses synthetic local state only.

@clawsweeper

clawsweeper Bot commented Nov 20, 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 20, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T17:29:08.235894Z 3e110f1 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 size: M labels Nov 20, 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR avoids private SQLite copies for ordinary shared-state inspection when the database has a verified live owner.

Example: Run openclaw plugins update better-prompt --dry-run beside a live Gateway with a 30.2 GB state database.

  • Before: The reported command copied the database repeatedly and stalled concurrent commits.
  • After: Ordinary live-owned reads bypass snapshot preparation; explicit frozen reports retain private images.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The repair has clear value, but supplied proof stops at tests and the shared selection change introduces three actionable regressions.
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) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Read-only CLI inspection copies a large live database repeatedly and delays unrelated Gateway commits.
Reason: The reported workload establishes concrete user value, and the supplied maintainer-authored classification establishes direction; the remaining problems are implementation defects.

Merge readiness

⛔ Needs changes before merge - 6 items remain

This PR addresses a concrete inspection bottleneck that remains on main, but the broader direct-read selection introduces owner-verification, schema-refusal, and scoped-consistency regressions.

Priority: P1
Reviewed head: dfd098889d652fafa290624f1ef9f958ca44aad3

Before merge

  • [P1] Preserve snapshot fallback for unverifiable owners (P1) - The author should treat GatewayLockNamespaceError as an unverified owner for this optimization. hasVerifiedLiveSqliteOwner throws for missing start identity or unknown namespaces, so this new call now aborts ordinary reads before the previous private-copy path can run. Older Gateway records and callers sharing state across containers are concrete affected inputs; fix(cli): stop cloning the state database for Gateway RPC commands #190761 explicitly preserved their fallback. Exact-head Doctor serving-owner CI also fails at this new boundary before reaching its expected read or service-stop operation. Retain the existing admission checks and choose a private image when live ownership cannot be verified.
  • [P1] Retain newer-schema refusal for live metadata reads (P1) - The author should preserve fresh schema admission when routing live metadata through the generic reader. Returning false here sets preserveArtifacts=false, bypassing startOpenClawStateReadOperation's currentMetadata child path and its fresh validation. The replacement path can reuse process-lifetime schema facts for the same physical file. In the existing live-writer regression, the writer commits user_version=2147483647 after successful reads, but the next read returns the previous installed inventory instead of SqliteSchemaVersionError; exact-head CI reports this failure at src/plugins/plugin-metadata-state-worker.test.ts:574. Preserve the metadata admission boundary without restoring whole-file copying.
  • [P2] Preserve the committed view within synchronous scopes (P2) - The author should keep explicit synchronous scopes coherent for live-owned databases. requiresArtifactPreservingSnapshot now returns false inside withSynchronousArtifactPreservingStateSnapshot, so withFreshOpenClawStateDatabaseReadOnly skips its reader map and opens separate live readers. With a verified owner, read value 'first', commit value 'second' from the writer, then read again within the same scope: the second read now observes 'second'. The existing scope contract requires 'first' until the next scope, as accepted in fix: avoid duplicate SQLite snapshots during CLI metadata loading #147861 and exercised by the retained consistency tests. Preserve a scope-owned committed view, using the existing private image until a direct transaction can supply that contract.
  • Explain or restore the original intent of Unknown live-owner handling - fix(cli): stop cloning the state database for Gateway RPC commands #190761: Unverifiable older or foreign-namespace owners retain the snapshot path rather than failing ordinary reads.
  • Explain or restore the original intent of Live metadata schema refusal - perf(config): speed up validation with large live shared state #183082: Live metadata inspection must retain physical identity, schema-version checks, and typed newer-schema errors.
  • Explain or restore the original intent of Synchronous read scope - 51c9122: One metadata resolution must observe one committed snapshot, with concurrent commits visible only to the next scope.

Findings

  • [P1] [P1] Preserve snapshot fallback for unverifiable owners — src/state/openclaw-state-db-readonly.ts:283
  • [P1] [P1] Retain newer-schema refusal for live metadata reads — src/state/openclaw-state-db-readonly.ts:283
  • [P2] [P2] Preserve the committed view within synchronous scopes — src/state/openclaw-state-db-readonly.ts:283

Provenance

Tests

  • Missing end-to-end proof: Provide redacted before/after output from the shipped plugin-update dry-run beside an isolated live Gateway, including a latest-stable upgrade retaining existing settings and state.
Agent review details

How this fits together

The shared-state read owner selects cached connections, direct read-only connections, or private SQLite images for CLI, plugin, config, and Doctor readers.

flowchart TD
  A[CLI and Doctor inspection] --> B[Shared state read owner]
  B --> C[Explicit frozen scope]
  B --> D[Live owner verification]
  C --> E[Private SQLite image]
  D --> F[Direct read only connection]
  D --> E
  E --> G[Committed query results]
  F --> G
Loading

Technical review

Best possible solution:

Keep direct reads in the existing owner while preserving unknown-owner fallback, current schema admission, and one committed view per explicit synchronous scope.

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

The base selects private snapshots for ordinary artifact-preserving reads, and the supplied regression fails on that base; this review inspected source and recorded CI failures without executing target code.

Is this the best way to solve the issue?

Centralizing copy avoidance in the existing read owner is appropriate, but a verified live owner cannot replace fallback handling, supported-schema admission, or explicit scope consistency.

Full review comments:

  • [P1] [P1] Preserve snapshot fallback for unverifiable owners — src/state/openclaw-state-db-readonly.ts:283
    The author should treat GatewayLockNamespaceError as an unverified owner for this optimization. hasVerifiedLiveSqliteOwner throws for missing start identity or unknown namespaces, so this new call now aborts ordinary reads before the previous private-copy path can run. Older Gateway records and callers sharing state across containers are concrete affected inputs; fix(cli): stop cloning the state database for Gateway RPC commands #190761 explicitly preserved their fallback. Exact-head Doctor serving-owner CI also fails at this new boundary before reaching its expected read or service-stop operation. Retain the existing admission checks and choose a private image when live ownership cannot be verified.
    Confidence: 0.99
  • [P1] [P1] Retain newer-schema refusal for live metadata reads — src/state/openclaw-state-db-readonly.ts:283
    The author should preserve fresh schema admission when routing live metadata through the generic reader. Returning false here sets preserveArtifacts=false, bypassing startOpenClawStateReadOperation's currentMetadata child path and its fresh validation. The replacement path can reuse process-lifetime schema facts for the same physical file. In the existing live-writer regression, the writer commits user_version=2147483647 after successful reads, but the next read returns the previous installed inventory instead of SqliteSchemaVersionError; exact-head CI reports this failure at src/plugins/plugin-metadata-state-worker.test.ts:574. Preserve the metadata admission boundary without restoring whole-file copying.
    Confidence: 0.97
  • [P2] [P2] Preserve the committed view within synchronous scopes — src/state/openclaw-state-db-readonly.ts:283
    The author should keep explicit synchronous scopes coherent for live-owned databases. requiresArtifactPreservingSnapshot now returns false inside withSynchronousArtifactPreservingStateSnapshot, so withFreshOpenClawStateDatabaseReadOnly skips its reader map and opens separate live readers. With a verified owner, read value 'first', commit value 'second' from the writer, then read again within the same scope: the second read now observes 'second'. The existing scope contract requires 'first' until the next scope, as accepted in fix: avoid duplicate SQLite snapshots during CLI metadata loading #147861 and exercised by the retained consistency tests. Preserve a scope-owned committed view, using the existing private image until a direct transaction can supply that contract.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/state/openclaw-state-db-readonly.source-identity.test.ts src/state/openclaw-state-db-readonly.test.ts --maxWorkers=1
  • pnpm test src/plugins/plugin-metadata-state-worker.test.ts src/commands/doctor-maintenance.serving-owner.test.ts --maxWorkers=1
  • pnpm tsgo:core
  • git diff --check

What I checked:

Likely related people:

  • Paul Frederiksen: Raw commit 51c9122 adds src/state/openclaw-state-db-readonly.ts:250 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 51c9122e1e9c; files: src/state/openclaw-state-db-readonly.ts)

PR surface

Source -4, Tests -1, Docs +3. Total -2 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 11 15 -4
Tests 2 109 110 -1
Docs 1 5 2 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 125 127 -2

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P1: The reported inspection workload stalls live commits for seconds, while the proposed shared-owner change also breaks existing Doctor and metadata-read contracts.
  • add merge-risk: 🚨 compatibility: Existing installations with unverifiable owner records can lose inspection access, and retained live readers can accept unsupported schema versions.
  • 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:

  • P1: The reported inspection workload stalls live commits for seconds, while the proposed shared-owner change also breaks existing Doctor and metadata-read contracts.
  • merge-risk: 🚨 compatibility: Existing installations with unverifiable owner records can lose inspection access, and retained live readers can accept unsupported schema versions.
  • 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 November 20, 2026, 12:16 PM ET / 17:16 UTC.

@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: 3e110f112f

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

return undefined;
}
if (!snapshot && preserveArtifacts && !independentWarmSource) {
if (!snapshot && !independentWarmSource) {

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 Keep PostgreSQL reads out of the SQLite metadata fast path

When shared state uses PostgreSQL and a separate CLI process reads metadata beside a live Gateway, preserveArtifacts is false and native is undefined. Removing the former guard now lets currentMetadata become true because PostgreSQL Gateways also acquire the state-owner lock (src/infra/gateway-lock.ts). This routes the request through startupMetadata.readCurrent, whose implementation opens the SQLite anchor directly rather than the PostgreSQL connection. The anchor contains openclaw_engine_anchor, not the state tables, so config-health and plugin-metadata queries fail instead of reading PostgreSQL. Gate this fast path on the SQLite backend while retaining the new direct-read behavior for live SQLite owners.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 2225592 into main Nov 20, 2026
140 of 142 checks passed
@steipete
steipete deleted the codex/state-read-no-live-copy branch November 20, 2026 17:54
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Nov 20, 2026
Consume the owner lifecycle’s existing path admission instead of resolving and reading the owner sidecar on every live check. Keep persisted verification for offline and unadmitted readers. This fixes the host identity-read regression from #202608 while retaining its no-copy behavior.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…02608)

* fix: avoid copying live state during read-only inspection

* fix: preserve live metadata and unverified-owner inspection
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
Consume the owner lifecycle’s existing path admission instead of resolving and reading the owner sidecar on every live check. Keep persisted verification for offline and unadmitted readers. This fixes the host identity-read regression from openclaw#202608 while retaining its no-copy behavior.
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
* fix: avoid copying live state during read-only inspection

* fix: preserve live metadata and unverified-owner inspection

(cherry picked from commit 2225592)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 8d2642eff08844061a82af7ab5df6f4a7f775a9c)
(cherry picked from commit 1a7533851a6c13c9fb913d7035bef6e8cc4bc2a1)
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
Consume the owner lifecycle’s existing path admission instead of resolving and reading the owner sidecar on every live check. Keep persisted verification for offline and unadmitted readers. This fixes the host identity-read regression from #202608 while retaining its no-copy behavior.

(cherry picked from commit 9175df9)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 56fe38c7ed1ba774955b94ed0793c9927dee7f41)
(cherry picked from commit 890454cafacfd2b7a11f8461b2193d53fa179bc8)
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Baseline adaptation: Use the canonical owner path, matching live process identity and existing WAL/SHM sidecars to select the stable-line direct read path. Retain offline and explicit frozen snapshots; no newer state-read controller or store schema.

(cherry picked from commit 2225592)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 03c531bae60afb99d8de7800e0ecd453ef8f6dfb)
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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