Skip to content

Commit f1afaa3

Browse files
authored
fix(sqlite): snapshot through online backup (#113385)
1 parent 3d48606 commit f1afaa3

5 files changed

Lines changed: 53 additions & 14 deletions

File tree

‎docs/cli/backup.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ The repository contains one directory per committed snapshot. Each snapshot dire
5151
- `manifest.json`
5252
- `database.sqlite`
5353

54-
Snapshot creation verifies the live database before reading it, uses SQLite `VACUUM INTO` to capture committed WAL state into a compact database, verifies the generated database again, and publishes the completed directory without overwriting existing paths. Global snapshots remove transient delivery queue rows and compact again so deleted queue payloads are not retained in free pages.
54+
Snapshot creation verifies the live database before reading it, uses SQLite's online backup API to capture committed WAL state without holding one long read transaction, closes the live database, compacts the private copy with `VACUUM`, verifies the generated database again, and publishes the completed directory without overwriting existing paths. Global snapshots remove transient delivery queue rows before compaction so deleted queue payloads are not retained in free pages.
5555

5656
Do not copy live `.sqlite`, `-wal`, `-shm`, or `-journal` files as a portability artifact. Copy only completed snapshot directories.
5757

@@ -103,7 +103,7 @@ During archive creation, OpenClaw excludes known live-mutation paths before `tar
103103

104104
These rules do not filter workspace files outside the state directory. They also omit completed transcript and log files that match the table, so retain those records separately when needed. The JSON result's `skippedVolatileCount` reports how many files were intentionally omitted.
105105

106-
SQLite databases under the state directory are compacted with `VACUUM INTO` so deleted-page remnants do not enter the archive, and live WAL/SHM files are not copied. A plugin-owned database that requires unavailable owner-defined SQLite capabilities fails closed rather than falling back to a raw page copy. SQLite files included through workspace backups are copied as workspace files and are not covered by the compaction guarantee.
106+
SQLite databases under the state directory are captured with SQLite's online backup API and compacted offline with `VACUUM` so deleted-page remnants do not enter the archive, and live WAL/SHM files are not copied. A plugin-owned database that requires unavailable owner-defined SQLite capabilities fails closed rather than falling back to a direct file copy. SQLite files included through workspace backups are copied as workspace files and are not covered by the compaction guarantee.
107107

108108
Installed plugin source and manifest files under the state directory's `extensions/` tree are included, but their nested `node_modules/` dependency trees are skipped as rebuildable install artifacts. After restoring an archive, use `openclaw plugins update <id>` or reinstall with `openclaw plugins install <spec> --force` if a restored plugin reports missing dependencies.
109109

‎docs/refactor/database-first.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1410,7 +1410,7 @@ sessionId})`; create, branch, continue, list, and fork flows live in their
14101410
Runtime tests no longer create invalid or empty `runs.json` fixtures to prove
14111411
registry behavior; they seed/read SQLite rows directly.
14121412
- Backup stages the state directory before archiving, copies non-database files,
1413-
snapshots databases with `VACUUM INTO`, omits live WAL/SHM sidecars, records
1413+
snapshots databases with online backup plus offline `VACUUM`, omits live WAL/SHM sidecars, records
14141414
snapshot metadata in the archive manifest, and records
14151415
completed backup runs in SQLite with the archive manifest. `openclaw backup
14161416
create` validates the written archive by default; `--no-verify` is the
@@ -1891,7 +1891,7 @@ The migration imports old JSONL files once, records counts/hashes in
18911891
Backups remain one archive file:
18921892

18931893
- Checkpoint every global and agent database.
1894-
- Snapshot each DB with SQLite backup semantics or `VACUUM INTO`.
1894+
- Snapshot each DB with SQLite online backup followed by offline `VACUUM`.
18951895
- Archive compact DB snapshots, config, external credentials, and requested
18961896
workspace exports.
18971897
- Omit raw live `*.sqlite-wal` and `*.sqlite-shm` files.
@@ -1932,9 +1932,10 @@ doctor input or support/export output:
19321932
Backups should be one archive file, but database capture should be
19331933
SQLite-native:
19341934

1935-
1. Stop long-running write activity or enter a short backup barrier.
1936-
2. For every global and agent database, run a checkpoint.
1937-
3. Snapshot databases with `VACUUM INTO` into a temporary backup directory.
1935+
1. Keep write transactions bounded so online backup can make forward progress.
1936+
2. Verify every live global and agent database before capture.
1937+
3. Capture each database with SQLite online backup into a temporary backup
1938+
directory, then close the live connection and `VACUUM` the private copy.
19381939
Plugin schemas that require owner-defined SQLite capabilities fail closed
19391940
until the owner provides a safe snapshot contract.
19401941
4. Archive the database snapshots, config file, credentials directory, selected
@@ -2057,8 +2058,8 @@ payload.
20572058
lifetime and cancellation behavior are boring.
20582059

20592060
8. Backup integration.
2060-
- Teach backup to snapshot global, agent, and plugin databases with
2061-
`VACUUM INTO`. Done for discovered `*.sqlite` files under the state asset;
2061+
- Teach backup to snapshot global, agent, and plugin databases with online
2062+
backup followed by offline `VACUUM`. Done for discovered `*.sqlite` files under the state asset;
20622063
plugin schemas requiring unavailable owner capabilities fail closed.
20632064
- Add backup verification for canonical SQLite integrity and schema identity,
20642065
plus generic file-shape validation for dedicated plugin snapshots. Done for

‎src/infra/backup-create.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -725,7 +725,7 @@ async function createStateSqliteBackupPlan(params: {
725725
});
726726
} catch (err) {
727727
throw new Error(
728-
`SQLite database cannot be compacted safely for backup: ${archiveSourcePath}. ${formatErrorMessage(err)}. The source must pass full integrity checks and VACUUM INTO with its required SQLite capabilities; raw page backup was refused because it can retain deleted data.`,
728+
`SQLite database cannot be compacted safely for backup: ${archiveSourcePath}. ${formatErrorMessage(err)}. The source must pass full integrity checks, online SQLite backup, and offline compaction with its required SQLite capabilities; a direct file copy was refused because it can retain deleted data.`,
729729
{ cause: err },
730730
);
731731
}

‎src/infra/sqlite-snapshot.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,47 @@ describe("createVerifiedSqliteSnapshot", () => {
154154
expect(snapshot.prepare("SELECT value FROM records").all()).toEqual([
155155
{ value: "survivor" },
156156
]);
157+
expect(snapshot.prepare("PRAGMA journal_mode;").get()).toEqual({
158+
journal_mode: "delete",
159+
});
157160
} finally {
158161
snapshot.close();
159162
}
163+
await expect(fs.access(`${targetPath}-wal`)).rejects.toMatchObject({ code: "ENOENT" });
164+
await expect(fs.access(`${targetPath}-shm`)).rejects.toMatchObject({ code: "ENOENT" });
160165
} finally {
161166
source.close();
162167
}
163168
});
164169

170+
it("uses online backup before compacting the private copy", async () => {
171+
const tempDir = await createTempDir();
172+
const sourcePath = path.join(tempDir, "source.sqlite");
173+
const targetPath = path.join(tempDir, "snapshot.sqlite");
174+
const sqlite = requireNodeSqlite();
175+
const source = new sqlite.DatabaseSync(sourcePath);
176+
source.exec("CREATE TABLE records (value TEXT NOT NULL); INSERT INTO records VALUES ('ok');");
177+
source.close();
178+
const backupSpy = vi.spyOn(sqlite, "backup");
179+
const prepareSpy = vi.spyOn(sqlite.DatabaseSync.prototype, "prepare");
180+
181+
try {
182+
await createVerifiedSqliteSnapshot({ sourcePath, targetPath });
183+
184+
expect(backupSpy).toHaveBeenCalledTimes(1);
185+
expect(prepareSpy.mock.calls.some(([sql]) => /\bVACUUM\s+INTO\b/iu.test(sql))).toBe(false);
186+
const snapshot = new sqlite.DatabaseSync(targetPath, { readOnly: true });
187+
try {
188+
expect(snapshot.prepare("SELECT value FROM records").get()).toEqual({ value: "ok" });
189+
} finally {
190+
snapshot.close();
191+
}
192+
} finally {
193+
prepareSpy.mockRestore();
194+
backupSpy.mockRestore();
195+
}
196+
});
197+
165198
it("rejects unsafe index drift and removes the failed target", async () => {
166199
const tempDir = await createTempDir();
167200
const sourcePath = path.join(tempDir, "source.sqlite");

‎src/infra/sqlite-snapshot.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -830,7 +830,9 @@ export async function createVerifiedSqliteSnapshot(
830830
await loadSqliteVecExtension({ db: source });
831831
assertSqliteIntegrity(source, options.sourcePath);
832832
options.validate?.(source, options.sourcePath);
833-
source.prepare("VACUUM INTO ?").run(resolveSqliteFilesystemPath(stagedPath));
833+
// Copy in incremental steps so concurrent writers are blocked only while
834+
// each batch is read. Compaction happens after releasing the live source.
835+
await sqlite.backup(source, resolveSqliteFilesystemPath(stagedPath));
834836
} finally {
835837
source.close();
836838
}
@@ -842,12 +844,15 @@ export async function createVerifiedSqliteSnapshot(
842844
try {
843845
snapshot.exec("PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;");
844846
await loadSqliteVecExtension({ db: snapshot });
847+
// Online backup preserves WAL mode. Switch the private copy to rollback
848+
// journaling so verification and restore need only the published file.
849+
snapshot.exec("PRAGMA journal_mode = DELETE;");
845850
if (options.transform) {
846851
await options.transform(snapshot);
847-
// A transform may delete sensitive rows. Compact again so the
848-
// published artifact cannot retain their bytes in free pages.
849-
snapshot.exec("VACUUM;");
850852
}
853+
// Compact the private copy so the published artifact is single-file and
854+
// cannot retain deleted or transformed data in free pages.
855+
snapshot.exec("VACUUM;");
851856
assertSqliteIntegrity(snapshot, options.targetPath);
852857
options.validate?.(snapshot, options.targetPath);
853858
const userVersion = readSqliteUserVersion(snapshot);

0 commit comments

Comments
 (0)