Files
rea/src/sqlite/SqliteDatabaseFailures.ts
morluto bd353e7e5c fix(errors)!: producers declare retry class, refusal recovery and real error codes (#15372)
* fix(errors)!: derive retryable from the producer's declared retry class

`retryable` means the unchanged request may succeed, but it was computed
downstream as an OR of a code table and five class rules. Every error
classification now declares a retry class (same_call, change_first, never,
unknown_outcome); `retryable` is `same_call` after one incomplete-cleanup
check, and the RETRYABLE_CODES table is deleted.

Producer corrections:
- update_unknown revision conflicts are change_first and report
  details.current_revision; duplicate record_unknown reports
  details.existing_unknown_id.
- close_gdb_session's explicit-disposition refusal is change_first.
- Per-call artifact reader limits are change_first (never when the limit
  cannot rise).
- An exited or unreachable Hopper bridge, and a Hopper start that another
  REA session owns, are change_first.
- File-descriptor exhaustion (EMFILE/ENFILE) outside process launch is
  occupied host capacity (same_call) for private workspaces, model and GPU
  readers and JavaScript application reads.
- apktool JVM native-thread exhaustion follows the shared capacity default.

BREAKING CHANGE: these refusals now report `retryable: false` (descriptor
pressure now reports `retryable: true` as `resource_constraint`). Callers
that repeated them unchanged should follow the remediation first: re-read
the unknown and retry with details.current_revision, dispose GDB inferiors,
raise the reported reader limit, or restart the Hopper provider.

* fix(errors): require producers to name recovery for conforming refusals

A refusal whose arguments match the input schema was presented as a schema
error whenever its producer left out remediation, and many producers did.
AnalysisInputError's options are now a union: a conforming refusal must
supply both its outcome (userMessage) and next step (remediationAction),
so the compiler lists every producer; only contract violations may fall
back to the schema guidance.

Producers fixed: unknown Frida session and script, decompile_all
output-directory state, the duplicate unknown build computer factory
(collapsed), stale Cutter sessions, Mach-O architecture selection, output
roots that already exist, selected files the host refuses, Ghidra lookups
the bridge could not resolve, YARA path refusals, unresolved native symbol
names, apt key files and withheld sign-in state. A missing selected APK is
now target_unavailable like every other selected-file reader.

The capability fallback "Choose another analysis or target" is deleted; a
capability refusal without its own recovery names details.reason and
binary_session.

Refs #15312

* fix(errors): classify caller selections and target bytes by their real failure

Several refusals reported a code that reads as corruption or a crash:
- a missing unknown_id and a missing Evidence reference now report
  invalid_request instead of execution_failure and
  evidence_integrity_mismatch;
- close_binary with snapshot_path in a resource-only session reports
  invalid_request instead of evidence_integrity_mismatch;
- ADB push onto an existing device path and pulls into an occupied output
  directory are conforming invalid_request refusals naming overwrite or
  output_directory, not unreadable_output;
- damaged APK ZIP, signing-block, signer and central-directory structures
  are malformed targets, not invalid input;
- NuGet and VSIX bytes without a ZIP signature are unrecognized, not
  malformed;
- a historical source graph file whose entries contradict its root
  commitment is an integrity failure, not invalid input;
- a CDP protocol failure states what happened instead of the unclassified
  fallback message.

Refs #15319

* feat(errors): expose the producer's retry class as retry_class

Every error projection now carries retry_class (same_call, change_first, never or unknown_outcome) beside retryable, which stays true exactly for same_call. The field is additive: the error schema accepts errors retained by earlier releases without it.

Refs #15323

* fix(errors): address review of the folded error-contract PRs

Keep a provider's own capability message as its remediation; the binary_session fallback applies only to a bare declared reason. Delete the unused conformingInputRefusal helper. Compose both retry fields for a refused publication whose cleanup is incomplete. Report descriptor exhaustion from a JavaScript directory opendir as occupied capacity. Let an exited Hopper startup attempt without a setup failure code retry unchanged. Declare retry for the Ghidra superseded checkpoint and unknown IDA readiness. Redact ambiguous selector candidates. Give a Ghidra document miss its own recovery. Drop an unchanged-files claim the journal repair cannot make. Name each withheld sign-in refusal's step. Hash the source graph commitment before the cancellation yield. Keep the browser protocol_error message neutral. Add tests for mutation-audit survivors C3, C5, P2, P4, P8, H1, H4 and H5.

* fix(errors): keep a missing Evidence reference an integrity failure and state only the observed commitment mismatch

* test(desktop): assert the unknown build computer refusal's remediation, not its message

The refusal now carries its next step in remediation.action instead of the message, so the closed-computer checks assert the exact code, message and remediation facts.

* fix(errors): keep producer retry choices apart from cleanup and fixed ceilings

A capture's retryable flag no longer folds in pending cleanup, so the projection applies the cleanup rule once and a transient capture with pending cleanup reports change_first instead of never. A release-fixed artifact allowance reports never, and a stale admitted session identity reports change_first (reopen, then retry); both have catalogue rows. The bare capability-unavailable remediation names binary_session only for a binary-analysis session, so standalone bridges such as Cutter are pointed at their own reason.

* test(vsix): expect a non-ZIP selection to be refused as unrecognized

This PR reports bytes without a ZIP signature as another format (unrecognized), not a damaged package; the exact-reason assertion added on main still expected malformed.

* test(delivery): expect the capacity refusal's retry class in delivered failure facts

The exact failure facts asserted on main predate the projection's retry_class; occupied capacity reports same_call.

* fix(errors): mark a sent Hopper cancellation unknown and missing Evidence recoverable

A cancellation Hopper already received may still apply, so its retry class is unknown_outcome instead of same_call; an unsent cancellation keeps same_call. A missing EvidenceReferenceError is change_first, since importing the referenced records lets the same request succeed; other reference failures stay never. Both have catalogue rows.

* fix(hopper): ask for changed launch arguments before retrying an unencodable launch

A launcher path or argument that cannot be encoded as an AppleScript literal meets the same pre-launch guard on every attempt, so the start refusal is change_first and its retry_action is unknown; a start failure without a declared reason stays same_call.

* fix(errors): keep a one-shot cleanup failure's retry class with its cleanup state

A one-shot reply that reports cleanup_incomplete spread the primary or cleanup projection and overrode only retryable, so a timed-out read whose close also failed carried retry_class same_call. The reply now reads its retry class from the typed composed failure, and never offers the same call before cleanup settles.

* test(evtx): expect an unreadable selected log to be refused with its own recovery

This PR treats a well-formed path the host refused as a regular file as conforming input with its own remediation; the evtx boundary test still expected a schema-recovery refusal.

* test(javascript): expect a broken source-graph commitment as an integrity failure

This PR reports a well-formed historical source graph whose entries disagree with its root_sha256 as evidence_integrity_mismatch, not an input issue; the exact refusal assertion added on main still expected invalid_request.
2026-12-01 05:32:33 +00:00

295 lines
12 KiB
TypeScript

import {
deadlineParameterLimit,
MAX_NODE_TIMER_DELAY_MS,
} from "../domain/analysisResourceLimits.js";
import { capturedProviderOutput } from "../process/capturedProviderOutput.js";
import {
ArtifactReaderFailure,
stableArtifactInputFailure,
readerIntegrityFailure,
ArtifactFileCleanupFailure,
bindArtifactFileCleanup,
} from "../resources/index.js";
import {
projectAnalysisError,
projectAnalysisErrorWithoutCapturedOutput,
} from "../domain/analysisErrorProjection.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
AnalysisCapabilityUnavailableError,
cancelledBy,
} from "../domain/analysisErrorCore.js";
import { isAbortOf } from "../process/SignalAbort.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import type { ProviderOutcome } from "../process/ProviderOutcome.js";
import type { ProviderOutcomeContext } from "../process/classifyProviderOutcome.js";
import { DEFAULT_SQLITE_WORKER_TIMEOUT_MS } from "../domain/sqlite/sqliteDatabase.js";
import { SQLITE_PROVIDER_IDENTITY } from "../domain/sqlite/SqliteProviderIdentity.js";
import {
SQLITE_DATABASE_LIMITS,
SQLITE_WORKER_HEAP_BYTES,
} from "./SqliteDatabaseLimits.js";
import { SqliteSnapshotAcquisitionFailure } from "./SqliteDatabaseSnapshot.js";
import {
classifyProviderFailure,
type ProviderFailureDialect,
} from "../providers/classifyProviderFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** Keep typed cleanup history and one canonical output owner, including after resolution. */
export const createSqliteCleanupError = (
resources: readonly string[],
diagnostics: Readonly<Record<string, JsonValue>>,
options: Omit<AnalysisErrorOptions, "diagnostics">,
): ProviderCleanupError => {
const capturedOutput =
options.capturedOutput ?? options.cleanupPrimary?.capturedOutput;
const previous =
options.cleanupPrimary === undefined
? null
: capturedOutput === undefined
? projectAnalysisError(options.cleanupPrimary)
: projectAnalysisErrorWithoutCapturedOutput(options.cleanupPrimary);
return new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
resources,
{
...diagnostics,
previous_error: previous ?? diagnostics.previous_error ?? null,
},
{
...options,
operation: "inspect_sqlite_database",
...(capturedOutput === undefined ? {} : { capturedOutput }),
},
);
};
/** The file-set member a filesystem error names, if it is the database, its WAL or its journal. */
const busyMember = (cause: Error, path: string): string => {
const failed = "path" in cause ? cause.path : undefined;
return typeof failed === "string" &&
[path, `${path}-wal`, `${path}-journal`].includes(failed)
? failed
: path;
};
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,
): 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 })),
},
});
if (cause instanceof ArtifactReaderFailure) {
if (cause.reason === "io" && cause.cause !== undefined)
return classifyProviderFailure(cause.cause, dialect);
// The shared owner names the integrity check that failed.
if (cause.reason === "integrity")
return readerIntegrityFailure(OPERATION, path, cause);
// The shared owner reports the read's cancellation.
return cause.reason === "cancelled"
? undefined
: stableArtifactInputFailure(cause, OPERATION);
}
// Only the caller's own abort is a cancellation. An abort error with
// another reason, or with no caller abort, is classified as itself.
if (isAbortOf(cause, signal)) return cancelledBy(OPERATION, signal);
// 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,
// Like occupied capacity, the holder may release the file by itself.
retry: "same_call",
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;
},
command: (outcome) =>
sqliteWorkerCommand(outcome, path, workerTimeoutMs, { phase, path }),
commandCleanup: sqliteWorkerCleanup,
// 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(
read.cleanup.resources,
{ reason: read.cleanup.reason },
{
cause: read,
...(previous === undefined ? {} : { cleanupPrimary: previous }),
},
);
bindArtifactFileCleanup(read, error);
return error;
},
unclassified: (cause) =>
new ProviderAdapterError(SQLITE_PROVIDER_IDENTITY.id, OPERATION, {
cause,
diagnostics: {
phase,
path,
reason: errorMessage(cause),
},
}),
};
return dialect;
};
/** The selected worker deadline, its setting and what it does not cover. */
const sqliteWorkerTimeout = (
workerTimeoutMs: number,
): ProviderOutcomeContext["timeout"] => ({
ms: workerTimeoutMs,
userMessage: `The SQLite worker reached its ${String(workerTimeoutMs)} ms server/provider deadline (worker_timeout_ms). This is not a whole-inspection or MCP client deadline.`,
limit: deadlineParameterLimit(
"worker_timeout_ms",
workerTimeoutMs,
DEFAULT_SQLITE_WORKER_TIMEOUT_MS,
),
remediationAction: `${
workerTimeoutMs < MAX_NODE_TIMER_DELAY_MS
? `Increase worker_timeout_ms above ${String(workerTimeoutMs)} (integer milliseconds, maximum ${String(MAX_NODE_TIMER_DELAY_MS)}).`
: `worker_timeout_ms is already at the maximum supported ${String(MAX_NODE_TIMER_DELAY_MS)} ms; no higher worker deadline is supported. Report the blocker or narrow the question with caller approval.`
} This per-call setting needs no server restart. It covers worker startup, queries and reply writing, not snapshot acquisition or final reply reads/cleanup. Allow client headroom for the whole call; increasing only the client deadline does not change the worker budget. Keep the selected database/WAL and requested facts; narrow table/columns/schema_scope/row_limit only if the question permits it. Byte and heap safety limits remain fixed. Resolve incomplete cleanup before retrying; do not repeat the unchanged failed call.`,
});
/** The fixed diagnostic capture allowance the owned worker's output exceeded. */
const SQLITE_DIAGNOSTIC_CAPTURE = fixedAllowanceOptions(
`The SQLite worker diagnostic capture allowance of ${String(SQLITE_DATABASE_LIMITS.diagnosticBytes)} bytes (this release has no runtime override; worker_timeout_ms does not raise it)`,
"capture",
{ limit: SQLITE_DATABASE_LIMITS.diagnosticBytes, unit: "bytes" },
);
/**
* How the owned SQLite worker's outcomes report. The shared classifier owns
* cancellation, the deadline, the capture allowance and the runtime's heap
* report; an exit or a collection failure has no SQLite meaning beyond the
* facts the provider's unclassified report keeps.
*/
const sqliteWorkerCommand = (
outcome: ProviderOutcome,
selectedPath: string,
workerTimeoutMs: number,
phaseDiagnostics: Readonly<Record<string, JsonValue>>,
): ProviderOutcomeContext => ({
providerId: SQLITE_PROVIDER_IDENTITY.id,
operation: OPERATION,
capturedOutput: capturedProviderOutput,
details:
outcome.kind === "runtime-exhausted"
? { diagnostics: { selected_path: selectedPath } }
: {},
timeout: sqliteWorkerTimeout(workerTimeoutMs),
outputLimit: {
reason: `SQLite worker diagnostics exceeded the ${String(SQLITE_DATABASE_LIMITS.diagnosticBytes)}-byte capture allowance.`,
limits: {
diagnostic_capture_bytes: SQLITE_DATABASE_LIMITS.diagnosticBytes,
},
recovery: SQLITE_DIAGNOSTIC_CAPTURE,
},
runtimeExhaustion: () => ({
limits: { javascript_heap_bytes: SQLITE_WORKER_HEAP_BYTES },
recovery: {
retryable: false,
remediationAction: `The SQLite worker's ${String(SQLITE_DATABASE_LIMITS.workerHeapMiB)} MiB JavaScript heap is fixed in this release; worker_timeout_ms does not raise it. Narrow table, columns, schema_scope or row_limit only if the question permits it; repeating the unchanged request is expected to fail the same way.`,
},
}),
// The unclassified report keeps the output in its diagnostics, beside the
// examined exit facts, so the classified output is not repeated.
dialect: (exit, _details, unclassified) =>
unclassified({
capturedOutput: undefined,
diagnostics: {
...phaseDiagnostics,
...(exit.output === undefined
? {}
: {
captured_output: {
...capturedProviderOutput(exit.output.snapshot),
},
}),
},
}),
});
/**
* A worker whose cleanup failed reports that cleanup. A deadline stays its
* typed primary; any other outcome is recorded as the failure it was.
*/
const sqliteWorkerCleanup = (
command: OwnedCommandFailure & { readonly cleanupFailure: string },
primary: AnalysisError,
outcome: ProviderOutcome,
): AnalysisError => {
const timeout = outcome.kind === "timeout" ? primary : undefined;
return createSqliteCleanupError(
command.resources,
{
reason: command.cleanupFailure,
...(timeout === undefined
? {
previous_error: {
failure_kind: command.reason,
message: command.message,
},
}
: {}),
},
{
cause: command,
...(command.snapshot === null
? {}
: { capturedOutput: capturedProviderOutput(command.snapshot) }),
...(timeout === undefined ? {} : { cleanupPrimary: timeout }),
},
);
};