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,597 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
expandProviderCapabilities,
|
||||
expandToolAvailability,
|
||||
providerCapabilitySet,
|
||||
toolAvailabilityInventory,
|
||||
} from "../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
|
||||
import { SQLITE_NATIVE_LIMITS_AVAILABLE } from "../fixtures/sqlite/database.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
const digest = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"bounds default context and projects exact columns without evaluating unrelated cells",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-selective-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`
|
||||
CREATE TABLE selected(id INTEGER, "" TEXT, payload BLOB GENERATED ALWAYS AS (zeroblob(72*1024*1024)) VIRTUAL);
|
||||
CREATE TABLE unrelated(value TEXT);
|
||||
CREATE VIEW unrelated_view AS SELECT value FROM unrelated;
|
||||
CREATE INDEX selected_id ON selected(id);
|
||||
CREATE TRIGGER selected_trigger AFTER INSERT ON selected BEGIN SELECT 1; END;
|
||||
WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<21)
|
||||
INSERT INTO selected(id, "") SELECT n, 'retained' FROM numbers;
|
||||
`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const before = await readFile(path);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const inventory = await call("inspect_sqlite_database", { path });
|
||||
expect(inventory.isError).not.toBe(true);
|
||||
const schema = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
schema: z.object({
|
||||
scope: z.literal("inventory"),
|
||||
tables: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
columns: z.array(z.unknown()),
|
||||
columns_completeness: z.literal("not_requested"),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(inventory.structuredContent).normalized_result.schema;
|
||||
expect(schema.tables.map((table) => table.name)).toEqual([
|
||||
"selected",
|
||||
"unrelated",
|
||||
]);
|
||||
expect(schema.tables.every((table) => table.columns.length === 0)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(JSON.stringify(inventory.structuredContent)).not.toContain(
|
||||
"zeroblob",
|
||||
);
|
||||
const selected = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "selected",
|
||||
columns: ["", "id", "id"],
|
||||
});
|
||||
expect(selected.isError).not.toBe(true);
|
||||
expect(selected.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
scope: "selected_table",
|
||||
tables: [{ name: "selected" }],
|
||||
views: [],
|
||||
indexes: [{ name: "selected_id" }],
|
||||
triggers: [{ name: "selected_trigger" }],
|
||||
},
|
||||
rows: {
|
||||
columns: ["", "id", "id"],
|
||||
row_limit: 20,
|
||||
returned_rows: 20,
|
||||
truncated: true,
|
||||
values: expect.arrayContaining([
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "retained",
|
||||
bytes_hex: "72657461696e6564",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
{ type: "integer", value: "1" },
|
||||
{ type: "integer", value: "1" },
|
||||
],
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const cliResult = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"selected",
|
||||
"--column",
|
||||
"id",
|
||||
"--column",
|
||||
"",
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stdout + cliResult.stderr).toBe(0);
|
||||
expect(cliResult.json).toMatchObject({
|
||||
normalized_result: { rows: { columns: ["id", ""], returned_rows: 1 } },
|
||||
});
|
||||
for (const input of [
|
||||
{ path, columns: ["id"] },
|
||||
{ path, schema_scope: "selected_table" },
|
||||
{ path, table: "selected", columns: [] },
|
||||
{ path, table: "selected", columns: ["ID"] },
|
||||
])
|
||||
expect((await call("inspect_sqlite_database", input)).isError).toBe(true);
|
||||
expect(await readFile(path)).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discovers SQLite runtime availability before inspecting a database through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["capabilities", "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
const status = z
|
||||
.object({
|
||||
open: z.literal(false),
|
||||
capabilities: z.array(providerCapabilitySet),
|
||||
})
|
||||
.parse(result.json);
|
||||
expect(expandProviderCapabilities(status.capabilities)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
reason: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
availability_code: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: "unsupported_version",
|
||||
limitations: [expect.stringContaining("DatabaseSync.limits")],
|
||||
effects: {
|
||||
mutates_artifact: false,
|
||||
launches_process: true,
|
||||
may_show_ui: false,
|
||||
may_access_network: false,
|
||||
may_write_filesystem: true,
|
||||
changes_permissions: false,
|
||||
requires_root: false,
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("binary_session", {});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const sessionStatus = z
|
||||
.object({
|
||||
result: z.object({ tool_availability: toolAvailabilityInventory }),
|
||||
})
|
||||
.parse(response.structuredContent);
|
||||
expect(
|
||||
expandToolAvailability(sessionStatus.result.tool_availability),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
remediation: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"reports the required native SQLite limits capability through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-unavailable-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec("CREATE TABLE items(value INTEGER)");
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", { path });
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response).error).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"accepts small samples above 1000 rows within the real resource budgets",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-row-budget-");
|
||||
const path = join(root, "rows.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`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;`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const limit of [1001, Number.MAX_SAFE_INTEGER]) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"items",
|
||||
"--row-limit",
|
||||
String(limit),
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
rows: {
|
||||
row_limit: limit,
|
||||
returned_rows: Math.min(limit, 1002),
|
||||
truncated: limit < 1002,
|
||||
},
|
||||
},
|
||||
});
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "items",
|
||||
row_limit: limit,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const sourceState = async (path: string) => {
|
||||
const bytes = await readFile(path);
|
||||
const metadata = await stat(path, { bigint: true });
|
||||
return {
|
||||
bytes,
|
||||
device: metadata.dev,
|
||||
inode: metadata.ino,
|
||||
size: metadata.size,
|
||||
modified: metadata.mtimeNs,
|
||||
changed: metadata.ctimeNs,
|
||||
};
|
||||
};
|
||||
|
||||
const createLosslessSnapshot = (path: string, journalMode: string): void => {
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`PRAGMA journal_mode=${journalMode}`);
|
||||
database.exec(`
|
||||
CREATE TABLE "odd "" table" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
payload BLOB,
|
||||
amount REAL,
|
||||
missing TEXT,
|
||||
text_value TEXT,
|
||||
negative_zero,
|
||||
generated TEXT GENERATED ALWAYS AS (hex(payload)) VIRTUAL
|
||||
);
|
||||
CREATE UNIQUE INDEX "quoted "" index" ON "odd "" table"(payload, id);
|
||||
CREATE VIEW readable AS SELECT id FROM "odd "" table";
|
||||
CREATE TRIGGER observed AFTER INSERT ON "odd "" table" BEGIN SELECT 1; END;
|
||||
CREATE TABLE keyed(k TEXT PRIMARY KEY) WITHOUT ROWID, STRICT;
|
||||
`);
|
||||
const insert = database.prepare(
|
||||
'INSERT INTO "odd "" table"(id,payload,amount,missing,text_value,negative_zero) VALUES(?,?,?,NULL,CAST(X\'80ff\' AS TEXT),?)',
|
||||
);
|
||||
insert.setReadBigInts(true);
|
||||
expect(
|
||||
insert.run(
|
||||
9007199254740993n,
|
||||
Buffer.from("deadbeef", "hex"),
|
||||
Infinity,
|
||||
-0,
|
||||
).lastInsertRowid,
|
||||
).toBe(9007199254740993n);
|
||||
insert.run(9007199254740994n, Buffer.from("deadbeef", "hex"), Infinity, -0);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
|
||||
cliTest
|
||||
.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)
|
||||
.for(["DELETE", "PERSIST", "TRUNCATE"])(
|
||||
"inspects a real %s SQLite schema and lossless selected records identically through CLI and MCP",
|
||||
async (journalMode, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-public-");
|
||||
const path = join(root, "selected.db");
|
||||
createLosslessSnapshot(path, journalMode);
|
||||
const original = await readFile(path);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
"selected.db",
|
||||
"--schema-scope",
|
||||
"database",
|
||||
"--table",
|
||||
'odd " table',
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
cwd: root,
|
||||
environment: {
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "ghidra",
|
||||
REA_GHIDRA_HOME: "/unconfigured/ghidra",
|
||||
},
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
operation: "inspect_sqlite_database",
|
||||
confidence: "observed",
|
||||
subject: { local_path: path, digest: { sha256: digest(original) } },
|
||||
normalized_result: {
|
||||
artifact: { path, sha256: digest(original), bytes: original.length },
|
||||
wal: null,
|
||||
schema: {
|
||||
completeness: "complete",
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'odd " table',
|
||||
columns: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "id",
|
||||
primary_key_position: 1,
|
||||
}),
|
||||
expect.objectContaining({ name: "generated", hidden: 2 }),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "keyed",
|
||||
without_rowid: true,
|
||||
strict: true,
|
||||
}),
|
||||
]),
|
||||
indexes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'quoted " index',
|
||||
table: 'odd " table',
|
||||
}),
|
||||
]),
|
||||
views: [
|
||||
{ name: "readable", sql: expect.stringContaining("SELECT id") },
|
||||
],
|
||||
triggers: [
|
||||
{
|
||||
name: "observed",
|
||||
table: 'odd " table',
|
||||
sql: expect.stringContaining("AFTER INSERT"),
|
||||
},
|
||||
],
|
||||
},
|
||||
rows: {
|
||||
table: 'odd " table',
|
||||
columns: [
|
||||
"id",
|
||||
"payload",
|
||||
"amount",
|
||||
"missing",
|
||||
"text_value",
|
||||
"negative_zero",
|
||||
"generated",
|
||||
],
|
||||
returned_rows: 1,
|
||||
row_limit: 1,
|
||||
truncated: true,
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "integer",
|
||||
value: expect.stringMatching(/^900719925474099[34]$/),
|
||||
},
|
||||
{ type: "blob", hex: "deadbeef" },
|
||||
{ type: "real", value: "Infinity" },
|
||||
{ type: "null" },
|
||||
{ type: "text", value: "\ufffd\ufffd", bytes_hex: "80ff" },
|
||||
{ type: "real", value: "-0" },
|
||||
{
|
||||
type: "text",
|
||||
value: "DEADBEEF",
|
||||
bytes_hex: "4445414442454546",
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: 'odd " table',
|
||||
schema_scope: "database",
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"includes uncheckpointed committed WAL data without modifying the source database or sidecars",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-wal-public-");
|
||||
const path = join(root, "wal.db");
|
||||
const database = new DatabaseSync(path);
|
||||
onTestFinished(() => database.close());
|
||||
database.exec(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE committed(value TEXT); INSERT INTO committed VALUES('only in WAL');",
|
||||
);
|
||||
const files = [path, `${path}-wal`, `${path}-shm`];
|
||||
const before = await Promise.all(files.map(sourceState));
|
||||
const db = before[0];
|
||||
const wal = before[1];
|
||||
expect(db).toBeDefined();
|
||||
expect(wal).toBeDefined();
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"committed",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
artifact: { sha256: db === undefined ? "missing" : digest(db.bytes) },
|
||||
wal: {
|
||||
path: `${path}-wal`,
|
||||
sha256: wal === undefined ? "missing" : digest(wal.bytes),
|
||||
},
|
||||
rows: {
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "only in WAL",
|
||||
bytes_hex: Buffer.from("only in WAL").toString("hex"),
|
||||
},
|
||||
],
|
||||
],
|
||||
returned_rows: 1,
|
||||
truncated: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "committed",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
const after = await Promise.all(files.map(sourceState));
|
||||
expect(after).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"returns actionable public errors for corrupt input, unknown or ambiguous tables and invalid record choices",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-errors-public-");
|
||||
const path = join(root, "invalid.db");
|
||||
await writeFile(path, "not a SQLite database");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const corrupt = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(corrupt.exitCode).toBe(1);
|
||||
expect(corrupt.json).toMatchObject({ code: "invalid_request" });
|
||||
expect((await call("inspect_sqlite_database", { path })).isError).toBe(
|
||||
true,
|
||||
);
|
||||
const valid = join(root, "valid.db");
|
||||
const database = new DatabaseSync(valid);
|
||||
try {
|
||||
database.exec(
|
||||
"CREATE TABLE present(value TEXT); CREATE VIRTUAL TABLE search USING fts5(body);",
|
||||
);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const bytes = await readFile(valid);
|
||||
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(valid, bytes);
|
||||
const schema = await call("inspect_sqlite_database", { path: valid });
|
||||
expect(schema.isError).not.toBe(true);
|
||||
expect(schema.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "search_data", kind: "unknown" }),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const ambiguous = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"search_data",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(ambiguous.exitCode).toBe(1);
|
||||
expect(ambiguous.stdout).toContain("shadow table");
|
||||
expect(
|
||||
(
|
||||
await call("inspect_sqlite_database", {
|
||||
path: valid,
|
||||
table: "search_data",
|
||||
})
|
||||
).isError,
|
||||
).toBe(true);
|
||||
const missing = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"absent",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.stdout).toContain("absent");
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", { path: valid, table: "absent" }))
|
||||
.isError,
|
||||
).toBe(true);
|
||||
for (const input of [
|
||||
{ path: valid, row_limit: 1 },
|
||||
{ path: valid, table: "present", row_limit: 0 },
|
||||
{ path: valid, query: "DELETE FROM present" },
|
||||
]) {
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", input)).isError,
|
||||
JSON.stringify(input),
|
||||
).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -442,6 +442,10 @@ it("rejects skipped selected work while allowing unselected lanes to skip", asyn
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
".github/workflows/sqlite-runtime.yml",
|
||||
{ workflows: true, code: true, package: false, website: false },
|
||||
],
|
||||
[
|
||||
".github/workflows/real-termux.yml",
|
||||
{ workflows: true, code: false, package: false, website: false },
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
import { z } from "zod";
|
||||
import { executeWorkflowFixture } from "../../support/workflowGit.js";
|
||||
|
||||
const workflow = async (filename = "ci.yml") =>
|
||||
z
|
||||
.object({
|
||||
jobs: z.record(
|
||||
z.string(),
|
||||
z
|
||||
.object({
|
||||
needs: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL(`../../../.github/workflows/${filename}`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it("binds SQLite compatibility jobs to the build's prepared runtime artifact and root layout", async () => {
|
||||
const steps = z.array(
|
||||
z.object({
|
||||
uses: z.string().optional(),
|
||||
with: z
|
||||
.object({ name: z.string().optional(), path: z.string().optional() })
|
||||
.optional(),
|
||||
}),
|
||||
);
|
||||
const uploads = steps.parse((await workflow()).jobs.build?.steps).filter(
|
||||
(step) =>
|
||||
step.uses?.startsWith("actions/upload-artifact@") &&
|
||||
step.with?.path
|
||||
?.split(/\r?\n/u)
|
||||
.map((path) => path.trim())
|
||||
.includes("dist/"),
|
||||
);
|
||||
expect(uploads).toHaveLength(1);
|
||||
const name = z.string().min(1).parse(uploads[0]?.with?.name);
|
||||
const downloads = steps
|
||||
.parse((await workflow("sqlite-runtime.yml")).jobs.sqlite?.steps)
|
||||
.filter((step) => step.uses?.startsWith("actions/download-artifact@"));
|
||||
expect(downloads).toHaveLength(1);
|
||||
expect(downloads[0]?.with).toEqual({ name, path: "." });
|
||||
});
|
||||
|
||||
const requiredNeeds = async () => {
|
||||
const { jobs } = await workflow();
|
||||
return { jobs, needs: z.array(z.string()).parse(jobs.required?.needs) };
|
||||
};
|
||||
|
||||
it("makes the required gate wait for every CI lane, including future additions", async () => {
|
||||
const { jobs, needs } = await requiredNeeds();
|
||||
expect(new Set(needs)).toEqual(
|
||||
new Set(Object.keys(jobs).filter((name) => name !== "required")),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["true", "success", true],
|
||||
["true", "failure", false],
|
||||
["true", "cancelled", false],
|
||||
["true", "skipped", false],
|
||||
["true", "missing", false],
|
||||
["false", "skipped", true],
|
||||
] as const)(
|
||||
"enforces the SQLite required gate for code=%s and result=%s",
|
||||
async (code, result, passes) => {
|
||||
const workflow = await requiredNeeds();
|
||||
// GitHub exposes only direct dependencies in the required job's needs context.
|
||||
const needs: Record<
|
||||
string,
|
||||
{ result: string; outputs?: Record<string, string> }
|
||||
> = Object.fromEntries(
|
||||
workflow.needs.map((name) => [name, { result: "success" }]),
|
||||
);
|
||||
needs.changes = { result: "success", outputs: { code } };
|
||||
if (result === "missing") delete needs["sqlite-runtime"];
|
||||
else if ("sqlite-runtime" in needs) needs["sqlite-runtime"] = { result };
|
||||
const execution = executeWorkflowFixture(
|
||||
process.execPath,
|
||||
[
|
||||
fileURLToPath(
|
||||
new URL("../../../scripts/ci/required.mjs", import.meta.url),
|
||||
),
|
||||
],
|
||||
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
|
||||
);
|
||||
if (passes) await expect(execution).resolves.toMatchObject({ stderr: "" });
|
||||
else
|
||||
await expect(execution).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining("sqlite-runtime"),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -8,9 +8,332 @@ import { HopperRemoteError } from "../../../src/domain/hopperErrors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { SqliteDatabaseService } from "../../../src/application/sqlite/SqliteDatabaseService.js";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { once } from "node:events";
|
||||
import { access } from "node:fs/promises";
|
||||
import {
|
||||
serveStdio,
|
||||
StdioServerTransport,
|
||||
} from "@modelcontextprotocol/server/stdio";
|
||||
import pino from "pino";
|
||||
import { createManagedBinarySession } from "../../../src/composition/binary.js";
|
||||
import { startMcpTransport } from "../../../src/main/transport.js";
|
||||
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
createSqliteDatabaseFixture,
|
||||
SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
} from "../../fixtures/sqlite/database.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
import { z } from "zod";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
it.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"drains an admitted SQLite inspection before changing the session binding",
|
||||
async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-mcp-admission-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root);
|
||||
database.close();
|
||||
const acquired = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
process.env,
|
||||
(spawn) =>
|
||||
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,
|
||||
});
|
||||
acquired.resolve();
|
||||
await release.promise;
|
||||
return root;
|
||||
},
|
||||
);
|
||||
const session = createManagedBinarySession();
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ sqliteDatabase: new SqliteDatabaseService(provider) },
|
||||
);
|
||||
const client = new Client({ name: "sqlite-admission", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const inspection = client.callTool({
|
||||
name: "inspect_sqlite_database",
|
||||
arguments: { path: database.path, table: "records", columns: ["id"] },
|
||||
});
|
||||
await acquired.promise;
|
||||
let closed = false;
|
||||
const closing = session.close().then((result) => {
|
||||
closed = true;
|
||||
return result;
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(closed).toBe(false);
|
||||
release.resolve();
|
||||
const result = await inspection;
|
||||
expect(result.isError).not.toBe(true);
|
||||
const evidenceId = z
|
||||
.object({ evidence_id: z.string() })
|
||||
.parse(result.structuredContent).evidence_id;
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
normalized_result: { rows: { columns: ["id"], returned_rows: 3 } },
|
||||
});
|
||||
expect(await closing).toMatchObject({ ok: true });
|
||||
// Closing a binding clears its ledger after the admitted recording succeeds.
|
||||
expect(session.evidenceById(evidenceId)).toBeUndefined();
|
||||
expect(closed).toBe(true);
|
||||
} finally {
|
||||
release.resolve();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"records completed SQLite evidence before delivering a cleanup failure",
|
||||
async () => {
|
||||
const workspace = await createTestWorkspace("rea-sqlite-mcp-retention-");
|
||||
const database = createSqliteDatabaseFixture(workspace.root);
|
||||
database.close();
|
||||
let removalAllowed = false;
|
||||
const provider = new SqliteDatabaseProvider(
|
||||
process.env,
|
||||
(spawn) =>
|
||||
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,
|
||||
});
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!removalAllowed)
|
||||
throw new Error(
|
||||
"Snapshot cleanup denied after completed observation",
|
||||
);
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
const session = createManagedBinarySession();
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ sqliteDatabase: new SqliteDatabaseService(provider) },
|
||||
);
|
||||
const client = new Client({
|
||||
name: "sqlite-retained-observation",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "inspect_sqlite_database",
|
||||
arguments: { path: database.path, table: "records", columns: ["id"] },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const error = z
|
||||
.object({
|
||||
error: z.object({
|
||||
details: z.object({
|
||||
partial_observation: z.object({
|
||||
kind: z.literal("retained-evidence"),
|
||||
evidence_id: z.string(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(parseMcpToolError(result)).error;
|
||||
const retained = session.evidenceById(
|
||||
error.details.partial_observation.evidence_id,
|
||||
);
|
||||
expect(retained).toMatchObject({
|
||||
operation: "inspect_sqlite_database",
|
||||
parameters: { columns: ["id"] },
|
||||
normalized_result: { rows: { columns: ["id"], returned_rows: 3 } },
|
||||
});
|
||||
expect(JSON.stringify(parseMcpToolError(result))).not.toContain(
|
||||
"normalized_result",
|
||||
);
|
||||
const bundle = await client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(bundle.isError).not.toBe(true);
|
||||
expect(JSON.stringify(bundle.structuredContent)).toContain(
|
||||
error.details.partial_observation.evidence_id,
|
||||
);
|
||||
} finally {
|
||||
removalAllowed = true;
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await removeTestWorkspace(workspace.root);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["handle", "stdin"] as const)(
|
||||
"retains failed SQLite cleanup through production stdio shutdown: %s",
|
||||
async (shutdown) => {
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
prefix: "rea-sqlite-stdio-cleanup-",
|
||||
});
|
||||
let removalAllowed = false;
|
||||
let attempts = 0;
|
||||
const sqliteDatabase = new SqliteDatabaseService({
|
||||
inspect: async () => {
|
||||
throw new Error("No inspection requested");
|
||||
},
|
||||
close: async () => {
|
||||
attempts += 1;
|
||||
if (!removalAllowed) throw new Error("SQLite snapshot removal denied");
|
||||
await root.close();
|
||||
},
|
||||
});
|
||||
const stdin = new PassThrough();
|
||||
const stdout = new PassThrough();
|
||||
const logger = pino({ enabled: false });
|
||||
const session = createManagedBinarySession();
|
||||
const started = await startMcpTransport(
|
||||
{
|
||||
env: {},
|
||||
serve: (factory, options) =>
|
||||
serveStdio(factory, {
|
||||
...options,
|
||||
transport: new StdioServerTransport(stdin, stdout),
|
||||
}),
|
||||
createServer: (source, options) =>
|
||||
createServer(source, { ...options, sqliteDatabase }),
|
||||
writeStderr: () => undefined,
|
||||
setExitCode: () => undefined,
|
||||
registerShutdown: () => () => undefined,
|
||||
},
|
||||
session,
|
||||
{
|
||||
environment: {},
|
||||
delivery: createToolResultDelivery(undefined),
|
||||
logger,
|
||||
serverLogger: logger,
|
||||
loadOptionalProviders: async () => ({}),
|
||||
},
|
||||
);
|
||||
if (!started.ok) throw new Error("Transport startup failed");
|
||||
try {
|
||||
const response = once(stdout, "data");
|
||||
stdin.write(
|
||||
`${JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: "2025-11-25",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "sqlite-cleanup-test", version: "1.0.0" },
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
const [reply] = await response;
|
||||
expect(JSON.parse(String(reply))).toMatchObject({
|
||||
id: 1,
|
||||
result: { serverInfo: { name: "rea" } },
|
||||
});
|
||||
if (shutdown === "stdin") {
|
||||
stdin.end();
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
await expect(started.handle.close()).rejects.toBeInstanceOf(
|
||||
AggregateError,
|
||||
);
|
||||
expect(attempts).toBeGreaterThan(0);
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
removalAllowed = true;
|
||||
await started.handle.close();
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const completedAttempts = attempts;
|
||||
await started.handle.close();
|
||||
expect(attempts).toBe(completedAttempts);
|
||||
} finally {
|
||||
removalAllowed = true;
|
||||
await started.handle.close();
|
||||
await started.closeAndroid();
|
||||
await session.close();
|
||||
await root.close();
|
||||
stdin.destroy();
|
||||
stdout.destroy();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("awaits SQLite cleanup and retries its retained owner after failed server shutdown", async () => {
|
||||
let removalAllowed = false;
|
||||
let attempts = 0;
|
||||
const sqliteDatabase = new SqliteDatabaseService({
|
||||
inspect: async () => {
|
||||
throw new Error("No inspection requested");
|
||||
},
|
||||
close: async () => {
|
||||
attempts += 1;
|
||||
if (!removalAllowed) throw new Error("SQLite snapshot removal denied");
|
||||
},
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "fixed", analysis: { execute: async () => ok(null) } },
|
||||
{ sqliteDatabase },
|
||||
);
|
||||
resources.push(server);
|
||||
try {
|
||||
await expect(server.close()).rejects.toBeInstanceOf(AggregateError);
|
||||
expect(attempts).toBe(1);
|
||||
} finally {
|
||||
removalAllowed = true;
|
||||
}
|
||||
await server.close();
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
Vendored
+3
@@ -159,3 +159,6 @@ for (const name of ["get_xrefs_to_class", "get_xrefs_to_method"])
|
||||
}),
|
||||
);
|
||||
await server.connect(new StdioServerTransport());
|
||||
// A refused cleanup must leave a live process for verified fixture teardown.
|
||||
// Otherwise stdin EOF races the ownership scan with the server's natural exit.
|
||||
if (mode === "cleanup-failure") setInterval(() => {}, 1000);
|
||||
|
||||
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** Engine-dependent cases require the same native limit capability as the worker. */
|
||||
export const SQLITE_NATIVE_LIMITS_AVAILABLE = (() => {
|
||||
const database = new DatabaseSync(":memory:");
|
||||
try {
|
||||
return "limits" in database;
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
})();
|
||||
|
||||
/** Exact selected SQLite fixture with committed rows and optional live WAL. */
|
||||
export interface SqliteDatabaseFixture {
|
||||
readonly path: string;
|
||||
readonly walPath: string;
|
||||
readonly quotedTable: string;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Produce schema and lossless SQLite values through the actual SQLite engine. */
|
||||
export const createSqliteDatabaseFixture = (
|
||||
root: string,
|
||||
wal = false,
|
||||
): SqliteDatabaseFixture => {
|
||||
const path = join(root, "selected.db");
|
||||
const db = new DatabaseSync(path);
|
||||
if (wal) db.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0");
|
||||
db.exec(`
|
||||
CREATE TABLE records (
|
||||
id INTEGER PRIMARY KEY,
|
||||
integer_value INTEGER,
|
||||
blob_value BLOB,
|
||||
real_value REAL,
|
||||
nullable_value TEXT,
|
||||
text_value TEXT,
|
||||
generated_value TEXT GENERATED ALWAYS AS (typeof(integer_value)) VIRTUAL
|
||||
);
|
||||
CREATE INDEX records_text ON records(text_value);
|
||||
CREATE VIEW record_names AS SELECT text_value FROM records;
|
||||
CREATE TRIGGER records_insert AFTER INSERT ON records BEGIN SELECT 1; END;
|
||||
CREATE TABLE "strange""'; DROP TABLE records;--" ("__proto__" TEXT);
|
||||
INSERT INTO "strange""'; DROP TABLE records;--" VALUES ('exact selected table');
|
||||
`);
|
||||
const insert = db.prepare(
|
||||
"INSERT INTO records(id, integer_value, blob_value, real_value, nullable_value, text_value) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
);
|
||||
insert.run(
|
||||
1,
|
||||
9223372036854775807n,
|
||||
Buffer.from([0, 31, 239, 255]),
|
||||
Infinity,
|
||||
null,
|
||||
"first é\0value",
|
||||
);
|
||||
insert.run(
|
||||
2,
|
||||
-9223372036854775808n,
|
||||
Buffer.alloc(0),
|
||||
-Infinity,
|
||||
"present",
|
||||
"second",
|
||||
);
|
||||
db.exec(
|
||||
"INSERT INTO records(id, integer_value, blob_value, real_value, nullable_value, text_value) VALUES (3, 0, X'FF', 1.25, NULL, CAST(X'FF00C0AF' AS TEXT))",
|
||||
);
|
||||
return {
|
||||
path,
|
||||
walPath: `${path}-wal`,
|
||||
quotedTable: "strange\"'; DROP TABLE records;--",
|
||||
close: () => db.close(),
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user