feat(sqlite): inspect offline snapshots with selective evidence (#2271)
Add offline SQLite database/WAL inspection through the shared CLI/MCP. Use compact inventory, selected-table schema, exact ordered columns and bounded row samples while preserving source identity and lossless values. Retain completed Evidence through late cancellation and private-root cleanup failures, bound concurrent inspections, and recheck journal validity after acquisition. Reuse prepared CI runtime artifacts across supported Node lines. Co-authored-by: Y0UW1SH <29498139+Y0UW1SH@users.noreply.github.com> Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
import { access } from "node:fs/promises";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
|
||||
import { ProviderProcessSupervisor } from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
spawnProviderProcessFixture,
|
||||
stopProviderProcessFixture,
|
||||
waitForProviderProcessReady,
|
||||
} from "../../fixtures/providerProcess.js";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
import { createSqliteDatabaseFixture } from "../../fixtures/sqlite/database.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
const createUnavailableProvider = (
|
||||
createRuntime: SqliteDatabaseProvider["createRuntime"],
|
||||
) =>
|
||||
new SqliteDatabaseProvider(
|
||||
{},
|
||||
() => {
|
||||
throw new Error("SQLite worker deliberately unavailable");
|
||||
},
|
||||
createRuntime,
|
||||
);
|
||||
|
||||
const cleanupFixture = async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-cleanup-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root);
|
||||
database.close();
|
||||
const roots: PrivateRuntimeRoot[] = [];
|
||||
let removalAllowed = false;
|
||||
let attempts = 0;
|
||||
const provider = createUnavailableProvider(async () => {
|
||||
const root = await PrivateRuntimeRoot.create({ parent: workspace.root });
|
||||
roots.push(root);
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
attempts += 1;
|
||||
if (!removalAllowed) throw new Error("snapshot removal denied");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await Promise.all(roots.map((root) => root.close()));
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
return {
|
||||
provider,
|
||||
roots,
|
||||
path: database.path,
|
||||
allowRemoval: () => {
|
||||
removalAllowed = true;
|
||||
},
|
||||
attempts: () => attempts,
|
||||
};
|
||||
};
|
||||
|
||||
it("retains failed snapshot owners and blocks new acquisition until retry succeeds", async () => {
|
||||
const fixture = await cleanupFixture();
|
||||
const first = await fixture.provider.inspect({ path: fixture.path });
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
const root = fixture.roots[0];
|
||||
if (root === undefined) throw new Error("Missing owned root");
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
const second = await fixture.provider.inspect({ path: fixture.path });
|
||||
expect(second).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(fixture.roots).toHaveLength(1);
|
||||
expect(fixture.attempts()).toBe(2);
|
||||
fixture.allowRemoval();
|
||||
await fixture.provider.inspect({ path: fixture.path });
|
||||
expect(fixture.roots).toHaveLength(2);
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await fixture.provider.close();
|
||||
});
|
||||
|
||||
it("awaits shared shutdown cleanup and retains failures for a later close", async () => {
|
||||
const fixture = await cleanupFixture();
|
||||
await fixture.provider.inspect({ path: fixture.path });
|
||||
const closed = await Promise.allSettled([
|
||||
fixture.provider.close(),
|
||||
fixture.provider.close(),
|
||||
]);
|
||||
expect(closed.map((result) => result.status)).toEqual([
|
||||
"rejected",
|
||||
"rejected",
|
||||
]);
|
||||
expect(fixture.attempts()).toBe(2);
|
||||
expect(await fixture.provider.inspect({ path: fixture.path })).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
fixture.allowRemoval();
|
||||
await fixture.provider.close();
|
||||
await fixture.provider.close();
|
||||
expect(fixture.attempts()).toBe(3);
|
||||
for (const root of fixture.roots)
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("waits for concurrent acquisitions and releases only owners whose cleanup succeeds", async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-concurrent-cleanup-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root);
|
||||
database.close();
|
||||
const acquired = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
const roots: PrivateRuntimeRoot[] = [];
|
||||
const allowed = new Set<PrivateRuntimeRoot>();
|
||||
const provider = createUnavailableProvider(async () => {
|
||||
const root = await PrivateRuntimeRoot.create({ parent: workspace.root });
|
||||
roots.push(root);
|
||||
if (roots.length === 2) acquired.resolve();
|
||||
await release.promise;
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!allowed.has(root)) throw new Error("snapshot removal denied");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
release.resolve();
|
||||
roots.forEach((root) => allowed.add(root));
|
||||
await provider.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
const inspections = [
|
||||
provider.inspect({ path: database.path }),
|
||||
provider.inspect({ path: database.path }),
|
||||
];
|
||||
await acquired.promise;
|
||||
// Two admitted snapshots occupy capacity even before the worker launches.
|
||||
expect(await provider.inspect({ path: database.path })).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisResourceConstraintError", resource: "capacity" },
|
||||
});
|
||||
expect(roots).toHaveLength(2);
|
||||
expect(
|
||||
await provider.inspect(
|
||||
{ path: database.path },
|
||||
{ signal: AbortSignal.abort() },
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
let settled = false;
|
||||
const closing = provider.close().finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
const rejected = expect(closing).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(settled).toBe(false);
|
||||
release.resolve();
|
||||
await Promise.all(inspections);
|
||||
await rejected;
|
||||
const [first, second] = roots;
|
||||
if (first === undefined || second === undefined)
|
||||
throw new Error("Missing owned roots");
|
||||
allowed.add(first);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupResources: [second.path],
|
||||
});
|
||||
await expect(access(first.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(access(second.path)).resolves.toBeUndefined();
|
||||
allowed.add(second);
|
||||
await provider.close();
|
||||
await expect(access(second.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("retains the snapshot until a failed worker cleanup owner can be stopped", async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-worker-cleanup-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root);
|
||||
database.close();
|
||||
const child = spawnProviderProcessFixture("graceful");
|
||||
let workerRemovalAllowed = false;
|
||||
let rootRemovalAllowed = false;
|
||||
let workerAttempts = 0;
|
||||
let rootAttempts = 0;
|
||||
const roots: PrivateRuntimeRoot[] = [];
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: async () => {
|
||||
workerAttempts += 1;
|
||||
if (!workerRemovalAllowed)
|
||||
return { cleaned: false, reason: "SQLite worker cleanup denied" };
|
||||
await stopProviderProcessFixture(child);
|
||||
return { cleaned: true, signaled: true };
|
||||
},
|
||||
});
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
{},
|
||||
async (spawn) => {
|
||||
const stopped = await supervisor.stop();
|
||||
if (stopped.status !== "incomplete")
|
||||
throw new Error("Expected retained worker");
|
||||
throw new OwnedCommandFailure(
|
||||
"process",
|
||||
"SQLite worker cleanup failed",
|
||||
supervisor.snapshot(),
|
||||
stopped.reason,
|
||||
undefined,
|
||||
[spawn.runId, spawn.cwd ?? ""],
|
||||
supervisor,
|
||||
);
|
||||
},
|
||||
async () => {
|
||||
const root = await PrivateRuntimeRoot.create({ parent: workspace.root });
|
||||
roots.push(root);
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
rootAttempts += 1;
|
||||
if (!rootRemovalAllowed)
|
||||
throw new Error("SQLite snapshot removal denied");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
workerRemovalAllowed = true;
|
||||
rootRemovalAllowed = true;
|
||||
await supervisor.stop();
|
||||
await provider.close();
|
||||
await Promise.all(roots.map((root) => root.close()));
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
await waitForProviderProcessReady(child);
|
||||
expect(await provider.inspect({ path: database.path })).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
// The snapshot cannot be removed while its worker may still use it.
|
||||
expect(rootAttempts).toBe(0);
|
||||
const root = roots[0];
|
||||
if (root === undefined) throw new Error("Missing retained snapshot");
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
expect(await provider.inspect({ path: database.path })).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(roots).toHaveLength(1);
|
||||
expect(workerAttempts).toBe(2);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
expect(rootAttempts).toBe(0);
|
||||
workerRemovalAllowed = true;
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupResources: [root.path],
|
||||
});
|
||||
expect(child.signalCode).toBe("SIGKILL");
|
||||
expect(workerAttempts).toBe(4);
|
||||
expect(rootAttempts).toBe(1);
|
||||
rootRemovalAllowed = true;
|
||||
await provider.close();
|
||||
expect(workerAttempts).toBe(4);
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
import { Cli } from "incur";
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { SqliteDatabaseService } from "../../../src/application/sqlite/SqliteDatabaseService.js";
|
||||
import { registerSqliteCommands } from "../../../src/cli/sqliteCommands.js";
|
||||
import { createSqliteDatabaseService } from "../../../src/composition/sqlite.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { createSqliteDatabaseFixture } from "../../fixtures/sqlite/database.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
const descriptorCleanup = vi.hoisted(() => ({
|
||||
path: "",
|
||||
denied: false,
|
||||
invalidate: false,
|
||||
attempts: 0,
|
||||
handles: [] as FileHandle[],
|
||||
readFailure: undefined as Error | undefined,
|
||||
onOpen: undefined as (() => void) | undefined,
|
||||
}));
|
||||
|
||||
vi.mock("../../../src/composition/sqlite.js", () => ({
|
||||
createSqliteDatabaseService: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...filesystem,
|
||||
open: async (...args: Parameters<typeof filesystem.open>) => {
|
||||
const handle = await filesystem.open(...args);
|
||||
if (args[0] === descriptorCleanup.path) {
|
||||
descriptorCleanup.handles.push(handle);
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
// FileHandle.close also asks attached streams to close the invalidated handle.
|
||||
if (handle.fd < 0) {
|
||||
await close();
|
||||
return;
|
||||
}
|
||||
descriptorCleanup.attempts += 1;
|
||||
if (descriptorCleanup.denied) {
|
||||
if (descriptorCleanup.invalidate) await close();
|
||||
throw new Error("injected SQLite descriptor close failure");
|
||||
}
|
||||
await close();
|
||||
};
|
||||
if (descriptorCleanup.readFailure !== undefined)
|
||||
vi.spyOn(handle, "stat").mockRejectedValue(
|
||||
descriptorCleanup.readFailure,
|
||||
);
|
||||
descriptorCleanup.onOpen?.();
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const fixture = async (
|
||||
member: "database" | "WAL" | "journal" | "reply",
|
||||
invalidate = false,
|
||||
) => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-descriptor-cleanup-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root, true);
|
||||
const path =
|
||||
member === "database"
|
||||
? database.path
|
||||
: member === "WAL"
|
||||
? database.walPath
|
||||
: member === "journal"
|
||||
? `${database.path}-journal`
|
||||
: "";
|
||||
if (member === "journal") await writeFile(path, Buffer.alloc(28));
|
||||
const roots: PrivateRuntimeRoot[] = [];
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
process.env,
|
||||
(spawn) => {
|
||||
if (member !== "reply")
|
||||
throw new Error("SQLite worker deliberately unavailable");
|
||||
return spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: spawn.arguments.map((argument, index) =>
|
||||
index === 1
|
||||
? fileURLToPath(
|
||||
new URL(
|
||||
"../../../dist/sqlite/SqliteDatabaseWorker.js",
|
||||
import.meta.url,
|
||||
),
|
||||
)
|
||||
: argument,
|
||||
),
|
||||
});
|
||||
},
|
||||
async () => {
|
||||
const root = await PrivateRuntimeRoot.create({ parent: workspace.root });
|
||||
if (member === "reply")
|
||||
descriptorCleanup.path = join(root.path, "reply.json");
|
||||
roots.push(root);
|
||||
return root;
|
||||
},
|
||||
);
|
||||
descriptorCleanup.path = path;
|
||||
descriptorCleanup.denied = true;
|
||||
descriptorCleanup.invalidate = invalidate;
|
||||
descriptorCleanup.attempts = 0;
|
||||
descriptorCleanup.handles = [];
|
||||
descriptorCleanup.readFailure = undefined;
|
||||
descriptorCleanup.onOpen = undefined;
|
||||
onTestFinished(async () => {
|
||||
descriptorCleanup.denied = false;
|
||||
try {
|
||||
await provider.close();
|
||||
} catch (cause) {
|
||||
if (!invalidate) throw cause;
|
||||
}
|
||||
for (const handle of descriptorCleanup.handles) await handle.close();
|
||||
descriptorCleanup.path = "";
|
||||
database.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
return { provider, roots, path, database };
|
||||
};
|
||||
|
||||
const serveInspection = async (
|
||||
provider: SqliteDatabaseProvider,
|
||||
path: string,
|
||||
) => {
|
||||
const previousExitCode = process.exitCode;
|
||||
onTestFinished(() => {
|
||||
process.exitCode = previousExitCode;
|
||||
});
|
||||
vi.mocked(createSqliteDatabaseService).mockReturnValue(
|
||||
new SqliteDatabaseService(provider),
|
||||
);
|
||||
const cli = Cli.create("rea-sqlite-cleanup-test", { sync: false });
|
||||
registerSqliteCommands(cli, silentLogger, {});
|
||||
let stdout = "";
|
||||
await cli.serve(["inspect-sqlite-database", path, "--json"], {
|
||||
env: {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
});
|
||||
return { output: JSON.parse(stdout) as unknown, exitCode: process.exitCode };
|
||||
};
|
||||
|
||||
it.each(["database", "WAL", "journal"] as const)(
|
||||
"retains a failed %s descriptor and retries it at shutdown",
|
||||
async (member) => {
|
||||
const selected = await fixture(member);
|
||||
const first = await selected.provider.inspect({
|
||||
path: selected.database.path,
|
||||
});
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [expect.stringContaining(selected.path)],
|
||||
},
|
||||
});
|
||||
const handle = descriptorCleanup.handles[0];
|
||||
if (handle === undefined)
|
||||
throw new Error("Expected owned source descriptor");
|
||||
expect(handle.fd).toBeGreaterThanOrEqual(0);
|
||||
const blocked = await selected.provider.inspect({
|
||||
path: selected.database.path,
|
||||
});
|
||||
expect(blocked).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(selected.roots).toHaveLength(1);
|
||||
await expect(selected.provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
expect(descriptorCleanup.attempts).toBe(3);
|
||||
descriptorCleanup.denied = false;
|
||||
await selected.provider.close();
|
||||
expect(descriptorCleanup.attempts).toBe(4);
|
||||
expect(handle.fd).toBe(-1);
|
||||
for (const root of selected.roots)
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["EACCES", "EPERM"])(
|
||||
"retains the original %s inspection diagnostics through CLI shutdown",
|
||||
async (code) => {
|
||||
const selected = await fixture("database");
|
||||
descriptorCleanup.readFailure = Object.assign(
|
||||
new Error("injected source read denial"),
|
||||
{ code },
|
||||
);
|
||||
const result = await serveInspection(
|
||||
selected.provider,
|
||||
selected.database.path,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 1,
|
||||
output: {
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
resources: [expect.stringContaining(selected.path)],
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
details: {
|
||||
diagnostics: {
|
||||
previous_error: {
|
||||
code: "access_denied",
|
||||
details: { path: selected.path, system_code: code },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(descriptorCleanup.attempts).toBe(2);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains cancellation diagnostics and the interrupt exit code through CLI shutdown", async () => {
|
||||
const selected = await fixture("database");
|
||||
descriptorCleanup.onOpen = () => {
|
||||
const interrupt = process.listeners("SIGINT").at(-1);
|
||||
if (interrupt === undefined)
|
||||
throw new Error("Missing CLI interrupt handler");
|
||||
interrupt("SIGINT");
|
||||
};
|
||||
const result = await serveInspection(
|
||||
selected.provider,
|
||||
selected.database.path,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 130,
|
||||
output: {
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
resources: [expect.stringContaining(selected.path)],
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
details: {
|
||||
diagnostics: { previous_error: { code: "cancelled" } },
|
||||
},
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(descriptorCleanup.attempts).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("retains reply-read cancellation and retries the failed reply descriptor close", async () => {
|
||||
const selected = await fixture("reply");
|
||||
const controller = new AbortController();
|
||||
descriptorCleanup.onOpen = () =>
|
||||
controller.abort(new Error("requested cancellation during reply read"));
|
||||
const result = await selected.provider.inspect(
|
||||
{ path: selected.database.path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected cancelled reply read");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
execution_failure: "cancelled",
|
||||
resources: [expect.stringContaining(descriptorCleanup.path)],
|
||||
captured_output: {
|
||||
stdout: "",
|
||||
stderr: expect.any(String),
|
||||
truncated: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const handle = descriptorCleanup.handles[0];
|
||||
if (handle === undefined) throw new Error("Expected owned reply descriptor");
|
||||
expect(handle.fd).toBeGreaterThanOrEqual(0);
|
||||
await expect(selected.provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
descriptorCleanup.denied = false;
|
||||
await selected.provider.close();
|
||||
expect(handle.fd).toBe(-1);
|
||||
for (const root of selected.roots)
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("retries source cleanup before admitting another snapshot", async () => {
|
||||
const selected = await fixture("database");
|
||||
await selected.provider.inspect({ path: selected.database.path });
|
||||
const first = descriptorCleanup.handles[0];
|
||||
if (first === undefined) throw new Error("Expected source descriptor");
|
||||
descriptorCleanup.denied = false;
|
||||
const resumed = await selected.provider.inspect({
|
||||
path: selected.database.path,
|
||||
});
|
||||
expect(selected.roots).toHaveLength(2);
|
||||
expect(first.fd).toBe(-1);
|
||||
if (resumed.ok) throw new Error("The worker is deliberately unavailable");
|
||||
expect(resumed.error.cleanupIncomplete).toBe(false);
|
||||
await selected.provider.close();
|
||||
});
|
||||
|
||||
it("keeps an invalidated descriptor close failure unconfirmed across retries", async () => {
|
||||
const selected = await fixture("journal", true);
|
||||
const first = await selected.provider.inspect({
|
||||
path: selected.database.path,
|
||||
});
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(descriptorCleanup.handles[0]?.fd).toBe(-1);
|
||||
descriptorCleanup.denied = false;
|
||||
await expect(selected.provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
await expect(selected.provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
expect(descriptorCleanup.attempts).toBe(1);
|
||||
});
|
||||
|
||||
it.each(["EACCES", "EPERM"])(
|
||||
"preserves %s read diagnostics alongside a failed descriptor close",
|
||||
async (code) => {
|
||||
const selected = await fixture("database");
|
||||
descriptorCleanup.readFailure = Object.assign(
|
||||
new Error("injected source read denial"),
|
||||
{ code },
|
||||
);
|
||||
const result = await selected.provider.inspect({
|
||||
path: selected.database.path,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: { previous_error: { code: "access_denied" } },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["database", "WAL", "journal"] as const)(
|
||||
"preserves caller cancellation alongside a failed %s descriptor close",
|
||||
async (member) => {
|
||||
const selected = await fixture(member);
|
||||
const controller = new AbortController();
|
||||
descriptorCleanup.onOpen = () =>
|
||||
controller.abort(new Error("requested caller cancellation"));
|
||||
const result = await selected.provider.inspect(
|
||||
{ path: selected.database.path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: { previous_error: { code: "cancelled" } },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,328 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { expect, it as nativeTest, onTestFinished } from "vitest";
|
||||
import { SQLITE_NATIVE_LIMITS_AVAILABLE } from "../../fixtures/sqlite/database.js";
|
||||
import { inspectSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseInspection.js";
|
||||
import { SqliteInspectionFailure } from "../../../src/sqlite/SqliteDatabaseLimits.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
const it = nativeTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE);
|
||||
|
||||
const createDatabase = async (sql: string): Promise<string> => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-expansion-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("private.db");
|
||||
const producer = new DatabaseSync(path);
|
||||
try {
|
||||
producer.exec(sql);
|
||||
} finally {
|
||||
producer.close();
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
it("preserves negative-zero REAL values through JSON separately from positive and integer zero", async () => {
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE numbers(value);
|
||||
INSERT INTO numbers VALUES (-0.0), (0.0), (0), (5e-324), (-5e-324);
|
||||
`);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "numbers",
|
||||
});
|
||||
expect(JSON.parse(JSON.stringify(result.rows))).toMatchObject({
|
||||
values: [
|
||||
[{ type: "real", value: "-0" }],
|
||||
[{ type: "real", value: 0 }],
|
||||
[{ type: "integer", value: "0" }],
|
||||
[{ type: "real", value: Number.MIN_VALUE }],
|
||||
[{ type: "real", value: -Number.MIN_VALUE }],
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["table", "view"] as const)(
|
||||
"inspects columns when a %s shadows the table-valued PRAGMA name",
|
||||
async (kind) => {
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE "selected "" table" ("0" TEXT, "" INTEGER);
|
||||
INSERT INTO "selected "" table" VALUES ('retained', 7);
|
||||
${kind === "table" ? "CREATE TABLE pragma_table_xinfo(value TEXT)" : "CREATE VIEW pragma_table_xinfo AS SELECT 1"};
|
||||
`);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: 'selected " table',
|
||||
});
|
||||
expect(result.schema.tables).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'selected " table',
|
||||
columns: [
|
||||
expect.objectContaining({ name: "0", declared_type: "TEXT" }),
|
||||
expect.objectContaining({ name: "", declared_type: "INTEGER" }),
|
||||
],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.rows).toMatchObject({
|
||||
columns: ["0", ""],
|
||||
values: [
|
||||
[
|
||||
{ type: "text", value: "retained" },
|
||||
{ type: "integer", value: "7" },
|
||||
],
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([6, 9])(
|
||||
"preserves a %i MiB schema statement without expanding its native record",
|
||||
async (mebibytes) => {
|
||||
const trigger = `CREATE TRIGGER large_definition AFTER INSERT ON records BEGIN /*${"x".repeat(mebibytes * 1024 * 1024)}*/ SELECT 1; END`;
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE records(value TEXT);
|
||||
${trigger};
|
||||
`);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
schema_scope: "database",
|
||||
});
|
||||
expect(result.schema.triggers).toEqual([
|
||||
{ name: "large_definition", table: "records", sql: trigger },
|
||||
]);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(
|
||||
16 * 1024 * 1024,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("inspects a large schema identifier without expanding a native sort record", async () => {
|
||||
const name = "x".repeat(4 * 1024 * 1024);
|
||||
const sql = `CREATE TABLE "${name}" (value TEXT)`;
|
||||
const path = await createDatabase(sql);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
schema_scope: "database",
|
||||
});
|
||||
expect(result.schema.tables).toMatchObject([
|
||||
{ name, sql, columns: [{ name: "value", declared_type: "TEXT" }] },
|
||||
]);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(
|
||||
16 * 1024 * 1024,
|
||||
);
|
||||
});
|
||||
|
||||
it("accounts for JSON escape expansion of a stored declaration in the reply limit", async () => {
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE records(value TEXT);
|
||||
CREATE TRIGGER expanded AFTER INSERT ON records BEGIN /*${"\u0001".repeat(3 * 1024 * 1024)}*/ SELECT 1; END;
|
||||
`);
|
||||
expect(() =>
|
||||
inspectSqliteDatabaseSnapshot(path, { path, schema_scope: "database" }),
|
||||
).toThrowError(expect.objectContaining({ reason: "output-limit" }));
|
||||
const inventory = inspectSqliteDatabaseSnapshot(path, { path });
|
||||
expect(inventory.schema.triggers).toEqual([
|
||||
{ name: "expanded", table: "records" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["UTF-8", "UTF-16le", "UTF-16be"])(
|
||||
"preserves exact %s schema text when decoding native bytes",
|
||||
async (encoding) => {
|
||||
const sql = 'CREATE TABLE "\uFEFFé𝄞" ("列" TEXT DEFAULT \'\uFEFFvalue\')';
|
||||
const path = await createDatabase(`PRAGMA encoding='${encoding}'; ${sql}`);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
schema_scope: "database",
|
||||
});
|
||||
expect(result.schema.tables).toMatchObject([
|
||||
{
|
||||
name: "\uFEFFé𝄞",
|
||||
sql,
|
||||
columns: [{ name: "列", default_sql: "'\uFEFFvalue'" }],
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("counts schema names once when enforcing the complete reply budget", async () => {
|
||||
const names = Array.from(
|
||||
{ length: 48 },
|
||||
(_, index) => `${index}_${"x".repeat(128 * 1024)}`,
|
||||
);
|
||||
const path = await createDatabase(
|
||||
names.map((name) => `CREATE TABLE "${name}" (value TEXT);`).join("\n"),
|
||||
);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
schema_scope: "database",
|
||||
});
|
||||
expect(result.schema.tables).toHaveLength(names.length);
|
||||
expect(result.schema.tables.map((table) => table.name)).toEqual(
|
||||
expect.arrayContaining(names),
|
||||
);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(
|
||||
16 * 1024 * 1024,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed schema bytes instead of returning replacement text", async () => {
|
||||
const path = await createDatabase(
|
||||
"CREATE TABLE records(value TEXT /*schema-marker*/)",
|
||||
);
|
||||
const bytes = await readFile(path);
|
||||
const marker = bytes.indexOf(Buffer.from("schema-marker"));
|
||||
if (marker < 0) throw new Error("Schema marker missing");
|
||||
bytes[marker] = 0xff;
|
||||
await writeFile(path, bytes);
|
||||
expect(() =>
|
||||
inspectSqliteDatabaseSnapshot(path, { path, schema_scope: "database" }),
|
||||
).toThrow(/schema sql contains malformed UTF-8 text/);
|
||||
});
|
||||
|
||||
it("refuses possible shadow tables when their virtual module is unavailable", async () => {
|
||||
const path = await createDatabase(`
|
||||
CREATE VIRTUAL TABLE "SeArCh_É" USING fts5(body);
|
||||
INSERT INTO "SeArCh_É" VALUES ('retained');
|
||||
CREATE TABLE "search_É_manual" (value TEXT);
|
||||
CREATE TABLE "search_é_manual" (value TEXT);
|
||||
INSERT INTO "search_é_manual" VALUES ('distinct Unicode name');
|
||||
CREATE TABLE "SeArCh_Élite" (value TEXT);
|
||||
`);
|
||||
const bytes = await readFile(path);
|
||||
const declaration = bytes.indexOf(Buffer.from("USING fts5"));
|
||||
if (declaration < 0) throw new Error("Virtual declaration missing");
|
||||
bytes.write("zzzz", declaration + Buffer.byteLength("USING "), "utf8");
|
||||
await writeFile(path, bytes);
|
||||
|
||||
for (const table of ["SeArCh_É_data", "search_É_manual"])
|
||||
expect(() => inspectSqliteDatabaseSnapshot(path, { path, table })).toThrow(
|
||||
/cannot determine.*shadow table/i,
|
||||
);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "search_é_manual",
|
||||
schema_scope: "database",
|
||||
});
|
||||
expect(result.schema.tables).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ name: "SeArCh_É", kind: "virtual" }),
|
||||
expect.objectContaining({ name: "SeArCh_É_data", kind: "unknown" }),
|
||||
expect.objectContaining({ name: "search_É_manual", kind: "unknown" }),
|
||||
expect.objectContaining({ name: "search_é_manual", kind: "table" }),
|
||||
expect.objectContaining({ name: "SeArCh_Élite", kind: "table" }),
|
||||
]),
|
||||
);
|
||||
expect(result.rows).toMatchObject({
|
||||
values: [[{ type: "text", value: "distinct Unicode name" }]],
|
||||
});
|
||||
expect(result.limitations.join("\n")).toMatch(/shadow table/i);
|
||||
});
|
||||
|
||||
it("rejects an oversized generated cell through SQLite's native value limit", async () => {
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE records (
|
||||
id INTEGER,
|
||||
payload BLOB GENERATED ALWAYS AS (zeroblob(72 * 1024 * 1024)) VIRTUAL
|
||||
);
|
||||
INSERT INTO records(id) VALUES (1);
|
||||
`);
|
||||
try {
|
||||
inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "records",
|
||||
row_limit: 1,
|
||||
});
|
||||
throw new Error("An oversized generated cell must not be projected");
|
||||
} catch (cause: unknown) {
|
||||
expect(cause).toMatchObject({
|
||||
code: "ERR_SQLITE_ERROR",
|
||||
errcode: 18,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("reports additional rows without expanding an unselected generated cell", async () => {
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE records (
|
||||
id INTEGER,
|
||||
payload BLOB GENERATED ALWAYS AS (
|
||||
CASE WHEN id = 2 THEN zeroblob(72 * 1024 * 1024) ELSE X'01' END
|
||||
) VIRTUAL
|
||||
);
|
||||
INSERT INTO records(id) VALUES (1), (2);
|
||||
`);
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "records",
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(result.rows).toMatchObject({
|
||||
columns: ["id", "payload"],
|
||||
values: [
|
||||
[
|
||||
{ type: "integer", value: "1" },
|
||||
{ type: "blob", hex: "01" },
|
||||
],
|
||||
],
|
||||
returned_rows: 1,
|
||||
truncated: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects the combined representation of individually small generated cells", async () => {
|
||||
const columns = Array.from(
|
||||
{ length: 6 },
|
||||
(_, index) =>
|
||||
`payload_${String(index)} BLOB GENERATED ALWAYS AS (zeroblob(2 * 1024 * 1024)) VIRTUAL`,
|
||||
);
|
||||
const path = await createDatabase(`
|
||||
CREATE TABLE records (id INTEGER, ${columns.join(", ")});
|
||||
INSERT INTO records(id) VALUES (1);
|
||||
`);
|
||||
try {
|
||||
inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "records",
|
||||
row_limit: 1,
|
||||
});
|
||||
throw new Error(
|
||||
"Aggregate row expansion must be rejected before projection",
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
expect(cause).toBeInstanceOf(SqliteInspectionFailure);
|
||||
expect(cause).toMatchObject({ reason: "output-limit" });
|
||||
}
|
||||
});
|
||||
|
||||
it("samples above 1000 rows and safe integer limits within the byte budget", async () => {
|
||||
const path = await createDatabase(`CREATE TABLE items(value INTEGER);
|
||||
WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers WHERE value < 1002)
|
||||
INSERT INTO items SELECT value FROM numbers;`);
|
||||
for (const row_limit of [1001, Number.MAX_SAFE_INTEGER]) {
|
||||
const result = inspectSqliteDatabaseSnapshot(path, {
|
||||
path,
|
||||
table: "items",
|
||||
row_limit,
|
||||
});
|
||||
expect(result.rows).toMatchObject({
|
||||
row_limit,
|
||||
returned_rows: Math.min(row_limit, 1002),
|
||||
truncated: row_limit < 1002,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
nativeTest.skipIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"rejects a runtime without native limits before querying the snapshot",
|
||||
async () => {
|
||||
const path = await createDatabase("CREATE TABLE items(value INTEGER)");
|
||||
expect(() =>
|
||||
inspectSqliteDatabaseSnapshot(path, { path, schema_scope: "database" }),
|
||||
).toThrow("DatabaseSync.limits");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,595 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, lstat, readFile, symlink, writeFile } from "node:fs/promises";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { promisify } from "node:util";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it as nativeTest, onTestFinished } from "vitest";
|
||||
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
import {
|
||||
createSqliteDatabaseFixture,
|
||||
SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
} from "../../fixtures/sqlite/database.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
const it = nativeTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE);
|
||||
|
||||
const workerUrl = new URL(
|
||||
"../../../dist/sqlite/SqliteDatabaseWorker.js",
|
||||
import.meta.url,
|
||||
);
|
||||
const createProvider = () =>
|
||||
new SqliteDatabaseProvider(process.env, (spawn) =>
|
||||
spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: spawn.arguments.map((argument, index) =>
|
||||
index === 1 ? fileURLToPath(workerUrl) : argument,
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const createFixture = async (wal = false) => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-boundary-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root, wal);
|
||||
if (!wal) database.close();
|
||||
onTestFinished(async () => {
|
||||
if (wal) database.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
return { workspace, database };
|
||||
};
|
||||
|
||||
const expectPrivateRootRemoved = (path: string) =>
|
||||
expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
it.each(["late-cancellation", "cleanup-failure"])(
|
||||
"preserves completed native-worker observations across %s",
|
||||
async (scenario) => {
|
||||
const { workspace, database } = await createFixture();
|
||||
const original = await readFile(database.path);
|
||||
const controller = new AbortController();
|
||||
let cleanupAllowed = false;
|
||||
let root: PrivateRuntimeRoot | undefined;
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
process.env,
|
||||
(spawn) =>
|
||||
spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: spawn.arguments.map((argument, index) =>
|
||||
index === 1 ? fileURLToPath(workerUrl) : argument,
|
||||
),
|
||||
}),
|
||||
async () => {
|
||||
root = await PrivateRuntimeRoot.create({ parent: workspace.root });
|
||||
const acquired = root;
|
||||
return {
|
||||
path: acquired.path,
|
||||
close: async () => {
|
||||
if (scenario === "late-cancellation") controller.abort();
|
||||
else if (!cleanupAllowed)
|
||||
throw new Error("Completed snapshot cleanup denied");
|
||||
await acquired.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspect(
|
||||
{ path: database.path, table: "records", columns: ["id"], row_limit: 1 },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (scenario === "late-cancellation") {
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { result: { rows: { columns: ["id"], returned_rows: 1 } } },
|
||||
});
|
||||
} else {
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
partialObservation: {
|
||||
operation: "inspect_sqlite_database",
|
||||
confidence: "observed",
|
||||
subject: {
|
||||
local_path: database.path,
|
||||
digest: { sha256: digestForTest(original) },
|
||||
},
|
||||
parameters: {
|
||||
path: database.path,
|
||||
table: "records",
|
||||
columns: ["id"],
|
||||
row_limit: 1,
|
||||
},
|
||||
normalized_result: { rows: { columns: ["id"], returned_rows: 1 } },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (root === undefined) throw new Error("Missing retained root");
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
await expectPrivateRootRemoved(root.path);
|
||||
}
|
||||
expect(await readFile(database.path)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
const digestForTest = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
it("inspects committed WAL schema and rows while preserving every source artifact", async () => {
|
||||
const { database } = await createFixture(true);
|
||||
const paths = [database.path, database.walPath, `${database.path}-shm`];
|
||||
const original = await Promise.all(
|
||||
paths.map(async (path) => ({
|
||||
path,
|
||||
bytes: await readFile(path),
|
||||
stat: await lstat(path),
|
||||
})),
|
||||
);
|
||||
const result = await createProvider().inspect({
|
||||
path: database.path,
|
||||
table: "records",
|
||||
schema_scope: "database",
|
||||
row_limit: 1,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const main = original[0];
|
||||
const wal = original[1];
|
||||
if (main === undefined || wal === undefined)
|
||||
throw new Error("Missing fixture identity");
|
||||
expect(result.value.result).toMatchObject({
|
||||
artifact: {
|
||||
path: database.path,
|
||||
bytes: main.bytes.length,
|
||||
sha256: createHash("sha256").update(main.bytes).digest("hex"),
|
||||
},
|
||||
wal: {
|
||||
path: database.walPath,
|
||||
bytes: wal.bytes.length,
|
||||
sha256: createHash("sha256").update(wal.bytes).digest("hex"),
|
||||
},
|
||||
schema: {
|
||||
completeness: "complete",
|
||||
tables: expect.arrayContaining([
|
||||
{
|
||||
name: "records",
|
||||
sql: expect.stringContaining("CREATE TABLE"),
|
||||
root_page: expect.any(Number),
|
||||
kind: "table",
|
||||
without_rowid: false,
|
||||
strict: false,
|
||||
column_count: 7,
|
||||
columns_completeness: "complete",
|
||||
columns: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "generated_value", hidden: 2 }),
|
||||
]),
|
||||
},
|
||||
]),
|
||||
indexes: [
|
||||
expect.objectContaining({ name: "records_text", table: "records" }),
|
||||
],
|
||||
views: [
|
||||
{
|
||||
name: "record_names",
|
||||
sql: expect.stringContaining("SELECT text_value"),
|
||||
},
|
||||
],
|
||||
triggers: [
|
||||
{
|
||||
name: "records_insert",
|
||||
table: "records",
|
||||
sql: expect.stringContaining("AFTER INSERT"),
|
||||
},
|
||||
],
|
||||
},
|
||||
rows: {
|
||||
table: "records",
|
||||
returned_rows: 1,
|
||||
truncated: true,
|
||||
row_limit: 1,
|
||||
order: "unspecified",
|
||||
},
|
||||
});
|
||||
for (const artifact of original) {
|
||||
expect(await readFile(artifact.path)).toEqual(artifact.bytes);
|
||||
const after = await lstat(artifact.path);
|
||||
expect({
|
||||
ino: after.ino,
|
||||
size: after.size,
|
||||
mtimeMs: after.mtimeMs,
|
||||
ctimeMs: after.ctimeMs,
|
||||
}).toEqual({
|
||||
ino: artifact.stat.ino,
|
||||
size: artifact.stat.size,
|
||||
mtimeMs: artifact.stat.mtimeMs,
|
||||
ctimeMs: artifact.stat.ctimeMs,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves SQLite integer, binary, nonfinite, null, and text byte values", async () => {
|
||||
const { database } = await createFixture();
|
||||
const result = await createProvider().inspect({
|
||||
path: database.path,
|
||||
table: "records",
|
||||
row_limit: 10,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toMatchObject({
|
||||
wal: null,
|
||||
rows: {
|
||||
columns: [
|
||||
"id",
|
||||
"integer_value",
|
||||
"blob_value",
|
||||
"real_value",
|
||||
"nullable_value",
|
||||
"text_value",
|
||||
"generated_value",
|
||||
],
|
||||
returned_rows: 3,
|
||||
truncated: false,
|
||||
values: [
|
||||
[
|
||||
{ type: "integer", value: "1" },
|
||||
{ type: "integer", value: "9223372036854775807" },
|
||||
{ type: "blob", hex: "001fefff" },
|
||||
{ type: "real", value: "Infinity" },
|
||||
{ type: "null" },
|
||||
{
|
||||
type: "text",
|
||||
value: "first é\0value",
|
||||
bytes_hex: Buffer.from("first é\0value").toString("hex"),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
value: "integer",
|
||||
bytes_hex: Buffer.from("integer").toString("hex"),
|
||||
},
|
||||
],
|
||||
[
|
||||
{ type: "integer", value: "2" },
|
||||
{ type: "integer", value: "-9223372036854775808" },
|
||||
{ type: "blob", hex: "" },
|
||||
{ type: "real", value: "-Infinity" },
|
||||
{
|
||||
type: "text",
|
||||
value: "present",
|
||||
bytes_hex: Buffer.from("present").toString("hex"),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
value: "second",
|
||||
bytes_hex: Buffer.from("second").toString("hex"),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
value: "integer",
|
||||
bytes_hex: Buffer.from("integer").toString("hex"),
|
||||
},
|
||||
],
|
||||
[
|
||||
{ type: "integer", value: "3" },
|
||||
{ type: "integer", value: "0" },
|
||||
{ type: "blob", hex: "ff" },
|
||||
{ type: "real", value: 1.25 },
|
||||
{ type: "null" },
|
||||
{ type: "text", bytes_hex: "ff00c0af" },
|
||||
{
|
||||
type: "text",
|
||||
value: "integer",
|
||||
bytes_hex: Buffer.from("integer").toString("hex"),
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(() => JSON.stringify(result.value.result)).not.toThrow();
|
||||
});
|
||||
|
||||
it("selects an exact quoted table and refuses to execute table input as SQL", async () => {
|
||||
const { database } = await createFixture();
|
||||
const provider = createProvider();
|
||||
const selected = await provider.inspect({
|
||||
path: database.path,
|
||||
table: database.quotedTable,
|
||||
row_limit: 1,
|
||||
});
|
||||
if (!selected.ok) throw selected.error;
|
||||
expect(selected.value.result).toMatchObject({
|
||||
rows: {
|
||||
table: database.quotedTable,
|
||||
columns: ["__proto__"],
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "exact selected table",
|
||||
bytes_hex: Buffer.from("exact selected table").toString("hex"),
|
||||
},
|
||||
],
|
||||
],
|
||||
returned_rows: 1,
|
||||
truncated: false,
|
||||
},
|
||||
});
|
||||
const unknown = await provider.inspect({
|
||||
path: database.path,
|
||||
table: 'records"; DROP TABLE records;--',
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(unknown).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
const after = await provider.inspect({
|
||||
path: database.path,
|
||||
table: "records",
|
||||
row_limit: 10,
|
||||
});
|
||||
if (!after.ok) throw after.error;
|
||||
expect(after.value.result).toMatchObject({ rows: { returned_rows: 3 } });
|
||||
});
|
||||
|
||||
it("does not execute views when selecting rows", async () => {
|
||||
const { database } = await createFixture();
|
||||
const result = await createProvider().inspect({
|
||||
path: database.path,
|
||||
table: "record_names",
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects malformed databases without altering the selected file", async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-invalid-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = await workspace.write(
|
||||
"not-a-database.db",
|
||||
"selected non-SQLite bytes",
|
||||
);
|
||||
const bytes = await readFile(path);
|
||||
const result = await createProvider().inspect({ path });
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
});
|
||||
|
||||
nativeTest.runIf(process.platform !== "win32")(
|
||||
"rejects a symlink database",
|
||||
async () => {
|
||||
const { database, workspace } = await createFixture();
|
||||
const alias = workspace.path("alias.db");
|
||||
await symlink(database.path, alias);
|
||||
const provider = createProvider();
|
||||
expect(await provider.inspect({ path: alias })).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
nativeTest(
|
||||
"rejects an actual open rollback transaction without changing its journal",
|
||||
async () => {
|
||||
const { database } = await createFixture();
|
||||
const writer = new DatabaseSync(database.path);
|
||||
writer.exec(
|
||||
"BEGIN IMMEDIATE; INSERT INTO records(id, text_value) VALUES (4, 'uncommitted')",
|
||||
);
|
||||
try {
|
||||
const main = await readFile(database.path);
|
||||
const journalPath = `${database.path}-journal`;
|
||||
const journal = await readFile(journalPath);
|
||||
expect(journal.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
await createProvider().inspect({ path: database.path }),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(await readFile(database.path)).toEqual(main);
|
||||
expect(await readFile(journalPath)).toEqual(journal);
|
||||
} finally {
|
||||
writer.exec("ROLLBACK");
|
||||
writer.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
nativeTest.runIf(process.platform !== "win32")(
|
||||
"rejects FIFO input without waiting for a writer",
|
||||
async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-fifo-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("database.fifo");
|
||||
await promisify(execFile)("mkfifo", [path]);
|
||||
const result = await createProvider().inspect({ path });
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
nativeTest(
|
||||
"honors a cancelled caller before opening the database",
|
||||
async () => {
|
||||
const { database } = await createFixture();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect(
|
||||
await createProvider().inspect(
|
||||
{ path: database.path },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
|
||||
},
|
||||
);
|
||||
|
||||
nativeTest(
|
||||
"removes an acquired private root when cancelled before snapshot creation",
|
||||
async () => {
|
||||
const { database } = await createFixture();
|
||||
const controller = new AbortController();
|
||||
let ownedRoot = "";
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
{},
|
||||
() => {
|
||||
throw new Error("Cancelled request must not launch SQLite");
|
||||
},
|
||||
async () => {
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-sqlite-cancel-root-",
|
||||
});
|
||||
ownedRoot = root.path;
|
||||
controller.abort();
|
||||
return root;
|
||||
},
|
||||
);
|
||||
expect(
|
||||
await provider.inspect(
|
||||
{ path: database.path },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
|
||||
await expectPrivateRootRemoved(ownedRoot);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["UTF-8", "UTF-16le", "UTF-16be"] as const)(
|
||||
"preserves %s text, a leading BOM and empty table selection",
|
||||
async (encoding) => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-encoding-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("encoding.db");
|
||||
const writer = new DatabaseSync(path);
|
||||
writer.exec(
|
||||
`PRAGMA encoding='${encoding}'; CREATE TABLE "" ("1" TEXT, "0" TEXT)`,
|
||||
);
|
||||
const value = "\uFEFFé𝄞\0selected";
|
||||
writer
|
||||
.prepare('INSERT INTO "" VALUES (?, ?)')
|
||||
.run(value, "second numeric column");
|
||||
writer.close();
|
||||
const bytes = Buffer.from(value, encoding === "UTF-8" ? "utf8" : "utf16le");
|
||||
if (encoding === "UTF-16be") bytes.swap16();
|
||||
const result = await createProvider().inspect({
|
||||
path,
|
||||
table: "",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toMatchObject({
|
||||
database_encoding: encoding,
|
||||
rows: {
|
||||
table: "",
|
||||
columns: ["1", "0"],
|
||||
returned_rows: 1,
|
||||
values: [
|
||||
[
|
||||
{ type: "text", value, bytes_hex: bytes.toString("hex"), encoding },
|
||||
{ type: "text", value: "second numeric column" },
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("retains an unavailable virtual module definition without executing it", async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-virtual-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("virtual.db");
|
||||
const writer = new DatabaseSync(path);
|
||||
writer.exec(
|
||||
"CREATE VIRTUAL TABLE optional_search USING fts5(body); INSERT INTO optional_search VALUES ('selected source')",
|
||||
);
|
||||
writer.close();
|
||||
const bytes = await readFile(path);
|
||||
const declaration = bytes.indexOf(Buffer.from("USING fts5"));
|
||||
if (declaration < 0)
|
||||
throw new Error("SQLite virtual module declaration not found");
|
||||
bytes.write("zzzz", declaration + Buffer.byteLength("USING "), "utf8");
|
||||
await writeFile(path, bytes);
|
||||
const provider = createProvider();
|
||||
const result = await provider.inspect({ path, schema_scope: "database" });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toMatchObject({
|
||||
rows: null,
|
||||
schema: {
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "optional_search",
|
||||
kind: "virtual",
|
||||
sql: expect.stringContaining("USING zzzz"),
|
||||
columns: [],
|
||||
columns_completeness: "unsupported",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await provider.inspect({ path, table: "optional_search" }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
});
|
||||
|
||||
nativeTest(
|
||||
"cancels an acquired SQLite worker and removes its private snapshot",
|
||||
async () => {
|
||||
const { database } = await createFixture();
|
||||
const controller = new AbortController();
|
||||
let ownedRoot = "";
|
||||
let pid: number | undefined;
|
||||
const provider = new SqliteDatabaseProvider({}, async (spawn) => {
|
||||
ownedRoot = spawn.cwd ?? "";
|
||||
const requestPath = spawn.arguments[2];
|
||||
if (requestPath === undefined)
|
||||
throw new Error("SQLite worker arguments missing");
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`await import(${JSON.stringify(workerUrl.href)}); process.stdout.write('ready\\n'); setInterval(() => {}, 1000);`,
|
||||
"sqlite-worker-test",
|
||||
requestPath,
|
||||
],
|
||||
});
|
||||
pid = launched.process.pid;
|
||||
await waitForProviderProcessReady(launched.process);
|
||||
await access(`${ownedRoot}/reply.json`);
|
||||
setImmediate(() => controller.abort());
|
||||
return launched;
|
||||
});
|
||||
const result = await provider.inspect(
|
||||
{ path: database.path, table: "records" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
if (pid === undefined) throw new Error("SQLite worker not acquired");
|
||||
const acquiredPid = pid;
|
||||
expect(() => process.kill(acquiredPid, 0)).toThrow();
|
||||
await expectPrivateRootRemoved(ownedRoot);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
readFile,
|
||||
rename,
|
||||
symlink,
|
||||
unlink,
|
||||
utimes,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import type { StableArtifactFileSystem } from "../../../src/artifacts/readStableArtifact.js";
|
||||
import { captureSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseSnapshot.js";
|
||||
import { inspectSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseInspection.js";
|
||||
import { sqliteDatabaseFailure } from "../../../src/sqlite/SqliteDatabaseFailures.js";
|
||||
import {
|
||||
createSqliteDatabaseFixture,
|
||||
SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
} from "../../fixtures/sqlite/database.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
const fixture = async (wal = false) => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-snapshot-race-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root, wal);
|
||||
if (!wal) database.close();
|
||||
const resourceScope = new ArtifactResourceScope();
|
||||
onTestFinished(async () => {
|
||||
await resourceScope.close();
|
||||
if (wal) database.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
});
|
||||
const root = await workspace.mkdir("private");
|
||||
const capture = (fileSystem?: StableArtifactFileSystem) =>
|
||||
captureSqliteDatabaseSnapshot(
|
||||
database.path,
|
||||
root,
|
||||
resourceScope,
|
||||
undefined,
|
||||
fileSystem,
|
||||
);
|
||||
return { workspace, database, root, capture };
|
||||
};
|
||||
|
||||
it.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE).each(["PERSIST", "TRUNCATE"])(
|
||||
"inspects a committed %s journal without modifying the source file set",
|
||||
async (mode) => {
|
||||
const { database, capture } = await fixture();
|
||||
const writer = new DatabaseSync(database.path);
|
||||
try {
|
||||
writer.exec(
|
||||
`PRAGMA journal_mode=${mode}; INSERT INTO records(id, text_value) VALUES (4, 'committed');`,
|
||||
);
|
||||
} finally {
|
||||
writer.close();
|
||||
}
|
||||
const journalPath = `${database.path}-journal`;
|
||||
const before = await readFile(journalPath);
|
||||
const beforeStat = await lstat(journalPath, { bigint: true });
|
||||
const snapshot = await capture();
|
||||
const result = inspectSqliteDatabaseSnapshot(snapshot.snapshotPath, {
|
||||
path: database.path,
|
||||
table: "records",
|
||||
});
|
||||
expect(result.rows).toMatchObject({ returned_rows: 4, truncated: false });
|
||||
expect(await readFile(journalPath)).toEqual(before);
|
||||
const afterStat = await lstat(journalPath, { bigint: true });
|
||||
expect([
|
||||
afterStat.ino,
|
||||
afterStat.size,
|
||||
afterStat.mtimeNs,
|
||||
afterStat.ctimeNs,
|
||||
]).toEqual([
|
||||
beforeStat.ino,
|
||||
beforeStat.size,
|
||||
beforeStat.mtimeNs,
|
||||
beforeStat.ctimeNs,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(process.platform !== "win32").each([
|
||||
["database", "remove"],
|
||||
["WAL", "remove"],
|
||||
["database", "replace with symlink"],
|
||||
["WAL", "replace with symlink"],
|
||||
])(
|
||||
"reports an observed %s change during acquisition as changed evidence: %s",
|
||||
async (member, change) => {
|
||||
const { database, workspace, capture } = await fixture(true);
|
||||
const replacement = await workspace.write("replacement", "");
|
||||
const selectedPath =
|
||||
member === "database" ? database.path : database.walPath;
|
||||
let observations = 0;
|
||||
const fileSystem: StableArtifactFileSystem = {
|
||||
lstat: async (path) => {
|
||||
if (path === selectedPath && ++observations === 2) {
|
||||
await unlink(path);
|
||||
if (change === "replace with symlink")
|
||||
await symlink(replacement, path);
|
||||
}
|
||||
return lstat(path, { bigint: true });
|
||||
},
|
||||
open,
|
||||
};
|
||||
try {
|
||||
await capture(fileSystem);
|
||||
throw new Error("A disappearing source must be rejected");
|
||||
} catch (cause) {
|
||||
expect(
|
||||
sqliteDatabaseFailure(cause, database.path, "artifact-read"),
|
||||
).toMatchObject({ _tag: "AnalysisArtifactChangedError" });
|
||||
expect(cause).toMatchObject({
|
||||
message: expect.stringContaining(selectedPath),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses an active journal even before SQLite writes its magic header", async () => {
|
||||
const { database, capture } = await fixture();
|
||||
const writer = new DatabaseSync(database.path);
|
||||
try {
|
||||
writer.exec(
|
||||
"PRAGMA journal_mode=PERSIST; BEGIN IMMEDIATE; INSERT INTO records(id, text_value) VALUES (4, 'uncommitted');",
|
||||
);
|
||||
const journalPath = `${database.path}-journal`;
|
||||
const journal = await readFile(journalPath);
|
||||
expect(journal.subarray(0, 8).every((byte) => byte === 0)).toBe(true);
|
||||
expect(journal.subarray(8, 28).some((byte) => byte !== 0)).toBe(true);
|
||||
const original = await readFile(database.path);
|
||||
await expect(capture()).rejects.toMatchObject({
|
||||
reason: "format",
|
||||
message: expect.stringContaining("recovery"),
|
||||
});
|
||||
expect(await readFile(database.path)).toEqual(original);
|
||||
expect(await readFile(journalPath)).toEqual(journal);
|
||||
} finally {
|
||||
writer.exec("ROLLBACK");
|
||||
writer.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses an incomplete zeroed journal header", async () => {
|
||||
const { database, capture } = await fixture();
|
||||
await writeFile(`${database.path}-journal`, Buffer.alloc(27));
|
||||
await expect(capture()).rejects.toMatchObject({ reason: "format" });
|
||||
});
|
||||
|
||||
it.runIf(process.platform !== "win32")(
|
||||
"refuses a journal symlink even when its target is empty",
|
||||
async () => {
|
||||
const { database, workspace, capture } = await fixture();
|
||||
const empty = await workspace.write("empty-journal", "");
|
||||
await symlink(empty, `${database.path}-journal`);
|
||||
await expect(capture()).rejects.toMatchObject({ reason: "path" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["activate", "replace", "remove"])(
|
||||
"rejects a cold journal changed during database acquisition: %s",
|
||||
async (change) => {
|
||||
const { database, capture } = await fixture();
|
||||
const journalPath = `${database.path}-journal`;
|
||||
await writeFile(journalPath, Buffer.alloc(28));
|
||||
const fileSystem: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open: async (path, flags) => {
|
||||
if (path === database.path) {
|
||||
if (change === "activate")
|
||||
await writeFile(journalPath, Buffer.alloc(28, 1));
|
||||
else if (change === "remove") await unlink(journalPath);
|
||||
else {
|
||||
await rename(journalPath, `${journalPath}.previous`);
|
||||
await writeFile(journalPath, Buffer.alloc(28));
|
||||
}
|
||||
}
|
||||
return open(path, flags);
|
||||
},
|
||||
};
|
||||
await expect(capture(fileSystem)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses an activated journal even when filesystem metadata cannot distinguish the write", async () => {
|
||||
const { database, capture } = await fixture();
|
||||
const journalPath = `${database.path}-journal`;
|
||||
await writeFile(journalPath, Buffer.alloc(28));
|
||||
const observed = await lstat(journalPath, { bigint: true });
|
||||
const fileSystem: StableArtifactFileSystem = {
|
||||
lstat: (path) =>
|
||||
path === journalPath
|
||||
? Promise.resolve(observed)
|
||||
: lstat(path, { bigint: true }),
|
||||
open: async (path, flags) => {
|
||||
if (path === database.path)
|
||||
await writeFile(journalPath, Buffer.alloc(28, 1));
|
||||
const handle = await open(path, flags);
|
||||
if (path === journalPath)
|
||||
vi.spyOn(handle, "stat").mockResolvedValue(observed);
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
await expect(capture(fileSystem)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a database changed after its copy but before WAL acquisition", async () => {
|
||||
const { database, root, capture } = await fixture(true);
|
||||
const initial = await readFile(database.path);
|
||||
const initialStat = await lstat(database.path);
|
||||
let changed = false;
|
||||
const fileSystem: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open: async (path, flags) => {
|
||||
if (path === database.walPath) {
|
||||
const bytes = Buffer.from(initial);
|
||||
const offset = bytes.length - 1;
|
||||
bytes[offset] = (bytes[offset] ?? 0) ^ 1;
|
||||
await writeFile(database.path, bytes);
|
||||
await utimes(database.path, initialStat.atime, initialStat.mtime);
|
||||
changed = true;
|
||||
}
|
||||
return open(path, flags);
|
||||
},
|
||||
};
|
||||
await expect(capture(fileSystem)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
});
|
||||
expect(changed).toBe(true);
|
||||
expect(await readFile(`${root}/database.snapshot`)).toEqual(initial);
|
||||
});
|
||||
|
||||
it.each(["-wal", "-journal"] as const)(
|
||||
"rejects a previously absent %s created during database acquisition",
|
||||
async (suffix) => {
|
||||
const { database, capture } = await fixture();
|
||||
let created = false;
|
||||
const fileSystem: StableArtifactFileSystem = {
|
||||
lstat: (path) => lstat(path, { bigint: true }),
|
||||
open: async (path, flags) => {
|
||||
if (path === database.path) {
|
||||
await writeFile(
|
||||
`${database.path}${suffix}`,
|
||||
"newly selected sidecar",
|
||||
);
|
||||
created = true;
|
||||
}
|
||||
return open(path, flags);
|
||||
},
|
||||
};
|
||||
await expect(capture(fileSystem)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
});
|
||||
expect(created).toBe(true);
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user