mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 18:06:46 +00:00
* feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors)!: refuse malformed SQLite, pwntools and EVM inputs as target failures The SQLite engine's `format` reason is renamed to `malformed` at its owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an AnalysisTargetFailureError at the selected path with format "sqlite". The pwntools and EVM worker replies keep their wire reason "format", which their workers define, and the adapters translate it once into a malformed target failure with the profile's format (elf, elf-core, evm-bytecode) instead of an invalid_format argument issue. SQLite joins the target-failure conformance registry. BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout, inspect_recorded_crash and inspect_evm_interface report a selected file's malformed bytes as unsupported_target with details.failure_kind "malformed", format_failure, format and path, instead of invalid_request with an invalid_format issue on path. * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): expect target failure facts in the pwntools and EVM reply suites The literal-replacement scenario now reads the failure's detail instead of an issues[] message, and a malformed reply wrapped by cleanup failure reports category unsupported_target. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * test(sqlite): drop the malformed-database provider test the conformance registry covers inspect_sqlite_database/not-a-database in the target-failure registry runs the same non-SQLite bytes through the CLI and MCP, asserts the malformed target facts and checks the selected file is unchanged. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * test(sqlite): expect a malformed target for non-database bytes in the CLI suite * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(pwntools): report a short ELF header as a truncated target The layout and recorded-crash workers raise a distinct truncated reason when the file ends inside the ELF identification or header, and the decoder projects it as failure_kind truncated instead of inferring it from the message. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * test(verify): expect target failures for damaged ELF, core and EVM inputs in real-provider verifiers The binary-layout, recorded-crash and EVM verifiers still expected invalid_input for malformed or truncated selected bytes. The pwntools and EVM adapters now report those as unsupported_target with failure_kind; a missing path remains invalid_input. * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
1352 lines
44 KiB
TypeScript
1352 lines
44 KiB
TypeScript
import { DatabaseSync } from "node:sqlite";
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
import { describe, expect, it as nativeTest, onTestFinished, vi } from "vitest";
|
|
import {
|
|
createSqliteApplicationCollationFixture,
|
|
createSqliteLongNameFixture,
|
|
SQLITE_NATIVE_LIMITS_AVAILABLE,
|
|
} from "../../fixtures/sqlite/database.js";
|
|
import { inspectSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseInspection.js";
|
|
import { SqliteInspectionFailure } from "../../../src/sqlite/SqliteDatabaseLimits.js";
|
|
import { jsonByteLength } from "../../../src/domain/jsonSerialization.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("attributes triggers declared with another ASCII case to the stored table name", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE Users(id INTEGER PRIMARY KEY, email TEXT);
|
|
CREATE INDEX users_email ON users(email);
|
|
CREATE TRIGGER audit_insert AFTER INSERT ON users BEGIN SELECT 1; END;
|
|
CREATE TRIGGER audit_delete AFTER DELETE ON USERS BEGIN SELECT 1; END;
|
|
CREATE VIEW recent AS SELECT 1;
|
|
CREATE TRIGGER recent_insert INSTEAD OF INSERT ON Recent BEGIN SELECT 1; END;
|
|
`);
|
|
const selected = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "Users",
|
|
});
|
|
expect(selected.schema).toMatchObject({
|
|
scope: "selected_table",
|
|
completeness: "complete",
|
|
tables: [{ name: "Users" }],
|
|
indexes: [{ name: "users_email", table: "Users" }],
|
|
views: [],
|
|
});
|
|
expect(
|
|
selected.schema.triggers.map(({ name, table }) => ({ name, table })),
|
|
).toEqual([
|
|
{ name: "audit_insert", table: "Users" },
|
|
{ name: "audit_delete", table: "Users" },
|
|
]);
|
|
const inventory = inspectSqliteDatabaseSnapshot(path, { path });
|
|
expect(inventory.schema.triggers).toEqual([
|
|
{ name: "audit_insert", table: "Users" },
|
|
{ name: "audit_delete", table: "Users" },
|
|
{ name: "recent_insert", table: "recent" },
|
|
]);
|
|
});
|
|
|
|
it.each([
|
|
{
|
|
selection: "a differently cased table",
|
|
schema: "CREATE TABLE Users(id INTEGER PRIMARY KEY)",
|
|
trigger: "AFTER INSERT ON Users",
|
|
table: "users",
|
|
},
|
|
{
|
|
selection: "an exact view",
|
|
schema: "CREATE VIEW Recent AS SELECT 1 AS id",
|
|
trigger: "INSTEAD OF INSERT ON recent",
|
|
table: "Recent",
|
|
},
|
|
])(
|
|
"refuses $selection before expanding declarations under another spelling",
|
|
async ({ schema, trigger, table }) => {
|
|
const path = await createDatabase(`
|
|
${schema};
|
|
CREATE TRIGGER expanded ${trigger} BEGIN /*${"\u0001".repeat(3 * 1024 * 1024)}*/ SELECT 1; END;
|
|
`);
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, { path, table }),
|
|
).toThrowError(
|
|
expect.objectContaining({
|
|
reason: "selection",
|
|
message: `Selected ordinary table does not exist with that exact name: ${table}`,
|
|
}),
|
|
);
|
|
},
|
|
);
|
|
|
|
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.each(["UTF-16le", "UTF-16be"] as const)(
|
|
"budgets %s catalog names by returned JSON rather than internal hex identity",
|
|
async (encoding) => {
|
|
const workspace = await createTestWorkspace("rea-sqlite-catalog-names-");
|
|
onTestFinished(() => removeTestWorkspace(workspace.root));
|
|
const { path, names } = createSqliteLongNameFixture(
|
|
workspace.root,
|
|
encoding,
|
|
);
|
|
for (const schema_scope of ["inventory", "database"] as const) {
|
|
const inspection = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
schema_scope,
|
|
});
|
|
expect(inspection.database_encoding).toBe(encoding);
|
|
expect(inspection.schema).toMatchObject({
|
|
scope: schema_scope,
|
|
completeness: "complete",
|
|
});
|
|
expect(inspection.schema.tables).toHaveLength(names.length);
|
|
expect(inspection.schema.tables.map((table) => table.name)).toEqual(
|
|
expect.arrayContaining(names),
|
|
);
|
|
for (const table of inspection.schema.tables) {
|
|
expect(table.columns_completeness).toBe(
|
|
schema_scope === "inventory" ? "not_requested" : "complete",
|
|
);
|
|
if (schema_scope === "database") {
|
|
expect(table.sql).toBe(`CREATE TABLE "${table.name}"(value TEXT)`);
|
|
expect(table.columns).toMatchObject([
|
|
{ name: "value", declared_type: "TEXT" },
|
|
]);
|
|
} else {
|
|
expect(table.sql).toBeUndefined();
|
|
expect(table.columns).toEqual([]);
|
|
}
|
|
}
|
|
expect(jsonByteLength({ ok: true, inspection })).toBeLessThan(
|
|
16 * 1024 * 1024,
|
|
);
|
|
}
|
|
},
|
|
);
|
|
|
|
it("keeps unrelated catalog names outside the selected-table reply budget", async () => {
|
|
const path = await createDatabase(
|
|
"CREATE TABLE selected(value TEXT); INSERT INTO selected VALUES ('retained');",
|
|
);
|
|
const producer = new DatabaseSync(path);
|
|
try {
|
|
producer.exec("BEGIN");
|
|
for (let index = 0; index < 60; index++) {
|
|
const name = `unrelated_${index}_${"x".repeat(300 * 1024)}`;
|
|
producer.exec(`CREATE TABLE "${name}" (value TEXT)`);
|
|
}
|
|
producer.exec("COMMIT");
|
|
} finally {
|
|
producer.close();
|
|
}
|
|
const selected = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "selected",
|
|
});
|
|
expect(selected.schema).toMatchObject({
|
|
scope: "selected_table",
|
|
completeness: "complete",
|
|
tables: [{ name: "selected" }],
|
|
indexes: [],
|
|
views: [],
|
|
triggers: [],
|
|
});
|
|
expect(selected.schema.tables).toHaveLength(1);
|
|
expect(selected.rows).toMatchObject({
|
|
returned_rows: 1,
|
|
values: [[{ type: "text", value: "retained" }]],
|
|
});
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, { path, table: "absent" }),
|
|
).toThrowError(
|
|
expect.objectContaining({
|
|
reason: "selection",
|
|
message: expect.stringMatching(/ordinary table.*exact name.*absent/i),
|
|
}),
|
|
);
|
|
for (const schema_scope of ["inventory", "database"] as const)
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, { path, schema_scope }),
|
|
).toThrowError(expect.objectContaining({ reason: "output-limit" }));
|
|
});
|
|
|
|
it.each(["inventory", "selected_table", "database"] as const)(
|
|
"reads sqlite_schema rows using PRAGMA row-source facts in %s scope",
|
|
async (schema_scope) => {
|
|
const path = await createDatabase(
|
|
"CREATE TABLE records(id INTEGER); INSERT INTO records VALUES (1);",
|
|
);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "sqlite_schema",
|
|
columns: ["name", "type"],
|
|
schema_scope,
|
|
});
|
|
|
|
expect(result.rows).toMatchObject({
|
|
table: "sqlite_schema",
|
|
columns: ["name", "type"],
|
|
values: [
|
|
[
|
|
{ type: "text", value: "records" },
|
|
{ type: "text", value: "table" },
|
|
],
|
|
],
|
|
});
|
|
expect(result.schema.tables).not.toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({ name: "sqlite_schema" }),
|
|
]),
|
|
);
|
|
},
|
|
);
|
|
|
|
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("attributes compile and row evaluation errors to each failing generated column", async () => {
|
|
const workspace = await createTestWorkspace("rea-sqlite-evaluation-");
|
|
onTestFinished(() => removeTestWorkspace(workspace.root));
|
|
const path = workspace.path("private.db");
|
|
// Writable schema plants an expression that fails only for the second
|
|
// stored row; virtual cells are not stored, so record layout is unchanged.
|
|
const producer = new DatabaseSync(path, { defensive: false });
|
|
try {
|
|
producer.function("application_digest", { deterministic: true }, (value) =>
|
|
String(value),
|
|
);
|
|
producer.exec(`
|
|
CREATE TABLE t(
|
|
id INTEGER,
|
|
payload TEXT,
|
|
digest TEXT GENERATED ALWAYS AS (application_digest(payload)) VIRTUAL,
|
|
stored_digest TEXT GENERATED ALWAYS AS (application_digest(payload)) STORED,
|
|
field GENERATED ALWAYS AS (payload) VIRTUAL,
|
|
upper_payload GENERATED ALWAYS AS (upper(payload)) VIRTUAL
|
|
);
|
|
INSERT INTO t(id, payload) VALUES (1, '{"k":1}'), (2, 'not json');
|
|
PRAGMA writable_schema = ON;
|
|
UPDATE sqlite_schema
|
|
SET sql = replace(sql, 'field GENERATED ALWAYS AS (payload)', 'field GENERATED ALWAYS AS (json_extract(payload, ''$.k''))')
|
|
WHERE name = 't';
|
|
PRAGMA writable_schema = OFF;
|
|
`);
|
|
} finally {
|
|
producer.close();
|
|
}
|
|
const failure = (input: { columns?: string[]; row_limit?: number }) => {
|
|
try {
|
|
inspectSqliteDatabaseSnapshot(path, { path, table: "t", ...input });
|
|
} catch (cause: unknown) {
|
|
return cause;
|
|
}
|
|
throw new Error("Expected a generated-column evaluation failure");
|
|
};
|
|
const prefix = `SQLite cannot evaluate selected column(s) of table "t" on REA's read-only connection: `;
|
|
expect(failure({})).toMatchObject({
|
|
reason: "column-evaluation",
|
|
message: `${prefix}"digest": unknown function: application_digest(); "field": malformed JSON`,
|
|
readableColumns: ["id", "payload", "stored_digest", "upper_payload"],
|
|
});
|
|
expect(failure({ columns: ["field", "id", "field"] })).toMatchObject({
|
|
message: `${prefix}"field": malformed JSON`,
|
|
readableColumns: ["id"],
|
|
});
|
|
// With no readable selection left, stored columns remain available without evaluation.
|
|
expect(failure({ columns: ["digest"] })).toMatchObject({
|
|
message: `${prefix}"digest": unknown function: application_digest()`,
|
|
readableColumns: ["id", "payload", "stored_digest"],
|
|
});
|
|
// Only sampled rows are evaluated, and stored or built-in generated cells are read.
|
|
expect(
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "t",
|
|
columns: ["field", "stored_digest", "upper_payload"],
|
|
row_limit: 1,
|
|
}).rows,
|
|
).toMatchObject({
|
|
values: [
|
|
[
|
|
{ type: "integer", value: "1" },
|
|
{ type: "text", value: '{"k":1}' },
|
|
{ type: "text", value: '{"K":1}' },
|
|
],
|
|
],
|
|
truncated: true,
|
|
});
|
|
});
|
|
|
|
const createApplicationDatabase = async (
|
|
sql: string,
|
|
edit?: (bytes: Buffer) => void,
|
|
): Promise<string> => {
|
|
const workspace = await createTestWorkspace("rea-sqlite-evaluation-");
|
|
onTestFinished(() => removeTestWorkspace(workspace.root));
|
|
const path = workspace.path("private.db");
|
|
const producer = new DatabaseSync(path);
|
|
try {
|
|
// The producing application supplies a function REA's connection lacks.
|
|
producer.function("application_digest", { deterministic: true }, (value) =>
|
|
String(value),
|
|
);
|
|
producer.exec(sql);
|
|
} finally {
|
|
producer.close();
|
|
}
|
|
if (edit !== undefined) {
|
|
const bytes = await readFile(path);
|
|
edit(bytes);
|
|
await writeFile(path, bytes);
|
|
}
|
|
return path;
|
|
};
|
|
|
|
it("never recommends a selected column whose own probe fails for another reason", async () => {
|
|
const path = await createApplicationDatabase(`
|
|
CREATE TABLE t(
|
|
id INTEGER,
|
|
digest TEXT GENERATED ALWAYS AS (application_digest(id)) VIRTUAL,
|
|
payload BLOB GENERATED ALWAYS AS (zeroblob(72 * 1024 * 1024)) VIRTUAL
|
|
);
|
|
INSERT INTO t(id) VALUES (1);
|
|
`);
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "t",
|
|
columns: ["payload", "digest", "id"],
|
|
}),
|
|
).toThrow(
|
|
expect.objectContaining({
|
|
reason: "column-evaluation",
|
|
message: `SQLite cannot evaluate selected column(s) of table "t" on REA's read-only connection: "payload": string or blob too big; "digest": unknown function: application_digest()`,
|
|
readableColumns: ["id"],
|
|
}),
|
|
);
|
|
});
|
|
|
|
it("recommends stored columns outside an inventory-scope selection without decoding malformed names", async () => {
|
|
const path = await createApplicationDatabase(
|
|
`
|
|
CREATE TABLE t(
|
|
id INTEGER,
|
|
"col" TEXT,
|
|
payload TEXT,
|
|
digest TEXT GENERATED ALWAYS AS (application_digest(payload)) VIRTUAL
|
|
);
|
|
INSERT INTO t(id, "col", payload) VALUES (1, 'kept', 'value');
|
|
`,
|
|
(bytes) => {
|
|
const marker = Buffer.from('"col"');
|
|
const offset = bytes.indexOf(marker);
|
|
if (offset < 0 || bytes.indexOf(marker, offset + 1) !== -1)
|
|
throw new Error("Expected unique authored column marker");
|
|
bytes[offset + 1] = 0xff;
|
|
},
|
|
);
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "t",
|
|
schema_scope: "inventory",
|
|
columns: ["digest"],
|
|
}),
|
|
).toThrow(
|
|
expect.objectContaining({
|
|
reason: "column-evaluation",
|
|
message: `SQLite cannot evaluate selected column(s) of table "t" on REA's read-only connection: "digest": unknown function: application_digest()`,
|
|
readableColumns: ["id", "payload"],
|
|
}),
|
|
);
|
|
// The recommended stored columns are themselves selectable in the same scope.
|
|
expect(
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "t",
|
|
schema_scope: "inventory",
|
|
columns: ["id", "payload"],
|
|
}).rows,
|
|
).toMatchObject({
|
|
values: [
|
|
[
|
|
{ type: "integer", value: "1" },
|
|
{ type: "text", value: "value" },
|
|
],
|
|
],
|
|
});
|
|
});
|
|
|
|
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,
|
|
});
|
|
}
|
|
});
|
|
|
|
it("pages a rowid table in rowid order without repeating or dropping rows", async () => {
|
|
const path = await createDatabase(`CREATE TABLE items(value TEXT);
|
|
INSERT INTO items(value) VALUES ('a'), ('b'), ('c'), ('d'), ('e');`);
|
|
const first = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 2,
|
|
});
|
|
expect(first.rows).toMatchObject({
|
|
order: "rowid",
|
|
row_offset: 0,
|
|
returned_rows: 2,
|
|
truncated: true,
|
|
next_row_offset: 2,
|
|
});
|
|
const second = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 2,
|
|
row_offset: first.rows?.next_row_offset ?? 0,
|
|
});
|
|
expect(second.rows).toMatchObject({
|
|
order: "rowid",
|
|
row_offset: 2,
|
|
returned_rows: 2,
|
|
truncated: true,
|
|
next_row_offset: 4,
|
|
});
|
|
const last = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 2,
|
|
row_offset: second.rows?.next_row_offset ?? 0,
|
|
});
|
|
expect(last.rows).toMatchObject({
|
|
row_offset: 4,
|
|
returned_rows: 1,
|
|
truncated: false,
|
|
next_row_offset: null,
|
|
});
|
|
// Reading every page once must reproduce the table exactly: asserting only
|
|
// counts and offsets would pass even if a page repeated the first rows.
|
|
expect(
|
|
[first, second, last].flatMap((page) =>
|
|
(page.rows?.values ?? []).map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
),
|
|
).toEqual([["a"], ["b"], ["c"], ["d"], ["e"]]);
|
|
});
|
|
|
|
it.each(["UTF-16le", "UTF-16be"] as const)(
|
|
"orders a %s WITHOUT ROWID table by its decoded primary key",
|
|
async (encoding) => {
|
|
const path = await createDatabase(
|
|
`PRAGMA encoding='${encoding}'; CREATE TABLE keyed(k INTEGER, label TEXT, PRIMARY KEY(k)) WITHOUT ROWID; INSERT INTO keyed VALUES (2, 'b'), (1, 'a');`,
|
|
);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "keyed",
|
|
row_limit: 20,
|
|
});
|
|
expect(result.rows).toMatchObject({ order: "primary_key" });
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([
|
|
["1", "a"],
|
|
["2", "b"],
|
|
]);
|
|
},
|
|
);
|
|
|
|
it("orders by a free rowid spelling when a virtual generated column shadows one", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE generated(name TEXT, rowid TEXT GENERATED ALWAYS AS (name || '!') VIRTUAL);
|
|
INSERT INTO generated(name) VALUES ('b'), ('a');`);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "generated",
|
|
columns: ["name"],
|
|
row_limit: 20,
|
|
});
|
|
// Rowid order is insertion order, which the generated expression reverses.
|
|
expect(result.rows).toMatchObject({ order: "rowid" });
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([["b"], ["a"]]);
|
|
});
|
|
|
|
it("does not decode an unselected malformed primary-key name on a rowid table", async () => {
|
|
// `key` is the declared primary key, but a rowid table orders by an alias, so
|
|
// its name never reaches ORDER BY. A selection that omits it must stay
|
|
// readable even when the stored name is not valid UTF-8.
|
|
const path = await createApplicationDatabase(
|
|
`CREATE TABLE wide("key" INTEGER PRIMARY KEY, label TEXT);
|
|
INSERT INTO wide("key", label) VALUES (1, 'a'), (2, 'b');`,
|
|
(bytes) => {
|
|
const marker = Buffer.from('"key"');
|
|
const offset = bytes.indexOf(marker);
|
|
if (offset < 0 || bytes.indexOf(marker, offset + 1) !== -1)
|
|
throw new Error("Expected unique authored key marker");
|
|
bytes[offset + 1] = 0xff;
|
|
},
|
|
);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "wide",
|
|
schema_scope: "inventory",
|
|
columns: ["label"],
|
|
row_limit: 20,
|
|
});
|
|
expect(result.rows).toMatchObject({ order: "rowid" });
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([["a"], ["b"]]);
|
|
});
|
|
|
|
it("orders a WITHOUT ROWID table by its primary key, including DESC direction and collation", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE ordered(k INTEGER, label TEXT COLLATE NOCASE, PRIMARY KEY(k DESC, label)) WITHOUT ROWID;
|
|
CREATE INDEX ordered_label ON ordered(label);
|
|
INSERT INTO ordered VALUES (1, 'b'), (3, 'a'), (2, 'c'), (3, 'd');`);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "ordered",
|
|
row_limit: 20,
|
|
});
|
|
expect(result.rows).toMatchObject({ order: "primary_key", truncated: false });
|
|
// k DESC, then label in its declared NOCASE order for equal keys.
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([
|
|
["3", "a"],
|
|
["3", "d"],
|
|
["2", "c"],
|
|
["1", "b"],
|
|
]);
|
|
});
|
|
|
|
it("keeps repeated primary-key terms in the order the index states them", async () => {
|
|
// PRIMARY KEY(a COLLATE BINARY, a COLLATE NOCASE DESC) is a valid composite
|
|
// key; collapsing the two terms to one column would advertise a unique order
|
|
// the key does not establish and read the offset window out of order.
|
|
const path = await createDatabase(`
|
|
CREATE TABLE repeated(a TEXT, PRIMARY KEY(a COLLATE BINARY, a COLLATE NOCASE DESC)) WITHOUT ROWID;
|
|
INSERT INTO repeated VALUES ('A'), ('a'), ('B');`);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "repeated",
|
|
row_limit: 20,
|
|
});
|
|
expect(result.rows).toMatchObject({ order: "primary_key" });
|
|
// BINARY order over the whole key: A (65), B (66), then a (97). Dropping the
|
|
// first term would sort by NOCASE DESC instead and put B first.
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([["A"], ["B"], ["a"]]);
|
|
});
|
|
|
|
it("orders by the first rowid spelling the table leaves unshadowed", async () => {
|
|
// Declaring `rowid` makes that spelling resolve to the stored column, so
|
|
// ORDER BY rowid would sort by a non-unique value instead of the row id.
|
|
const path =
|
|
await createDatabase(`CREATE TABLE shadowed(rowid TEXT, value TEXT);
|
|
INSERT INTO shadowed(rowid, value) VALUES ('z', 'first'), ('a', 'second'), ('z', 'third');`);
|
|
const first = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "shadowed",
|
|
row_limit: 2,
|
|
});
|
|
expect(first.rows).toMatchObject({
|
|
order: "rowid",
|
|
row_offset: 0,
|
|
truncated: true,
|
|
next_row_offset: 2,
|
|
});
|
|
expect(
|
|
first.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([
|
|
["z", "first"],
|
|
["a", "second"],
|
|
]);
|
|
const second = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "shadowed",
|
|
row_limit: 2,
|
|
row_offset: first.rows?.next_row_offset ?? 0,
|
|
});
|
|
// The page continues in insertion order rather than re-sorting by the text
|
|
// column that shadows `rowid`.
|
|
expect(
|
|
second.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([["z", "third"]]);
|
|
});
|
|
|
|
it("does not publish a next offset the row-offset rule would refuse", async () => {
|
|
const path = await createDatabase(
|
|
`CREATE TABLE shadowed(rowid TEXT, _rowid_ TEXT, oid TEXT);
|
|
INSERT INTO shadowed VALUES ('a', 'a', 'a'), ('b', 'b', 'b');`,
|
|
);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "shadowed",
|
|
row_limit: 1,
|
|
});
|
|
expect(result.rows).toMatchObject({
|
|
order: "unspecified",
|
|
truncated: true,
|
|
next_row_offset: null,
|
|
});
|
|
});
|
|
|
|
it("pages by a declared rowid alias when all standard names are shadowed", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE keyed("item id" INTEGER PRIMARY KEY, "RoWiD" TEXT,
|
|
"_rowid_" TEXT, "OID" TEXT, label TEXT);
|
|
INSERT INTO keyed("item id", label) VALUES (20, 'later'), (4, 'first');
|
|
`);
|
|
const input = {
|
|
path,
|
|
table: "keyed",
|
|
schema_scope: "inventory" as const,
|
|
columns: ["label"],
|
|
row_limit: 1,
|
|
};
|
|
const first = inspectSqliteDatabaseSnapshot(path, input);
|
|
expect(first.rows).toMatchObject({
|
|
order: "rowid",
|
|
columns: ["label"],
|
|
values: [[{ type: "text", value: "first" }]],
|
|
truncated: true,
|
|
next_row_offset: 1,
|
|
});
|
|
const next = inspectSqliteDatabaseSnapshot(path, {
|
|
...input,
|
|
row_offset: 1,
|
|
});
|
|
expect(next.rows).toMatchObject({
|
|
order: "rowid",
|
|
row_offset: 1,
|
|
values: [[{ type: "text", value: "later" }]],
|
|
truncated: false,
|
|
next_row_offset: null,
|
|
});
|
|
});
|
|
|
|
it("discovers a WITHOUT ROWID primary key the inventory projection omits", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE keyed(k INTEGER, label TEXT, PRIMARY KEY(k)) WITHOUT ROWID;
|
|
INSERT INTO keyed VALUES (2, 'b'), (1, 'a');`);
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "keyed",
|
|
schema_scope: "inventory",
|
|
columns: ["label"],
|
|
row_limit: 1,
|
|
});
|
|
expect(result.rows).toMatchObject({
|
|
order: "primary_key",
|
|
columns: ["label"],
|
|
truncated: true,
|
|
next_row_offset: 1,
|
|
});
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((cell) => ("value" in cell ? cell.value : cell.type)),
|
|
),
|
|
).toEqual([["a"]]);
|
|
});
|
|
|
|
it.each(["", ", key INTEGER PRIMARY KEY DESC", ", key INT PRIMARY KEY"])(
|
|
"refuses a row offset for shadowed built-in names without a declared rowid alias (%s)",
|
|
async (keyDeclaration) => {
|
|
const path = await createDatabase(
|
|
`CREATE TABLE shadowed(rowid TEXT, _rowid_ TEXT, oid TEXT${keyDeclaration});
|
|
INSERT INTO shadowed(rowid, _rowid_, oid) VALUES ('a', 'a', 'a'), ('b', 'b', 'b');`,
|
|
);
|
|
expect(
|
|
inspectSqliteDatabaseSnapshot(path, { path, table: "shadowed" }).rows,
|
|
).toMatchObject({
|
|
order: "unspecified",
|
|
row_offset: 0,
|
|
next_row_offset: null,
|
|
});
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "shadowed",
|
|
row_offset: 1,
|
|
}),
|
|
).toThrow(
|
|
expect.objectContaining({
|
|
reason: "row-offset",
|
|
message: expect.stringContaining("row_offset"),
|
|
}),
|
|
);
|
|
},
|
|
);
|
|
|
|
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");
|
|
},
|
|
);
|
|
|
|
it("classifies SQLite's result-column capacity refusal without blaming the database", async () => {
|
|
const path = await createDatabase(
|
|
"CREATE TABLE records(email TEXT); INSERT INTO records VALUES ('sample');",
|
|
);
|
|
const reader = new DatabaseSync(path, { readOnly: true });
|
|
const engineColumnLimit = (() => {
|
|
try {
|
|
return reader.limits.column;
|
|
} finally {
|
|
reader.close();
|
|
}
|
|
})();
|
|
const columns = (count: number): string[] =>
|
|
Array.from({ length: count }, () => "email");
|
|
const atLimit = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "records",
|
|
columns: columns(engineColumnLimit),
|
|
});
|
|
expect(atLimit.rows).toMatchObject({
|
|
columns: columns(engineColumnLimit),
|
|
returned_rows: 1,
|
|
});
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "records",
|
|
columns: columns(engineColumnLimit + 1),
|
|
}),
|
|
).toThrow(
|
|
expect.objectContaining({
|
|
reason: "column-limit",
|
|
selectedColumns: engineColumnLimit + 1,
|
|
engineColumnLimit,
|
|
message: expect.stringContaining("too many columns in result set"),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it.each(["inventory", "selected_table", "database"] as const)(
|
|
"keeps unavailable row sources separate from generated expressions in %s scope",
|
|
async (schema_scope) => {
|
|
const workspace = await createTestWorkspace("rea-sqlite-collation-");
|
|
onTestFinished(() => removeTestWorkspace(workspace.root));
|
|
const path = createSqliteApplicationCollationFixture(workspace.root);
|
|
const before = await readFile(path);
|
|
const schema = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
schema_scope: "database",
|
|
});
|
|
expect(schema.rows).toBeNull();
|
|
expect(schema.schema.tables[0]).toMatchObject({
|
|
name: "items",
|
|
without_rowid: true,
|
|
sql: expect.stringContaining("COLLATE APPLICATION_COLLATION"),
|
|
columns: [
|
|
expect.objectContaining({ name: "name", hidden: 0 }),
|
|
expect.objectContaining({ name: "value", hidden: 0 }),
|
|
expect.objectContaining({ name: "generated_value", hidden: 2 }),
|
|
],
|
|
});
|
|
for (const columns of [undefined, ["value"], ["generated_value"]])
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
schema_scope,
|
|
...(columns === undefined ? {} : { columns }),
|
|
}),
|
|
).toThrow(
|
|
expect.objectContaining({
|
|
reason: "row-evaluation",
|
|
message: expect.stringMatching(
|
|
/rows of table "items".*(?:no query solution|no such collation sequence)/,
|
|
),
|
|
}),
|
|
);
|
|
expect(Buffer.compare(await readFile(path), before)).toBe(0);
|
|
},
|
|
);
|
|
|
|
describe("SQLite short-page truncation and reusable TextDecoder codecs", () => {
|
|
it("skips redundant truncation probes on short pages while classifying exact-fit pages accurately", async () => {
|
|
const path = await createDatabase(`
|
|
CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT);
|
|
INSERT INTO items (label) VALUES ('first'), ('second'), ('third');
|
|
`);
|
|
const prepareSpy = vi.spyOn(DatabaseSync.prototype, "prepare");
|
|
const probeQueries = (): string[] =>
|
|
prepareSpy.mock.calls
|
|
.map(([sql]) => sql)
|
|
.filter((sql) => /^SELECT 1 FROM .* LIMIT 1 OFFSET \?$/.test(sql));
|
|
|
|
try {
|
|
prepareSpy.mockClear();
|
|
const shortPage = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 10,
|
|
});
|
|
expect(shortPage.rows).toMatchObject({
|
|
row_offset: 0,
|
|
row_limit: 10,
|
|
truncated: false,
|
|
next_row_offset: null,
|
|
});
|
|
expect(shortPage.rows?.values).toHaveLength(3);
|
|
expect(probeQueries()).toHaveLength(0);
|
|
|
|
prepareSpy.mockClear();
|
|
const exactNonTruncated = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 3,
|
|
});
|
|
expect(exactNonTruncated.rows).toMatchObject({
|
|
row_limit: 3,
|
|
truncated: false,
|
|
next_row_offset: null,
|
|
});
|
|
expect(exactNonTruncated.rows?.values).toHaveLength(3);
|
|
expect(probeQueries()).toHaveLength(1);
|
|
|
|
prepareSpy.mockClear();
|
|
const exactTruncated = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_limit: 2,
|
|
});
|
|
expect(exactTruncated.rows).toMatchObject({
|
|
row_limit: 2,
|
|
truncated: true,
|
|
next_row_offset: 2,
|
|
});
|
|
expect(exactTruncated.rows?.values).toHaveLength(2);
|
|
expect(probeQueries()).toHaveLength(1);
|
|
|
|
prepareSpy.mockClear();
|
|
const offsetShortPage = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
row_offset: 2,
|
|
row_limit: 5,
|
|
});
|
|
expect(offsetShortPage.rows).toMatchObject({
|
|
row_offset: 2,
|
|
row_limit: 5,
|
|
truncated: false,
|
|
next_row_offset: null,
|
|
});
|
|
expect(offsetShortPage.rows?.values).toHaveLength(1);
|
|
expect(probeQueries()).toHaveLength(0);
|
|
} finally {
|
|
prepareSpy.mockRestore();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{
|
|
encoding: "UTF-8",
|
|
markerBytes: Buffer.from("schema-marker", "utf8"),
|
|
corruptBytes: [0xff],
|
|
},
|
|
{
|
|
encoding: "UTF-16le",
|
|
markerBytes: Buffer.from("schema-marker", "utf16le"),
|
|
corruptBytes: [0x00, 0xd8],
|
|
},
|
|
{
|
|
encoding: "UTF-16be",
|
|
markerBytes: Buffer.from("schema-marker", "utf16le").swap16(),
|
|
corruptBytes: [0xd8, 0x00],
|
|
},
|
|
] as const)(
|
|
"resets shared %s fatal and lenient decoders cleanly after malformed schema errors",
|
|
async ({ encoding, markerBytes, corruptBytes }) => {
|
|
const badPath = await createDatabase(
|
|
`PRAGMA encoding='${encoding}'; CREATE TABLE records(value TEXT /*schema-marker*/);`,
|
|
);
|
|
const raw = await readFile(badPath);
|
|
const index = raw.indexOf(markerBytes);
|
|
expect(index).toBeGreaterThanOrEqual(0);
|
|
corruptBytes.forEach((byte, offset) => {
|
|
raw[index + offset] = byte;
|
|
});
|
|
await writeFile(badPath, raw);
|
|
|
|
expect(() =>
|
|
inspectSqliteDatabaseSnapshot(badPath, {
|
|
path: badPath,
|
|
schema_scope: "database",
|
|
}),
|
|
).toThrowError(
|
|
expect.objectContaining({
|
|
reason: "malformed",
|
|
message: expect.stringContaining(`malformed ${encoding} text`),
|
|
}),
|
|
);
|
|
|
|
const goodPath = await createDatabase(`
|
|
PRAGMA encoding='${encoding}';
|
|
CREATE TABLE "t_é𝄞" (label TEXT);
|
|
INSERT INTO "t_é𝄞" VALUES ('\uFEFFalpha'), ('bravo𝄞');
|
|
`);
|
|
for (let pass = 0; pass < 2; pass++) {
|
|
const result = inspectSqliteDatabaseSnapshot(goodPath, {
|
|
path: goodPath,
|
|
table: "t_é𝄞",
|
|
schema_scope: "database",
|
|
});
|
|
expect(result.database_encoding).toBe(encoding);
|
|
expect(result.schema.tables).toMatchObject([{ name: "t_é𝄞" }]);
|
|
expect(
|
|
result.rows?.values.map((row) =>
|
|
row.map((entry) => ("value" in entry ? entry.value : entry.type)),
|
|
),
|
|
).toEqual([["\uFEFFalpha"], ["bravo𝄞"]]);
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
const encodeTextBytes = (
|
|
value: string,
|
|
encoding: "UTF-8" | "UTF-16le" | "UTF-16be",
|
|
): Buffer => {
|
|
const bytes = Buffer.from(value, encoding === "UTF-8" ? "utf8" : "utf16le");
|
|
if (encoding === "UTF-16be") bytes.swap16();
|
|
return bytes;
|
|
};
|
|
|
|
describe("SQLite lenient text decoder isolation across cells", () => {
|
|
it.each([
|
|
{
|
|
encoding: "UTF-8",
|
|
incompleteHex: "61f09f",
|
|
secondMalformedHex: "ff00c0af62e282",
|
|
secondMalformedValue: "\uFFFD\0\uFFFD\uFFFDb\uFFFD",
|
|
},
|
|
{
|
|
encoding: "UTF-16le",
|
|
incompleteHex: "610000d8",
|
|
secondMalformedHex: "410042",
|
|
secondMalformedValue: "A\uFFFD",
|
|
},
|
|
{
|
|
encoding: "UTF-16be",
|
|
incompleteHex: "0061d800",
|
|
secondMalformedHex: "004100",
|
|
secondMalformedValue: "A\uFFFD",
|
|
},
|
|
] as const)(
|
|
"flushes malformed %s cells before decoding subsequent BOM-prefixed cells",
|
|
async ({
|
|
encoding,
|
|
incompleteHex,
|
|
secondMalformedHex,
|
|
secondMalformedValue,
|
|
}) => {
|
|
const follow1 = "\uFEFFalphaé𝄞";
|
|
const follow2 = "\uFEFFbravo𝄞";
|
|
const path = await createDatabase(
|
|
`PRAGMA encoding='${encoding}'; CREATE TABLE items(id INTEGER PRIMARY KEY, first TEXT, pad INTEGER, second TEXT);`,
|
|
);
|
|
const writer = new DatabaseSync(path);
|
|
try {
|
|
writer
|
|
.prepare(
|
|
`INSERT INTO items VALUES (1, CAST(X'${incompleteHex}' AS TEXT), 0, ?)`,
|
|
)
|
|
.run(follow1);
|
|
if (encoding === "UTF-8") {
|
|
writer
|
|
.prepare(
|
|
`INSERT INTO items VALUES (2, CAST(X'${secondMalformedHex}' AS TEXT), 0, ?)`,
|
|
)
|
|
.run(follow2);
|
|
} else {
|
|
writer
|
|
.prepare("INSERT INTO items VALUES (2, 'AB', 258, ?)")
|
|
.run(follow2);
|
|
}
|
|
} finally {
|
|
writer.close();
|
|
}
|
|
if (encoding !== "UTF-8") {
|
|
const raw = await readFile(path);
|
|
const ab = encodeTextBytes("AB", encoding);
|
|
const follow2Bytes = encodeTextBytes(follow2, encoding);
|
|
const serialType = 13 + 2 * follow2Bytes.length;
|
|
const needle = Buffer.concat([
|
|
Buffer.from([0x05, 0x00, 0x15, 0x02, serialType]),
|
|
ab,
|
|
Buffer.from([0x01, 0x02]),
|
|
follow2Bytes,
|
|
]);
|
|
const index = raw.indexOf(needle);
|
|
expect(index).toBeGreaterThanOrEqual(0);
|
|
expect(raw.indexOf(needle, index + 1)).toBe(-1);
|
|
// Shrink `first` from 4 bytes ('AB') to 3 odd bytes while expanding
|
|
// `pad` from a 2-byte to a 3-byte integer so the record size holds.
|
|
raw[index + 2] = 0x13;
|
|
raw[index + 3] = 0x03;
|
|
await writeFile(path, raw);
|
|
}
|
|
|
|
const result = inspectSqliteDatabaseSnapshot(path, {
|
|
path,
|
|
table: "items",
|
|
columns: ["first", "second"],
|
|
});
|
|
expect(result.database_encoding).toBe(encoding);
|
|
expect(result.rows?.values).toEqual([
|
|
[
|
|
{
|
|
type: "text",
|
|
value: "a\uFFFD",
|
|
bytes_hex: incompleteHex,
|
|
encoding,
|
|
},
|
|
{
|
|
type: "text",
|
|
value: follow1,
|
|
bytes_hex: encodeTextBytes(follow1, encoding).toString("hex"),
|
|
encoding,
|
|
},
|
|
],
|
|
[
|
|
{
|
|
type: "text",
|
|
value: secondMalformedValue,
|
|
bytes_hex: secondMalformedHex,
|
|
encoding,
|
|
},
|
|
{
|
|
type: "text",
|
|
value: follow2,
|
|
bytes_hex: encodeTextBytes(follow2, encoding).toString("hex"),
|
|
encoding,
|
|
},
|
|
],
|
|
]);
|
|
},
|
|
);
|
|
});
|