Skip to content

Commit e8dfaf6

Browse files
committed
fix(backup): skip transient gateway lock databases
Reported by @AgentSolomon in #119757. Fixes #119757 Punchcard-Session: amber-meadow-timber-8r
1 parent a20746e commit e8dfaf6

6 files changed

Lines changed: 228 additions & 36 deletions

File tree

‎src/commands/backup-verify.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,11 @@ describe("backupVerifyCommand", () => {
836836
contents: invalidSqlite,
837837
archivePath: `${stateAssetArchivePath}/memory/main.sqlite.reindex-lock.sqlite`,
838838
},
839+
{
840+
fileName: "reindex-lock.sqlite-wal",
841+
contents: invalidSqlite,
842+
archivePath: `${stateAssetArchivePath}/memory/main.sqlite.reindex-lock.sqlite-wal`,
843+
},
839844
{
840845
fileName: "reindex-tmp",
841846
contents: invalidSqlite,

‎src/commands/backup-verify.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { DatabaseSync } from "node:sqlite";
66
import { readStringValue } from "@openclaw/normalization-core/string-coerce";
77
import * as tar from "tar";
88
import { loadSqliteVecExtension } from "../../packages/memory-host-sdk/src/engine-storage.js";
9+
import { isTransientSqliteBackupPath } from "../infra/backup-volatile-filter.js";
910
import { formatDiskSpaceBytes, tryReadDiskSpace } from "../infra/disk-space.js";
1011
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
1112
import { assertSqliteIntegrity } from "../infra/sqlite-integrity.js";
@@ -18,9 +19,6 @@ const MAX_MANIFEST_BYTES = 1024 * 1024;
1819
const MAX_SQLITE_SNAPSHOT_EXTRACT_BYTES = 64 * 1024 * 1024 * 1024;
1920
const SQLITE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES = 256 * 1024 * 1024;
2021
const SQLITE_SNAPSHOT_SIDECAR_SUFFIXES = ["-wal", "-shm", "-journal"] as const;
21-
const SQLITE_BACKUP_EXCLUDED_SUFFIXES = [".reindex-lock.sqlite"] as const;
22-
const SQLITE_BACKUP_REINDEX_TRANSIENT_PATTERN =
23-
/\.sqlite\.(?:backup|memory-reindex|tmp)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
2422

2523
type BackupManifestAsset = {
2624
kind: string;
@@ -400,9 +398,7 @@ function isSqliteSnapshotRelativePath(relativePath: string): boolean {
400398
return true;
401399
}
402400
return (
403-
!portablePath.split("/").includes("node_modules") &&
404-
!SQLITE_BACKUP_REINDEX_TRANSIENT_PATTERN.test(relativePath) &&
405-
!SQLITE_BACKUP_EXCLUDED_SUFFIXES.some((suffix) => portablePath.endsWith(suffix))
401+
!portablePath.split("/").includes("node_modules") && !isTransientSqliteBackupPath(portablePath)
406402
);
407403
}
408404

‎src/infra/backup-create.test.ts‎

Lines changed: 138 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import * as tar from "tar";
88
import { describe, expect, it, vi } from "vitest";
99
import { saveAuthProfileStore } from "../agents/auth-profiles/store.js";
1010
import { backupVerifyCommand } from "../commands/backup-verify.js";
11+
import { isPathWithin } from "../commands/cleanup-utils.js";
1112
import { CONFIG_AUDIT_MAX_ENTRIES, CONFIG_AUDIT_SCOPE } from "../config/io.audit.js";
13+
import { resolveGatewayLockDir } from "../config/paths.js";
1214
import type { RuntimeEnv } from "../runtime.js";
1315
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
1416
import {
@@ -33,6 +35,7 @@ import {
3335
import { writeTarArchiveWithRetry } from "./backup-tar-retry.js";
3436
import { isVolatileBackupPath } from "./backup-volatile-filter.js";
3537
import { createBackupVolatileStatCache } from "./backup-volatile-stat-cache.js";
38+
import { acquireGatewayLock } from "./gateway-lock.js";
3639
import { requireNodeSqlite } from "./node-sqlite.js";
3740
import { createSqliteAuditRecordStore } from "./sqlite-audit-record-store.js";
3841
import { detectLegacyAuditLogs, migrateLegacyAuditLogs } from "./state-migrations.audit-logs.js";
@@ -1659,7 +1662,7 @@ describe("createBackupArchive", () => {
16591662
);
16601663
});
16611664

1662-
it("snapshots nested live SQLite databases with transaction continuity", async () => {
1665+
it("snapshots lock-named plugin SQLite databases with transaction continuity", async () => {
16631666
await withOpenClawTestState(
16641667
{
16651668
layout: "state-only",
@@ -1669,7 +1672,7 @@ describe("createBackupArchive", () => {
16691672
async (state) => {
16701673
const outputDir = state.path("backups");
16711674
const extractDir = state.path("extract");
1672-
const dbPath = state.statePath("plugins", "dedicated", "live.sqlite");
1675+
const dbPath = state.statePath("plugins", "dedicated", "cache.lock.sqlite");
16731676
await fs.mkdir(path.dirname(dbPath), { recursive: true });
16741677
await fs.mkdir(outputDir, { recursive: true });
16751678
await fs.mkdir(extractDir, { recursive: true });
@@ -1714,13 +1717,13 @@ describe("createBackupArchive", () => {
17141717
});
17151718
const entries = await listArchiveEntries(result.archivePath);
17161719
const archivedDbEntries = entries.filter((entry) =>
1717-
entry.endsWith("/state/plugins/dedicated/live.sqlite"),
1720+
entry.endsWith("/state/plugins/dedicated/cache.lock.sqlite"),
17181721
);
17191722
expect(archivedDbEntries).toHaveLength(1);
17201723
for (const suffix of ["-wal", "-shm", "-journal"]) {
17211724
expect(
17221725
entries.some((entry) =>
1723-
entry.endsWith(`/state/plugins/dedicated/live.sqlite${suffix}`),
1726+
entry.endsWith(`/state/plugins/dedicated/cache.lock.sqlite${suffix}`),
17241727
),
17251728
suffix,
17261729
).toBe(false);
@@ -2025,6 +2028,137 @@ describe("createBackupArchive", () => {
20252028
);
20262029
});
20272030

2031+
it("backs up durable SQLite while live gateway coordinators remain held under state", async () => {
2032+
await withOpenClawTestState(
2033+
{
2034+
layout: "state-only",
2035+
prefix: "openclaw-backup-gateway-lock-sqlite-",
2036+
scenario: "minimal",
2037+
},
2038+
async (state) => {
2039+
const outputDir = state.path("backups");
2040+
const extractDir = state.path("extract");
2041+
const lockDir = resolveGatewayLockDir(() => state.statePath("tmp"));
2042+
const pluginDbPath = state.statePath("plugins", "dedicated", "durable.sqlite");
2043+
const producerShapedDbPath = state.statePath(
2044+
"plugins",
2045+
"dedicated",
2046+
"gateway.12345678.lock.sqlite",
2047+
);
2048+
const colocatedDbPath = path.join(lockDir, "retained.sqlite");
2049+
await fs.mkdir(outputDir, { recursive: true });
2050+
await fs.mkdir(extractDir, { recursive: true });
2051+
await fs.mkdir(path.dirname(pluginDbPath), { recursive: true });
2052+
await fs.mkdir(lockDir, { recursive: true });
2053+
2054+
const sqlite = requireNodeSqlite();
2055+
for (const [databasePath, value] of [
2056+
[pluginDbPath, "plugin-state"],
2057+
[producerShapedDbPath, "producer-shaped-state"],
2058+
[colocatedDbPath, "colocated-state"],
2059+
] as const) {
2060+
const database = new sqlite.DatabaseSync(databasePath);
2061+
try {
2062+
database.exec("CREATE TABLE durable_state (value TEXT NOT NULL)");
2063+
database.prepare("INSERT INTO durable_state (value) VALUES (?)").run(value);
2064+
} finally {
2065+
database.close();
2066+
}
2067+
}
2068+
2069+
const gatewayLock = await acquireGatewayLock({
2070+
allowInTests: true,
2071+
env: state.env,
2072+
lockDir,
2073+
timeoutMs: 100,
2074+
});
2075+
if (!gatewayLock) {
2076+
throw new Error("expected test gateway lock");
2077+
}
2078+
expect(isPathWithin(resolveGatewayLockDir(), state.stateDir)).toBe(false);
2079+
const gatewayCoordinatorPaths = [
2080+
`${gatewayLock.lockPath}.sqlite`,
2081+
`${gatewayLock.stateLockPath}.sqlite`,
2082+
];
2083+
const extraTransientPaths = [
2084+
path.join(lockDir, "device-identity.12345678.lock.sqlite"),
2085+
state.statePath("memory", "main.sqlite.reindex-lock.sqlite"),
2086+
];
2087+
2088+
try {
2089+
for (const transientPath of [...gatewayCoordinatorPaths, ...extraTransientPaths]) {
2090+
await fs.mkdir(path.dirname(transientPath), { recursive: true });
2091+
if (!gatewayCoordinatorPaths.includes(transientPath)) {
2092+
await fs.writeFile(transientPath, "transient coordinator database");
2093+
}
2094+
for (const suffix of ["-wal", "-shm", "-journal"]) {
2095+
await fs.writeFile(`${transientPath}${suffix}`, "transient coordinator sidecar");
2096+
}
2097+
}
2098+
2099+
const result = await createBackupArchive({
2100+
output: outputDir,
2101+
includeWorkspace: false,
2102+
nowMs: Date.UTC(2026, 7, 5, 12, 0, 0),
2103+
});
2104+
const entries = await listArchiveEntries(result.archivePath);
2105+
for (const transientPath of [...gatewayCoordinatorPaths, ...extraTransientPaths]) {
2106+
const relativeTransientPath = path
2107+
.relative(state.stateDir, transientPath)
2108+
.split(path.sep)
2109+
.join("/");
2110+
for (const suffix of ["", "-wal", "-shm", "-journal"]) {
2111+
expect(
2112+
entries.some((entry) => entry.endsWith(`/state/${relativeTransientPath}${suffix}`)),
2113+
`${relativeTransientPath}${suffix}`,
2114+
).toBe(false);
2115+
}
2116+
}
2117+
expect(
2118+
entries.some((entry) => entry.endsWith("/state/plugins/dedicated/durable.sqlite")),
2119+
).toBe(true);
2120+
expect(
2121+
entries.some((entry) =>
2122+
entry.endsWith("/state/plugins/dedicated/gateway.12345678.lock.sqlite"),
2123+
),
2124+
).toBe(true);
2125+
expect(
2126+
entries.some((entry) => entry.endsWith(`/${path.basename(lockDir)}/retained.sqlite`)),
2127+
).toBe(true);
2128+
2129+
const runtime: RuntimeEnv = { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
2130+
await expect(
2131+
backupVerifyCommand(runtime, { archive: result.archivePath }),
2132+
).resolves.toMatchObject({ ok: true });
2133+
2134+
await tar.x({ file: result.archivePath, gzip: true, cwd: extractDir });
2135+
for (const [entrySuffix, value] of [
2136+
["/state/plugins/dedicated/durable.sqlite", "plugin-state"],
2137+
["/state/plugins/dedicated/gateway.12345678.lock.sqlite", "producer-shaped-state"],
2138+
[`/${path.basename(lockDir)}/retained.sqlite`, "colocated-state"],
2139+
] as const) {
2140+
const archivedEntry = expectDefined(
2141+
entries.find((entry) => entry.endsWith(entrySuffix)),
2142+
`archive entry ending with ${entrySuffix}`,
2143+
);
2144+
const archivedDb = new sqlite.DatabaseSync(path.join(extractDir, archivedEntry), {
2145+
readOnly: true,
2146+
});
2147+
try {
2148+
expect(archivedDb.prepare("SELECT value FROM durable_state").get()).toEqual({
2149+
value,
2150+
});
2151+
} finally {
2152+
archivedDb.close();
2153+
}
2154+
}
2155+
} finally {
2156+
await gatewayLock.release();
2157+
}
2158+
},
2159+
);
2160+
});
2161+
20282162
it("preserves noncanonical symlinked SQLite paths without dereferencing them", async () => {
20292163
if (process.platform === "win32") {
20302164
return;

‎src/infra/backup-create.ts‎

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
resolveBackupPlanFromDisk,
1313
} from "../commands/backup-shared.js";
1414
import { isPathWithin } from "../commands/cleanup-utils.js";
15+
import { resolveGatewayLockDir } from "../config/paths.js";
1516
import { normalizeAgentId } from "../routing/session-key.js";
1617
import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
1718
import { assertOpenClawAgentDatabaseOwner } from "../state/openclaw-agent-db-maintenance.js";
@@ -31,7 +32,7 @@ import {
3132
} from "./backup-archive-publication.js";
3233
import { removePreparedBackupArchive, writeArchiveStreamToFile } from "./backup-create-stream.js";
3334
import { writeTarArchiveWithRetry } from "./backup-tar-retry.js";
34-
import { isVolatileBackupPath } from "./backup-volatile-filter.js";
35+
import { isTransientSqliteBackupPath, isVolatileBackupPath } from "./backup-volatile-filter.js";
3536
import {
3637
createBackupLinkCache,
3738
createBackupVolatileStatCache,
@@ -376,9 +377,6 @@ type StateSqliteBackupPlan = {
376377
};
377378

378379
const SQLITE_BACKUP_SOURCE_SUFFIXES = ["", "-wal", "-shm", "-journal"] as const;
379-
const SQLITE_BACKUP_EXCLUDED_SUFFIXES = [".reindex-lock.sqlite"] as const;
380-
const SQLITE_BACKUP_REINDEX_TRANSIENT_PATTERN =
381-
/\.sqlite\.(?:backup|memory-reindex|tmp)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
382380

383381
function isCanonicalAgentSqlitePathOrAncestor(sourcePath: string, stateDir: string): boolean {
384382
const relativePath = path.relative(path.resolve(stateDir), path.resolve(sourcePath));
@@ -445,18 +443,10 @@ function resolveSqliteBackupDatabasePath(sourcePath: string): string | undefined
445443
return sourcePath.endsWith(".sqlite") ? sourcePath : undefined;
446444
}
447445

448-
function resolveSqliteBackupBasePath(sourcePath: string): string {
449-
for (const suffix of SQLITE_BACKUP_SOURCE_SUFFIXES.slice(1)) {
450-
if (sourcePath.endsWith(suffix)) {
451-
return sourcePath.slice(0, -suffix.length);
452-
}
453-
}
454-
return sourcePath;
455-
}
456-
457446
function classifyStateSqliteBackupSourcePath(
458447
sourcePath: string,
459448
stateDir: string,
449+
gatewayLockDirs: readonly string[],
460450
): "excluded" | "sqlite" | undefined {
461451
const resolvedSourcePath = path.resolve(sourcePath);
462452
if (!isPathWithin(resolvedSourcePath, stateDir)) {
@@ -465,18 +455,14 @@ function classifyStateSqliteBackupSourcePath(
465455
if (isStatePackageContentPath(resolvedSourcePath, stateDir)) {
466456
return undefined;
467457
}
468-
if (
469-
SQLITE_BACKUP_REINDEX_TRANSIENT_PATTERN.test(resolveSqliteBackupBasePath(resolvedSourcePath))
470-
) {
458+
if (isTransientSqliteBackupPath(resolvedSourcePath, gatewayLockDirs)) {
471459
return "excluded";
472460
}
473461
const databasePath = resolveSqliteBackupDatabasePath(resolvedSourcePath);
474462
if (!databasePath) {
475463
return undefined;
476464
}
477-
return SQLITE_BACKUP_EXCLUDED_SUFFIXES.some((suffix) => databasePath.endsWith(suffix))
478-
? "excluded"
479-
: "sqlite";
465+
return "sqlite";
480466
}
481467

482468
function isBackupTarFilterFile(entry: import("node:fs").Stats | import("tar").ReadEntry): boolean {
@@ -486,6 +472,7 @@ function isBackupTarFilterFile(entry: import("node:fs").Stats | import("tar").Re
486472
async function listStateSqlitePaths(params: {
487473
stateDir: string;
488474
globalStateSqlitePath: string;
475+
gatewayLockDirs: readonly string[];
489476
preservedStatePaths?: readonly string[];
490477
}): Promise<{ snapshotPaths: string[]; discoveredSourcePaths: Set<string> }> {
491478
const snapshotPaths = new Set<string>();
@@ -534,13 +521,15 @@ async function listStateSqlitePaths(params: {
534521
!isStatePackageContentPath(entryPath, params.stateDir)
535522
) {
536523
const resolvedEntryPath = path.resolve(entryPath);
537-
if (resolveSqliteBackupDatabasePath(resolvedEntryPath)) {
524+
const sqliteSourceKind = classifyStateSqliteBackupSourcePath(
525+
resolvedEntryPath,
526+
params.stateDir,
527+
params.gatewayLockDirs,
528+
);
529+
if (sqliteSourceKind === "sqlite") {
538530
discoveredSourcePaths.add(resolvedEntryPath);
539531
}
540-
if (
541-
entry.name.endsWith(".sqlite") &&
542-
!SQLITE_BACKUP_EXCLUDED_SUFFIXES.some((suffix) => entry.name.endsWith(suffix))
543-
) {
532+
if (entry.name.endsWith(".sqlite") && sqliteSourceKind === "sqlite") {
544533
snapshotPaths.add(resolvedEntryPath);
545534
}
546535
}
@@ -607,6 +596,12 @@ async function createStateSqliteBackupPlan(params: {
607596
const discovery = await listStateSqlitePaths({
608597
stateDir: params.stateDir,
609598
globalStateSqlitePath,
599+
// CLI and managed services use different temp roots for the same
600+
// disposable gateway/device coordination databases.
601+
gatewayLockDirs: [
602+
resolveGatewayLockDir(),
603+
resolveGatewayLockDir(() => path.join(params.stateDir, "tmp")),
604+
],
610605
preservedStatePaths: params.preservedStatePaths,
611606
});
612607
const globalStateIdentity = await fs.stat(globalStateSqlitePath).catch((error: unknown) => {
@@ -871,6 +866,10 @@ export async function createBackupArchive(
871866
const stateFilter = stateAsset
872867
? buildStateBackupFilter(stateAsset.sourcePath, preservedStatePaths)
873868
: undefined;
869+
const gatewayLockDirs = [
870+
resolveGatewayLockDir(),
871+
resolveGatewayLockDir(() => path.join(plan.stateDir, "tmp")),
872+
];
874873
const volatilePlan = { stateDirs: [stateAsset?.sourcePath ?? plan.stateDir] };
875874
let skippedVolatileCount = 0;
876875
// node-tar invokes filters from async stat callbacks, so throwing inside
@@ -896,7 +895,11 @@ export async function createBackupArchive(
896895
return false;
897896
}
898897
const sqliteSourceKind = stateAsset
899-
? classifyStateSqliteBackupSourcePath(resolvedEntryPath, stateAsset.sourcePath)
898+
? classifyStateSqliteBackupSourcePath(
899+
resolvedEntryPath,
900+
stateAsset.sourcePath,
901+
gatewayLockDirs,
902+
)
900903
: undefined;
901904
if (sqliteSourceKind === "excluded") {
902905
return false;

0 commit comments

Comments
 (0)