Files
reverse-engineering-anything/src/domain/analysisErrorClassification.ts
T

700 lines
22 KiB
TypeScript

import {
AnalysisCapabilityUnavailableError,
AnalysisResourceConstraintError,
AnalysisTargetFailureError,
} from "./analysisErrorCore.js";
import {
TARGET_FAILURE_KINDS,
TARGET_FAILURE_PROJECTIONS,
targetFailureRetryClass,
type TargetFailureKind,
} from "./targetFailure.js";
import {
domainErrorTag,
type AnalysisError,
type AnalysisErrorTag,
type ProviderErrorTag,
} from "./analysisErrorBase.js";
import type { AnalysisErrorProjection } from "./analysisErrorProjection.js";
import {
ArtifactOperationError,
integrityCheckMeansChanged,
} from "./artifactOperationError.js";
import { BrowserObservationError } from "./browserObservationError.js";
import type { BrowserObservationFailureReason } from "./browserObservationErrors.js";
import {
BinaryTargetError,
type BinaryTargetErrorOptions,
} from "./configurationErrors.js";
import {
EvidenceFileError,
EvidenceReferenceError,
ResourceSnapshotMismatchError,
} from "./evidenceErrors.js";
import {
ProviderSelectionError,
type ProviderSelectionFailureReason,
} from "./providerSelectionError.js";
import { UnknownRegistryError } from "./unknownRegistryError.js";
type ErrorCode = AnalysisErrorProjection["code"];
type ErrorCategory = AnalysisErrorProjection["category"];
/**
* What the caller must do before the failed request can succeed. Only the
* failure's producer knows this, so every classification declares it:
* - `same_call`: the unchanged request may succeed later (a transient fault,
* occupied capacity, a cancellation or a deadline).
* - `change_first`: the caller must change the request or the state it reads
* first (re-read a revision, raise a limit, settle a disposition).
* - `never`: no change the caller can make to this request clears it.
* - `unknown_outcome`: the request may have taken effect; reconcile the
* resulting state before deciding to repeat it.
*/
export type AnalysisRetryClass =
| "same_call"
| "change_first"
| "never"
| "unknown_outcome";
/** The caller-facing code, category and retry class of one error case. */
export interface AnalysisErrorClassification {
readonly code: ErrorCode;
readonly category: ErrorCategory;
readonly retry: AnalysisRetryClass;
}
/** Domain tags whose classification depends on the error's own facts. */
type SpecializedErrorTag =
| "AnalysisTargetFailureError"
| "ArtifactOperationError"
| "BinaryTargetError"
| "BrowserObservationError"
| "EvidenceFileError"
| "ProcessCaptureError"
| "ProviderSelectionError"
| "UnknownRegistryError";
const classified = (
code: ErrorCode,
category: ErrorCategory,
retry: AnalysisRetryClass,
): AnalysisErrorClassification => ({ code, category, retry });
const STATIC_ERROR_CLASSIFICATIONS = {
AnalysisProtocolError: classified(
"unreadable_output",
"execution_failure",
"never",
),
AnalysisOutputError: classified(
"unreadable_output",
"execution_failure",
"never",
),
AnalysisInputError: classified(
"invalid_request",
"invalid_input",
"change_first",
),
AnalysisAccessDeniedError: classified(
"access_denied",
"unavailable",
"change_first",
),
AnalysisArtifactChangedError: classified(
"artifact_changed",
"integrity_mismatch",
"same_call",
),
AnalysisCapabilityUnavailableError: classified(
"capability_unavailable",
"unsupported_provider",
"never",
),
AnalysisCancelledError: classified("cancelled", "cancelled", "same_call"),
AnalysisTimeoutError: classified("provider_timeout", "timeout", "same_call"),
AnalysisResourceConstraintError: classified(
"resource_constraint",
"resource_constraint",
"change_first",
),
ConfigurationError: classified(
"configuration_invalid",
"invalid_input",
"change_first",
),
NoBinaryOpenError: classified(
"target_unavailable",
"unavailable",
"change_first",
),
EvidenceIntegrityError: classified(
"evidence_integrity_mismatch",
"integrity_mismatch",
"never",
),
ProviderAdapterError: classified(
"execution_failure",
"execution_failure",
"never",
),
} as const satisfies Readonly<
Record<
Exclude<AnalysisErrorTag, SpecializedErrorTag>,
AnalysisErrorClassification
>
>;
/**
* A capability the caller may wait for, or make available, is unavailable,
* not unsupported. Its producer says which.
*/
const availableLaterCapability = (
retry: "same_call" | "change_first",
): AnalysisErrorClassification =>
classified("capability_unavailable", "unavailable", retry);
/** The classification the projection table gives one target failure kind. */
const kindClassification = (
kind: TargetFailureKind,
): AnalysisErrorClassification => {
const { code, category, retryClass } = TARGET_FAILURE_PROJECTIONS[kind];
return { code, category, retry: retryClass };
};
/** A reader admission or fixed allowance that refused an artifact read. */
const ARTIFACT_ADMISSION_LIMIT = classified(
"resource_constraint",
"resource_constraint",
"change_first",
);
const ARTIFACT_OPERATION_CLASSIFICATIONS = {
cancelled: classified("cancelled", "cancelled", "same_call"),
// A `limit` without admission facts reports `partial`: the result was cut
// short. One with a reader limit or fixed allowance is
// ARTIFACT_ADMISSION_LIMIT.
integrity: classified(
"artifact_operation_failed",
"integrity_mismatch",
"never",
),
limit: classified("partial", "partial", "change_first"),
path: classified("artifact_operation_failed", "execution_failure", "never"),
unavailable: classified(
"artifact_operation_failed",
"unavailable",
"change_first",
),
io: classified("artifact_operation_failed", "execution_failure", "never"),
} as const satisfies Readonly<
Record<ArtifactOperationError["reason"], AnalysisErrorClassification>
>;
/** An integrity failure that names the artifact's expected and observed identity. */
const ARTIFACT_IDENTITY_MISMATCH = classified(
"artifact_integrity_mismatch",
"integrity_mismatch",
"never",
);
/**
* The session's opened target no longer matches its bytes: reopening the
* artifact, then retrying, recovers.
*/
const ARTIFACT_ADMITTED_IDENTITY_STALE = classified(
"artifact_operation_failed",
"integrity_mismatch",
"change_first",
);
const EVIDENCE_FILE_CLASSIFICATIONS = {
// A missing, non-file or already-existing path is the caller's selection.
"not-file": classified("invalid_request", "invalid_input", "change_first"),
exists: classified("invalid_request", "invalid_input", "change_first"),
"wrong-kind": classified("invalid_request", "invalid_input", "change_first"),
missing: classified("invalid_request", "invalid_input", "change_first"),
"symlink-traversal": classified(
"invalid_request",
"invalid_input",
"change_first",
),
"invalid-json": classified(
"evidence_integrity_mismatch",
"execution_failure",
"never",
),
"path-limit": classified(
"resource_constraint",
"resource_constraint",
"change_first",
),
"storage-limit": classified(
"resource_constraint",
"resource_constraint",
"change_first",
),
io: classified("execution_failure", "execution_failure", "never"),
} as const satisfies Readonly<
Record<EvidenceFileError["reason"], AnalysisErrorClassification>
>;
const UNKNOWN_REGISTRY_CLASSIFICATIONS = {
// An unknown_id this session does not hold is the caller's selection.
"not-found": classified("invalid_request", "invalid_input", "change_first"),
"already-exists": classified(
"invalid_request",
"invalid_input",
"change_first",
),
"revision-conflict": classified(
"revision_conflict",
"execution_failure",
"change_first",
),
"invalid-transition": classified(
"execution_failure",
"execution_failure",
"change_first",
),
integrity: classified(
"evidence_integrity_mismatch",
"execution_failure",
"never",
),
limit: classified("partial", "execution_failure", "change_first"),
constraint: classified("invalid_request", "invalid_input", "change_first"),
} as const satisfies Readonly<
Record<UnknownRegistryError["reason"], AnalysisErrorClassification>
>;
const PROVIDER_SELECTION_CLASSIFICATIONS = {
unknown_provider: classified(
"capability_unavailable",
"unsupported_provider",
"change_first",
),
provider_unavailable: classified(
"provider_unavailable",
"unavailable",
"same_call",
),
target_unsupported: classified(
"capability_unavailable",
"unsupported_provider",
"never",
),
ambiguous: classified(
"capability_unavailable",
"unsupported_provider",
"change_first",
),
invalid_options: classified(
"capability_unavailable",
"unsupported_provider",
"change_first",
),
} as const satisfies Readonly<
Record<ProviderSelectionFailureReason, AnalysisErrorClassification>
>;
type BinaryTargetConstraintKey =
| NonNullable<BinaryTargetErrorOptions["constraint"]>
| "unconstrained";
const unavailableBinaryTarget = (
category: "unavailable" | "unsupported_target",
) => classified("target_unavailable", category, "change_first");
const BINARY_TARGET_CLASSIFICATIONS = {
unconstrained: unavailableBinaryTarget("unavailable"),
directory_requires_file: unavailableBinaryTarget("unavailable"),
wasm_requires_static_inspection:
unavailableBinaryTarget("unsupported_target"),
file_format_rejected: unavailableBinaryTarget("unsupported_target"),
load_selection_rejected: classified(
"invalid_request",
"invalid_input",
"change_first",
),
bundle_type_unsupported: unavailableBinaryTarget("unsupported_target"),
bundle_info_plist_decode_budget_exceeded:
unavailableBinaryTarget("unavailable"),
bundle_info_plist_missing: unavailableBinaryTarget("unavailable"),
bundle_layout_ambiguous: unavailableBinaryTarget("unavailable"),
bundle_executable_undeclared: unavailableBinaryTarget("unavailable"),
bundle_program_missing: unavailableBinaryTarget("unavailable"),
bundle_current_version_missing: unavailableBinaryTarget("unavailable"),
bundle_path_escapes: unavailableBinaryTarget("unavailable"),
} as const satisfies Readonly<
Record<BinaryTargetConstraintKey, AnalysisErrorClassification>
>;
/** A target the host refused to read keeps its constraint's category. */
const binaryTargetClassification = (
constraint: BinaryTargetConstraintKey,
readPermissionDenied: boolean,
): AnalysisErrorClassification => {
const base = BINARY_TARGET_CLASSIFICATIONS[constraint];
return readPermissionDenied && constraint !== "load_selection_rejected"
? { ...base, code: "access_denied" }
: base;
};
const BROWSER_OBSERVATION_CLASSIFICATIONS = {
endpoint_unreachable: classified(
"provider_unavailable",
"unavailable",
"same_call",
),
invalid_endpoint_response: classified(
"unreadable_output",
"execution_failure",
"never",
),
target_not_found: classified(
"target_unavailable",
"unavailable",
"change_first",
),
target_not_allowed: classified(
"target_unavailable",
"unavailable",
"change_first",
),
application_already_running: classified(
"target_unavailable",
"unavailable",
"change_first",
),
service_worker_blocked: classified(
"target_unavailable",
"unavailable",
"change_first",
),
target_changed: classified(
"target_unavailable",
"unavailable",
"change_first",
),
target_session_detached: classified(
"target_unavailable",
"unavailable",
"change_first",
),
protocol_error: classified("unreadable_output", "execution_failure", "never"),
disconnected: classified("provider_unavailable", "unavailable", "same_call"),
payload_limit: classified("partial", "partial", "change_first"),
window_not_found: classified(
"unreadable_output",
"execution_failure",
"never",
),
window_metadata_missing: classified(
"unreadable_output",
"execution_failure",
"never",
),
process_ownership_unavailable: classified(
"unreadable_output",
"execution_failure",
"never",
),
cleanup_failed: classified("execution_failure", "execution_failure", "never"),
cancelled: classified("cancelled", "cancelled", "same_call"),
timeout: classified("provider_timeout", "timeout", "same_call"),
} as const satisfies Readonly<
Record<BrowserObservationFailureReason, AnalysisErrorClassification>
>;
/**
* A snapshot path given to a resource-only session, which has no executable
* binding: the caller's selection, not changed or forged Evidence.
*/
const RESOURCE_SNAPSHOT_NOT_APPLICABLE = classified(
"invalid_request",
"invalid_input",
"change_first",
);
/**
* Referenced Evidence this session does not hold, including a retained source
* or closure member that supplied Evidence names: the request lacks records
* the caller can supply, so importing them lets the same request succeed.
* Altered or unauthenticated Evidence stays an integrity failure.
*/
const EVIDENCE_REFERENCE_MISSING = classified(
"invalid_request",
"invalid_input",
"change_first",
);
/** Any error the caller's cancellation caused reports as that cancellation. */
const CANCELLED = classified("cancelled", "cancelled", "same_call");
const PROCESS_CAPTURE_FAILED = classified(
"process_capture_failed",
"execution_failure",
"never",
);
/** A tag whose code and category do not depend on the error's facts. */
const staticClassification = (
error: AnalysisError,
): AnalysisErrorClassification => {
const tag = domainErrorTag(error);
if (tag === undefined)
throw new TypeError(`Unpresented provider error: ${error._tag}`);
switch (tag) {
case "AnalysisTargetFailureError":
case "ArtifactOperationError":
case "BinaryTargetError":
case "BrowserObservationError":
case "EvidenceFileError":
case "ProcessCaptureError":
case "ProviderSelectionError":
case "UnknownRegistryError":
throw new TypeError(`Unhandled specialized analysis error: ${tag}`);
default:
return STATIC_ERROR_CLASSIFICATIONS[tag];
}
};
/**
* The code, category and retry class of a domain-presented error. A
* provider-owned error supplies its own through `ownPresentation()`. Cleanup
* state is applied by the projection, which reports `cleanup_incomplete`
* above this code.
*/
export const classifyAnalysisError = (
error: AnalysisError,
): AnalysisErrorClassification => {
const owned = error.ownPresentation();
if (owned !== undefined)
return { code: owned.code, category: owned.category, retry: owned.retry };
if (
error instanceof AnalysisCapabilityUnavailableError &&
error.retry !== "never"
)
return availableLaterCapability(error.retry);
if (error instanceof AnalysisTargetFailureError)
return {
...kindClassification(error.failure.kind),
retry: targetFailureRetryClass(error.failure),
};
if (error instanceof ProviderSelectionError)
return PROVIDER_SELECTION_CLASSIFICATIONS[error.reason];
if (error instanceof BrowserObservationError)
return error.userCategory === "cancelled"
? CANCELLED
: BROWSER_OBSERVATION_CLASSIFICATIONS[error.reason];
if (error instanceof ArtifactOperationError) {
// A reader limit says whether the caller can raise it; a release-fixed
// allowance cannot change. Either one refused the read at admission, so
// a limit with those facts is a resource constraint, not a result cut
// short.
const admission = (
classification: AnalysisErrorClassification,
): AnalysisErrorClassification =>
error.reason === "limit" ? ARTIFACT_ADMISSION_LIMIT : classification;
if (error.reason !== "integrity" && error.fixedAllowance !== undefined)
return {
...admission(ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason]),
retry: "never",
};
if (error.readerLimit !== undefined && error.reason !== "integrity")
return {
...admission(ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason]),
retry: error.readerLimit.can_increase ? "change_first" : "never",
};
if (error.reason !== "integrity")
return ARTIFACT_OPERATION_CLASSIFICATIONS[error.reason];
if (error.artifactDetails !== undefined) return ARTIFACT_IDENTITY_MISMATCH;
if (error.integrityCheck === "admitted-identity")
return ARTIFACT_ADMITTED_IDENTITY_STALE;
// A target that changed during the read is the model's `changed` kind.
return integrityCheckMeansChanged(error.integrityCheck)
? kindClassification("changed")
: ARTIFACT_OPERATION_CLASSIFICATIONS.integrity;
}
if (error instanceof BinaryTargetError)
return binaryTargetClassification(
error.constraint ?? "unconstrained",
error.systemCode !== undefined,
);
if (error instanceof EvidenceFileError)
return EVIDENCE_FILE_CLASSIFICATIONS[error.reason];
if (error instanceof ResourceSnapshotMismatchError)
return RESOURCE_SNAPSHOT_NOT_APPLICABLE;
if (error instanceof EvidenceReferenceError && error.reason === "missing")
return EVIDENCE_REFERENCE_MISSING;
if (error instanceof UnknownRegistryError)
return UNKNOWN_REGISTRY_CLASSIFICATIONS[error.reason];
if (error._tag === "ProcessCaptureError")
return error.userCategory === "cancelled"
? CANCELLED
: "retryable" in error && error.retryable === true
? { ...PROCESS_CAPTURE_FAILED, retry: "same_call" }
: PROCESS_CAPTURE_FAILED;
if (error instanceof AnalysisResourceConstraintError)
return {
...STATIC_ERROR_CLASSIFICATIONS.AnalysisResourceConstraintError,
retry: resourceConstraintRetry(error),
};
return staticClassification(error);
};
/**
* A resource refusal's producer declares whether the same request can be
* admitted later. Occupied capacity can; a fixed allowance cannot change;
* any other bound needs a changed request or limit first.
*/
const resourceConstraintRetry = (
error: AnalysisResourceConstraintError,
): AnalysisRetryClass =>
(error.retryable ?? error.resource === "capacity")
? "same_call"
: error.fixedAllowance === undefined
? "change_first"
: "never";
/** One row of the generated error catalogue. */
export interface AnalysisErrorCatalogueEntry extends AnalysisErrorClassification {
readonly tag: AnalysisErrorTag | ProviderErrorTag;
/** The fact that selects this row; empty when the tag alone does. */
readonly discriminant: string;
/**
* Whether the projection reports the case as retryable: its retry class is
* `same_call`. An error's own facts can still change the class: a resource
* constraint's recovery, a reader limit, a capture's retry flag, or a
* capability's declared availability.
*/
readonly retryableByDefault: boolean;
}
/**
* One catalogue row. A provider that presents its own errors lists them
* through this, so its rows read like the domain's.
*/
export const catalogueRow = (
tag: AnalysisErrorTag | ProviderErrorTag,
discriminant: string,
classification: AnalysisErrorClassification,
): AnalysisErrorCatalogueEntry => ({
tag,
discriminant,
...classification,
retryableByDefault: classification.retry === "same_call",
});
const reasonRows = (
tag: AnalysisErrorTag,
table: Readonly<Record<string, AnalysisErrorClassification>>,
): AnalysisErrorCatalogueEntry[] =>
Object.entries(table).map(([reason, classification]) =>
catalogueRow(tag, `reason=${reason}`, classification),
);
/**
* Every domain error case and its caller-facing code and category. A
* provider-owned error presents itself, and its provider lists its rows.
* Cleanup that did not complete reports `cleanup_incomplete` above any row.
*/
export const analysisErrorCatalogue =
(): readonly AnalysisErrorCatalogueEntry[] => [
...Object.entries(STATIC_ERROR_CLASSIFICATIONS).map(
([tag, classification]) =>
catalogueRow(tag as AnalysisErrorTag, "", classification),
),
catalogueRow(
"AnalysisCapabilityUnavailableError",
"retry=same_call",
availableLaterCapability("same_call"),
),
catalogueRow(
"AnalysisCapabilityUnavailableError",
"retry=change_first",
availableLaterCapability("change_first"),
),
...TARGET_FAILURE_KINDS.map((kind) =>
catalogueRow(
"AnalysisTargetFailureError",
`kind=${kind}`,
kindClassification(kind),
),
),
...reasonRows("ArtifactOperationError", ARTIFACT_OPERATION_CLASSIFICATIONS),
catalogueRow(
"ArtifactOperationError",
"reason=limit; reader limit that can be raised",
ARTIFACT_ADMISSION_LIMIT,
),
catalogueRow(
"ArtifactOperationError",
"reason=limit; reader limit already at its maximum",
{ ...ARTIFACT_ADMISSION_LIMIT, retry: "never" },
),
catalogueRow(
"ArtifactOperationError",
"reason=integrity; artifact identity reported",
ARTIFACT_IDENTITY_MISMATCH,
),
catalogueRow(
"ArtifactOperationError",
"reason=limit; release-fixed allowance",
{ ...ARTIFACT_ADMISSION_LIMIT, retry: "never" },
),
catalogueRow(
"ArtifactOperationError",
"reason=integrity; the session's admitted identity no longer matches",
ARTIFACT_ADMITTED_IDENTITY_STALE,
),
catalogueRow(
"ArtifactOperationError",
"reason=integrity; target changed during the read",
kindClassification("changed"),
),
...Object.keys(BINARY_TARGET_CLASSIFICATIONS).flatMap((key) => {
const constraint = key as BinaryTargetConstraintKey;
const allowed = binaryTargetClassification(constraint, false);
const denied = binaryTargetClassification(constraint, true);
return [
catalogueRow("BinaryTargetError", `constraint=${constraint}`, allowed),
...(denied.code === allowed.code
? []
: [
catalogueRow(
"BinaryTargetError",
`constraint=${constraint}; read permission denied`,
denied,
),
]),
];
}),
...reasonRows(
"BrowserObservationError",
BROWSER_OBSERVATION_CLASSIFICATIONS,
),
catalogueRow(
"BrowserObservationError",
"caused by cancellation",
CANCELLED,
),
...reasonRows("EvidenceFileError", EVIDENCE_FILE_CLASSIFICATIONS),
catalogueRow(
"EvidenceIntegrityError",
"analysis snapshot selected for a resource-only session",
RESOURCE_SNAPSHOT_NOT_APPLICABLE,
),
catalogueRow(
"EvidenceIntegrityError",
"referenced Evidence missing from this session",
EVIDENCE_REFERENCE_MISSING,
),
catalogueRow("ProcessCaptureError", "", PROCESS_CAPTURE_FAILED),
catalogueRow("ProcessCaptureError", "caused by cancellation", CANCELLED),
...reasonRows("ProviderSelectionError", PROVIDER_SELECTION_CLASSIFICATIONS),
...reasonRows("UnknownRegistryError", UNKNOWN_REGISTRY_CLASSIFICATIONS),
];