mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
fix: inspect backup health without blocking the event loop (#14674)
## Thinking Path > - The health endpoint reports database backup status. > - Backup directories and marker files may live on slow storage. > - Synchronous filesystem reads hold Node's event loop during each check. > - Other requests wait behind that filesystem work. > - Await filesystem operations and preserve the existing health response. ## Linked Issues or Issue Description **What happened?** A backup-health check scans and reads files synchronously on the HTTP event loop. **Expected behavior:** Filesystem work yields so unrelated timers and requests can proceed. **Steps to reproduce:** Enable database backup health with a slow backup directory, request `/api/health`, and observe unrelated event-loop work waiting for synchronous filesystem calls. The regression deterministically holds an asynchronous directory read and verifies another timer can run before it completes. **Paperclip version or commit:** `master` at `a027f76a7`. **Deployment mode:** Built from source; tested using temporary backup files and controlled filesystem responses. Related PRs #13308 (empty archive health) and #10736 (backup retention) address different backup behavior. This change leaves archive validation and retention policy alone; those branches may need small textual reconciliations if merged first. ## What Changed - Use `node:fs/promises` for directory enumeration, file metadata and failure markers. - Scan archive metadata in batches of at most four reads to bound filesystem work while allowing parallel I/O. - Await the result in the health route. - Treat only missing files as absent, including files removed by retention during enumeration. - Preserve warnings for actual filesystem failures and existing newest-file/marker behavior. - Add coverage for freshness, missing directories, marker text, read errors, retention races, bounded scan concurrency and event-loop progress. ## Verification - Backup-health and health route suites (4 files): 35 passed. - The event-loop regression fails with the original synchronous service. - The archive-only concurrency regression also fails against the sequential scan; optional marker reads cannot mask that failure. - `pnpm --filter @paperclipai/server typecheck`: passed. - `git diff --check`: passed. - Refreshed with upstream `master` at `7d59de6113caf5219d34d65e1fb5f0c1a7fbdc2a`, which includes the Runner qualified-command fixture fix. The fresh branch diff remains limited to this fix and its tests. - Re-ran all four focused suites on `8e96930537774ac4623cd493ba065b8a6f5d3269`: 35 passed. The first [refreshed CI run](https://github.com/paperclipai/paperclip/actions/runs/37038481259) passed every test gate except the touch-picker browser shard. The failure screenshot shows the last option already visible at the scroll boundary. The source-identical retry at `eeaeb752a36e0acd5129b6c6bce40e24fdefe1bd` [passed all CI](https://github.com/paperclipai/paperclip/actions/runs/37040261790), including the touch-picker shard, both Runner shards, build, typecheck, server suites, canary dry run and the final aggregate. - Greptile is 5/5 and all review threads are resolved. ## Risks The internal inspection helper now returns a Promise; its route caller awaits it. The response schema and freshness threshold are unchanged. No database migration or cache is introduced. ## Model Used OpenAI GPT-6 through Codex, with reasoning, Git and code execution tools. The exact deployment identifier and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used, including the available version and capability details - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs - [x] I have described the issue using the bug report fields - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket ID - [x] I have run tests locally and they pass - [x] I have added a regression test - [x] I have documented the affected request behavior and risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open findings - [x] I will address reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
6c6e978725
commit
51b398194a
3 files changed
+154
-27
No files matched your search
@@ -399,7 +399,7 @@ export function healthRoutes(
|
||||
: null;
|
||||
|
||||
const databaseBackup = opts.databaseBackupHealth
|
||||
? inspectDatabaseBackupHealth(opts.databaseBackupHealth)
|
||||
? await inspectDatabaseBackupHealth(opts.databaseBackupHealth)
|
||||
: undefined;
|
||||
const warnings = databaseBackup?.warnings.length ? databaseBackup.warnings : undefined;
|
||||
const nativeRecovery = exposeFullDetails
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { inspectDatabaseBackupHealth } from "./database-backup-health.js";
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return { ...actual, readdir: vi.fn(actual.readdir), stat: vi.fn(actual.stat) };
|
||||
});
|
||||
|
||||
const NOW = new Date("2026-09-30T12:00:00Z");
|
||||
let directory: string;
|
||||
const inspect = () => inspectDatabaseBackupHealth({ enabled: true, backupDir: directory, maxAgeHours: 24, now: NOW });
|
||||
|
||||
async function backup(name: string, ageHours: number) {
|
||||
const file = path.join(directory, name);
|
||||
await fs.writeFile(file, "backup");
|
||||
const date = new Date(NOW.getTime() - ageHours * 3_600_000);
|
||||
await fs.utimes(file, date, date);
|
||||
return file;
|
||||
}
|
||||
|
||||
beforeEach(async () => { vi.resetAllMocks(); directory = await fs.mkdtemp(path.join(os.tmpdir(), "backup-health-")); });
|
||||
afterEach(async () => { vi.restoreAllMocks(); await fs.rm(directory, { recursive: true, force: true }); });
|
||||
|
||||
describe("database backup health", () => {
|
||||
it("selects the newest backup by modification time", async () => {
|
||||
await backup("a.sql.gz", 1);
|
||||
await backup("z.sql.gz", 2);
|
||||
expect(await inspect()).toMatchObject({ status: "ok", latestBackup: { name: "a.sql.gz", ageHours: 1, sizeBytes: 6 }, warnings: [] });
|
||||
});
|
||||
|
||||
it("reports an old backup as stale", async () => {
|
||||
await backup("old.sql.gz", 25);
|
||||
expect((await inspect()).warnings[0].code).toBe("database_backup_stale");
|
||||
});
|
||||
|
||||
it("reports a missing directory as missing, without a check failure", async () => {
|
||||
await fs.rm(directory, { recursive: true });
|
||||
expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_missing"]);
|
||||
});
|
||||
|
||||
it("reports the first line of a failure marker", async () => {
|
||||
await backup("recent.sql.gz", 1);
|
||||
await fs.writeFile(path.join(directory, "db-backup-to-s3.failure"), "Backup upload failed\nprivate diagnostic\n");
|
||||
expect((await inspect()).lastFailure?.message).toBe("Backup upload failed");
|
||||
});
|
||||
|
||||
it("reports an unreadable directory as a failed check", async () => {
|
||||
vi.mocked(fs.readdir).mockRejectedValueOnce(Object.assign(new Error("permission denied"), { code: "EACCES" }));
|
||||
expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_check_failed"]);
|
||||
});
|
||||
|
||||
it("ignores a backup removed by retention after the directory listing", async () => {
|
||||
await backup("removed.sql.gz", 1);
|
||||
vi.mocked(fs.stat).mockRejectedValueOnce(Object.assign(new Error("removed"), { code: "ENOENT" }));
|
||||
expect((await inspect()).warnings.map((warning) => warning.code)).toEqual(["database_backup_missing"]);
|
||||
});
|
||||
|
||||
it("bounds metadata reads while scanning retained backups", async () => {
|
||||
for (let index = 0; index < 12; index++) await backup(`${index}.sql.gz`, index + 1);
|
||||
const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
vi.mocked(fs.stat).mockImplementation((async (...args: Parameters<typeof fs.stat>) => {
|
||||
const isArchive = String(args[0]).endsWith(".sql.gz");
|
||||
if (isArchive) {
|
||||
active++;
|
||||
peak = Math.max(peak, active);
|
||||
}
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
return await actual.stat(...args);
|
||||
} finally {
|
||||
if (isArchive) active--;
|
||||
}
|
||||
}) as typeof fs.stat);
|
||||
expect((await inspect()).latestBackup?.name).toBe("0.sql.gz");
|
||||
// Count archive I/O only; parallel marker reads must not make a fully
|
||||
// sequential archive scan satisfy the lower bound.
|
||||
const archiveReads = vi.mocked(fs.stat).mock.calls.filter(([file]) => String(file).endsWith(".sql.gz"));
|
||||
expect(archiveReads).toHaveLength(12);
|
||||
expect(peak).toBeGreaterThan(1);
|
||||
expect(peak).toBeLessThanOrEqual(4);
|
||||
});
|
||||
|
||||
it("lets a timer run while the filesystem observation is pending", async () => {
|
||||
let release!: () => void;
|
||||
const held = new Promise<string[]>((resolve) => { release = () => resolve([]); });
|
||||
vi.mocked(fs.readdir).mockImplementationOnce(() => held as unknown as ReturnType<typeof fs.readdir>);
|
||||
let finished = false;
|
||||
const pending = inspect().then((result) => { finished = true; return result; });
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(finished).toBe(false);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
expect((await pending).warnings[0].code).toBe("database_backup_missing");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { readdir, readFile, stat } from "node:fs/promises";
|
||||
import type { Stats } from "node:fs";
|
||||
import { basename, join, resolve } from "node:path";
|
||||
|
||||
export type DatabaseBackupHealthWarningCode =
|
||||
@@ -54,20 +55,28 @@ function alertFileCandidates(opts: InspectDatabaseBackupHealthOptions) {
|
||||
].filter((value): value is string => Boolean(value)))];
|
||||
}
|
||||
|
||||
function readLastFailure(alertFiles: string[]) {
|
||||
const failures = alertFiles
|
||||
.filter((alertFile) => existsSync(alertFile))
|
||||
.map((alertFile) => {
|
||||
const stat = statSync(alertFile);
|
||||
const message = readFileSync(alertFile, "utf8").trim().split(/\r?\n/)[0] ||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
||||
}
|
||||
|
||||
async function readLastFailure(alertFiles: string[]) {
|
||||
const failures = (await Promise.all(alertFiles.map(async (alertFile) => {
|
||||
try {
|
||||
const metadata = await stat(alertFile);
|
||||
const message = (await readFile(alertFile, "utf8")).trim().split(/\r?\n/)[0] ||
|
||||
"Database backup failure marker is present.";
|
||||
return {
|
||||
path: alertFile,
|
||||
mtime: new Date(stat.mtimeMs).toISOString(),
|
||||
mtimeMs: stat.mtimeMs,
|
||||
mtime: new Date(metadata.mtimeMs).toISOString(),
|
||||
mtimeMs: metadata.mtimeMs,
|
||||
message,
|
||||
};
|
||||
})
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
})))
|
||||
.filter((failure) => failure !== null)
|
||||
.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
||||
const latest = failures[0];
|
||||
if (!latest) return null;
|
||||
@@ -78,19 +87,35 @@ function readLastFailure(alertFiles: string[]) {
|
||||
};
|
||||
}
|
||||
|
||||
function findLatestBackup(backupDir: string, nowMs: number) {
|
||||
if (!existsSync(backupDir)) return null;
|
||||
|
||||
const candidates = readdirSync(backupDir)
|
||||
.filter((name) => name.endsWith(".sql.gz"))
|
||||
.map((name) => {
|
||||
async function findLatestBackup(backupDir: string, nowMs: number) {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await readdir(backupDir);
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
let latest: { fullPath: string; stat: Stats } | null = null;
|
||||
// Keep bounded parallelism so a retained history neither floods the
|
||||
// filesystem thread pool nor waits for every metadata read sequentially.
|
||||
const archives = names.filter((name) => name.endsWith(".sql.gz"));
|
||||
for (let index = 0; index < archives.length; index += 4) {
|
||||
const batch = await Promise.all(archives.slice(index, index + 4).map(async (name) => {
|
||||
const fullPath = join(backupDir, name);
|
||||
const stat = statSync(fullPath);
|
||||
return { fullPath, name, stat };
|
||||
})
|
||||
.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
||||
|
||||
const latest = candidates[0];
|
||||
try {
|
||||
return { fullPath, stat: await stat(fullPath) };
|
||||
} catch (error) {
|
||||
// Retention can remove a listed backup while its metadata is read.
|
||||
if (isMissing(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}));
|
||||
for (const candidate of batch) {
|
||||
if (candidate && (!latest || candidate.stat.mtimeMs > latest.stat.mtimeMs)) {
|
||||
latest = candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!latest) return null;
|
||||
|
||||
return {
|
||||
@@ -102,9 +127,9 @@ function findLatestBackup(backupDir: string, nowMs: number) {
|
||||
};
|
||||
}
|
||||
|
||||
export function inspectDatabaseBackupHealth(
|
||||
export async function inspectDatabaseBackupHealth(
|
||||
opts: InspectDatabaseBackupHealthOptions,
|
||||
): DatabaseBackupHealthStatus {
|
||||
): Promise<DatabaseBackupHealthStatus> {
|
||||
const warnings: DatabaseBackupHealthWarning[] = [];
|
||||
const now = opts.now ?? new Date();
|
||||
const maxAgeHours = Math.max(1, opts.maxAgeHours);
|
||||
@@ -113,8 +138,8 @@ export function inspectDatabaseBackupHealth(
|
||||
let lastFailure: DatabaseBackupHealthStatus["lastFailure"] = null;
|
||||
|
||||
try {
|
||||
latestBackup = findLatestBackup(opts.backupDir, now.getTime());
|
||||
lastFailure = readLastFailure(alertFileCandidates(opts));
|
||||
latestBackup = await findLatestBackup(opts.backupDir, now.getTime());
|
||||
lastFailure = await readLastFailure(alertFileCandidates(opts));
|
||||
|
||||
if (!latestBackup) {
|
||||
warnings.push({
|
||||
|
||||
Reference in new issue
Block a user