Skip to content

fix: prevent externally supervised state schema drift - #121069

Merged
steipete merged 15 commits into
mainfrom
fix/external-state-schema-ownership
Aug 9, 2026
Merged

steipete merged 15 commits into
mainfrom
fix/external-state-schema-ownership

Conversation

@steipete

@steipete steipete commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #121068

What Problem This Solves

Fixes an issue where externally supervised OpenClaw installations could let different immutable releases enter writable shared-state lifecycle without a durable owner, and where equal numeric SQLite schema versions could hide incompatible physical column shapes.

This affected rollback, startup, update, Doctor, config-health, proxy-capture, checkpoint, and detached fallback workflows around the shared state database.

Why This Change Was Made

Shared-state lifecycle now records a versioned external-supervision claim in the existing machine-state table and fences non-owner writes both before opening state and again inside BEGIN IMMEDIATE. An explicit copied-state preflight opens consolidated SQLite snapshots read-only and immutable, returning structured compatibility outcomes without modifying the target.

The fix covers startup checkpoints, compaction, debug proxy capture, config health, update handoff, and direct writer paths. It does not bump the SQLite schema version, add an environment variable or config option, automatically unclaim ownership, add a dependency, or introduce a fallback writer. The generated Plugin SDK contract manifest records reviewed private declaration-closure changes; visible Plugin SDK exports are unchanged.

User Impact

Operators can give an external supervisor durable ownership of shared-state writes, detect incompatible same-version copied state before switching releases, and receive an explicit refusal when an unmarked process attempts to write externally owned state. Compatible ordinary installations continue using the existing state lifecycle.

Evidence

ClawSweeper disposition

  • Cold-open index and compatible-additive repairs execute inside the fenced BEGIN IMMEDIATE, after ownership and schema-version checks. A deterministic regression claims ownership during cold open and proves the unmarked opener cannot mutate the database.
  • Projected copied-state preflight preserves allowCompatibleAdditiveColumns. A copied-snapshot regression proves a future bare nullable column remains downgrade-safe and the source snapshot is untouched.
  • The requested rank-up proof is present: both regressions are included, the 13 semantic commits remained patch-identical through the final rebase, the generated Plugin SDK baseline combines the PR closure with current main, and the exact integration head passed focused and full CI proof.

The later ClawSweeper review on eb80c650375affb5249e2a5f6c244a4ea851d03b raised two additional coordination concerns. Their landing disposition is explicit:

  • Permission/WAL setup: no further change in this landing. Logical state and schema repair are rechecked after BEGIN IMMEDIATE; pathname permission hardening is idempotent OS metadata. Stronger coordination around all connection setup would broaden the accepted owner boundary beyond this repair.
  • Offline Doctor compaction: no further change in this landing. Doctor holds the exclusive Gateway/SQLite-maintenance lock and validates durable ownership on the opened database immediately before checkpoint/VACUUM. Claiming external ownership concurrently with an explicitly offline Doctor operation is outside the supported supervisor transition order.

These are deliberate maintainer scope decisions, not silent omissions. An exact-head @clawsweeper re-review was requested, but GitHub installation throttling deferred its live-item check; the native review artifacts record the same disposition.

Final exact-head proof

  • Exact integration head: 32d8b3bf81adf4baaf5172bec708bd24cd74d5d6.
  • The signed integration commit has the reviewed PR head 2b02823de87d752a1a6d37b3ebf0109e47a10253 and current main bff0494f33b24aef664990dafda0d38750d798bc as parents.
  • Exact-head CI: run 31335265063, including successful openclaw/ci-gate, build artifacts, Windows, Plugin SDK baseline, SQLite guards, all selected Node tests, lint/types, docs, and security-fast.
  • Exact merge-tree Blacksmith Testbox (provider=blacksmith-testbox, id=tbx_01kzm4b3rnxpws9g1s1218zmvt): run 31335044287.
    • pnpm plugin-sdk:api:check: passed.
    • pnpm plugin-sdk:surface:check: passed with zero forbidden package subpaths.
    • Five focused state/database files: 172 tests passed (ownership 10, copied-state preflight 17, state DB 116, corruption recovery 12, maintenance 17).
  • The merge result retains the same 41-file +2885/-577 PR surface; its non-generated stable patch ID exactly matches the reviewed head. The only recomputed file is the generated Plugin SDK checksum baseline.
  • git diff --check: passed.
  • Exact merge-tree synthetic autoreview: secret scan clean and no accepted/actionable findings (0.98).

