Skip to content

Commit 56dbdfa

Browse files
committed
fix: close external state ownership races
1 parent 86fe1fa commit 56dbdfa

4 files changed

Lines changed: 111 additions & 13 deletions

File tree

‎src/state/openclaw-database-preflight.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,35 @@ describe("OpenClaw database schema preflight", () => {
118118
});
119119
});
120120

121+
it("accepts a copied current schema with a future bare nullable column without touching it", async () => {
122+
const sourcePath = createExplicitStateDatabase();
123+
const databasePath = path.join(
124+
tempDirs.make("openclaw-copied-state-preflight-"),
125+
"candidate.sqlite",
126+
);
127+
fs.copyFileSync(sourcePath, databasePath);
128+
const { DatabaseSync } = requireNodeSqlite();
129+
const database = new DatabaseSync(databasePath);
130+
try {
131+
database.exec("ALTER TABLE worktrees ADD COLUMN future_note TEXT;");
132+
} finally {
133+
database.close();
134+
}
135+
const before = snapshotSourceFamily(databasePath);
136+
137+
await expect(preflightOpenClawStateDatabasePath(databasePath)).resolves.toEqual({
138+
schema: "openclaw.state-schema-preflight.v1",
139+
databasePath,
140+
targetVersion: OPENCLAW_STATE_SCHEMA_VERSION,
141+
foundVersion: OPENCLAW_STATE_SCHEMA_VERSION,
142+
ownership: null,
143+
status: "exact",
144+
requiresWrite: false,
145+
issues: [],
146+
});
147+
expect(snapshotSourceFamily(databasePath)).toEqual(before);
148+
});
149+
121150
it("classifies a drifted canonical named index as startup-repairable", async () => {
122151
const databasePath = createExplicitStateDatabase();
123152
const { DatabaseSync } = requireNodeSqlite();

‎src/state/openclaw-state-db.ts‎

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -392,12 +392,15 @@ function ensureSchema(db: DatabaseSync, pathname: string, env: NodeJS.ProcessEnv
392392
runSqliteImmediateTransactionSync(
393393
db,
394394
() => {
395+
// Recheck ownership after BEGIN IMMEDIATE so no current-schema repair
396+
// can race a durable external ownership claim.
395397
assertOpenClawStateWriteAllowed({ database: db, databasePath: pathname, env });
396398
assertSupportedSchemaVersion(db, pathname);
397399
const previousVersion = readSqliteUserVersion(db);
398400
if (previousVersion === OPENCLAW_STATE_SCHEMA_VERSION) {
399-
repairCanonicalSqliteIndexes(db, pathname, OPENCLAW_STATE_SCHEMA_SQL, {
400-
verifyPhysicalIntegrity: false,
401+
verifyAndRepairCanonicalSqliteIndexes(db, pathname, OPENCLAW_STATE_SCHEMA_SQL, {
402+
allowMissingColumns: true,
403+
validateAfterRepair: () => assertCurrentStateRuntimeSchema(db, pathname),
401404
});
402405
ensureAdditiveStateColumns(db);
403406
assertCurrentStateRuntimeSchema(db, pathname);
@@ -549,19 +552,10 @@ function assertStateDatabaseIntegrityBeforeMutation(
549552
toVersion: OPENCLAW_STATE_SCHEMA_VERSION,
550553
});
551554
}
552-
if (userVersion === OPENCLAW_STATE_SCHEMA_VERSION) {
553-
verifyAndRepairCanonicalSqliteIndexes(database, pathname, OPENCLAW_STATE_SCHEMA_SQL, {
554-
allowMissingColumns: true,
555-
validateAfterRepair: () => assertCurrentStateRuntimeSchema(database, pathname),
556-
});
557-
ensureAdditiveStateColumns(database);
558-
} else {
555+
if (userVersion !== OPENCLAW_STATE_SCHEMA_VERSION) {
559556
// Every physical open proves the full file before schema mutation or exposure.
560557
assertSqliteIntegrity(database, pathname);
561558
}
562-
if (userVersion === OPENCLAW_STATE_SCHEMA_VERSION) {
563-
assertCurrentStateRuntimeSchema(database, pathname);
564-
}
565559
}
566560

567561
/** Open or return a cached shared state database after schema and migration checks. */

‎src/state/openclaw-state-ownership.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,81 @@ describe("external shared-state ownership", () => {
140140
).toBeDefined();
141141
});
142142

143+
it("fences a claim made immediately before cold-open schema repair", () => {
144+
const env = createEnv();
145+
const databasePath = openOpenClawStateDatabase({ env }).path;
146+
closeOpenClawStateDatabaseForTest();
147+
const { DatabaseSync } = requireNodeSqlite();
148+
const drifted = new DatabaseSync(databasePath);
149+
try {
150+
drifted.exec(`
151+
ALTER TABLE worktrees DROP COLUMN run_end_cleanup_json;
152+
DROP INDEX idx_task_runs_status;
153+
`);
154+
} finally {
155+
drifted.close();
156+
}
157+
158+
const originalExec = Object.getOwnPropertyDescriptor(DatabaseSync.prototype, "exec")?.value as
159+
| ((this: import("node:sqlite").DatabaseSync, sql: string) => void)
160+
| undefined;
161+
if (!originalExec) {
162+
throw new Error("DatabaseSync.exec descriptor is unavailable");
163+
}
164+
let immediateTransactionCount = 0;
165+
const exec = vi.spyOn(DatabaseSync.prototype, "exec").mockImplementation(function (
166+
this: import("node:sqlite").DatabaseSync,
167+
sql: string,
168+
) {
169+
if (sql === "BEGIN IMMEDIATE" && ++immediateTransactionCount === 1) {
170+
const claimant = new DatabaseSync(databasePath);
171+
try {
172+
claimant
173+
.prepare(
174+
`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
175+
VALUES (?, ?, ?)`,
176+
)
177+
.run(
178+
STATE_SUPERVISION_KEY,
179+
JSON.stringify({
180+
version: 1,
181+
mode: "external",
182+
managerId: "race-manager",
183+
claimedAt: 1,
184+
}),
185+
1,
186+
);
187+
} finally {
188+
claimant.close();
189+
}
190+
}
191+
return originalExec.call(this, sql);
192+
});
193+
194+
try {
195+
expect(() => openOpenClawStateDatabase({ env })).toThrow(OpenClawStateOwnershipError);
196+
} finally {
197+
exec.mockRestore();
198+
}
199+
expect(immediateTransactionCount).toBe(1);
200+
201+
const verify = new DatabaseSync(databasePath, { readOnly: true });
202+
try {
203+
expect(
204+
verify
205+
.prepare("SELECT 1 FROM pragma_table_info('worktrees') WHERE name = ?")
206+
.get("run_end_cleanup_json"),
207+
).toBeUndefined();
208+
expect(
209+
verify
210+
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'index' AND name = ?")
211+
.get("idx_task_runs_status"),
212+
).toBeUndefined();
213+
} finally {
214+
verify.close();
215+
}
216+
});
217+
143218
it("fences injected and pre-claim handles on their next canonical write", () => {
144219
const externalEnv = createEnv(true);
145220
const opened = openOpenClawStateDatabase({ env: externalEnv });

‎src/state/openclaw-state-schema-compatibility.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export function getOpenClawStateRuntimeSchema(options: {
6969
}
7070

7171
export const STATE_PERSISTENT_SCHEMA_COMPATIBILITY: SqliteSchemaCompatibility = {
72+
allowCompatibleAdditiveColumns: true,
7273
allowedColumnDefinitions: {
7374
"diagnostic_events.sequence": ["sequence INTEGER NOT NULL DEFAULT 0"],
7475
"commitments.attempts": ["attempts INTEGER NOT NULL DEFAULT 0"],
@@ -106,7 +107,6 @@ export const STATE_PERSISTENT_SCHEMA_COMPATIBILITY: SqliteSchemaCompatibility =
106107

107108
export const OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY: SqliteSchemaCompatibility = {
108109
...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
109-
allowCompatibleAdditiveColumns: true,
110110
allowedMissingTables: LAZY_ADDITIVE_STATE_TABLES,
111111
allowedMissingColumns: CLAW_LAZY_ADDITIVE_STATE_COLUMNS,
112112
};

0 commit comments

Comments
 (0)