Skip to content

feat(errors)!: add the TargetFailure model, its projection table and conformance registry - #14247

Merged
morluto merged 18 commits into
mainfrom
feat/target-failure-model
Nov 25, 2026
Merged

morluto merged 18 commits into
mainfrom
feat/target-failure-model

Conversation

@morluto

@morluto morluto commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

First PR of the #14239 stack. It adds the TargetFailure model, its single projection table and the declarative conformance registry, and migrates the first area onto them: selected-file malformed and truncated refusals.

Root cause

The same fact ("why could this target not be read") is spelled in several vocabularies: ArtifactReaderFailure.reason, ParseFailure.kind, ArtifactOperationError.reason, MachoReadIssue and per-adapter mappers. The classification is keyed by error tag and reason, so each consumer re-derives the class, and a new reader can pick any of them. The shared stableArtifactParserFailureCli loop also became a merge hotspot (#14224 and #14225 conflicted there, and a row-shape mismatch broke typecheck on #14233).

Structural fix

  • Model (src/domain/targetFailure.ts). TargetFailure is a discriminated union of 10 kinds: selection, unrecognized, unsupported, malformed, truncated, integrity, conflict, changed, access and io. All kinds share format, detail, offset and field. Some variants add their own facts: unsupported.undecodedContent, truncated.availableBytes/requiredBytes, conflict.inputs (a list of { field, path }) and io.transient, the owner's errno fact.
  • failure_kind is the primary identifier, in the sense of an RFC 9457 problem type. TARGET_FAILURE_PROJECTIONS derives everything else from it: title, a coarse code, category, the retry hint and the recovery. The table is checked with satisfies Record<TargetFailureKind, …>, and the switches are exhaustive, ending in unhandledTargetFailureCase(never).
  • Codes. Only the four target refusals share unsupported_target, because each needs a different target or tool. integrity → target_integrity_mismatch, conflict → input_conflict, io → host_io_failed, changed → artifact_changed, access → access_denied, selection → invalid_request. Inventory malformed, truncated and unsupported reasons take their codes from the same table.
  • Retry. retry is none, backoff or after_change, after gRPC's status semantics. io gives backoff only when its errno is transient. retryable keeps its shared-contract meaning, that the unchanged request may succeed, so it is true exactly for backoff.
  • One meaning for "truncated". The limit-cut result code and category truncated are renamed to partial. failure_kind: "truncated" is the only use of the word left.
  • Operation outcomes stay outside. Cancellation and admission limits describe the operation, so they keep AnalysisCancelledError and AnalysisResourceConstraintError. Identifiers use American spelling.
  • First area migrated. AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError(operation, path, failure). ParseFailure's malformed, truncated and unsupported variants are the TargetFailure variants. details.format_failure is removed, and failure_kind is the only identifier.
  • MCP placement. EvidenceMcpServer's single tool wrapper returns a target failure that a handler throws as a projected isError result. Before this, the SDK flattened it into a plain-text "Malformed …". No target failure maps to a JSON-RPC error.
  • Conformance registry (tests/support/targetFailure/). Each area exports targetFailureReaders([...]) from its own module. One generated suite runs every case through the compiled CLI and the stdio MCP, and asserts the contract from TARGET_FAILURE_CONTRACT, isError, and that the selected file is unchanged.

Design notes

Research and its sources are on #14239 (comment). In short:

  1. Exhaustive tagged unions. One literal kind, never-checked switches, and satisfies Record tables, so the compiler finds every consumer of a new kind.
  2. Stable identifiers, additive facts (RFC 9457). code stays the primary identifier and failure_kind is an extension member. message, remediation.action and details.reason are for people. The error reference tells clients to keep a default arm for kinds they don't know, as with Rust's #[non_exhaustive] io::ErrorKind.
  3. Retry semantics (gRPC).
    • Only changed (ABORTED: retry the whole read) and cancelled are retryable.
    • selection and conflict are INVALID_ARGUMENT-like.
    • malformed, truncated, unsupported and unrecognised need another target or tool.
    • integrity is a declared-checksum contradiction (DATA_LOSS), kept apart from changed.
    • access (FAILED_PRECONDITION) is split from io. io stays non-retryable, because REA cannot tell transient EIO from a failing device.
  4. Different caller actions get different recoveries. malformed says "choose another target or a well-formed copy". truncated says "re-acquire the complete file; do not pad or cut". These are the same code with different failure_kind. The truncated code keeps its one meaning, a result cut short by a limit.
  5. One system of record, derived views. The format owner raises the failure once. Code, category, retryable, recovery and details are computed from it, never stored a second time and never re-derived from message text.
  6. Schema evolution. The model is additive here. Codes and format_failure are unchanged. Areas that change codes (inventory truncated, the container readers' format, the six adapters) declare it in their own PRs.

Where later PRs attach

  • Each area adds a readers/<area>.ts module with its cases, and constructs AnalysisTargetFailureError (or, for inventory, carries the same TargetFailure) at its owner. It deletes its old reason path in the same PR.
  • The last PR adds a guard to scripts/verify/architecture-guards.mjs that rejects the old reason vocabularies, plus a repo-wide search as evidence.
  • [Bug] MCP error remediation does not name the alternative tool or provider, and embeds CLI commands #14162 (per-adapter recovery that names alternative tools and providers) goes into targetFailureRecovery, keyed by kind and owner facts.

Removed tests and the registry case that covers each

Removed Registry case (tests/support/targetFailure/readers/)
stableArtifactParserFailureCli: "refuses a truncated ELF header as a malformed target", 18 commands selectedFileFormats.ts, <operation>/elf-magic-only
stableArtifactParserFailureCli: managed pe-cli section past EOF, 3 commands selectedFileFormats.ts, inspect_managed_*/pe-cli-section-past-eof
stableArtifactParserFailureCli: overlapping universal Mach-O, 4 commands selectedFileFormats.ts, */macho-overlapping-slices
stableArtifactParserFailureCli body table: truncated BEAM and short certificate header inspect_erlang_beam/beam-form-header-only, inspect_pe_certificates/short-certificate-header
peImportsCli: "rejects non-MZ PE32/PE32+ imports across CLI and MCP" (ZZ and high-bit) peHeaders.ts, inspect_pe_imports/pe{32,64}-{zz,high-bit}-dos-signature
peLoadConfigCli: "rejects non-MZ PE32/PE32+ load config across CLI and MCP" peHeaders.ts, inspect_pe_load_config/pe{32,64}-{zz,high-bit}-dos-signature
appleIpsCli: "reports a truncated IPS as a malformed target" selectedFileFormats.ts, inspect_apple_ips/ips-truncated-body

The generated suite also checks the invariants the removed PE tests asserted: that the refusal leaves the selected file unchanged, and that both adapters report it. The PE tests keep their valid-image controls. The foreign-bytes identity loop stays in stableArtifactParserFailureCli until the unsupported and unrecognised refusals migrate.

Mutation checks on the removals, using the registry run in-process from source:

  • Giving the PE fixtures a valid MZ signature fails the 4 *-zz-dos-signature cases.
  • An untruncated IPS body fails inspect_apple_ips/ips-truncated-body.

Both pass after revert.

Behaviour changes

  • details.format_failure is removed. Read details.failure_kind.
  • Every target failure carries a top-level retry.
  • The truncated result code and category become partial. This covers artifact reader limits, browser payload limits and registry limits.
  • Inventory refusals of truncated container bytes report unsupported_target instead of truncated.
  • New codes: target_integrity_mismatch, input_conflict and host_io_failed.
  • A truncated target's remediation tells the caller to re-acquire the complete file.
  • docs/user-visible-errors.csv and docs/error-contract.schema.json were regenerated from source with tsx, because the generators read dist/.
  • New reference: docs/reference/target-failures.md, linked from docs/README.md and the documentation sidebar.

Validation

  • npx vitest run on src/domain, src/resources, src/native, src/electron, src/dotnet, src/il2cpp and the touched boundary suites (filesystem, go, gpu, il2cpp, model, native selection, MCP format-failure suites): every run passed (14756 tests across the domain, resources, managed and IL2CPP sweep after merging main).
  • An in-process probe from source ran all 27 registry cases through createCli (serveInProcessCli) and the MCP server. All CLI paths passed, and all MCP paths passed except the 3 managed tools, which need a deep-provider session in the in-process harness. The compiled-adapter suite in CI covers them.
  • Mutation checks: making io retry backoff fails the contract and errno tests; letting the server wrapper rethrow a target failure fails the MCP tool-result test (the result degrades to plain text). Both pass after revert.
  • Scoped tsc over the changed files and their import closure (1091 source files): no errors except the pre-existing frida typing errors. Also clean: oxfmt, oxlint (no new warnings) and architecture-guards.
  • Not run locally, so CI must confirm: tests/acceptance/* (needs dist/), the full typecheck, knip and docs:check.
  • No public-corpus before/after pass: no code changes in this PR. The first code-changing PR of the stack records one.

Real-provider verification scope

None needed. The affected readers are local static parsers.

Remaining cleanup

The rest of the stack, each PR deleting its old path:

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-24T02:04:20.648717Z
We couldn’t complete this review. Comment @codex review to try again.
bfa7876 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[High impact] The reviewed revision appears safe to merge with the verified dependent fix in #14265.

Summary

Adds TargetFailure, its shared error projections, and a registry that checks CLI and MCP refusals.

  • Target errors now share one kind that shapes their public details and recovery.
  • Selected-file parser refusals now carry the shared target-failure details.
  • MCP tools now return escaped target failures as projected error results.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Reader establishes TargetFailure] --> B[AnalysisTargetFailureError]
  B --> C[Shared error projection]
  C --> D[CLI diagnostic]
  C --> E[MCP isError result]
  E --> F[Transport removes private structuredContent]
  F --> G[Client reads JSON text]
Loading

Reviews (12) · Last reviewed commit: "test(errors): check the MCP target failu..." · Reviewed by Greptile

Comment thread src/domain/targetFailure.ts Resolved
Comment thread docs/reference/target-failures.md Resolved
#14225 refuses a non-regular dyld input as ArtifactReaderFailure("path");
dylibFileLifetime still expected "format" and fails on main's shard 9.
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.
… 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.
…odel

# Conflicts:
#	tests/boundary/filesystem/stableArtifact.test.ts
…d 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.
…etry 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.
Comment thread src/domain/targetFailure.ts Resolved
…odel

# Conflicts:
#	src/domain/analysisErrorProjection.ts
#	src/domain/parseFailure.ts
#	tests/acceptance/stableArtifactParserFailureCli.test.ts
#	tests/boundary/cli/managedMemberComparisonCli.test.ts
@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

CI note on the goBinaryMcp / goBinaryCli / denoStandaloneCli failures: these come from main, not this PR.

  • tests/boundary/mcp/goBinaryMcp.test.ts "distinguishes unsupported MZ carriers from malformed PE through MCP" fails identically on origin/main (669147e), run from source on macOS. So it is not Linux-specific. My earlier local pass predated the main merge.
  • The diagnostic (f93b368, which names the fixture) shows the PE header owner from fix(pe)!: share one loader-equivalent PE header owner across static readers #14253 diverging on two createGoBinaryDiagnosticFixtures cases:
    • optional-header-0-bytes / optional-header-1-bytes: it reads the optional-header magic from bytes past the declared SizeOfOptionalHeader (the fixture fills those with 0xff to catch this). It then refuses with "Only PE32 and PE32+ image optional headers are supported" (unsupported) instead of malformed.
    • absent-directories (NumberOfRvaAndSizes = 1): now accepted and inspected successfully.
  • denoStandaloneCli "distinguishes the fixed Deno PE entry allowance from malformed framing": the off-by-one language directory now reports a limit instead of malformed. This PR differs from main there only in test vocabulary.

These are PE header admission decisions that #14253 owns, so I have not changed them here. Whether absent-directories acceptance is intended (loader-equivalent) and the magic read is a bug is for the #14253 owner to decide.

Also fixed on this branch: a Windows-lane test from main still expected the old truncated limit code (now partial), in 1de699e.

…odel

# Conflicts:
#	docs/.vitepress/documentation.ts
#	docs/README.md
#	tests/boundary/go/goBinaryProvider.test.ts
#	tests/boundary/mcp/nodeSeaMcp.test.ts
#	tests/fixtures/go/image.ts
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.
@morluto
morluto merged commit 40e9a3f into main Nov 25, 2026
59 checks passed
@morluto
morluto deleted the feat/target-failure-model branch November 25, 2026 00:39
leockl added a commit to leockl/rea that referenced this pull request Nov 25, 2026
…nonicalize

Resolve src/resources/AsarHeader.ts and adapt the canonicalize ASAR path to
upstream's breaking reader-failure vocabulary change (morluto#14247/morluto#14265/morluto#14277):

- readAsarHeader: keep the extracted parseAsarHeaderJson helper our feature
  reuses, over upstream's new integrity read-coverage short-read refusal.
- parseAsarHeaderExtents now returns plain refusal tags; expose the owner's
  tag->failure mapping as asarExtentRefusal so admitAsarHeader and the
  canonicalize adapter build the one owned failure rather than each spelling
  the message, offset and reason.
- CanonicalizeProvider.unclassified now delegates to translateArtifactFailure,
  so a malformed/truncated ASAR header becomes the target failure of the
  selected path instead of naming an operation reason the vocabulary no longer
  permits; asarCanonicalize's defensive JSON fallback uses malformedArtifact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
morluto added a commit that referenced this pull request Nov 25, 2026
Brings in the failure-model stack (#14247, #14265, #14268, #14272,
#14277, #14281, #14289). Target failures reach MCP through
toErrorToolResult and the CLI through projectCliAnalysisResult; neither
path calls the budget decision, so their projection is unchanged.

Conflicts: the Android verifiers keep main's sha256File helper and this
branch's complete-evidence wrappers; the ELF and Rust MCP tests and the
EVM description take main's version, since the harness default already
requests complete Evidence. A leftover delivery reassignment in the
EvidenceMcpServerCore constructor, already set by its parameter
property, is removed.
@morluto morluto added area: domain Domain logic, errors, and pure functions enhancement New feature or request labels Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: domain Domain logic, errors, and pure functions enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant