Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud backups: stage consistent copies of the databases before a server packs its volume (#7135)
Milind Soni67bb1462e0a2
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjsindex 6c8a6ec90a..bed78502d3 100644--- a/scripts/bundle-server.mjs+++ b/scripts/bundle-server.mjs@@ -41,6 +41,8 @@ const ENTRY_POINTS = ["stall-watch.worker.ts",// the OMB Cloud Pro home image's entry point"cloud-home-start.ts",+ // a Cloud server's backup runs it in the home before it packs the volume (cloud-backup-stage.ts)+ "cloud-backup-db-snapshot.ts",// the container image's entry point"server-launcher.ts",// Imported directly by the packaged smoke probes. An explicit root sibling,diff --git a/server/cloud-backup-db-snapshot.ts b/server/cloud-backup-db-snapshot.tsnew file mode 100644index 0000000000..d898bf3337--- /dev/null+++ b/server/cloud-backup-db-snapshot.ts@@ -0,0 +1,20 @@+// A Cloud server's backup asks the running home for consistent copies of its databases before it packs the volume+// (cloud-backup-stage.ts): `docker exec -u maus omb-home timeout 1800 node /app/dist-server/cloud-backup-db-snapshot.js`.+// Prints each database it staged, one per line. Exit 0 whatever it staged (the backup packs only what the stage holds);+// 2 with no data folder named; 1 when it could not run (the backup then packs the live files, as before).+import { prepareBackupStage } from "./cloud-backup-stage.ts";++const dataDir = process.env.OMB_DATA_DIR;+if (!dataDir) {+ console.error("omb backup: OMB_DATA_DIR is not set; no database snapshots");+ process.exit(2);+}+try {+ const { staged } = await prepareBackupStage({ dataDir });+ if (staged.length) console.log(staged.join("\n"));+ console.error(`omb backup: ${staged.length ? `snapshotted ${staged.join(", ")}` : "no database snapshotted"}`);+ process.exit(0);+} catch (error) {+ console.error(`omb backup: no database snapshots: ${error instanceof Error ? error.message : String(error)}`);+ process.exit(1);+}diff --git a/server/cloud-backup-stage.test.ts b/server/cloud-backup-stage.test.tsnew file mode 100644index 0000000000..408bd6c5ec--- /dev/null+++ b/server/cloud-backup-stage.test.ts@@ -0,0 +1,173 @@+// A Cloud server's backup of its volume packs consistent copies of the databases (cloud-backup-stage.ts): one moment of each,+// taken while the server goes on writing, never more than the disk can hold, and only as the data folder's owner.+import { spawn, spawnSync } from "node:child_process";+import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { DatabaseSync } from "node:sqlite";+import { afterEach, describe, expect, it } from "vitest";++import { BACKUP_STAGE, prepareBackupStage, stageReserve } from "./cloud-backup-stage.ts";++const GB = 1024 ** 3;+const scratch: string[] = [];+afterEach(() => { for (const path of scratch.splice(0)) rmSync(path, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); });+const directory = () => { const path = mkdtempSync(join(tmpdir(), "omb-backup-stage-")); scratch.push(path); return path; };+const roomy = () => ({ free: 100 * GB, total: 200 * GB });+const posix = process.platform !== "win32";++/** A database the server keeps: WAL mode, rows `id` 1.. in a table `m`. */+function database(path: string, rows: number) {+ const db = new DatabaseSync(path);+ try {+ db.exec("PRAGMA journal_mode = WAL; CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT NOT NULL)");+ const insert = db.prepare("INSERT INTO m (id, body) VALUES (?, ?)");+ db.exec("BEGIN"); for (let id = 1; id <= rows; id++) insert.run(id, "x".repeat(500)); db.exec("COMMIT");+ } finally { db.close(); }+}+/** What a restore of the archive gives the server: the copy alone under the live name, its integrity, and its rows. */+function restored(copy: string) {+ const into = directory();+ copyFileSync(copy, join(into, "messages.db"));+ const db = new DatabaseSync(join(into, "messages.db"), { readOnly: true });+ try {+ const check = db.prepare("PRAGMA integrity_check").get() as { integrity_check: string };+ const rows = db.prepare("SELECT count(*) AS count, coalesce(max(id), 0) AS top FROM m").get() as { count: number; top: number };+ const mode = (db.prepare("PRAGMA journal_mode").get() as { journal_mode: string }).journal_mode;+ return { check: check.integrity_check, count: Number(rows.count), top: Number(rows.top), mode };+ } finally { db.close(); }+}++const WRITER = `import { DatabaseSync } from "node:sqlite";+import { renameSync, writeFileSync } from "node:fs";+const [file, mark] = process.argv.slice(2);+const db = new DatabaseSync(file);+db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA wal_autocheckpoint = 16; CREATE TABLE IF NOT EXISTS m (id INTEGER PRIMARY KEY, body TEXT NOT NULL)");+const insert = db.prepare("INSERT INTO m (id, body) VALUES (?, ?)"), body = "x".repeat(4000);+let n = 0, stop = false;+process.on("SIGTERM", () => { stop = true; });+const tick = () => {+ if (stop) { db.close(); process.exit(0); }+ db.exec("BEGIN"); for (let i = 0; i < 25; i++) insert.run(++n, body); db.exec("COMMIT");+ writeFileSync(mark + ".tmp", String(n)); renameSync(mark + ".tmp", mark);+ setImmediate(tick);+};+tick();+`;++describe("prepareBackupStage", () => {+ it("copies one moment of messages.db while another process commits and checkpoints: it restores whole, with every row committed before it began", async () => {+ const data = directory(), work = directory();+ writeFileSync(join(work, "writer.mjs"), WRITER);+ const mark = join(work, "committed"), live = join(data, "messages.db");+ const child = spawn(process.execPath, [join(work, "writer.mjs"), live, mark], { stdio: ["ignore", "ignore", "inherit"] });+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));+ const committed = () => (existsSync(mark) ? Number(readFileSync(mark, "utf8")) : 0);+ try {+ for (const until = Date.now() + 60_000; committed() < 3_000;) {+ if (Date.now() > until || child.exitCode !== null) throw new Error("the writer never got going");+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ const before = committed();+ const lines: string[] = [];+ const done = await prepareBackupStage({ dataDir: data, disk: roomy, log: (line) => lines.push(line) });+ expect(done).toMatchObject({ staged: ["messages.db"], skipped: [] });+ expect(lines).toEqual([]);+ // The writer went on: the copy was of a live database, not one at rest.+ for (const until = Date.now() + 60_000; committed() <= before && Date.now() < until;) await new Promise((resolve) => setTimeout(resolve, 50));+ expect(committed()).toBeGreaterThan(before);+ expect(readdirSync(done.stage)).toEqual(["messages.db"]);+ child.kill("SIGTERM"); await exited;+ const reader = new DatabaseSync(live, { readOnly: true });+ const top = Number((reader.prepare("SELECT max(id) AS top FROM m").get() as { top: number }).top);+ reader.close();+ const got = restored(join(done.stage, "messages.db"));+ expect(got.check).toBe("ok");+ expect(got.mode).toBe("delete");+ expect(got.count).toBe(got.top);+ expect(got.top).toBeGreaterThanOrEqual(before);+ expect(got.top).toBeLessThanOrEqual(top);+ } finally {+ if (child.exitCode === null && child.signalCode === null) { child.kill("SIGTERM"); await exited; }+ }+ }, 120_000);++ it("stages each database there is, under its own name, keeps its mode, and leaves nothing of an earlier run", async () => {+ const data = directory();+ database(join(data, "messages.db"), 50);+ database(join(data, "runtime.db"), 5);+ mkdirSync(join(data, BACKUP_STAGE));+ writeFileSync(join(data, BACKUP_STAGE, "bursts.db"), "stale, from a backup that was killed");+ writeFileSync(join(data, BACKUP_STAGE, "messages.db.partial"), "half");+ const done = await prepareBackupStage({ dataDir: data, disk: roomy, log: () => {} });+ expect(done.staged).toEqual(["messages.db", "runtime.db"]);+ expect(readdirSync(done.stage).sort()).toEqual(["messages.db", "runtime.db"]);+ expect(restored(join(done.stage, "messages.db"))).toMatchObject({ check: "ok", count: 50, top: 50 });+ if (posix) {+ expect(lstatSync(done.stage).mode & 0o777).toBe(0o700);+ expect(lstatSync(join(done.stage, "messages.db")).mode & 0o777).toBe(lstatSync(join(data, "messages.db")).mode & 0o777);+ }+ });++ it("skips a database the disk has no room to copy (leaving the reserve free), says so, and leaves no partial copy", async () => {+ const data = directory();+ database(join(data, "messages.db"), 200);+ database(join(data, "runtime.db"), 2);+ const messages = lstatSync(join(data, "messages.db")).size;+ // A 10 GB disk: the reserve is 1 GB. Room for the small database, not for the large one after the reserve.+ const total = 10 * GB, free = stageReserve(total) + messages - 1;+ const lines: string[] = [];+ const done = await prepareBackupStage({ dataDir: data, disk: () => ({ free, total }), log: (line) => lines.push(line) });+ expect(done.staged).toEqual(["runtime.db"]);+ expect(done.skipped.map((item) => item.name)).toEqual(["messages.db"]);+ expect(lines).toEqual([expect.stringMatching(/^omb backup: messages\.db not snapshotted \(.+ free, the copy needs up to .+ and must leave 1\.0 GB\); the backup packs its live files$/)]);+ expect(readdirSync(done.stage)).toEqual(["runtime.db"]);+ expect(stageReserve(200 * GB)).toBe(10 * GB);+ });++ it("skips a database it cannot copy, removing what it began, and still stages the others", async () => {+ const data = directory();+ writeFileSync(join(data, "messages.db"), "not a database at all, but long enough to be read as a header ".repeat(4));+ database(join(data, "runtime.db"), 3);+ const lines: string[] = [];+ const done = await prepareBackupStage({ dataDir: data, disk: roomy, log: (line) => lines.push(line) });+ expect(done.staged).toEqual(["runtime.db"]);+ expect(done.skipped.map((item) => item.name)).toEqual(["messages.db"]);+ expect(readdirSync(done.stage)).toEqual(["runtime.db"]);+ expect(lines).toHaveLength(1);+ });++ it.skipIf(!posix)("never follows a database that is a link", async () => {+ const data = directory(), elsewhere = directory();+ database(join(elsewhere, "messages.db"), 3);+ symlinkSync(join(elsewhere, "messages.db"), join(data, "messages.db"));+ const done = await prepareBackupStage({ dataDir: data, disk: roomy, log: () => {} });+ expect(done.staged).toEqual([]);+ expect(done.skipped).toEqual([{ name: "messages.db", why: "not a plain file" }]);+ });++ it.skipIf(!posix)("runs only as the data folder's owner, so no copy is ever root's", async () => {+ const data = directory();+ database(join(data, "messages.db"), 3);+ const owner = lstatSync(data).uid;+ await expect(prepareBackupStage({ dataDir: data, disk: roomy, log: () => {}, uid: owner + 1 })).rejects.toThrow(/only as the data folder's owner/);+ expect(existsSync(join(data, BACKUP_STAGE))).toBe(false);+ });+});++describe("the command a Cloud server's backup runs", () => {+ const entry = fileURLToPath(new URL("./cloud-backup-db-snapshot.ts", import.meta.url));+ it("stages the data folder OMB_DATA_DIR names and prints what it staged; with none named, exits 2", () => {+ const data = directory();+ database(join(data, "messages.db"), 7);+ const ran = spawnSync(process.execPath, [entry], { encoding: "utf8", env: { ...process.env, OMB_DATA_DIR: data } });+ expect(ran.status, ran.stderr).toBe(0);+ expect(ran.stdout.trim()).toBe("messages.db");+ expect(restored(join(data, BACKUP_STAGE, "messages.db"))).toMatchObject({ check: "ok", count: 7 });+ const env: NodeJS.ProcessEnv = { ...process.env };+ delete env.OMB_DATA_DIR;+ const unnamed = spawnSync(process.execPath, [entry], { encoding: "utf8", env });+ expect(unnamed.status).toBe(2);+ });+});diff --git a/server/cloud-backup-stage.ts b/server/cloud-backup-stage.tsnew file mode 100644index 0000000000..19d4d2c024--- /dev/null+++ b/server/cloud-backup-stage.ts@@ -0,0 +1,80 @@+// Consistent databases for a Cloud server's own backup of its volume (its boot script, behind a switch on the Cloud's+// control side, off by default). That backup is a tar of the whole volume while the home runs, and a tar reads+// messages.db and its -wal at different moments: a checkpoint between the two reads leaves an archive that restores a+// database missing pages, or a corrupt one. So, just before the tar, the server's backup runs+// `docker exec -u maus omb-home timeout 1800 node /app/dist-server/cloud-backup-db-snapshot.js`, which writes one moment of+// each database (snapshotDatabase: SQLite's backup API in one step; writers go on meanwhile) into <data>/backup-stage/<name>.+// The tar packs each copy under its live name and leaves out the live file, its -wal and -shm; it removes the stage after.+//+// The contract with that script: only finished copies are left in the stage, each under its database's own name (a copy is+// written as <name>.partial and renamed when done); the stage holds nothing from an earlier run; and a database the disk has+// no room to copy is left out (its live files are packed, as before), never filling the disk. It runs as the data folder's+// owner only, so every copy is the server's own, as the live file is.+// Not covered: each bot's Data tables (DuckDB, bots/<id>/data.duckdb), which the server closes after 10 idle minutes and only+// it can let go of (releaseDataForBackup); sync/index.db (a rebuildable cache); the engines' and browsers' own databases.+import { chmodSync, existsSync, lstatSync, mkdirSync, renameSync, rmSync, statfsSync } from "node:fs";+import { join } from "node:path";++import { SNAPSHOT_DATABASES, snapshotDatabase } from "./workspace-backup-databases.ts";++/** The stage's folder in the data folder (the boot script reads it at /mnt/omb-data/.openmausbot/backup-stage). */+export const BACKUP_STAGE = "backup-stage";+const GB = 1024 ** 3;+/** Room a copy must leave free on the disk: the larger of 1 GB and 5% of it. The live WAL grows meanwhile (no checkpoint+ * passes the copy's read), and the server keeps writing; this is what they get. */+export const stageReserve = (total: number) => Math.max(GB, Math.ceil(total * 0.05));++export interface StageDisk { free: number; total: number }+export interface PrepareBackupStage {+ dataDir: string;+ /** The disk under the data folder now (statfs): bytes free to this user, and its size. */+ disk?: (path: string) => StageDisk;+ log?: (line: string) => void;+ /** This process's user id (null where there is none, as on Windows). */+ uid?: number | null;+}+export interface PreparedBackupStage { stage: string; staged: string[]; skipped: { name: string; why: string }[] }++const statDisk = (path: string): StageDisk => {+ const disk = statfsSync(path);+ return { free: disk.bavail * disk.bsize, total: disk.blocks * disk.bsize };+};+const size = (path: string) => (existsSync(path) ? lstatSync(path).size : 0);+const gb = (bytes: number) => `${(bytes / GB).toFixed(1)} GB`;++export async function prepareBackupStage(options: PrepareBackupStage): Promise<PreparedBackupStage> {+ const { dataDir } = options;+ const log = options.log ?? ((line: string) => console.error(line));+ const disk = options.disk ?? statDisk;+ const uid = options.uid === undefined ? (process.getuid?.() ?? null) : options.uid;+ const folder = lstatSync(dataDir);+ if (!folder.isDirectory()) throw new Error(`The data folder ${dataDir} is not a folder.`);+ // As root (docker exec without -u), the copies would be root's and the server could not open them after a restore.+ if (uid !== null && uid !== folder.uid) throw new Error(`Runs only as the data folder's owner (uid ${folder.uid}), not uid ${uid}.`);+ const stage = join(dataDir, BACKUP_STAGE);+ rmSync(stage, { recursive: true, force: true });+ mkdirSync(stage, { mode: 0o700 });+ const staged: string[] = [], skipped: { name: string; why: string }[] = [];+ const skip = (name: string, why: string) => { skipped.push({ name, why }); log(`omb backup: ${name} not snapshotted (${why}); the backup packs its live files`); };+ for (const name of Object.keys(SNAPSHOT_DATABASES)) {+ const source = join(dataDir, name);+ if (!existsSync(source)) continue;+ const live = lstatSync(source);+ if (!live.isFile()) { skip(name, "not a plain file"); continue; }+ // The copy is at most the database and its log; it must leave the reserve free.+ const need = live.size + size(`${source}-wal`);+ const { free, total } = disk(dataDir);+ if (free - need < stageReserve(total)) { skip(name, `${gb(free)} free, the copy needs up to ${gb(need)} and must leave ${gb(stageReserve(total))}`); continue; }+ const partial = join(stage, `${name}.partial`);+ try {+ await snapshotDatabase(dataDir, name, partial);+ chmodSync(partial, live.mode & 0o777);+ renameSync(partial, join(stage, name));+ staged.push(name);+ } catch (error) {+ for (const path of [partial, `${partial}-journal`]) rmSync(path, { force: true });+ skip(name, error instanceof Error ? error.message : String(error));+ }+ }+ return { stage, staged, skipped };+}diff --git a/server/workspace-backup-databases.ts b/server/workspace-backup-databases.tsindex 03e5211c4e..61262e03a5 100644--- a/server/workspace-backup-databases.ts+++ b/server/workspace-backup-databases.ts@@ -30,21 +30,27 @@ export async function snapshotDatabases(root: string, snapshot: string): Promisefor (const [name, snapshotName] of Object.entries(SNAPSHOT_DATABASES)) {const sourceDb = join(root, name);if (!existsSync(sourceDb)) continue;- if (lstatSync(sourceDb).isSymbolicLink()) throw new Error(`The ${LABELS[name]} database must not be a symbolic link.`);- // Another connection may open this database meanwhile; without a busy timeout the backup fails at once ("database is locked").- const db = new DatabaseSync(sourceDb, { readOnly: true, timeout: 5_000 });- // Node 26's native backup completion can wait on unrelated event-loop activity after an async scrypt; this pulse keeps it moving.- const completionPulse = setInterval(() => {}, 25);- // In one step: a backup in steps starts again whenever another connection writes between them, and a writer that keeps- // writing would keep it from ever finishing. SQLite reads -1 as every page, but Node 24.22 refuses a rate under 1, so- // the step is the largest rate Node takes, more pages than any database here holds.- try { await backup(db, join(snapshot, snapshotName), { rate: ONE_STEP }); }- finally { clearInterval(completionPulse); db.close(); }- const snapshotDb = new DatabaseSync(join(snapshot, snapshotName));- try { snapshotDb.exec("PRAGMA journal_mode = DELETE"); } finally { snapshotDb.close(); }+ await snapshotDatabase(root, name, join(snapshot, snapshotName));}}+/** One moment of the database `name` in `root`, written to `destination` in DELETE mode. */+export async function snapshotDatabase(root: string, name: string, destination: string): Promise<void> {+ const sourceDb = join(root, name);+ if (lstatSync(sourceDb).isSymbolicLink()) throw new Error(`The ${LABELS[name] ?? name} database must not be a symbolic link.`);+ // Another connection may open this database meanwhile; without a busy timeout the backup fails at once ("database is locked").+ const db = new DatabaseSync(sourceDb, { readOnly: true, timeout: 5_000 });+ // Node 26's native backup completion can wait on unrelated event-loop activity after an async scrypt; this pulse keeps it moving.+ const completionPulse = setInterval(() => {}, 25);+ // In one step: a backup in steps starts again whenever another connection writes between them, and a writer that keeps+ // writing would keep it from ever finishing. SQLite reads -1 as every page, but Node 24.22 refuses a rate under 1, so+ // the step is the largest rate Node takes, more pages than any database here holds.+ try { await backup(db, destination, { rate: ONE_STEP }); }+ finally { clearInterval(completionPulse); db.close(); }+ const snapshotDb = new DatabaseSync(destination);+ try { snapshotDb.exec("PRAGMA journal_mode = DELETE"); } finally { snapshotDb.close(); }+}+/** An older backup's raw WAL goes into its database before the restore installs it, so the restored folder holds one* file per database as a new backup does. SQLite applies what of the log matches the database, as it would have on open. */export function foldLegacySidecars(prepared: string): void {diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 3ef8853130..ba2d05a83b 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -58,6 +58,8 @@ const EXCLUDED = new Set([// The doctor's copies of what it repaired, and the version it last ran for (doctor/backup.ts, doctor/start.ts): this// folder's own history, and copies of files a backup already holds."doctor-backups", "doctor-state.json",+ // A Cloud server's database copies for its own backup of the volume (cloud-backup-stage.ts), removed when it is packed.+ "backup-stage",]);const EXCLUSION_NOTES = ["Device pairing, server identity, live leases and runtime files (existing destination identities are preserved).",