Skip to content

Commit f31d9d8

Browse files
authored
fix: prevent externally supervised state schema drift (#121069)
* 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
1 parent bff0494 commit f31d9d8

41 files changed

Lines changed: 2885 additions & 577 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 46 additions & 46 deletions
Large diffs are not rendered by default.

‎docs/cli/gateway.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,19 @@ Set `OPENCLAW_SUPERVISOR_MODE=external` only when another process manager owns t
160160
- OpenClaw self-update is refused so the supervisor can stop the Gateway, replace and finalize the runtime, and restart it safely.
161161
- A fresh-process restart writes a bounded SQLite handoff before clean exit. If persistence fails, the Gateway falls back to an in-process restart instead of exiting without a consumable handoff.
162162

163+
An external supervisor can also claim durable ownership of shared-state writes:
164+
165+
```bash
166+
OPENCLAW_SUPERVISOR_MODE=external \
167+
openclaw database ownership claim --manager gateway-supervisor --json
168+
```
169+
170+
Before claiming, stop and verify every older Gateway, CLI, Doctor, updater, and native app process that can write the shared state database. Pre-contract processes do not understand the ownership row and cannot be retroactively fenced. Claim only after every remaining writer uses ownership-aware code and carries `OPENCLAW_SUPERVISOR_MODE=external`.
171+
172+
The claim is idempotent for the same stable manager identifier and refuses a different manager. There is no automatic claim or unclaim path. Once claimed, unmarked writable shared-state opens fail before permissions, schema migration, additive repair, compaction, or other mutation. Read-only access remains available. This is protection against accidental unmarked same-user writers, not an authentication or lease protocol.
173+
174+
For upgrades and rollbacks, have the supervisor create a consolidated WAL-consistent copied snapshot with no SQLite sidecars, then run the target release's own `openclaw database preflight <copied-state.sqlite> --json` before activation. Numeric schema versions alone do not prove that a same-version additive shape is compatible. See [Database schemas](/reference/database-schemas).
175+
163176
`OPENCLAW_SERVICE_REPAIR_POLICY=external` remains a separate Doctor repair policy. It does not declare runtime ownership; supervisors that need both behaviors should set both variables.
164177

165178
External supervisors can negotiate and consume restart handoffs through the hidden machine contract:

‎docs/reference/database-schemas.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,30 @@ OpenClaw applies forward-only migrations when it opens an older supported databa
2929

3030
Changes may stay at the same schema version only when downgraded readers remain safe. New tables qualify because older builds ignore them. An explicitly compatible column on an existing table qualifies only when its declaration is exactly one bare nullable SQLite `STRICT` datatype: `ANY`, `BLOB`, `INT`, `INTEGER`, `REAL`, or `TEXT`. The declaration cannot have a default, `NOT NULL`, a primary or unique key, a check, a reference, a collation, a generated expression, or another suffix. Constrained existing-table additions require a schema-version bump or a companion table instead.
3131

32+
Matching numeric versions are necessary but not sufficient. A release can add a lazy or startup-repairable table, column, index, or trigger without advancing `user_version`, so two databases at the same version can still have different shapes. OpenClaw validates the canonical table definitions, constraints, indexes, triggers, virtual tables, and table options owned by the running release.
33+
3234
Installing OpenClaw manually through npm bypasses the updater guard. Database open checks still refuse an incompatible build.
3335

36+
## Preflight a target release
37+
38+
Before activating or rolling back a release, run that target release's CLI against one explicit copied state database:
39+
40+
```bash
41+
openclaw database preflight <copied-state.sqlite> --json
42+
```
43+
44+
The command does not read the default state directory or mutate the supplied file. It opens the supplied consolidated file as immutable/read-only, compares the target release's own schema contract, and reports one status:
45+
46+
- `exact`: the copied database matches the target release's runtime schema. Feature-local tables that are intentionally absent until first use do not require repair.
47+
- `startup-repairable`: the numeric version matches and a runtime-owned additive difference remains; startup needs a write to converge the shape.
48+
- `migration-required`: the database is older than the target release.
49+
- `incompatible`: the database is newer, or its same-version shape has blocking drift such as an unexpected column.
50+
- `indeterminate`: the file, integrity metadata, or ownership metadata could not be verified.
51+
52+
JSON output is identified by `schema: "openclaw.state-schema-preflight.v1"`.
53+
54+
Use a SQLite online backup or another WAL-aware snapshot produced while the source is safely coordinated. The resulting preflight input must be one consolidated file with no sibling `-wal`, `-shm`, or `-journal`; sidecars make the result `indeterminate`. Do not copy only the main `.sqlite` file from an active WAL database. Preflight the exact runtime that will be activated; a package version or numeric schema version alone does not prove same-version shape compatibility.
55+
3456
## Agent schema history
3557

3658
| Version | Change | First release |
@@ -65,7 +87,7 @@ Version 3 was an unshipped development step folded into version 4.
6587
| Gateway background verifier | Run the full scan about once daily and log results |
6688
| Doctor, backup verification, and compaction | Run the full scan before accepting or rewriting the database |
6789

68-
The Gateway preflight reads schema headers only. The background verifier owns the slower full scan for databases that do not need migration.
90+
The Gateway startup preflight reads schema headers only. `openclaw database preflight` performs the release-local shape comparison for an explicit copied file. The background verifier owns the slower recurring full scan for live databases that do not need migration.
6991
Quarantine decisions live only in a dedicated `openclaw-quarantine.sqlite` store, so they survive damage to the databases being quarantined. Verification results are logged.
7092

7193
## Troubleshooting
@@ -86,7 +108,7 @@ Since 2026.7.2, `openclaw update` refuses to install a release that cannot open
86108

87109
A newer OpenClaw build wrote your databases, and the running build is older. The error names the refusing install — release version, commit, and install root — plus the schema it supports and the schema it found.
88110

89-
Act on the install root, not the version. One release version string spans many `main` commits and several schema levels, so two installs can both call themselves `2026.7.2` and support different schemas. A prerelease version may not exist on the `latest` npm tag at all: check `npm view openclaw dist-tags` before reinstalling, because the tag carrying the schema you need may be `beta`, and reinstalling from `latest` can move you further away.
111+
Act on the install root, not the version. One release version string spans many `main` commits, schema levels, and same-version schema shapes, so two installs can both call themselves `2026.7.2` and still disagree about a database. A prerelease version may not exist on the `latest` npm tag at all: check `npm view openclaw dist-tags` before reinstalling, because the tag carrying the schema you need may be `beta`, and reinstalling from `latest` can move you further away.
90112

91113
A linked source checkout is the case where the commit misleads: `openclaw --version` reports the checkout's git HEAD, but the code actually executing is whatever `dist/` was last built. If the install root is a checkout, rebuild it (`pnpm build`) before concluding the version is wrong.
92114

‎scripts/check-kysely-guardrails.mts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ const rawSqliteAllowPathGroups = {
6464
"src/state/openclaw-state-db-schema-repair.ts",
6565
"src/state/openclaw-state-db-startup-checkpoint.ts",
6666
"src/state/openclaw-state-db.ts",
67+
"src/state/openclaw-state-ownership-operations.ts",
6768
"src/transcripts/sqlite-schema.ts",
6869
"src/state/sqlite-schema-shape.test-support.ts",
6970
],
@@ -85,6 +86,7 @@ const rawSqliteAllowPathGroups = {
8586
"read-only schema preflight and integrity verification access": [
8687
"src/state/openclaw-database-preflight.ts",
8788
"src/state/openclaw-database-verify.worker.ts",
89+
"src/state/openclaw-state-ownership.ts",
8890
],
8991
"quarantine store must work when other databases are damaged": [
9092
"src/state/openclaw-quarantine-store.ts",

‎src/claws/read-only-state-compat.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
44
import { join } from "node:path";
55
import { afterEach, describe, expect, it } from "vitest";
66
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
7-
import { CLAW_LAZY_ADDITIVE_STATE_COLUMNS } from "../state/openclaw-state-db-maintenance.js";
87
import {
98
closeOpenClawStateDatabaseForTest,
109
openOpenClawStateDatabase,
1110
} from "../state/openclaw-state-db.js";
11+
import { OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY } from "../state/openclaw-state-schema-compatibility.js";
1212
import { readClawResumeStateReadOnly } from "./package-resume.js";
1313
import { parseClawManifest } from "./schema.js";
1414
import type { ClawSourceIdentity } from "./types.js";
@@ -39,7 +39,8 @@ function createBaseShapeState(params: {
3939
)`,
4040
)
4141
.run(params.packageRoot, join(params.packageRoot, "CLAW.md"), params.workspace);
42-
for (const column of CLAW_LAZY_ADDITIVE_STATE_COLUMNS) {
42+
for (const column of OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY.allowedMissingColumns ??
43+
[]) {
4344
const [table, name] = column.split(".");
4445
database.db.exec(`ALTER TABLE ${table} DROP COLUMN ${name};`);
4546
}

‎src/cli/command-catalog.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,17 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
102102
// read, validate, migrate, or inherit proxy policy from operator state.
103103
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
104104
},
105+
{
106+
commandPath: ["database"],
107+
// Release-local database inspection must not observe default state or load runtime policy.
108+
policy: {
109+
configGuard: "skip",
110+
loadPlugins: "never",
111+
hideBanner: true,
112+
ensureCliPath: false,
113+
networkProxy: "bypass",
114+
},
115+
},
105116
{
106117
commandPath: ["crestodian"], // hidden alias
107118
policy: { configGuard: "skip", loadPlugins: "never", ensureCliPath: false },

‎src/cli/command-startup-policy.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ describe("command-startup-policy", () => {
2626
it("resolves config guard policy for Commander and invocation-aware commands", () => {
2727
for (const commandPath of [
2828
["backup", "create"],
29+
["database"],
2930
["config"],
3031
["config", "file"],
3132
["config", "validate"],

‎src/cli/program/command-registry-core.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ const coreEntrySpecs: readonly CommandGroupDescriptorSpec<
7474
loadModule: () => import("./register.backup.js"),
7575
exportName: "registerBackupCommand",
7676
},
77+
{
78+
commandNames: ["database"],
79+
loadModule: () => import("./register.database.js"),
80+
exportName: "registerDatabaseCommand",
81+
},
7782
{
7883
commandNames: ["migrate"],
7984
loadModule: () => import("./register.migrate.js"),

‎src/cli/program/core-command-descriptors.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ const coreCliCommandCatalog = defineCommandDescriptorCatalog([
4848
description: "Create and verify backup archives and SQLite snapshots",
4949
hasSubcommands: true,
5050
},
51+
{
52+
name: "database",
53+
description: "Inspect shared-state schema compatibility and write ownership",
54+
hasSubcommands: true,
55+
parentDefaultHelp: true,
56+
},
5157
{
5258
name: "migrate",
5359
description: "Import state from another agent system",
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import type { Command } from "commander";
2+
import { formatErrorMessage } from "../../infra/errors.js";
3+
import { defaultRuntime, writeRuntimeJson, writeRuntimeStdout } from "../../runtime.js";
4+
import {
5+
OPENCLAW_DATABASE_SCHEMA_DOCS_URL,
6+
preflightOpenClawStateDatabasePath,
7+
} from "../../state/openclaw-database-preflight.js";
8+
import { resolveDatabasePath } from "../../state/openclaw-state-db-maintenance.js";
9+
import { claimOpenClawStateOwnership } from "../../state/openclaw-state-ownership-operations.js";
10+
import { inspectOpenClawStateOwnershipAtPath } from "../../state/openclaw-state-ownership.js";
11+
import { applyParentDefaultHelpAction } from "./parent-default-help.js";
12+
13+
type DatabaseOutputOptions = { json?: boolean };
14+
15+
function writeDatabaseError(error: unknown, json: boolean): void {
16+
const message = formatErrorMessage(error);
17+
if (json) {
18+
writeRuntimeJson(defaultRuntime, { error: message });
19+
} else {
20+
defaultRuntime.error(message);
21+
}
22+
defaultRuntime.exit(1);
23+
}
24+
25+
async function runDatabasePreflight(databasePath: string, options: DatabaseOutputOptions) {
26+
const result = await preflightOpenClawStateDatabasePath(databasePath);
27+
if (options.json) {
28+
writeRuntimeJson(defaultRuntime, result);
29+
} else {
30+
const detail = result.reason ?? result.issues[0]?.message;
31+
writeRuntimeStdout(
32+
defaultRuntime,
33+
`Database preflight: ${result.status} (found ${result.foundVersion ?? "unknown"}, target ${result.targetVersion}).${detail ? `\n${detail}` : ""}\nSee ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.\n`,
34+
);
35+
}
36+
if (result.status === "incompatible" || result.status === "indeterminate") {
37+
defaultRuntime.exit(1);
38+
}
39+
}
40+
41+
function runDatabaseOwnership(options: DatabaseOutputOptions & { manager?: string }): void {
42+
try {
43+
const databasePath = resolveDatabasePath({ env: process.env });
44+
const ownership =
45+
options.manager !== undefined
46+
? claimOpenClawStateOwnership(options.manager, {
47+
path: databasePath,
48+
env: process.env,
49+
})
50+
: inspectOpenClawStateOwnershipAtPath(databasePath);
51+
const status = ownership
52+
? { status: "external" as const, ownership }
53+
: { status: "unowned" as const };
54+
if (options.json) {
55+
writeRuntimeJson(defaultRuntime, { databasePath, ...status });
56+
return;
57+
}
58+
const message =
59+
status.status === "external"
60+
? `Shared state is externally owned by ${status.ownership.managerId}.`
61+
: "Shared state is not externally owned.";
62+
writeRuntimeStdout(defaultRuntime, `${message}\nSee ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.\n`);
63+
} catch (error) {
64+
writeDatabaseError(error, options.json === true);
65+
}
66+
}
67+
68+
export function registerDatabaseCommand(program: Command): void {
69+
const database = program
70+
.command("database")
71+
.description("Inspect shared-state schema compatibility and write ownership")
72+
.addHelpText("after", `\nDocs: ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}\n`);
73+
74+
database
75+
.command("preflight")
76+
.description("Compare one copied SQLite file with this release's state schema")
77+
.argument("<path>", "explicit copied SQLite database path")
78+
.option("--json", "emit machine-readable JSON", false)
79+
.action(async (databasePath: string, options: DatabaseOutputOptions) => {
80+
await runDatabasePreflight(databasePath, options);
81+
});
82+
83+
const ownership = database.command("ownership").description("Inspect or claim write ownership");
84+
ownership
85+
.command("status")
86+
.description("Show durable shared-state write ownership")
87+
.option("--json", "emit machine-readable JSON", false)
88+
.action((options: DatabaseOutputOptions) => runDatabaseOwnership(options));
89+
ownership
90+
.command("claim")
91+
.description("Claim shared-state writes for the active external supervisor")
92+
.requiredOption("--manager <id>", "stable external manager identifier")
93+
.option("--json", "emit machine-readable JSON", false)
94+
.action((options: DatabaseOutputOptions & { manager: string }) =>
95+
runDatabaseOwnership(options),
96+
);
97+
applyParentDefaultHelpAction(ownership);
98+
applyParentDefaultHelpAction(database);
99+
}

0 commit comments

Comments
 (0)