Files
reverse-engineering-anything/tests/boundary/sqlite/sqliteDatabaseSnapshot.test.ts
T
6f267022ed fix(errors)!: raise container reader byte faults as malformed or truncated targets (#14265)
* 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): 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): 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.

* 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.

* 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(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(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>
2026-11-24 21:17:43 -05:00

557 lines
20 KiB
TypeScript

import {
lstat,
open,
readFile,
rename,
rm,
symlink,
unlink,
utimes,
writeFile,
} from "node:fs/promises";
import { classifyProviderFailure } from "../../../src/providers/classifyProviderFailure.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { DatabaseSync } from "node:sqlite";
import { createHash } from "node:crypto";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
import type { StableArtifactFileSystem } from "../../../src/resources/readStableArtifact.js";
import { captureSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseSnapshot.js";
import { inspectSqliteDatabaseSnapshot } from "../../../src/sqlite/SqliteDatabaseInspection.js";
import { sqliteDatabaseDialect } 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,
signal?: AbortSignal,
) =>
captureSqliteDatabaseSnapshot(
database.path,
root,
resourceScope,
signal,
fileSystem,
);
return { workspace, database, root, resourceScope, 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);
if (mode === "TRUNCATE") expect(before).toHaveLength(0);
else expect(before.subarray(0, 28).equals(Buffer.alloc(28))).toBe(true);
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(Buffer.compare(await readFile(journalPath), before)).toBe(0);
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(
classifyProviderFailure(
cause,
sqliteDatabaseDialect(database.path, "artifact-read"),
),
).toMatchObject({ _tag: "AnalysisArtifactChangedError" });
expect(cause).toMatchObject({
message: expect.stringContaining(selectedPath),
});
}
},
);
it.each(["ELOOP", "ENAMETOOLONG"] as const)(
"treats %s during file acquisition as changed evidence, not an invalid input path",
async (code) => {
const { database, capture } = await fixture();
const fileSystem: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open: async (path, flags) => {
if (path === database.path)
throw Object.assign(
new Error(`${code}: path changed after observation`),
{ code },
);
return open(path, flags);
},
};
await expect(capture(fileSystem)).rejects.toMatchObject({
reason: "integrity",
message: expect.stringContaining(database.path),
});
},
);
it("retains changed-evidence semantics when a sidecar path failure follows database removal", async () => {
const { database, capture } = await fixture();
const fileSystem: StableArtifactFileSystem = {
lstat: async (path) => {
if (path === database.walPath) {
await unlink(database.path);
throw Object.assign(new Error("derived sidecar path is too long"), {
code: "ENAMETOOLONG",
});
}
return lstat(path, { bigint: true });
},
open,
};
await expect(capture(fileSystem)).rejects.toMatchObject({
reason: "integrity",
message: expect.stringContaining(database.path),
});
});
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: "unsupported",
message: expect.stringContaining("recovery"),
});
expect(Buffer.compare(await readFile(database.path), original)).toBe(0);
expect(Buffer.compare(await readFile(journalPath), journal)).toBe(0);
} 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: "unsupported" });
});
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.runIf(process.platform !== "win32")(
"does not offer a resolved-file retry for a derived WAL symlink",
async () => {
const { database, workspace, capture } = await fixture(true);
const target = workspace.path("wal-target");
await rename(database.walPath, target);
await symlink(target, database.walPath);
await expect(capture()).rejects.toMatchObject({
operationCause: { reason: "path", resolvedPath: undefined },
completedMembers: [{ role: "database", path: database.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({
_tag: "SqliteSnapshotAcquisitionFailure",
operationCause: { 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({
_tag: "SqliteSnapshotAcquisitionFailure",
operationCause: { 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({
_tag: "SqliteSnapshotAcquisitionFailure",
operationCause: { reason: "integrity" },
completedMembers: expect.arrayContaining([
{
role: "database",
path: database.path,
sha256: createHash("sha256").update(initial).digest("hex"),
bytes: initial.length,
},
]),
});
expect(changed).toBe(true);
expect(
Buffer.compare(await readFile(`${root}/database.snapshot`), initial),
).toBe(0);
});
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({
_tag: "SqliteSnapshotAcquisitionFailure",
operationCause: { reason: "integrity" },
});
expect(created).toBe(true);
},
);
describe("SQLite snapshot streaming copy and destination isolation", () => {
it("streams multi-megabyte DB and WAL files byte-for-byte", async () => {
const workspace = await createTestWorkspace("rea-sqlite-large-stream-");
const resourceScope = new ArtifactResourceScope();
const dbPath = `${workspace.root}/large.db`;
const db = new DatabaseSync(dbPath);
onTestFinished(async () => {
db.close();
await resourceScope.close();
await removeTestWorkspace(workspace.root);
});
db.exec("PRAGMA journal_mode = WAL;");
db.exec("CREATE TABLE items (id INTEGER PRIMARY KEY, payload TEXT);");
const insert = db.prepare("INSERT INTO items (payload) VALUES (?);");
const bigRow = "x".repeat(4096);
db.exec("BEGIN;");
for (let i = 0; i < 650; i += 1) insert.run(bigRow);
db.exec("COMMIT;");
// Force a checkpoint so the DB file exceeds 1 MiB, then grow the WAL > 1.2 MiB too.
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
db.exec("BEGIN;");
for (let i = 0; i < 400; i += 1) insert.run(bigRow);
db.exec("COMMIT;");
const sourceDb = await readFile(dbPath);
const sourceWal = await readFile(`${dbPath}-wal`);
expect(sourceDb.length).toBeGreaterThan(1_048_576);
expect(sourceWal.length).toBeGreaterThan(1_048_576);
const snapshotDir = await workspace.mkdir("snap-large");
const snapshot = await captureSqliteDatabaseSnapshot(
dbPath,
snapshotDir,
resourceScope,
);
expect(snapshot.wal?.path).toBe(`${dbPath}-wal`);
expect(
Buffer.compare(await readFile(snapshot.snapshotPath), sourceDb),
).toBe(0);
expect(
Buffer.compare(await readFile(`${snapshot.snapshotPath}-wal`), sourceWal),
).toBe(0);
});
it("preserves a 0-byte WAL file via lazy destination open", async () => {
const { database, root, capture } = await fixture(true);
await writeFile(database.walPath, Buffer.alloc(0));
const result = await capture();
expect(result.wal?.path).toBe(database.walPath);
expect((await readFile(`${root}/database.snapshot-wal`)).length).toBe(0);
});
it("isolates destination ENOENT from source container-identity attribution", async () => {
const { database, root, capture } = await fixture();
const fileSystem: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open: async (path, flags) => {
const handle = await open(path, flags);
if (path === database.path) {
// Removing privateRoot after source admission triggers ENOENT on destination
// open; duringAcquisition must not blame the source path as container-identity.
await rm(root, { recursive: true, force: true });
}
return handle;
},
};
const error = await capture(fileSystem).catch((cause: unknown) => cause);
expect(error).toBeInstanceOf(Error);
expect(error).toMatchObject({
code: "ENOENT",
path: `${root}/database.snapshot`,
});
});
});
describe("SQLite snapshot destination cleanup lifecycle", () => {
it("retains source and destination handles across write and close failures and retries cleanup", async () => {
const { database, root, resourceScope, capture } = await fixture();
const destinationPath = `${root}/database.snapshot`;
let denySourceClose = true;
let denyDestWrite = true;
let denyDestClose = true;
const fileSystem: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open: async (path, flags, mode) => {
const handle = await open(path, flags, mode);
const origClose = handle.close.bind(handle);
if (path === database.path) {
handle.close = async () => {
if (denySourceClose) throw new Error("source close denied");
await origClose();
};
} else if (path === destinationPath) {
const origWrite = handle.write.bind(handle);
handle.write = (async (...args: Parameters<typeof origWrite>) => {
if (denyDestWrite)
throw Object.assign(new Error("no space left on destination"), {
code: "ENOSPC",
});
return await origWrite(...args);
}) as typeof handle.write;
handle.close = async () => {
if (denyDestClose) throw new Error("destination close denied");
await origClose();
};
}
return handle;
},
};
try {
const error = await capture(fileSystem).catch((cause: unknown) => cause);
expect(error).toMatchObject({
reason: "io",
cleanup: {
resources: expect.arrayContaining([database.path, destinationPath]),
},
});
expect((error as Error).message).toContain(
"no space left on destination",
);
const providerError = classifyProviderFailure(
error,
sqliteDatabaseDialect(database.path, "snapshot-capture"),
);
expect(providerError.cleanupIncomplete).toBe(true);
expect(providerError.cleanupResources).toEqual(
expect.arrayContaining([database.path, destinationPath]),
);
await expect(resourceScope.retryCleanup()).rejects.toMatchObject({
cleanup: {
resources: expect.arrayContaining([database.path, destinationPath]),
},
});
denySourceClose = false;
denyDestClose = false;
await expect(resourceScope.retryCleanup()).resolves.toBeUndefined();
} finally {
denySourceClose = false;
denyDestClose = false;
}
});
it("handles cancellation during destination close and retains failed close until retry", async () => {
for (const failClose of [false, true]) {
const { database, root, resourceScope, capture } = await fixture();
const destinationPath = `${root}/database.snapshot`;
const controller = new AbortController();
let denyDestClose = failClose;
const fileSystem: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open: async (path, flags, mode) => {
const handle = await open(path, flags, mode);
if (path === destinationPath) {
const origClose = handle.close.bind(handle);
handle.close = async () => {
if (!controller.signal.aborted)
controller.abort(
new Error("cancelled during destination close"),
);
if (denyDestClose) throw new Error("destination close failed");
await origClose();
};
}
return handle;
},
};
try {
const error = await capture(fileSystem, controller.signal).catch(
(cause: unknown) => cause,
);
expect(error).toMatchObject({
_tag: "SqliteSnapshotAcquisitionFailure",
operationCause: { reason: "cancelled" },
});
const providerError = classifyProviderFailure(
error,
sqliteDatabaseDialect(
database.path,
"snapshot-capture",
controller.signal,
),
);
if (failClose) {
expect(providerError).toBeInstanceOf(ProviderCleanupError);
expect(providerError.cleanupPrimary?._tag).toBe(
"AnalysisCancelledError",
);
expect(error).toMatchObject({
operationCause: { cleanup: { resources: [destinationPath] } },
});
expect(providerError.cleanupIncomplete).toBe(true);
expect(providerError.cleanupResources).toEqual([destinationPath]);
denyDestClose = false;
await expect(resourceScope.retryCleanup()).resolves.toBeUndefined();
} else {
expect(providerError._tag).toBe("AnalysisCancelledError");
expect(providerError.cleanupIncomplete).toBe(false);
expect(providerError.cleanupResources).toEqual([]);
}
} finally {
denyDestClose = false;
}
}
});
});