Earlier proof

  • Pre-integration exact-head CI: run 31332964611, successful including openclaw/ci-gate.
  • Pre-integration exact-head Testbox (id=tbx_01kzm1551cb38r4fkgrq1th7k1): run 31332652949, Plugin SDK API/surface green and 172/172 focused tests passed.
  • Combined Plugin SDK baseline generation/check (id=tbx_01kzm0q7a5bd3yn0tt9594v92g): run 31332316601.
  • Earlier broader Testbox (id=tbx_01kzkc52y2p3akndvrcg7txt80, slug=harbor-lobster-22e9): run 31316502806, with the changed gate, 508 focused tests, build, and docs passing.
  • Exact P1 patch proof: run 31330745504, 172 focused tests passed.
  • Autoreview: the source patch, both generated baseline integrations, final rebased branch, and exact merge tree passed secret scanning with no accepted/actionable findings.

AI-assisted: yes. The implementation and follow-up simplification were reviewed, and I understand the ownership, schema-preflight, and direct-writer boundaries changed here. No prompts or agent transcript are included.

@clawsweeper

clawsweeper Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes commands Command implementations size: XL maintainer Maintainer-authored PR labels Aug 9, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Aug 9, 2026
@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 9, 2026, 4:44 PM ET / 20:44 UTC.

ClawSweeper review

What this changes

Adds external-supervisor ownership for shared SQLite state, immutable copied-state schema preflight, and write checks across Gateway, CLI, Doctor, updater, and diagnostic paths.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 7 items remain

Keep this PR open: both previously identified P1 ownership races remain at the exact head, so its documented once-claimed refusal guarantee is not yet true.

Priority: P1
Reviewed head: 2b02823de87d752a1a6d37b3ebf0109e47a10253
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has strong stated validation, but two P1 owner-boundary defects leave it short of merge readiness.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless links exact-head CI and isolated Gateway/state evidence.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless links exact-head CI and isolated Gateway/state evidence.
Evidence reviewed 7 items Unfenced cold-open mutation: The exact head checks ownership, then performs permission hardening before its later transactional recheck; a claim between those operations lets an unmarked process mutate filesystem permissions despite the documented guarantee.
Documented contract: The new operator documentation says an unmarked writable open fails before permissions or other mutation, which the claim-after-check race violates.
Doctor remains concurrent with claims: Doctor validates ownership before checkpoint/VACUUM, but claim operations do not take Doctor’s maintenance lock, so a claim can commit after validation and before the destructive SQLite operations.
Findings 2 actionable findings [P1] Fence state-open setup under the ownership claim
[P1] Serialize Doctor compaction with ownership claims
Security None None.

How this fits together

Gateway, CLI, Doctor, updater, and diagnostics share OpenClaw’s SQLite state database. The new ownership row should make unmarked writers refuse while copied snapshots are assessed read-only before activation or rollback.

flowchart LR
A[External supervisor] --> B[Durable ownership claim]
C[Gateway CLI Doctor updater] --> D{Shared-state write path}
B --> D
D -->|authorized| E[SQLite state and WAL]
D -->|unmarked| F[Explicit refusal]
G[Copied SQLite snapshot] --> H[Immutable schema preflight]
H --> I[Release activation decision]
Loading

Decision needed

Question Recommendation
Should external ownership guarantee refusal before every filesystem, WAL, and Doctor mutation once a claim commits, or should the product explicitly narrow that guarantee to a coordinated transition protocol? Complete the durable ownership boundary: Serialize claims with cold-open setup and Doctor compaction, and prove both claim-during-operation races refuse before mutation.

Why: The branch deliberately leaves both concurrent windows open while public documentation promises the broader guarantee; choosing the permanent operator contract requires maintainer intent.

Before merge

  • Fence state-open setup under the ownership claim (P1) - A claim can commit after the check at line 591 but before this permission/WAL setup. That lets an unmarked opener change filesystem or SQLite state after ownership exists, contradicting the documented pre-mutation refusal guarantee; the existing race test starts at BEGIN IMMEDIATE and misses this window.
  • Serialize Doctor compaction with ownership claims (P1) - This check is not held through wal_checkpoint(TRUNCATE) and VACUUM, while the claim path does not acquire Doctor’s maintenance lock. A claim can therefore commit immediately after validation and the unmarked Doctor still mutates the database; add shared coordination and an injected-race regression.
  • Resolve merge risk (P1) - An external ownership claim can commit after the fast pre-open check, allowing an unmarked process to chmod or initialize SQLite/WAL state after the documented refusal boundary.
  • Resolve merge risk (P1) - Doctor can still checkpoint and VACUUM after an external claim commits because its maintenance lock is not shared by the claim path.
  • Resolve merge risk (P1) - GitHub currently reports a dirty merge state, so an exact merged result must be revalidated after the ownership-boundary repair.
  • Complete next step (P2) - Protected maintainer-owned scope and the explicit ownership-contract choice require human direction before a repair or merge.

Findings

  • [P1] Fence state-open setup under the ownership claim — src/state/openclaw-state-db.ts:592-604
  • [P1] Serialize Doctor compaction with ownership claims — src/commands/doctor-state-sqlite-compact.ts:89-92
