refactor(sqlite): classify database failures through the shared provider classifier

This commit is contained in:
morluto committed 2026-11-15 02:48:07 -05:00
1 parent 161f0ad1d6
commit 075dc37842
6 files changed
+153 -184

No files matched your search

@@ -62,7 +62,6 @@
"src/process/privateWorkspaceFailure.ts": 1,
"src/providers/AnalysisClientFailure.ts": 1,
"src/providers/OwnedCommandCleanup.ts": 2,
"src/rust/RustBinaryProvider.ts": 1,
"src/sqlite/SqliteDatabaseFailures.ts": 1
"src/rust/RustBinaryProvider.ts": 1
}
}
+105 -138
View File
@@ -3,7 +3,6 @@ import { stableArtifactInputFailure } from "../artifacts/StableArtifactFailure.j
import {
ArtifactFileCleanupFailure,
bindArtifactFileCleanup,
artifactFileCancellationCause,
} from "../artifacts/ArtifactFileOperation.js";
import {
projectAnalysisError,
@@ -16,11 +15,9 @@ import {
} from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCapabilityUnavailableError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
@@ -38,6 +35,10 @@ import {
import { SQLITE_PROVIDER_IDENTITY } from "../domain/sqlite/SqliteProviderIdentity.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
import { SqliteSnapshotAcquisitionFailure } from "./SqliteDatabaseSnapshot.js";
import {
classifyProviderFailure,
type ProviderFailureDialect,
} from "../providers/classifyProviderFailure.js";
/** Preserve diagnostics independently of worker exit and private-root cleanup. */
export const capturedSqliteOutput = (
@@ -86,154 +87,120 @@ const busyMember = (cause: Error, path: string): string => {
: path;
};
/** Preserve artifact, caller, process, resource and output failure meanings. */
export const sqliteDatabaseFailure = (
cause: unknown,
const OPERATION = "inspect_sqlite_database";
/**
* The SQLite dialect for the shared provider failure classifier: snapshot
* acquisition, the selected database file set, and the owned worker.
*/
export const sqliteDatabaseDialect = (
path: string,
phase: string,
signal?: AbortSignal,
workerTimeoutMs = DEFAULT_SQLITE_WORKER_TIMEOUT_MS,
): AnalysisError => {
const operation = "inspect_sqlite_database";
if (cause instanceof SqliteSnapshotAcquisitionFailure) {
const failure = sqliteDatabaseFailure(
cause.operationCause,
path,
phase,
signal,
workerTimeoutMs,
);
const diagnostics = {
snapshot_acquisition: {
consistency: "unverified",
members: cause.completedMembers.map((member) => ({ ...member })),
},
};
failure.retainPrimaryDiagnostics(diagnostics);
return failure;
}
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure) {
if (cause.cleanup !== undefined) {
const physicalRead =
cause instanceof ArtifactFileCleanupFailure
? cause.fileCleanupFailure.outcome
: undefined;
let previous: AnalysisError | undefined;
if (physicalRead?.kind === "failed")
previous = sqliteDatabaseFailure(
physicalRead.cause,
path,
phase,
undefined,
workerTimeoutMs,
);
else if (cause.reason === "cancelled")
previous = new AnalysisCancelledError(operation, {
cause: artifactFileCancellationCause(cause),
): ProviderFailureDialect => {
const dialect: ProviderFailureDialect = {
providerId: SQLITE_PROVIDER_IDENTITY.id,
operation: OPERATION,
recognise: (cause) => {
if (cause instanceof SqliteSnapshotAcquisitionFailure)
return classifyProviderFailure(
cause.operationCause,
dialect,
).retainPrimaryDiagnostics({
snapshot_acquisition: {
consistency: "unverified",
members: cause.completedMembers.map((member) => ({ ...member })),
},
});
else if (physicalRead?.kind === "completed") previous = undefined;
else if (cause.cause !== undefined)
previous = sqliteDatabaseFailure(
cause.cause,
path,
phase,
undefined,
workerTimeoutMs,
if (cause instanceof ArtifactReaderFailure) {
if (cause.reason === "io" && cause.cause !== undefined)
return classifyProviderFailure(cause.cause, dialect);
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(
OPERATION,
path,
cause.message,
{ cause },
);
// The shared owner reports the read's cancellation.
return cause.reason === "cancelled"
? undefined
: stableArtifactInputFailure(cause, OPERATION);
}
if (cause instanceof Error && cause.name === "AbortError")
return new AnalysisCancelledError(OPERATION, {
cause:
signal?.aborted === true && cause.cause === signal.reason
? signal.reason
: cause,
});
if (cause instanceof OwnedCommandFailure)
return ownedCommandFailure(cause, path, workerTimeoutMs);
// Windows reports a sharing violation as EBUSY: another process holds
// the file without read sharing. The unchanged request succeeds once
// that process releases it. Name the member of the file set that was
// busy (the database, its WAL or its journal) when the error says.
if (
phase === "artifact-read" &&
cause instanceof Error &&
"code" in cause &&
cause.code === "EBUSY"
)
return new AnalysisCapabilityUnavailableError(
SQLITE_PROVIDER_IDENTITY.id,
OPERATION,
`Selected database file set is in use by another process (EBUSY): ${busyMember(cause, path)}`,
{
cause,
retryable: true,
userMessage:
"The selected SQLite database is held open by another process without read sharing. Close that application or inspect a copy, then retry.",
},
);
return undefined;
},
// A database file the read could not open names the selected file set.
...(phase === "artifact-read"
? { file: { path, description: "database file set" } }
: {}),
readCleanup: (read, primary) => {
// A plain read failure carries its physical cause beside the cleanup.
const previous =
primary ??
(read instanceof ArtifactFileCleanupFailure || read.cause === undefined
? undefined
: classifyProviderFailure(read.cause, dialect));
const error = createSqliteCleanupError(
cause.cleanup.resources,
read.cleanup.resources,
{ reason: read.cleanup.reason },
{
reason: cause.cleanup.reason,
},
{
cause,
cause: read,
...(previous === undefined ? {} : { cleanupPrimary: previous }),
},
);
bindArtifactFileCleanup(cause, error);
bindArtifactFileCleanup(read, error);
return error;
}
if (cause.reason === "io" && cause.cause !== undefined)
return sqliteDatabaseFailure(
cause.cause,
path,
phase,
signal,
workerTimeoutMs,
);
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(operation, path, cause.message, {
cause,
});
if (cause.reason === "cancelled")
return new AnalysisCancelledError(operation, {
cause: artifactFileCancellationCause(cause),
});
return stableArtifactInputFailure(cause, operation);
}
if (cause instanceof Error && cause.name === "AbortError")
return new AnalysisCancelledError(operation, {
cause:
signal?.aborted === true && cause.cause === signal.reason
? signal.reason
: cause,
});
if (cause instanceof OwnedCommandFailure) {
const projected = ownedCommandFailure(cause, path, workerTimeoutMs);
if (projected !== undefined) return projected;
}
if (phase === "artifact-read" && cause instanceof Error && "code" in cause) {
if (cause.code === "EACCES" || cause.code === "EPERM")
return new AnalysisAccessDeniedError(operation, path, cause.code, {
cause,
});
// Windows reports a sharing violation as EBUSY: another process holds the file without read
// sharing. The unchanged request succeeds once that process releases it. Name the member of the
// file set that was busy (the database, its WAL or its journal) when the error identifies it.
if (cause.code === "EBUSY")
return new AnalysisCapabilityUnavailableError(
SQLITE_PROVIDER_IDENTITY.id,
operation,
`Selected database file set is in use by another process (EBUSY): ${busyMember(cause, path)}`,
{
cause,
retryable: true,
userMessage:
"The selected SQLite database is held open by another process without read sharing. Close that application or inspect a copy, then retry.",
},
);
if (
cause.code === "ENOENT" ||
cause.code === "ENOTDIR" ||
cause.code === "ELOOP" ||
cause.code === "ENAMETOOLONG"
)
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected database file set could not be read (${String(cause.code)}): ${path}`,
},
]);
}
return new ProviderAdapterError(SQLITE_PROVIDER_IDENTITY.id, operation, {
cause,
diagnostics: {
phase,
path,
reason: cause instanceof Error ? cause.message : String(cause),
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
failure_kind: cause.reason,
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
captured_output: { ...capturedSqliteOutput(cause.snapshot) },
}
: {}),
},
});
unclassified: (cause) =>
new ProviderAdapterError(SQLITE_PROVIDER_IDENTITY.id, OPERATION, {
cause,
diagnostics: {
phase,
path,
reason: cause instanceof Error ? cause.message : String(cause),
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
failure_kind: cause.reason,
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
captured_output: { ...capturedSqliteOutput(cause.snapshot) },
}
: {}),
},
}),
};
return dialect;
};
const ownedCommandFailure = (
+11 -10
View File
@@ -3,6 +3,7 @@ import {
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
import type { SqliteDatabasePort } from "../application/sqlite/SqliteDatabasePort.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
@@ -43,7 +44,7 @@ import type {
} from "../process/ProviderProcess.js";
import {
createSqliteCleanupError,
sqliteDatabaseFailure,
sqliteDatabaseDialect,
} from "./SqliteDatabaseFailures.js";
import { captureSqliteDatabaseSnapshot } from "./SqliteDatabaseSnapshot.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
@@ -118,11 +119,9 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort {
.run(() => this.#inspect(input, options))
.catch((cause: unknown) =>
err(
sqliteDatabaseFailure(
classifyProviderFailure(
cause,
input.path,
"artifact-read",
options?.signal,
sqliteDatabaseDialect(input.path, "artifact-read", options?.signal),
),
),
);
@@ -343,12 +342,14 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort {
cause.cleanupOwner !== undefined
)
processOwner = cause.cleanupOwner;
const failure = sqliteDatabaseFailure(
const failure = classifyProviderFailure(
cause,
input.path,
phase,
options?.signal,
workerTimeoutMs,
sqliteDatabaseDialect(
input.path,
phase,
options?.signal,
workerTimeoutMs,
),
);
retainedOutput ??= failure.capturedOutput;
result = err(failure);
+16 -13
View File
@@ -7,6 +7,7 @@ import {
rm,
writeFile,
} from "node:fs/promises";
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -21,7 +22,7 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { AnalysisPartialObservation } from "../domain/analysisErrorBase.js";
import { captureSqliteDatabaseSnapshot } from "./SqliteDatabaseSnapshot.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
import { sqliteDatabaseFailure } from "./SqliteDatabaseFailures.js";
import { sqliteDatabaseDialect } from "./SqliteDatabaseFailures.js";
it("tags an exact caller reason at snapshot admission", async () => {
const workspace = await mkdtemp(join(tmpdir(), "rea-sqlite-snapshot-entry-"));
@@ -47,11 +48,13 @@ it("tags an exact caller reason at snapshot admission", async () => {
reason: "cancelled",
cancellation: { reason },
});
const projected = sqliteDatabaseFailure(
const projected = classifyProviderFailure(
failure,
join(workspace, "selected.db"),
"artifact-read",
controller.signal,
sqliteDatabaseDialect(
join(workspace, "selected.db"),
"artifact-read",
controller.signal,
),
);
expect(projected).toBeInstanceOf(AnalysisCancelledError);
expect(projected.cause).toBe(reason);
@@ -99,11 +102,9 @@ it("keeps the exact caller reason when cancellation lands at final snapshot veri
},
(cause: unknown) => cause,
);
const projected = sqliteDatabaseFailure(
const projected = classifyProviderFailure(
failure,
databasePath,
"artifact-read",
controller.signal,
sqliteDatabaseDialect(databasePath, "artifact-read", controller.signal),
);
expect(journalStats).toBe(2);
expect(projected).toBeInstanceOf(AnalysisCancelledError);
@@ -161,7 +162,10 @@ it("reports filesystem sizes above the safe-integer range exactly before opening
(cause: unknown) => cause,
);
const projected = projectAnalysisError(
sqliteDatabaseFailure(failure, databasePath, "artifact-read"),
classifyProviderFailure(
failure,
sqliteDatabaseDialect(databasePath, "artifact-read"),
),
);
expect(failure).toMatchObject({
_tag: "AnalysisResourceConstraintError",
@@ -274,10 +278,9 @@ it.each([
cause: expect.any(ArtifactReaderFailure),
});
expect(failure).toMatchObject({ partialObservation, details });
const projectedFailure = sqliteDatabaseFailure(
const projectedFailure = classifyProviderFailure(
failure,
databasePath,
"artifact-read",
sqliteDatabaseDialect(databasePath, "artifact-read"),
);
if (retainCleanup) {
expect(projectedFailure).toBeInstanceOf(ProviderCleanupError);
@@ -1,8 +1,9 @@
import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
import { classifyProviderFailure } from "../../../src/providers/classifyProviderFailure.js";
import { expect, it } from "vitest";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { sqliteDatabaseFailure } from "../../../src/sqlite/SqliteDatabaseFailures.js";
import { sqliteDatabaseDialect } from "../../../src/sqlite/SqliteDatabaseFailures.js";
import { SQLITE_DATABASE_LIMITS } from "../../../src/sqlite/SqliteDatabaseLimits.js";
it.each([null, "owned stop unconfirmed"])(
@@ -21,12 +22,9 @@ it.each([null, "owned stop unconfirmed"])(
undefined,
["pid:owned-fixture"],
);
const failure = sqliteDatabaseFailure(
const failure = classifyProviderFailure(
cause,
"/selected.db",
"worker",
undefined,
1234,
sqliteDatabaseDialect("/selected.db", "worker", undefined, 1234),
);
expect(failure.cause).toBe(cause);
const projected = projectAnalysisError(failure);
@@ -76,12 +74,9 @@ it.each([null, "owned stop unconfirmed"])(
it("does not recommend a timer above the supported maximum", () => {
const failure = projectAnalysisError(
sqliteDatabaseFailure(
classifyProviderFailure(
new OwnedCommandFailure("timeout", "deadline"),
"/selected.db",
"worker",
undefined,
2_147_483_647,
sqliteDatabaseDialect("/selected.db", "worker", undefined, 2_147_483_647),
),
);
expect(failure.details).toMatchObject({ timeout_ms: 2_147_483_647 });
@@ -91,10 +86,9 @@ it("does not recommend a timer above the supported maximum", () => {
it("says diagnostic capture has no runtime override", () => {
const projected = projectAnalysisError(
sqliteDatabaseFailure(
classifyProviderFailure(
new OwnedCommandFailure("output-limit", "diagnostics exceeded"),
"/selected.db",
"worker",
sqliteDatabaseDialect("/selected.db", "worker"),
),
);
expect(projected.remediation.action).toContain(
@@ -130,7 +124,10 @@ it.each(["/selected.db", "./Database files/another.db"])(
invalidUtf8: false,
},
});
const failure = sqliteDatabaseFailure(cause, path, "worker");
const failure = classifyProviderFailure(
cause,
sqliteDatabaseDialect(path, "worker"),
);
expect(failure.cause).toBe(cause);
expect(projectAnalysisError(failure)).toMatchObject({
code: "resource_constraint",
@@ -161,11 +158,9 @@ it("does not infer cancellation from a later signal when cleanup carries no canc
cleanup: { reason: "close failed", resources: ["/owned/reply.json"] },
});
controller.abort(new Error("later caller cancellation"));
const failure = sqliteDatabaseFailure(
const failure = classifyProviderFailure(
cause,
"/selected.db",
"worker",
controller.signal,
sqliteDatabaseDialect("/selected.db", "worker", controller.signal),
);
expect(failure.cleanupIncomplete).toBe(true);
expect(failure.cleanupPrimary).toBeUndefined();
@@ -8,6 +8,7 @@ import {
utimes,
writeFile,
} from "node:fs/promises";
import { classifyProviderFailure } from "../../../src/providers/classifyProviderFailure.js";
import { DatabaseSync } from "node:sqlite";
import { createHash } from "node:crypto";
import { expect, it, onTestFinished, vi } from "vitest";
@@ -15,7 +16,7 @@ import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceSc
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 { sqliteDatabaseDialect } from "../../../src/sqlite/SqliteDatabaseFailures.js";
import {
createSqliteDatabaseFixture,
SQLITE_NATIVE_LIMITS_AVAILABLE,
@@ -113,7 +114,10 @@ it.runIf(process.platform !== "win32").each([
throw new Error("A disappearing source must be rejected");
} catch (cause) {
expect(
sqliteDatabaseFailure(cause, database.path, "artifact-read"),
classifyProviderFailure(
cause,
sqliteDatabaseDialect(database.path, "artifact-read"),
),
).toMatchObject({ _tag: "AnalysisArtifactChangedError" });
expect(cause).toMatchObject({
message: expect.stringContaining(selectedPath),