Skip to content

Commit 3e6aec1

Browse files
authored
fix(state): avoid startup ownership snapshots (#122518)
1 parent ce56c40 commit 3e6aec1

6 files changed

Lines changed: 151 additions & 12 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1967,7 +1967,7 @@
19671967
"test:unit:fast:audit": "node --import tsx scripts/test-unit-fast-audit.mts",
19681968
"test:voicecall:closedloop": "node --import tsx scripts/test-voicecall-closedloop.mts",
19691969
"test:watch": "node --import tsx scripts/test-projects.mts --watch",
1970-
"test:windows:ci": "node --import tsx scripts/test-projects.mts src/shared/runtime-import.test.ts src/config/sessions/session-accessor.sqlite-archive.worker.test.ts src/commands/doctor-gateway-auth-token.windows.test.ts src/agents/tools/media-tool-file-url.windows.test.ts src/media/local-media-path.windows.test.ts src/infra/sqlite-snapshot.test.ts src/infra/ssh-client.windows.test.ts src/infra/ports.test.ts src/infra/advertised-lan-host.windows.test.ts src/infra/update-managed-service-handoff-command.test.ts src/infra/update-managed-service-handoff-lifecycle.test.ts src/infra/exec-allowlist-pattern.test.ts src/infra/executable-path.test.ts src/infra/process-env.test.ts src/infra/fs-safe-remove.test.ts src/snapshot/local-repository.windows.test.ts src/state/openclaw-database-paths.windows.test.ts src/commands/backup-verify.test.ts src/infra/state-migrations.legacy-session-store.test.ts src/test-utils/openclaw-test-state.test.ts src/agents/provider-local-service.env-case.test.ts src/agents/sessions/windows-git-bash-path.test.ts src/agents/bash-tools.exec.script-preflight.test.ts src/process/exec.windows.test.ts src/process/exec.windows.integration.test.ts src/process/windows-command.test.ts src/process/terminal-pty.test.ts src/plugin-sdk/node-host.test.ts src/tui/tui.resolve-codex-bin.test.ts src/infra/windows-install-roots.test.ts src/node-host/invoke-system-run-allowlist.test.ts src/auto-reply/usage-bar/template.windows.test.ts src/auto-reply/reply.triggers.trigger-handling.stages-inbound-media-into-sandbox-workspace.test.ts src/media-understanding/attachments.file-url.windows.test.ts src/utils.test.ts src/commands/agents.commands.list.test.ts src/cli/daemon-cli/status.print.test.ts src/cli/mcp-cli.path-case.windows.test.ts extensions/memory-core/src/memory-extra-file-path.windows.test.ts packages/terminal-core/src/display-string.test.ts src/agents/sandbox/fs-paths.test.ts src/agents/sessions/tools/render-utils.test.ts src/agents/agent-tools.read.windows.test.ts src/agents/agent-tools.read.host-operations.test.ts src/agents/sessions/tools/path-utils.test.ts src/daemon/schtasks.startup-fallback.test.ts src/media/web-media.file-url.windows.test.ts extensions/lobster/src/lobster-runner.test.ts extensions/msteams/src/media-helpers.test.ts extensions/msteams/src/messenger.test.ts extensions/mxc/test/mxc-backend.test.ts extensions/mxc/test/sandbox-policy-loader.test.ts test/e2e/qa-lab/runtime/package-openclaw-for-docker.e2e.test.ts test/scripts/direct-run-entrypoints.test.ts test/scripts/format-generated-module.test.ts test/scripts/npm-runner.test.ts test/scripts/openclaw-cross-os-installer.windows.test.ts test/scripts/openclaw-cross-os-release-workflow.test.ts test/scripts/pnpm-runner.test.ts test/scripts/run-with-env.test.ts test/scripts/ts-topology.test.ts test/scripts/ui.test.ts test/scripts/vitest-process-group.test.ts",
1970+
"test:windows:ci": "node --import tsx scripts/test-projects.mts src/shared/runtime-import.test.ts src/config/sessions/session-accessor.sqlite-archive.worker.test.ts src/commands/doctor-gateway-auth-token.windows.test.ts src/agents/tools/media-tool-file-url.windows.test.ts src/media/local-media-path.windows.test.ts src/infra/sqlite-snapshot.test.ts src/state/openclaw-state-ownership.test.ts src/infra/ssh-client.windows.test.ts src/infra/ports.test.ts src/infra/advertised-lan-host.windows.test.ts src/infra/update-managed-service-handoff-command.test.ts src/infra/update-managed-service-handoff-lifecycle.test.ts src/infra/exec-allowlist-pattern.test.ts src/infra/executable-path.test.ts src/infra/process-env.test.ts src/infra/fs-safe-remove.test.ts src/snapshot/local-repository.windows.test.ts src/state/openclaw-database-paths.windows.test.ts src/commands/backup-verify.test.ts src/infra/state-migrations.legacy-session-store.test.ts src/test-utils/openclaw-test-state.test.ts src/agents/provider-local-service.env-case.test.ts src/agents/sessions/windows-git-bash-path.test.ts src/agents/bash-tools.exec.script-preflight.test.ts src/process/exec.windows.test.ts src/process/exec.windows.integration.test.ts src/process/windows-command.test.ts src/process/terminal-pty.test.ts src/plugin-sdk/node-host.test.ts src/tui/tui.resolve-codex-bin.test.ts src/infra/windows-install-roots.test.ts src/node-host/invoke-system-run-allowlist.test.ts src/auto-reply/usage-bar/template.windows.test.ts src/auto-reply/reply.triggers.trigger-handling.stages-inbound-media-into-sandbox-workspace.test.ts src/media-understanding/attachments.file-url.windows.test.ts src/utils.test.ts src/commands/agents.commands.list.test.ts src/cli/daemon-cli/status.print.test.ts src/cli/mcp-cli.path-case.windows.test.ts extensions/memory-core/src/memory-extra-file-path.windows.test.ts packages/terminal-core/src/display-string.test.ts src/agents/sandbox/fs-paths.test.ts src/agents/sessions/tools/render-utils.test.ts src/agents/agent-tools.read.windows.test.ts src/agents/agent-tools.read.host-operations.test.ts src/agents/sessions/tools/path-utils.test.ts src/daemon/schtasks.startup-fallback.test.ts src/media/web-media.file-url.windows.test.ts extensions/lobster/src/lobster-runner.test.ts extensions/msteams/src/media-helpers.test.ts extensions/msteams/src/messenger.test.ts extensions/mxc/test/mxc-backend.test.ts extensions/mxc/test/sandbox-policy-loader.test.ts test/e2e/qa-lab/runtime/package-openclaw-for-docker.e2e.test.ts test/scripts/direct-run-entrypoints.test.ts test/scripts/format-generated-module.test.ts test/scripts/npm-runner.test.ts test/scripts/openclaw-cross-os-installer.windows.test.ts test/scripts/openclaw-cross-os-release-workflow.test.ts test/scripts/pnpm-runner.test.ts test/scripts/run-with-env.test.ts test/scripts/ts-topology.test.ts test/scripts/ui.test.ts test/scripts/vitest-process-group.test.ts",
19711971
"test:windows:schtasks:integration": "node --import tsx scripts/run-with-env.mts CI_WINDOWS_SCHTASKS_INTEGRATION=1 OPENCLAW_E2E_VERBOSE=1 OPENCLAW_VITEST_MAX_WORKERS=1 -- node scripts/run-vitest.mjs src/daemon/schtasks.integration.e2e.test.ts",
19721972
"tool-display:check": "node --import tsx scripts/tool-display.ts --check",
19731973
"tool-display:write": "node --import tsx scripts/tool-display.ts --write",

‎src/commands/doctor-config-preflight.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import { setActiveDegradedPlugins } from "../plugins/runtime-degraded-state.js";
2525
import { ExitError } from "../runtime.js";
2626
import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
2727
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
28-
import { assertOpenClawStateWriteAllowed } from "../state/openclaw-state-ownership.js";
28+
import { assertOpenClawStateWriteAllowedAtPath } from "../state/openclaw-state-ownership.js";
2929
import { resolveHomeDir } from "../utils.js";
3030
import { noteIncludeConfinementWarning } from "./doctor-config-analysis.js";
3131
import {
@@ -208,7 +208,7 @@ export async function runDoctorConfigPreflight(
208208
): Promise<DoctorConfigPreflightResult> {
209209
const stateMigrationsRequested = options.migrateState !== false;
210210
if (stateMigrationsRequested) {
211-
assertOpenClawStateWriteAllowed({
211+
await assertOpenClawStateWriteAllowedAtPath({
212212
databasePath: resolveOpenClawStateSqlitePath(process.env),
213213
env: process.env,
214214
});

‎src/gateway/server-startup-bootstrap.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import { getActiveGatewayRootWorkCount } from "../process/gateway-work-admission
4141
import { createLazyPromise } from "../shared/lazy-runtime.js";
4242
import { roleScopesAllow } from "../shared/operator-scope-compat.js";
4343
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
44-
import { assertOpenClawStateWriteAllowed } from "../state/openclaw-state-ownership.js";
44+
import { assertOpenClawStateWriteAllowedAtPath } from "../state/openclaw-state-ownership.js";
4545
import { ADMIN_SCOPE } from "./method-scopes.js";
4646
import { listCoreGatewayMethodNames } from "./methods/core-descriptors.js";
4747
import {
@@ -80,7 +80,7 @@ export async function prepareGatewayServerBootstrap(input: {
8080
const { port, opts, log, logSecrets, loadWorkerEnvironmentStartupModule } = input;
8181
const formatRuntimeGatewayAuthTokenWarning = input.formatRuntimeGatewayAuthTokenWarning;
8282
normalizeStateDirEnv(process.env);
83-
assertOpenClawStateWriteAllowed({
83+
await assertOpenClawStateWriteAllowedAtPath({
8484
databasePath: resolveOpenClawStateSqlitePath(process.env),
8585
env: process.env,
8686
});

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

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import fs from "node:fs";
22
import path from "node:path";
33
import { afterEach, describe, expect, it, vi } from "vitest";
44
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { runDoctorConfigPreflight } from "../commands/doctor-config-preflight.js";
56
import { runDoctorStateSqliteCompact } from "../commands/doctor-state-sqlite-compact.js";
7+
import { planPristineStartupStateMigrations } from "../commands/doctor/shared/pristine-startup-state.js";
68
import {
79
readConfigHealthStateFromStore,
810
writeConfigHealthStateToStore,
@@ -11,7 +13,8 @@ import { resolveGatewayLockDir } from "../config/paths.js";
1113
import { resolvePathViaExistingAncestorSync } from "../infra/boundary-path.js";
1214
import { sha256HexPrefixCore } from "../infra/crypto-digest.js";
1315
import { requireNodeSqlite, resolveImmutableSqliteFileUri } from "../infra/node-sqlite.js";
14-
import { withEnv } from "../test-utils/env.js";
16+
import * as sqliteReadonlyLocation from "../infra/sqlite-readonly-location.js";
17+
import { withEnv, withEnvAsync } from "../test-utils/env.js";
1518
import { withOpenClawStateStartupMigrationCheckpointDatabase } from "./openclaw-state-db-startup-checkpoint.js";
1619
import {
1720
closeOpenClawStateDatabaseForTest,
@@ -25,6 +28,7 @@ import {
2528
import { resolveOpenClawStateDirForDatabasePath } from "./openclaw-state-db.paths.js";
2629
import { claimOpenClawStateOwnership } from "./openclaw-state-ownership-operations.js";
2730
import {
31+
assertOpenClawStateWriteAllowedAtPath,
2832
inspectOpenClawStateOwnershipAtPath,
2933
OpenClawStateOwnershipError,
3034
OpenClawStateOwnershipMetadataError,
@@ -118,14 +122,41 @@ function mockCoordinatorRollbackFailure(onRollback?: () => void) {
118122
}
119123

120124
describe("external shared-state ownership", () => {
121-
it("returns unowned for a missing path without creating its state tree", () => {
125+
it("returns unowned for a missing path without creating its state tree", async () => {
122126
const rootDir = tempDirs.make("openclaw-state-ownership-missing-");
123127
const missingStateDir = path.join(rootDir, "missing-state");
124128
const databasePath = path.join(missingStateDir, "state", "openclaw.sqlite");
125129

126130
expect(fs.existsSync(missingStateDir)).toBe(false);
127131
expect(inspectOpenClawStateOwnershipAtPath(databasePath)).toBeNull();
128132
expect(fs.existsSync(missingStateDir)).toBe(false);
133+
await assertOpenClawStateWriteAllowedAtPath({ databasePath });
134+
expect(fs.existsSync(missingStateDir)).toBe(false);
135+
});
136+
137+
it("keeps missing-database admission eligible for pristine startup", async () => {
138+
const home = tempDirs.make("openclaw-state-ownership-pristine-");
139+
const stateDir = path.join(home, "state");
140+
const configPath = path.join(stateDir, "openclaw.json");
141+
const databasePath = path.join(stateDir, "state", "openclaw.sqlite");
142+
const env = {
143+
HOME: home,
144+
OPENCLAW_CONFIG_PATH: configPath,
145+
OPENCLAW_STATE_DIR: stateDir,
146+
};
147+
fs.mkdirSync(stateDir, { recursive: true });
148+
fs.writeFileSync(configPath, "{}\n");
149+
150+
expect(planPristineStartupStateMigrations(env)).toEqual({
151+
skipAllStateMigrations: true,
152+
skipCoreStateMigrations: true,
153+
});
154+
await assertOpenClawStateWriteAllowedAtPath({ databasePath, env });
155+
expect(fs.readdirSync(stateDir)).toEqual(["openclaw.json"]);
156+
expect(planPristineStartupStateMigrations(env)).toEqual({
157+
skipAllStateMigrations: true,
158+
skipCoreStateMigrations: true,
159+
});
129160
});
130161

131162
it("preserves ordinary unowned database behavior", () => {
@@ -135,6 +166,37 @@ describe("external shared-state ownership", () => {
135166
expect(inspectOpenClawStateOwnershipAtPath(database.path)).toBeNull();
136167
});
137168

169+
it("checks Doctor startup admission without staging a public snapshot", async () => {
170+
const fixture = claimFixture();
171+
const home = tempDirs.make("openclaw-state-ownership-doctor-");
172+
const snapshotStaging = vi.spyOn(sqliteReadonlyLocation, "prepareSqliteReadOnlyLocationSync");
173+
const runPreflight = async (env: NodeJS.ProcessEnv) =>
174+
await withEnvAsync(
175+
{
176+
HOME: home,
177+
OPENCLAW_CONFIG_PATH: path.join(home, "openclaw.json"),
178+
OPENCLAW_PROFILE: undefined,
179+
OPENCLAW_STATE_DIR: env.OPENCLAW_STATE_DIR,
180+
OPENCLAW_SUPERVISOR_MODE: env.OPENCLAW_SUPERVISOR_MODE,
181+
},
182+
async () =>
183+
await runDoctorConfigPreflight({
184+
invalidConfigNote: false,
185+
migrateLegacyConfig: false,
186+
migrateState: true,
187+
observe: false,
188+
skipPristineStartupStateMigrations: true,
189+
}),
190+
);
191+
try {
192+
await expect(runPreflight(fixture.unmarkedEnv)).rejects.toThrow(OpenClawStateOwnershipError);
193+
await expect(runPreflight(fixture.externalEnv)).resolves.toBeDefined();
194+
expect(snapshotStaging).not.toHaveBeenCalled();
195+
} finally {
196+
snapshotStaging.mockRestore();
197+
}
198+
});
199+
138200
it("reads ownership from a WAL when the SHM index is absent", () => {
139201
const env = createEnv(true);
140202
const databasePath = openOpenClawStateDatabase({ env }).path;
@@ -167,6 +229,44 @@ describe("external shared-state ownership", () => {
167229
}
168230
});
169231

232+
it("rejects unmarked WAL ownership without modifying the SQLite family", async () => {
233+
const env = createEnv(true);
234+
const databasePath = openOpenClawStateDatabase({ env }).path;
235+
closeOpenClawStateDatabaseForTest();
236+
const { DatabaseSync } = requireNodeSqlite();
237+
const writer = new DatabaseSync(databasePath);
238+
const ownership = {
239+
version: 1,
240+
mode: "external",
241+
managerId: "wal-only-manager",
242+
claimedAt: 1,
243+
} as const;
244+
const copyDir = tempDirs.make("openclaw-state-ownership-wal-rejection-");
245+
const copyPath = path.join(copyDir, "openclaw.sqlite");
246+
try {
247+
writer.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0;");
248+
writer
249+
.prepare(
250+
"INSERT INTO config_machine_state (state_key, value_json, updated_at_ms) VALUES (?, ?, ?)",
251+
)
252+
.run(STATE_SUPERVISION_KEY, JSON.stringify(ownership), ownership.claimedAt);
253+
fs.copyFileSync(databasePath, copyPath);
254+
fs.copyFileSync(`${databasePath}-wal`, `${copyPath}-wal`);
255+
} finally {
256+
writer.close();
257+
}
258+
259+
expect(fs.existsSync(`${copyPath}-shm`)).toBe(false);
260+
const before = snapshotSqliteFamily(copyPath);
261+
await expect(
262+
assertOpenClawStateWriteAllowedAtPath({
263+
databasePath: copyPath,
264+
env: withoutExternalMarker(env),
265+
}),
266+
).rejects.toThrow(OpenClawStateOwnershipError);
267+
expect(snapshotSqliteFamily(copyPath)).toEqual(before);
268+
});
269+
170270
it("observes committed ownership that is still resident in the live WAL", () => {
171271
const env = createEnv();
172272
const databasePath = openOpenClawStateDatabase({ env }).path;

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

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import {
1616
runWithSqliteCoordinator,
1717
SqliteCoordinatorError,
1818
} from "../infra/sqlite-coordinator.js";
19-
import { prepareSqliteReadOnlyLocationSync } from "../infra/sqlite-readonly-location.js";
19+
import {
20+
prepareSqliteReadOnlyLocation,
21+
prepareSqliteReadOnlyLocationSync,
22+
} from "../infra/sqlite-readonly-location.js";
2023
import { OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract.js";
2124
import { tableExists } from "./openclaw-state-db-schema-helpers.js";
2225
import { resolveOpenClawStateDirForDatabasePath } from "./openclaw-state-db.paths.js";
@@ -279,15 +282,45 @@ export function runWithOpenClawStateWriteAccess<T>(
279282
);
280283
}
281284

285+
/** Check path-based write admission without retaining the coordinator past this call. */
286+
export async function assertOpenClawStateWriteAllowedAtPath(options: {
287+
databasePath: string;
288+
env?: NodeJS.ProcessEnv;
289+
}): Promise<void> {
290+
const databasePath = path.resolve(options.databasePath);
291+
if (!existsSync(databasePath)) {
292+
return;
293+
}
294+
const env = options.env ?? process.env;
295+
if (isGatewayExternallySupervised(env)) {
296+
runWithOpenClawStateWriteAccess(
297+
{ ...options, databasePath },
298+
"shared state write admission",
299+
() => undefined,
300+
);
301+
return;
302+
}
303+
// Unmarked startup must discover ownership without opening the source writable.
304+
// The async private snapshot keeps Windows PowerShell work off the sync startup path.
305+
const prepared = await prepareSqliteReadOnlyLocation(databasePath);
306+
try {
307+
assertOwnershipAllowsWrite(
308+
inspectOwnershipThroughConnection(prepared.location, databasePath),
309+
databasePath,
310+
env,
311+
);
312+
} finally {
313+
prepared.cleanup();
314+
}
315+
}
316+
282317
/** Fence shared-state writes once an external manager has claimed ownership. */
283318
export function assertOpenClawStateWriteAllowed(options: {
284-
database?: DatabaseSync;
319+
database: DatabaseSync;
285320
databasePath: string;
286321
env?: NodeJS.ProcessEnv;
287322
}): void {
288323
const resolvedPath = path.resolve(options.databasePath);
289-
const status = options.database
290-
? inspectOpenClawStateOwnershipFromDatabase(options.database, resolvedPath)
291-
: inspectOpenClawStateOwnershipAtPath(resolvedPath);
324+
const status = inspectOpenClawStateOwnershipFromDatabase(options.database, resolvedPath);
292325
assertOwnershipAllowsWrite(status, resolvedPath, options.env ?? process.env);
293326
}

‎test/package-scripts.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,12 @@ describe("package scripts", () => {
221221
);
222222
});
223223

224+
it("runs shared-state ownership coverage in Windows CI", () => {
225+
expect(readPackageJson().scripts["test:windows:ci"]).toContain(
226+
"src/state/openclaw-state-ownership.test.ts",
227+
);
228+
});
229+
224230
it("runs mixed-case local media file URL coverage in Windows CI", () => {
225231
expect(readPackageJson().scripts["test:windows:ci"]).toContain(
226232
"src/media/local-media-path.windows.test.ts",

0 commit comments

Comments
 (0)