Agent review details

Security

None.

PR surface

Source +947, Tests +1324, Docs +35, Generated 0, Other +2. Total +2308 across 41 files.

View PR surface stats
Area Files Added Removed Net
Source 23 1458 511 +947
Tests 14 1342 18 +1324
Docs 2 37 2 +35
Config 0 0 0 0
Generated 1 46 46 0
Other 1 2 0 +2
Total 41 2885 577 +2308

Review metrics

Metric Value Why it matters
Operator command surface 2 subcommands added database preflight and database ownership become public operator interfaces, so their safety contract must match runtime behavior.
Configuration surfaces 0 new config options or environment variables The repair uses the existing external-supervisor marker rather than expanding configuration surface.

Stored data model

Persistent data-model change detected: database schema: src/infra/sqlite-schema-contract.test.ts, database schema: src/proxy-capture/store.sqlite.test.ts, migration/backfill/repair: src/commands/doctor-config-preflight.ts, migration/backfill/repair: src/commands/doctor-state-sqlite-compact.ts, migration/backfill/repair: src/infra/startup-migration-checkpoint.test.ts, migration/backfill/repair: src/state/openclaw-state-ownership.test.ts, and 23 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #121068
Summary: This PR is the linked candidate repair for externally supervised same-version state schema drift.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Close the ownership race windows (recommended)
    Make claims and every state-opening or Doctor mutation use the same owner boundary, with injected-race regressions before merge.
  2. Adopt a narrower contract
    Explicitly limit the ownership promise to an externally coordinated transition and revise the operator documentation to match.

Technical review

Best possible solution:

Use one lifecycle coordination boundary for ownership claims, state-open setup, and destructive Doctor maintenance, then add claim-during-open and claim-during-compaction regressions.

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

Yes—injecting a claim after the pre-open ownership check or after Doctor validation gives a high-confidence source-level reproduction; the current tests inject only before schema repair.

Is this the best way to solve the issue?

No—the state lifecycle is the correct owner, but the patch does not fence all mutations that its new public contract says occur after a claim.

Full review comments:

  • [P1] Fence state-open setup under the ownership claim — src/state/openclaw-state-db.ts:592-604
    A claim can commit after the check at line 591 but before this permission/WAL setup. That lets an unmarked opener change filesystem or SQLite state after ownership exists, contradicting the documented pre-mutation refusal guarantee; the existing race test starts at BEGIN IMMEDIATE and misses this window.
    Confidence: 0.99
  • [P1] Serialize Doctor compaction with ownership claims — src/commands/doctor-state-sqlite-compact.ts:89-92
    This check is not held through wal_checkpoint(TRUNCATE) and VACUUM, while the claim path does not acquire Doctor’s maintenance lock. A claim can therefore commit immediately after validation and the unmarked Doctor still mutates the database; add shared coordination and an injected-race regression.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against bff0494f33b2.

Labels

Label justifications:

  • P1: Incomplete ownership fencing can let an unmarked shared-state writer mutate state during external-supervisor lifecycle transitions.
  • merge-risk: 🚨 compatibility: The new durable ownership contract can refuse existing writable state paths and is presently inconsistent at concurrent mutation boundaries.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its body nevertheless links exact-head CI and isolated Gateway/state evidence.

Evidence

What I checked:

  • Unfenced cold-open mutation: The exact head checks ownership, then performs permission hardening before its later transactional recheck; a claim between those operations lets an unmarked process mutate filesystem permissions despite the documented guarantee. (src/state/openclaw-state-db.ts:591, 2b02823de87d)
  • Documented contract: The new operator documentation says an unmarked writable open fails before permissions or other mutation, which the claim-after-check race violates. Public docs: docs/cli/gateway.md. (docs/cli/gateway.md:172, 2b02823de87d)
  • Doctor remains concurrent with claims: Doctor validates ownership before checkpoint/VACUUM, but claim operations do not take Doctor’s maintenance lock, so a claim can commit after validation and before the destructive SQLite operations. (src/commands/doctor-state-sqlite-compact.ts:89, 2b02823de87d)
  • Existing tests miss both timing windows: The cold-open test injects a claim at BEGIN IMMEDIATE and verifies schema repair is stopped; it does not inject after the pre-open check or after Doctor validation. (src/state/openclaw-state-ownership.test.ts:143, 2b02823de87d)
  • Current-main comparison: Current main has no external-state ownership module, so this PR’s central repair is not already implemented. (src/state/openclaw-state-ownership.ts, bff0494f33b2)
  • Feature-history provenance: The final functional commit is titled “fix: close external state ownership races”; the residual windows above show that it closed only later transaction/schema windows. (src/state/openclaw-state-db.ts, 56dbdfa8b8f5)

