Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Doctor: bounded at start, repairs only from a newer copy, and in the Cloud health report

milind-soni29b8d3a79c8c
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index 1047dcefd3..69ee4960a8 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -510,6 +510,11 @@ every file's owner and mode either way. The script then:
before (the server's own count of ready engines, `GET /api/health/engines`,
which a hardened server answers too; `openmausbot doctor` on a version
without it), and Caddy runs again.
+ If it does not, the new version's doctor runs on the data
+ (`openmausbot doctor --data --fix`: in the server's container while it is up,
+ else in a one-off one with the server stopped). When the doctor repaired
+ something, the new version is started once more and step 4 is tried again.
+ [What the doctor checks and repairs](self-hosting.md#the-doctor-checking-and-repairing-the-data).
5. If any of that fails: puts back the data from the copy, `.env` and the old
image, starts the old version, and tells you what went wrong. Your server
is as it was before step 1, `.env` included, byte for byte. Only when `.env`
diff --git a/docs/headless-cli.md b/docs/headless-cli.md
index 064fbe47dc..916a94d14a 100644
--- a/docs/headless-cli.md
+++ b/docs/headless-cli.md
@@ -80,6 +80,7 @@ redaction the transcript uses). Durations are written `90`, `90s`, `5m`, `2h` or
| 5 | Cannot reach the server, not allowed, or the server is too old |
| 6 | `team apply --check` found changes |
| 7 | `doctor --host`: this machine is missing something the server needs |
+| 8 | `doctor --data`: the data folder has a problem left (after `--fix`, one it could not repair) |
| 130 | Ctrl-C (the work keeps running) |
## Commands
@@ -92,6 +93,7 @@ one of its conversations.
|---|---|
| `doctor [--wait 2m]` | Checks the server answers, is new enough, who you are to it (and when your session expires), that an engine is ready, and whether bots have a browser. On a shared server without a session (`docker compose exec omb openmausbot doctor`), it learns only how many engines are ready, not which (`GET /api/health/engines`). |
| `doctor --host` | Checks this Linux machine can run the server and the bots' sandbox (below). |
+| `doctor --data [--fix] [--data-dir DIR]` | Checks this computer's data folder without the server; `--fix` applies the repairs that cannot lose data, while no server uses it ([self-hosting](self-hosting.md#the-doctor-checking-and-repairing-the-data)). |
| `bots`, `channels`, `models` | Your bots and what each is doing, your rooms, the engines and the models each offers. |
| `messages TARGET [--limit 30]` | The latest messages of a conversation. |
| `send TARGET TEXT` | Sends one message and returns at once, to the conversation the bot or room has open. `--task new` starts a new conversation for it (`--title` names it, else the message's first line), and `--task ID` picks one. It says which conversation it went to. `--send-id ID` makes a retry safe: the same id never sends twice. |
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index de168c982b..4755d21100 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1856,11 +1856,15 @@ fine (after `--fix`, fine now) and 8 when a problem is left.
| Bots and rooms | `bots.json`, `groups.json` | An unreadable file is put back from the whole temp file of a save that was cut short. With no such copy, a copy of the damaged file is kept and you are told how to restore it. |
| Unfinished saves | `<file>.<pid>.<id>.tmp` at the top of the data folder | Moved into the backup. |
| Engine-run records | `engine-runs/` | Records with neither a server nor a process to stop are moved into the backup. |
-| Messages database | `messages.db` | A large write-ahead log is folded back into the database. A damaged database is reported, never rewritten. |
+| Messages database | `messages.db` | SQLite's `quick_check`. A write-ahead log over 64 MB is folded back into the database. A damaged database is reported, never rewritten. |
| Private files | `config.json`, `sessions.json`, `bots.json`, `messages.db`, … | Made owner-only (0600). Not on Windows. |
| Settings file | `config.json` | Never: it tells you `openmausbot config restore latest` when dated copies exist. |
Before changing anything, a repair copies it into
`<data>/doctor-backups/<time>/`, with a `manifest.json` that lists what changed
-(for a file mode, the old mode). These copies stay on that computer and are not
-part of a workspace backup. Delete them once the server runs well.
+(for a file mode, the old mode). The ten newest runs' copies are kept. They
+stay on that computer and are not part of a workspace backup.
+
+As a server starts, the doctor reads `messages.db` through and copies it before
+a checkpoint only up to 256 MB, so an update never waits on a large database;
+`openmausbot doctor --data` does both at any size.
diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.ts
index bc3641ecc9..9ca3adaf41 100644
--- a/server/cloud-health.test.ts
+++ b/server/cloud-health.test.ts
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
-import { mkdirSync, rmSync } from "node:fs";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import { join } from "node:path";
import { PassThrough } from "node:stream";
@@ -12,6 +12,7 @@ import { CLOUD_HEALTH_MAX_BYTES, HEALTH_BUCKET_CAP, createCloudHealth, createClo
import { DATA_DIR, EVENTS_DIR } from "./config.ts";
import { memoryStallText, memoryStopText } from "./engine-memory.ts";
import type { RuntimeEvent } from "./contracts.ts";
+import { doctorAtStart } from "./doctor/start.ts";
import { toolFailureMessage } from "./drivers/tool-failure.ts";
import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";
import { SessionRegistry } from "./sessions.ts";
@@ -57,6 +58,17 @@ describe("a Cloud home's memory pressure in its health report", () => {
});
});
+describe("the doctor in a Cloud home's health report", () => {
+ it("carries the check ids and counts of this version's first start, and null before it ran", () => {
+ expect(world().health.report(undefined)).toMatchObject({ doctor: null });
+ writeFileSync(join(DATA_DIR, `config.json.31337.${"0b4d8f7a-3c2e-4f1a-9b6d-5e7c8a9f0d1e"}.tmp`), "{}");
+ doctorAtStart(DATA_DIR, "0.1.120", { now: () => START, pidAlive: () => false, log: () => {} });
+ const { doctor } = world().health.report(undefined);
+ expect(doctor).toMatchObject({ at: START, version: "0.1.120", fixed: expect.arrayContaining(["temp-files"]), problems: [], thisStart: true });
+ expect(JSON.stringify(doctor)).not.toContain(DATA_DIR);
+ });
+});
+
describe("a Cloud home's speed in its health report", () => {
it("times a person's message to its engine's turn through the store and the bus, in a few numbers and fixed buckets", () => {
const w = world();
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index d3a03dbd04..674ccc7939 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -12,6 +12,7 @@ import type { FirstHourReport } from "./host/first-hour.ts";
import type { ValueReport } from "./host/value-ledger.ts";
import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";
import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";
+import { doctorSummary } from "./doctor/start.ts";
import { classifyError } from "./drivers/retry.ts";
import type { PerfHealth } from "./perf/perf-report.ts";
import type { RoutineHealth } from "./routine-health.ts";
@@ -265,6 +266,14 @@ export function boxSummary(report: BoxReport | undefined): { box: BoxReport["box
return { box: report.box, reason: report.reason, checks: report.checks ? `${report.checks.passed}/${report.checks.total}` : null, failed, boxed: report.boxed, refused: report.refused, broker, hardening: report.hardening };
}
+/** The doctor's last run, as fixed codes and counts. */
+function doctorHealth() {
+ const summary = doctorSummary();
+ if (!summary) return null;
+ const ids = (list: string[]) => list.filter((id) => CODE.test(id)).slice(0, 20);
+ return { at: Date.parse(summary.at) || null, version: match(VERSION, summary.version), checked: summary.checked, fixed: ids(summary.fixed), problems: ids(summary.problems), thisStart: summary.thisStart };
+}
+
/** What the scheduler says of itself, or `fallback` when asking it throws: the rest of the report is still answered. The log names no cause, which could quote a routine. */
function guarded<T>(read: () => T, fallback: T): T {
try { return read(); } catch { console.error("cloud health: the scheduler's part of the report could not be read"); return fallback; }
@@ -315,6 +324,8 @@ export function createCloudHealth(deps: CloudHealthDeps) {
browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },
box: boxSummary(deps.box?.()),
firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(),
+ // The data checks of this version's first start: check ids and counts (server/doctor/start.ts).
+ doctor: doctorHealth(),
system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },
};
let budget = CLOUD_HEALTH_MAX_BYTES - JSON.stringify({ ...base, cursor: ledger.cursor(read.seq), truncated: true, incidents: [] }).length;
diff --git a/server/doctor/backup.ts b/server/doctor/backup.ts
index dbf723df87..b67cdebd2c 100644
--- a/server/doctor/backup.ts
+++ b/server/doctor/backup.ts
@@ -1,10 +1,12 @@
// <data>/doctor-backups/<time>/: every fix puts what it is about to change here first, at the same path it has in the
// data folder, and writes a line in manifest.json. Made on the first fix of a run, so a run that changes nothing leaves
// no folder. Owner-only: it holds copies of the registries.
-import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, relative, sep } from "node:path";
export const DOCTOR_BACKUPS_DIR = "doctor-backups";
+/** The newest runs' copies kept; an older run's go when a new run copies something. */
+export const DOCTOR_BACKUPS_KEPT = 10;
export type BackupEntry = { check: string; action: string; path: string; savedAs?: string; mode?: string };
@@ -37,6 +39,11 @@ export class DoctorBackup {
const folder = join(root, name);
mkdirSync(folder, { mode: 0o700 });
this.folder = folder;
+ // The names sort by time.
+ const runs = readdirSync(root).filter((entry) => /^\d{4}-\d{2}-\d{2}T/.test(entry)).sort();
+ for (const old of runs.slice(0, Math.max(0, runs.length - DOCTOR_BACKUPS_KEPT))) {
+ try { rmSync(join(root, old), { recursive: true, force: true }); } catch {}
+ }
return folder;
}
diff --git a/server/doctor/checks/lease.test.ts b/server/doctor/checks/lease.test.ts
index c5b551270e..b83bdc633c 100644
--- a/server/doctor/checks/lease.test.ts
+++ b/server/doctor/checks/lease.test.ts
@@ -10,7 +10,7 @@ import { leaseCheck } from "./lease.ts";
const LEASE = "openmausbot-server.lease";
const lease = (data: string, pid: number) => {
- const record = `${JSON.stringify({ version: 1, pid, host: hostname(), token: randomUUID(), createdAt: NOW })}\n`;
+ const record = `${JSON.stringify({ version: 1, pid, host: hostname(), token: randomUUID(), createdAt: Date.now() })}\n`;
writeFileSync(join(data, LEASE), record, { mode: 0o600 });
return record;
};
diff --git a/server/doctor/checks/messages-db.ts b/server/doctor/checks/messages-db.ts
index 7c39315fc1..47aae559a6 100644
--- a/server/doctor/checks/messages-db.ts
+++ b/server/doctor/checks/messages-db.ts
@@ -8,7 +8,8 @@ import { DatabaseSync } from "node:sqlite";
import type { DoctorCheck } from "../types.ts";
const DB = "messages.db";
-/** Above this, the check at start is skipped (it reads the whole file, and the update waits on the start). */
+/** Above this, the check and the copy before a checkpoint are not done at start: both read the whole file, and an update
+ * waits on the start. `openmausbot doctor --data` does them at any size. */
export const START_CHECK_MAX_BYTES = 256 * 1024 * 1024;
/** A log this big is folded back into the database. */
export const LARGE_WAL_BYTES = 64 * 1024 * 1024;
@@ -28,13 +29,14 @@ export function messagesDbCheck(limits: { startCheckMaxBytes?: number; largeWalB
const file = join(ctx.dataDir, DB);
if (!existsSync(file)) return { status: "ok", summary: "Not there yet." };
const dbBytes = size(file), walBytes = size(`${file}-wal`);
- const full = ctx.mode === "command";
+ const atStart = ctx.mode === "start";
let verdict: string | null = null;
- if (full || dbBytes <= startMax) {
+ if (!atStart || dbBytes <= startMax) {
let db: DatabaseSync | null = null;
try {
db = new DatabaseSync(file, { readOnly: true });
- const rows = db.prepare(full ? "PRAGMA integrity_check(20)" : "PRAGMA quick_check(20)").all() as Record<string, unknown>[];
+ // SQLite's integrity check without the slow comparison of every index with its table.
+ const rows = db.prepare("PRAGMA quick_check(20)").all() as Record<string, unknown>[];
const lines = rows.map((row) => String(Object.values(row)[0]));
verdict = lines.length === 1 && lines[0] === "ok" ? "ok" : `${lines.length} problem${lines.length === 1 ? "" : "s"} (first: ${lines[0]?.slice(0, 160) ?? "unknown"})`;
} catch (error) {
@@ -51,9 +53,11 @@ export function messagesDbCheck(limits: { startCheckMaxBytes?: number; largeWalB
if (walBytes > largeWal) {
const free = freeBytes(ctx.dataDir);
const room = free === null || free > 2 * (dbBytes + walBytes);
- return { status: "problem", fixable: room, detail: { file },
+ const now = !atStart || dbBytes + walBytes <= startMax;
+ return { status: "problem", fixable: room && now, detail: { file },
summary: `${checked}; its write-ahead log is ${Math.round(walBytes / 1024 / 1024)} MB.`,
- ...(room ? {} : { instruction: "There is not room to copy it first: free some disk, then run openmausbot doctor --data --fix." }) };
+ ...(!room ? { instruction: "There is not room to copy it first: free some disk, then run openmausbot doctor --data --fix." }
+ : !now ? { instruction: "Too large to copy as the server starts: stop the server, then run openmausbot doctor --data --fix." } : {}) };
}
return { status: "ok", summary: `${checked}.` };
},
diff --git a/server/doctor/checks/registry.test.ts b/server/doctor/checks/registry.test.ts
index b2ccba6b9a..a79423cf4f 100644
--- a/server/doctor/checks/registry.test.ts
+++ b/server/doctor/checks/registry.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -43,12 +43,29 @@ describe("registry check", () => {
const report = run(data);
expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });
expect(report.checks[0]!.fixed).toContain("kept a copy of the unreadable groups.json");
+ expect(report.checks[0]!.repaired).toBe(false);
+ expect(report.counts.fixed).toBe(0);
expect(report.checks[0]!.instruction).toContain("./update.sh --rollback");
expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("{}");
expect(readFileSync(join(backupFolder(data)!, "bots.json"), "utf8")).toBe("{}");
expect(existsSync(join(backupFolder(data)!, "groups.json"))).toBe(true);
});
+ it("never takes a save from before the damaged file was written", () => {
+ const data = dataFolder();
+ writeFileSync(join(data, "bots.json"), "[{\"id\":");
+ const older = join(data, `bots.json.4242.${UUID}.tmp`);
+ writeFileSync(older, "[]");
+ utimesSync(older, new Date(NOW - 86_400_000), new Date(NOW - 86_400_000));
+ utimesSync(join(data, "bots.json"), new Date(NOW), new Date(NOW));
+ expect(registryCheck().check(context(data))).toMatchObject({ status: "problem", fixable: false, keepCopy: true });
+ const report = run(data);
+ expect(report.checks[0]).toMatchObject({ status: "problem", repaired: false });
+ // The older save is not lost either: it goes into the backup with the other unfinished saves.
+ expect(report.checks[1]).toMatchObject({ id: "temp-files", status: "fixed" });
+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("[{\"id\":");
+ });
+
it("never takes the temp file of a save still running", () => {
const data = dataFolder();
writeFileSync(join(data, "bots.json"), "nope");
diff --git a/server/doctor/checks/registry.ts b/server/doctor/checks/registry.ts
index 8c6e646158..cda5d39f6c 100644
--- a/server/doctor/checks/registry.ts
+++ b/server/doctor/checks/registry.ts
@@ -1,8 +1,8 @@
// bots.json and groups.json (registry-store.ts). The Store takes one it cannot read for an empty list, and the next save
-// writes over it. Fixed only from a whole copy the server itself wrote: the temp file of a save that was interrupted
-// after it was written and before it was renamed, which is newer than anything else. Otherwise a copy of the damaged
+// writes over it. Fixed only from a whole copy the server itself wrote after the damaged file: the temp file of a save
+// that was interrupted after it was written and before it was renamed. Otherwise a copy of the damaged
// file goes into the backup before the server starts, so a later save cannot take the last of it.
-import { chmodSync, renameSync } from "node:fs";
+import { chmodSync, renameSync, statSync } from "node:fs";
import { join } from "node:path";
import { leftoverTemps, registryState, type LeftoverTemp } from "../files.ts";
@@ -22,14 +22,17 @@ export function registryCheck(): DoctorCheck {
for (const file of REGISTRY_FILES) {
const path = join(ctx.dataDir, file);
if (registryState(path) !== "unreadable") continue;
- const copies = leftoverTemps(ctx).filter((temp) => temp.of === file && registryState(temp.path) === "ok").sort((a, b) => b.mtimeMs - a.mtimeMs);
+ // Only a save begun after the damaged file was written: an older one would bring back a list from before it.
+ let damagedAt = Infinity;
+ try { damagedAt = statSync(path).mtimeMs; } catch {}
+ const copies = leftoverTemps(ctx).filter((temp) => temp.of === file && temp.mtimeMs >= damagedAt && registryState(temp.path) === "ok").sort((a, b) => b.mtimeMs - a.mtimeMs);
damaged.push({ file, path, copy: copies[0] ?? null });
}
if (!damaged.length) return { status: "ok", summary: "Both read as lists (or are not there yet)." };
const lost = damaged.filter((damage) => !damage.copy);
return {
status: "problem",
- fixable: lost.length === 0,
+ fixable: lost.length < damaged.length,
keepCopy: lost.length > 0,
summary: damaged.map((damage) => `${damage.file} cannot be read${damage.copy ? ", and a whole copy from an interrupted save is there" : ""}.`).join(" "),
...(lost.length ? { instruction: `Stop the server and put back ${lost.map((damage) => damage.file).join(" and ")} from the copy taken before the last update (./update.sh --rollback) or from a workspace backup. Until then the server shows no ${lost.some((damage) => damage.file === "bots.json") ? "bots" : "rooms"}.` } : {}),
diff --git a/server/doctor/checks/temp-files.test.ts b/server/doctor/checks/temp-files.test.ts
index a602554660..5e5b3aac94 100644
--- a/server/doctor/checks/temp-files.test.ts
+++ b/server/doctor/checks/temp-files.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -11,12 +11,14 @@ describe("temp-files check", () => {
const data = dataFolder();
const dead = `config.json.31337.${UUID}.tmp`, live = `routines.json.4242.${UUID}.tmp`, own = `sessions.json.${process.pid}.${UUID}.tmp`;
for (const name of [dead, live, own, "notes.123.tmp", "bots.json"]) writeFileSync(join(data, name), name);
+ // This process's pid, on a file from after it started: its own save, still running.
+ utimesSync(join(data, own), new Date(NOW + 60_000), new Date(NOW + 60_000));
mkdirSync(join(data, "bots"));
writeFileSync(join(data, "bots", `work.31337.${UUID}.tmp`), "a person's file");
const pidAlive = (pid: number) => pid === 4242;
expect(tempFilesCheck().check(context(data, { pidAlive }))).toMatchObject({ status: "problem", fixable: true, summary: "1 temp file left by save that did not finish (config.json)." });
- const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, pidAlive, checks: [tempFilesCheck()] });
+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, startedAt: NOW, pidAlive, checks: [tempFilesCheck()] });
expect(report.checks[0]).toMatchObject({ status: "fixed", fixed: "Moved 1 into the backup." });
expect(existsSync(join(data, dead))).toBe(false);
expect(readFileSync(join(backupFolder(data)!, dead), "utf8")).toBe(dead);
@@ -25,6 +27,14 @@ describe("temp-files check", () => {
expect(existsSync(join(data, "bots", `work.31337.${UUID}.tmp`))).toBe(true);
});
+ it("takes a temp file with this process's pid from before it started for a predecessor's (a restarted container)", () => {
+ const data = dataFolder();
+ const name = `bots.json.${process.pid}.${UUID}.tmp`;
+ writeFileSync(join(data, name), "[]");
+ utimesSync(join(data, name), new Date(NOW - 60_000), new Date(NOW - 60_000));
+ expect(tempFilesCheck().check(context(data, { pidAlive: () => true })).status).toBe("problem");
+ });
+
it("is fine with none", () => {
expect(tempFilesCheck().check(context(dataFolder())).status).toBe("ok");
});
diff --git a/server/doctor/files.ts b/server/doctor/files.ts
index d1022dc4b3..23d5b72f70 100644
--- a/server/doctor/files.ts
+++ b/server/doctor/files.ts
@@ -10,7 +10,8 @@ const ATOMIC_TEMP = /^(.+)\.([1-9]\d{0,9})\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-
export type LeftoverTemp = { name: string; path: string; of: string; pid: number; mtimeMs: number };
-/** The temp files in `dir` (not below it) whose writer is no longer running: never this process's, never a live one's. */
+/** The temp files in `dir` (not below it) whose writer is no longer running: never a live process's, and this process's
+ * pid only for a file older than this process (a restarted container's server is often given its predecessor's pid). */
export function leftoverTemps(ctx: DoctorContext, dir: string = ctx.dataDir): LeftoverTemp[] {
let names: string[];
try { names = readdirSync(dir); } catch { return []; }
@@ -19,11 +20,12 @@ export function leftoverTemps(ctx: DoctorContext, dir: string = ctx.dataDir): Le
const match = ATOMIC_TEMP.exec(name);
if (!match) continue;
const pid = Number(match[2]);
- if (pid === process.pid || ctx.pidAlive(pid)) continue;
+ if (pid !== process.pid && ctx.pidAlive(pid)) continue;
const path = join(dir, name);
try {
const stat = statSync(path);
- if (stat.isFile()) found.push({ name, path, of: match[1]!, pid, mtimeMs: stat.mtimeMs });
+ if (!stat.isFile() || (pid === process.pid && stat.mtimeMs >= ctx.startedAt)) continue;
+ found.push({ name, path, of: match[1]!, pid, mtimeMs: stat.mtimeMs });
} catch {}
}
return found;
diff --git a/server/doctor/run.ts b/server/doctor/run.ts
index c7fbb16fb5..9fe9e6b65a 100644
--- a/server/doctor/run.ts
+++ b/server/doctor/run.ts
@@ -29,6 +29,7 @@ export interface RunDoctorOptions {
checks?: DoctorCheck[];
now?: () => number;
pidAlive?: (pid: number) => boolean;
+ startedAt?: number;
/** "command" mode only: takes the data folder's lease for the repairs. */
acquireLease?: (dataDir: string) => { release(): unknown };
}
@@ -59,7 +60,8 @@ const wantsFix = (check: DoctorCheck, finding: Finding) => Boolean(check.fix &&
export function runDoctor(options: RunDoctorOptions): DoctorReport {
const now = options.now ?? Date.now;
- const ctx: DoctorContext = { dataDir: options.dataDir, version: options.version, mode: options.mode, now, pidAlive: options.pidAlive ?? pidAlive };
+ const ctx: DoctorContext = { dataDir: options.dataDir, version: options.version, mode: options.mode, now, pidAlive: options.pidAlive ?? pidAlive,
+ startedAt: options.startedAt ?? performance.timeOrigin };
const checks = options.checks ?? defaultChecks();
const findings = checks.map((check) => look(check, ctx));
const results = checks.map((check, at) => resultOf(check, findings[at]!));
@@ -83,7 +85,7 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {
if (holder?.state === "dead") backup.copy("lease", holder.path, "the lease a dead process left, before it was retired");
const lease = (options.acquireLease ?? acquireDataDirLease)(options.dataDir);
release = () => { lease.release(); };
- if (holder?.state === "dead") Object.assign(results[leaseAt]!, { status: "fixed", fixed: `Retired the lease process ${holder.pid} left.` });
+ if (holder?.state === "dead") Object.assign(results[leaseAt]!, { status: "fixed", fixable: false, repaired: true, fixed: `Retired the lease process ${holder.pid} left.` });
} catch (error) {
fix.why = `The data folder's lease could not be taken (${errorText(error)}). Nothing was changed.`;
}
@@ -107,9 +109,10 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {
return;
}
const after = look(check, ctx);
+ const repaired = Boolean(fresh.fixable);
results[at] = after.status === "ok"
- ? { ...resultOf(check, fresh), status: "fixed", fixable: false, fixed: did }
- : { ...resultOf(check, after), fixed: did };
+ ? { ...resultOf(check, fresh), status: "fixed", fixable: false, fixed: did, repaired }
+ : { ...resultOf(check, after), fixed: did, repaired };
});
} finally {
try { release?.(); } catch {}
@@ -128,7 +131,7 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {
counts: {
checked: results.length,
problems,
- fixed: results.filter((result) => result.fixed !== undefined).length,
+ fixed: results.filter((result) => result.repaired).length,
blocking: results.filter((result) => result.blocking).length,
},
};
diff --git a/server/doctor/start.test.ts b/server/doctor/start.test.ts
index 187fd8b1a6..356c11c592 100644
--- a/server/doctor/start.test.ts
+++ b/server/doctor/start.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -56,6 +56,19 @@ describe("the doctor at start", () => {
});
});
+describe("doctor-backups", () => {
+ it("keeps the newest ten runs' copies", () => {
+ const data = dataFolder();
+ for (let n = 0; n < 12; n += 1) {
+ stray(data);
+ runDoctor({ dataDir: data, version: "1.0.0", mode: "start", fix: true, now: () => NOW + n * 1000, pidAlive: () => false });
+ }
+ const runs = readdirSync(join(data, "doctor-backups")).sort();
+ expect(runs).toHaveLength(10);
+ expect(runs[0]).toBe("2026-11-17T09-30-02Z");
+ });
+});
+
describe("openmausbot doctor --data", () => {
it("reports without changing anything, and says --fix repairs it; exit 8 while a problem is left", () => {
const data = dataFolder();
diff --git a/server/doctor/start.ts b/server/doctor/start.ts
index b6c82177e3..3939b90451 100644
--- a/server/doctor/start.ts
+++ b/server/doctor/start.ts
@@ -46,7 +46,7 @@ export function summaryOf(report: DoctorReport): Omit<DoctorSummary, "thisStart"
at: report.at,
version: report.version,
checked: report.counts.checked,
- fixed: report.checks.filter((result) => result.fixed !== undefined).map((result) => result.id),
+ fixed: report.checks.filter((result) => result.repaired).map((result) => result.id),
problems: report.checks.filter((result) => result.status === "problem" || result.status === "failed").map((result) => result.id),
};
}
diff --git a/server/doctor/types.ts b/server/doctor/types.ts
index 31a43a76ea..684b862c61 100644
--- a/server/doctor/types.ts
+++ b/server/doctor/types.ts
@@ -10,6 +10,8 @@ export interface DoctorContext {
/** "start": the server's own run as it starts, holding the lease; "command": `openmausbot doctor --data`. */
mode: "start" | "command";
now(): number;
+ /** When this process started (ms): a temp file with its pid from before then is a predecessor's. */
+ startedAt: number;
/** Whether a process with this pid runs on this machine (EPERM counts as running). */
pidAlive(pid: number): boolean;
}
@@ -51,6 +53,8 @@ export type CheckResult = {
instruction?: string;
/** What the fix did, when it ran. */
fixed?: string;
+ /** The fix repaired something (a copy kept of what it could not repair is not a repair). */
+ repaired?: boolean;
};
export type DoctorReport = {
diff --git a/server/testing/doctor-folders.ts b/server/testing/doctor-folders.ts
index 667d12c228..c0f1c72cd4 100644
--- a/server/testing/doctor-folders.ts
+++ b/server/testing/doctor-folders.ts
@@ -24,7 +24,7 @@ export function dataFolder(): string {
}
export function context(dataDir: string, more: Partial<DoctorContext> = {}): DoctorContext {
- return { dataDir, version: "9.9.9", mode: "command", now: () => NOW, pidAlive: () => false, ...more };
+ return { dataDir, version: "9.9.9", mode: "command", now: () => NOW, startedAt: NOW, pidAlive: () => false, ...more };
}
/** The pid of a process that has ended. */