Skip to content

Commit dfd2e74

Browse files
authored
fix(state): renew maintenance leases during synchronous work (#134880)
* fix(state): renew maintenance leases during synchronous work * test(state): align maintenance worker integration checks
1 parent 4bbdedb commit dfd2e74

21 files changed

Lines changed: 711 additions & 233 deletions

‎config/knip.config.ts‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*/
44
import fs from "node:fs";
55
import path from "node:path";
6+
import { runtimeProcessBuildEntries } from "../scripts/lib/runtime-process-build-entries.mts";
67

78
const BUNDLED_PLUGIN_ROOT_DIR = "extensions";
89

@@ -152,6 +153,10 @@ function listScriptShimEntries(dir = "scripts"): string[] {
152153
const rootEntries = [
153154
...repositoryScriptEntries,
154155
...listScriptShimEntries(),
156+
// Runtime launchers resolve these by URL rather than a static import edge.
157+
...Object.values(runtimeProcessBuildEntries).map(
158+
(source) => `${path.relative(".", source).replaceAll("\\", "/")}!`,
159+
),
155160
// Knip loads these audit configurations directly by command-line path.
156161
"config/knip.config.ts!",
157162
"config/knip.all-exports.config.ts!",
@@ -167,8 +172,6 @@ const rootEntries = [
167172
"src/commands/status.ts!",
168173
"src/cli/daemon-cli.ts!",
169174
"src/agents/code-mode.worker.ts!",
170-
// The local exec bootstrap launches credential resolution by computed subprocess URL.
171-
"src/agents/github-exec-launcher.ts!",
172175
// Worker-thread and script entrypoints import contracts that production Knip cannot trace.
173176
"src/agents/compaction-planning.worker.ts!",
174177
"scripts/print-cli-backend-live-metadata.ts!",
@@ -184,17 +187,8 @@ const rootEntries = [
184187
// Docker/manual E2E executables and their nested assertion/probe entrypoints.
185188
"scripts/e2e/*.{js,mjs,ts}!",
186189
"scripts/e2e/lib/**/{assertions,probe,mock-server}.{js,mjs,ts}!",
187-
// Loaded by URL from the SQLite lifecycle archive owner.
188-
"src/config/sessions/session-accessor.sqlite-archive.worker.ts!",
189-
"src/state/openclaw-database-verify.worker.ts!",
190-
// Spawned by path from sqlite-readonly-location.ts to isolate raw-fd snapshot preparation.
191-
"src/infra/sqlite-readonly-location.worker.ts!",
192-
// Loaded by URL from tailscale.ts to outlive abrupt Gateway process exit.
193-
"src/infra/tailscale-route-owner.worker.ts!",
194190
"src/agents/model-provider-auth.worker.ts!",
195191
"src/agents/prepared-model-catalog.worker.ts!",
196-
// Spawned through computed sibling URLs by the service-child host and relay.
197-
"src/process/supervisor/{service-child-relay,service-child-group-anchor,service-child-windows-job-anchor}.ts!",
198192
// Loaded by URL from setup-inference-detection.ts; no static import edge exists.
199193
"src/system-agent/setup-inference-detection.worker.ts!",
200194
// Split runtime loaded through a path assembled in subagent-registry.ts.

‎docs/reference/database-schemas.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,10 @@ Schema 9 stores an `agent_databases.path` value relative to the state directory
248248
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.
249249
Quarantine decisions live only in a dedicated `openclaw-quarantine.sqlite` store, so they survive damage to the databases being quarantined. Verification results are logged.
250250

251+
Agent database maintenance fences other writers with a 60-second lease in the shared state database. A dedicated worker renews that lease during synchronous integrity scans and migration phases. Maintenance still checks the exact persisted owner before mutations and commit, and stops if the heartbeat fails or ownership expires or changes. Finishing or cancelling maintenance stops renewal before releasing the lease; process death leaves at most the remaining lease duration.
252+
253+
The heartbeat proves ownership, not migration progress. A live but stuck maintenance process can keep its lease; stop that process before retrying Doctor.
254+
251255
## Troubleshooting
252256

253257
### Why you cannot go back after updating to 2026.7.2
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { fileURLToPath } from "node:url";
21
import { vectorKnnProcessEntrypoint } from "../../extensions/memory-core/src/memory/manager-search-knn-entrypoint.ts";
3-
import { runtimeProcessEntrypoints } from "../../src/infra/runtime-process-entrypoints.ts";
2+
import {
3+
createRuntimeProcessBuildEntries,
4+
runtimeProcessCoreBuildEntries,
5+
} from "./runtime-process-core-build-entries.mts";
46

5-
export const runtimeProcessBuildEntries = Object.fromEntries(
6-
[...Object.values(runtimeProcessEntrypoints), vectorKnnProcessEntrypoint].map((entry) => [
7-
entry.distWorkerPath.replace(/\.js$/u, ""),
8-
fileURLToPath(new URL(`./${entry.sourceWorkerName}.ts`, entry.currentModuleUrl)),
9-
]),
10-
);
7+
export const runtimeProcessBuildEntries = {
8+
...runtimeProcessCoreBuildEntries,
9+
...createRuntimeProcessBuildEntries([vectorKnnProcessEntrypoint]),
10+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { fileURLToPath } from "node:url";
2+
import { runtimeProcessEntrypoints } from "../../src/infra/runtime-process-entrypoints.ts";
3+
4+
export function createRuntimeProcessBuildEntries(
5+
entries: readonly {
6+
currentModuleUrl: string;
7+
sourceWorkerName: string;
8+
distWorkerPath: string;
9+
}[],
10+
) {
11+
return Object.fromEntries(
12+
entries.map((entry) => [
13+
entry.distWorkerPath.replace(/\.js$/u, ""),
14+
fileURLToPath(new URL(`./${entry.sourceWorkerName}.ts`, entry.currentModuleUrl)),
15+
]),
16+
);
17+
}
18+
19+
export const runtimeProcessCoreBuildEntries = createRuntimeProcessBuildEntries(
20+
Object.values(runtimeProcessEntrypoints),
21+
);

‎scripts/lib/vitest-worker-compiler.mts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ async function compileVitestWorkerArtifacts(directory: string): Promise<void> {
4646
"scripts/lib/windows-taskkill.mjs",
4747
"scripts/windows-cmd-helpers.mjs",
4848
"scripts/lib/runtime-process-build-entries.mts",
49+
"scripts/lib/runtime-process-core-build-entries.mts",
4950
"scripts/lib/vitest-worker-build-entries.mts",
5051
"scripts/lib/fs-safe-native-assets.mts",
5152
"scripts/lib/state-schema-inline-plugin.mts",

‎src/commands/doctor-session-sqlite.memory.test.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
55
import { promisify } from "node:util";
66
import { build as esbuild } from "esbuild";
77
import { afterAll, beforeAll, expect, it } from "vitest";
8+
import { runtimeProcessCoreBuildEntries } from "../../scripts/lib/runtime-process-core-build-entries.mts";
89
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
910
import { sqliteImportMemorySupportUrl } from "./doctor-session-sqlite.memory.test-support.js";
1011

@@ -15,19 +16,25 @@ let childPath: string;
1516
beforeAll(async () => {
1617
fs.mkdirSync(path.join(process.cwd(), ".artifacts"), { recursive: true });
1718
bundleDir = fs.mkdtempSync(path.join(process.cwd(), ".artifacts/import-memory-"));
18-
childPath = path.join(bundleDir, "child.mjs");
19+
// Runtime workers resolve stable packaged paths beneath dist, even from a bundled caller.
20+
const outDir = path.join(bundleDir, "dist");
21+
fs.mkdirSync(outDir);
22+
childPath = path.join(outDir, "child.js");
1923
for (const schema of ["openclaw-agent-schema.sql", "openclaw-state-schema.sql"]) {
20-
fs.copyFileSync(path.join(process.cwd(), "src/state", schema), path.join(bundleDir, schema));
24+
fs.copyFileSync(path.join(process.cwd(), "src/state", schema), path.join(outDir, schema));
2125
}
2226
await esbuild({
2327
bundle: true,
24-
entryPoints: [fileURLToPath(sqliteImportMemorySupportUrl)],
28+
entryPoints: {
29+
child: fileURLToPath(sqliteImportMemorySupportUrl),
30+
...runtimeProcessCoreBuildEntries,
31+
},
2532
format: "esm",
2633
// Keep generated source overhead out of the transcript-data heap budget;
2734
// preserve function/class names used by runtime dispatch and diagnostics.
2835
minify: true,
2936
keepNames: true,
30-
outfile: childPath,
37+
outdir: outDir,
3138
packages: "external",
3239
platform: "node",
3340
target: "node22",

‎src/infra/runtime-process-entrypoints.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ export const runtimeProcessEntrypoints = {
1717
sourceWorkerName: "../state/openclaw-database-verify.worker",
1818
distWorkerPath: "state/openclaw-database-verify.worker.js",
1919
},
20+
stateLeaseHeartbeat: {
21+
currentModuleUrl,
22+
sourceWorkerName: "../state/openclaw-state-lease-heartbeat.worker",
23+
distWorkerPath: "state/openclaw-state-lease-heartbeat.worker.js",
24+
},
2025
sessionTranscriptArchive: {
2126
currentModuleUrl,
2227
sourceWorkerName: "../config/sessions/session-accessor.sqlite-archive.worker",

‎src/infra/state-migrations.transcript-directives.test.ts‎

Lines changed: 73 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
openOpenClawStateDatabase,
2424
} from "../state/openclaw-state-db.js";
2525
import { openNodeSqliteDatabase, requireNodeSqlite } from "./node-sqlite.js";
26+
import { TRANSCRIPT_DIRECTIVE_MIGRATION_BATCH_SIZE } from "./state-migrations.transcript-directives-archives.js";
2627
import { migrateHistoricalTranscriptDirectives } from "./state-migrations.transcript-directives.js";
2728

2829
const tempDirs: string[] = [];
@@ -162,7 +163,6 @@ function parseArchive(content: string): FixtureEvent[] {
162163
}
163164

164165
afterEach(() => {
165-
vi.useRealTimers();
166166
vi.restoreAllMocks();
167167
closeOpenClawAgentDatabasesForTest();
168168
closeOpenClawStateDatabaseForTest();
@@ -519,44 +519,6 @@ describe("historical transcript directive migration", () => {
519519
}
520520
});
521521

522-
it("renews maintenance during a versioned schema upgrade beyond the original lease lifetime", async () => {
523-
vi.useFakeTimers();
524-
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
525-
const startedAt = Date.now();
526-
const stateDir = makeTempDir(tempDirs, "transcript-directive-old-schema-renewal-");
527-
const env = { OPENCLAW_STATE_DIR: stateDir };
528-
const opened = openOpenClawAgentDatabase({ agentId: "main", env });
529-
const databasePath = opened.path;
530-
opened.db.exec(`
531-
DROP TABLE session_participants;
532-
${withLegacySessionParticipantsSchema(sessionParticipantsSchemaSql())}
533-
PRAGMA user_version = 17;
534-
UPDATE schema_meta SET schema_version = 17 WHERE meta_key = 'primary';
535-
`);
536-
closeOpenClawAgentDatabasesForTest();
537-
538-
const agentDatabaseLease = await import("../state/openclaw-agent-db-lease.js");
539-
const originalRenew = agentDatabaseLease.renewAgentDatabaseMaintenanceAuthorityIfPresent;
540-
const renew = vi
541-
.spyOn(agentDatabaseLease, "renewAgentDatabaseMaintenanceAuthorityIfPresent")
542-
.mockImplementation(() => {
543-
vi.setSystemTime(Date.now() + 30_000);
544-
originalRenew();
545-
});
546-
547-
const result = await migrateHistoricalTranscriptDirectives({ env });
548-
549-
expect(result.warnings).toEqual([]);
550-
expect(Date.now() - startedAt).toBeGreaterThan(60_000);
551-
expect(renew).toHaveBeenCalledTimes(3);
552-
const migrated = openNodeSqliteDatabase(databasePath, { readOnly: true });
553-
try {
554-
expect(migrated.prepare("PRAGMA user_version").get()?.user_version).toBe(19);
555-
} finally {
556-
migrated.close();
557-
}
558-
});
559-
560522
it("rolls back same-version convergence when maintenance expires before commit", async () => {
561523
const stateDir = makeTempDir(tempDirs, "transcript-directive-same-version-expiry-");
562524
const env = { OPENCLAW_STATE_DIR: stateDir };
@@ -920,12 +882,14 @@ describe("historical transcript directive migration", () => {
920882
releaseOpenClawAgentDatabaseLease(competingLeaseId as string, { env });
921883
});
922884

923-
it("renews maintenance beyond its original lifetime and fences writers through final mutation", async () => {
924-
vi.useFakeTimers();
885+
it("renews maintenance through a blocked schema upgrade and fences the final transcript batch", async () => {
925886
const stateDir = makeTempDir(tempDirs, "transcript-directive-lease-renewal-");
926887
const env = { OPENCLAW_STATE_DIR: stateDir };
927888
const opened = openOpenClawAgentDatabase({ agentId: "main", env });
928-
for (let index = 0; index <= 32; index += 1) {
889+
const batchSize = TRANSCRIPT_DIRECTIVE_MIGRATION_BATCH_SIZE;
890+
const sessionIdAt = (index: number) =>
891+
`session-${String(index).padStart(String(batchSize).length, "0")}`;
892+
for (let index = 0; index <= batchSize; index += 1) {
929893
insertSession(opened.db, {
930894
events: [
931895
messageEvent({
@@ -936,46 +900,86 @@ describe("historical transcript directive migration", () => {
936900
}),
937901
],
938902
generation: "before",
939-
sessionId: `session-${String(index).padStart(2, "0")}`,
903+
sessionId: sessionIdAt(index),
940904
});
941905
}
906+
opened.db.exec(`
907+
DROP TABLE session_participants;
908+
${withLegacySessionParticipantsSchema(sessionParticipantsSchemaSql())}
909+
PRAGMA user_version = 17;
910+
UPDATE schema_meta SET schema_version = 17 WHERE meta_key = 'primary';
911+
`);
942912
closeOpenClawAgentDatabasesForTest();
943913

944-
vi.spyOn(globalThis, "setImmediate").mockImplementationOnce(
945-
(callback) => setTimeout(callback, 61_000) as unknown as NodeJS.Immediate,
914+
const stateLease = await import("../state/openclaw-state-lease.js");
915+
const withLease = stateLease.withOpenClawStateLease;
916+
vi.spyOn(stateLease, "withOpenClawStateLease").mockImplementationOnce((options, operation) =>
917+
withLease({ ...options, leaseMs: 1_000 }, operation),
946918
);
919+
const agentDatabaseLease = await import("../state/openclaw-agent-db-lease.js");
920+
const originalRenew = agentDatabaseLease.renewAgentDatabaseMaintenanceAuthorityIfPresent;
921+
let originalExpiresAt = 0;
922+
vi.spyOn(
923+
agentDatabaseLease,
924+
"renewAgentDatabaseMaintenanceAuthorityIfPresent",
925+
).mockImplementationOnce(() => {
926+
originalExpiresAt = Number(
927+
openOpenClawStateDatabase({ env })
928+
.db.prepare("SELECT expires_at FROM state_leases WHERE scope = ? AND lease_key = ?")
929+
.get(AGENT_DATABASE_MAINTENANCE_LEASE.scope, AGENT_DATABASE_MAINTENANCE_LEASE.key)
930+
?.expires_at,
931+
);
932+
// Parent fake timers cannot control the real heartbeat Worker.
933+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1_250);
934+
originalRenew();
935+
});
936+
947937
let competingWriterError: unknown;
948938
let competingLeaseId: string | undefined;
949-
setTimeout(() => {
950-
try {
951-
competingLeaseId = claimOpenClawAgentDatabaseLease({
952-
agentId: "competitor",
953-
path: path.join(stateDir, "competitor.sqlite"),
954-
env,
955-
});
956-
} catch (error) {
957-
competingWriterError = error;
958-
}
959-
}, 60_500);
960-
961-
let migrationDone = false;
962-
const migration = migrateHistoricalTranscriptDirectives({ env }).finally(() => {
963-
migrationDone = true;
964-
});
965-
await vi.advanceTimersByTimeAsync(61_000);
966-
for (let turn = 0; turn < 10; turn += 1) {
967-
await vi.advanceTimersByTimeAsync(1);
968-
if (migrationDone) {
969-
break;
970-
}
971-
}
972-
await expect(migration).resolves.toMatchObject({ warnings: [] });
939+
let cursorAtCompetition: unknown;
940+
let competedAt = 0;
941+
const scheduleImmediate = globalThis.setImmediate;
942+
vi.spyOn(globalThis, "setImmediate").mockImplementationOnce((callback, ...args) =>
943+
scheduleImmediate(() => {
944+
cursorAtCompetition = readMigrationCursor(opened.path);
945+
competedAt = Date.now();
946+
try {
947+
competingLeaseId = claimOpenClawAgentDatabaseLease({
948+
agentId: "competitor",
949+
path: path.join(stateDir, "competitor.sqlite"),
950+
env,
951+
});
952+
} catch (error) {
953+
competingWriterError = error;
954+
}
955+
callback(...args);
956+
}),
957+
);
973958

959+
await expect(migrateHistoricalTranscriptDirectives({ env })).resolves.toMatchObject({
960+
warnings: [],
961+
});
962+
963+
expect(originalExpiresAt).toBeGreaterThan(0);
964+
expect(competedAt).toBeGreaterThan(originalExpiresAt);
965+
expect(cursorAtCompetition).toEqual({
966+
phase: "transcripts",
967+
sessionId: sessionIdAt(batchSize - 1),
968+
});
974969
expect(competingWriterError).toEqual(
975970
expect.objectContaining({ message: expect.stringContaining("maintenance is in progress") }),
976971
);
977972
expect(competingLeaseId).toBeUndefined();
978973
expect(readMigrationCursor(opened.path)).toEqual({ phase: "complete" });
974+
expect(JSON.parse(readEventJson(opened.path, sessionIdAt(batchSize), 0))).toMatchObject({
975+
message: { content: [{ type: "text", text: "Migrating" }] },
976+
});
977+
const migrated = openNodeSqliteDatabase(opened.path, { readOnly: true });
978+
try {
979+
expect(migrated.prepare("PRAGMA user_version").get()?.user_version).toBe(19);
980+
} finally {
981+
migrated.close();
982+
}
979983
const leaseId = claimOpenClawAgentDatabaseLease({
980984
agentId: "competitor",
981985
path: path.join(stateDir, "competitor.sqlite"),

‎src/infra/state-migrations.transcript-directives.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ function hasActiveAgentDatabaseLease(agentId: string, env: NodeJS.ProcessEnv): b
257257
}
258258
}
259259

260-
async function yieldToMaintenanceHeartbeat(): Promise<void> {
260+
async function yieldBetweenTranscriptBatches(): Promise<void> {
261261
await new Promise<void>((resolve) => {
262262
setImmediate(resolve);
263263
});
@@ -317,9 +317,9 @@ async function migrateTranscriptSessions(params: {
317317
rewrittenSessions += changedRows.length > 0 ? 1 : 0;
318318
afterSessionId = sessionId;
319319
}
320-
// The persisted lease renews from the event loop. Yield after each bounded
321-
// batch, then revalidate inside the next transaction before mutating state.
322-
await yieldToMaintenanceHeartbeat();
320+
// Keep the caller responsive between bounded batches. The next transaction
321+
// revalidates maintenance ownership before mutating state.
322+
await yieldBetweenTranscriptBatches();
323323
}
324324
}
325325

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export function assertAgentDatabaseMaintenanceAuthorityIfPresent(): void {
6060
maintenanceAuthority.getStore()?.assertOwned();
6161
}
6262

63-
/** Renew a maintenance owner before a synchronous schema phase can block its heartbeat. */
63+
/** Verify the maintenance owner and its independent heartbeat before a synchronous phase. */
6464
export function renewAgentDatabaseMaintenanceAuthorityIfPresent(): void {
6565
const authority = maintenanceAuthority.getStore();
6666
if (!authority) {

0 commit comments

Comments
 (0)