Likely related people:

  • steipete: Authored the PR’s ownership-race commit and has substantial recent history in the state database owner path. (role: recent shared-state lifecycle contributor; confidence: high; commits: 56dbdfa8b8f5, e7950d968b87; files: src/state/openclaw-state-db.ts, src/state/openclaw-state-ownership-operations.ts)
  • Vincent Koc: Recent state-history work covers canonical SQLite repair, verification, and compatibility boundaries affected by this change. (role: adjacent state-integrity contributor; confidence: medium; commits: 663c4fba1053, f288589166e0; files: src/state/openclaw-state-db.ts, src/infra/sqlite-schema-contract.ts)

Rank-up moves

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

  • Serialize claims with cold-open permissions/WAL setup and test a claim in that interval.
  • Serialize claims with Doctor compaction and test a claim after validation but before checkpoint/VACUUM.
  • Resolve the dirty merge state and rerun exact-head validation.

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 (4 earlier review cycles)
  • reviewed 2026-08-09T13:47:50.370Z sha f4ab91d88b4d4dd636c79e17608476909d94ac93 :: found issues before merge. :: [P1] Preserve the existing shared_host lazy-column compatibility | [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-09T14:54:55.803Z sha a864c75 :: found issues before merge. :: [P3] Remove the release-owned changelog entry
  • reviewed 2026-08-09T18:46:17.846Z sha afa84ebaba322440e08c23fae9069c9509769986 :: found issues before merge. :: [P1] Fence state-open repairs before they execute | [P1] Accept safe same-version additive columns during preflight
  • reviewed 2026-08-09T19:42:43.209Z sha eb80c650375affb5249e2a5f6c244a4ea851d03b :: needs changes before merge. :: [P1] Fence permission and WAL changes under the ownership lock | [P1] Serialize Doctor compaction with ownership claims

@steipete
steipete force-pushed the fix/external-state-schema-ownership branch from f4ab91d to a864c75 Compare August 9, 2026 14:16
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 9, 2026
@steipete
steipete force-pushed the fix/external-state-schema-ownership branch 2 times, most recently from 31f5aa9 to 76a6f7e Compare August 9, 2026 18:14
@steipete
steipete marked this pull request as ready for review August 9, 2026 18:14
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Aug 9, 2026
@steipete
steipete force-pushed the fix/external-state-schema-ownership branch from 9f1a47d to afa84eb Compare August 9, 2026 18:39
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 9, 2026
@steipete
steipete force-pushed the fix/external-state-schema-ownership branch from f3427b3 to 5b69452 Compare August 9, 2026 19:21
@steipete steipete self-assigned this Aug 9, 2026
@steipete
steipete force-pushed the fix/external-state-schema-ownership branch from 5b69452 to eb80c65 Compare August 9, 2026 19:32
@steipete
steipete force-pushed the fix/external-state-schema-ownership branch from eb80c65 to 2b02823 Compare August 9, 2026 19:56
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 9, 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 repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit f31d9d8 into main Aug 9, 2026
126 checks passed
@steipete
steipete deleted the fix/external-state-schema-ownership branch August 9, 2026 21:04
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 10, 2026
* fix: prevent externally supervised state schema drift

* refactor: isolate schema ownership support code

* test: follow canonical additive column order

* test: keep older schema fixture valid

* fix: preserve additive schema compatibility

* chore: remove release-owned changelog entry

* test: follow schema compatibility owner

* style: format schema compatibility test

* refactor: split sqlite schema sql helpers

* fix: preserve desktop schema compatibility

* fix: preserve ownership gates across platforms

* fix: preserve detached updater long paths

* fix: close external state ownership races

* chore: refresh plugin sdk api baseline
Rorqualx pushed a commit to Rorqualx/cortex that referenced this pull request Aug 13, 2026
…ream

The 2026-08-12 resync left this file a hybrid merge that dropped upstream's
handoff rework while its callers and tests already expected the new API:

- root-mismatch binding (openclaw#121288): concurrent handoffs across distinct install
  roots silently coalesced instead of rejecting; single-flight test failed
  ("promise resolved 'joined' instead of rejecting").
- tag threading (openclaw#121328): callers pass `tag` via a conditional spread that
  bypasses TS excess-property checking, so the pinned/adopted target version was
  silently dropped and a moving channel could update to the wrong version.
- externally-supervised state-drift guard (openclaw#121069): the detached update helper
  could write/migrate an externally-supervised gateway's shared SQLite.

Take upstream's file wholesale — no fork-specific logic in it; callers and all
four handoff test files are already byte-identical to upstream. Verified: repro
test now passes, all 4 handoff test files green (28 passed), tsgo:core update
surface clean, autoreview clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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.

Externally supervised installs can suffer same-version state schema drift

1 participant