Skip to content

fix(errors)!: raise container reader byte faults as malformed or truncated targets - #14265

Merged
morluto merged 40 commits into
mainfrom
fix/container-reader-target-failures
Nov 25, 2026
Merged

morluto merged 40 commits into
mainfrom
fix/container-reader-target-failures

Conversation

@morluto

@morluto morluto commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Depends on #14247. The base branch is #14247's, so the diff shows only this PR.

Second PR of the #14239 stack. It removes the ambiguous format reason from artifact readers and from ArtifactOperationError.

Root cause

ArtifactReaderFailure("format") meant three different things: corrupt bytes, a path-kind selection, and bytes that came up short after REA had measured the file. Consumers either gave up (artifact_operation_failed on inventory) or re-derived a class from the reason. The trace, NTFS journal, release exposure and web capture adapters mapped format to invalid_request, which blamed the caller's arguments. #14225 listed these as follow-ups.

Structural fix

  • The format reason is deleted from ArtifactOperationError["reason"], and so from ArtifactReaderFailureReason. The reason=format classification row and the presentation branch are deleted too. The compiler then found every producer and consumer, about 95 sites.

  • Each reader raises the failure once, with its own facts. New helpers in src/resources/ArtifactReader.ts build the malformed/truncated reason together with its parseFailure (format, offset, field, availableBytes/requiredBytes):

    • malformedArtifact(format, detail, site)
    • truncatedArtifact(format, detail, site)
    • artifactFormatFailure(failure)

    Readers: ZIP, ASAR (header, listing, reader, entry stream, fallback), Android OTA, DecodedRegionArtifactReader, NTFS $MFT, DesktopFileInspection, ArtifactFileRange, .NET bundle, ESP image, FIT, uImage, iNES, Godot PCK, UnityFS, wxapkg, Node SEA, Deno, Bun, PyInstaller, keyed archive, Mach-O source reads, NuGet's ZIP, and web artifact reads.

  • Each class has one meaning.

    • Truncated: only where the owner measured the end. Examples: the ASAR prefix and a header that leaves the file, a FIT totalsize past the end (with extents), a range read past its source (with extents), and PyInstaller EOF before a declared structure.
    • Changed: a short read after the size was measured is integrity / read-coverage. Examples: the ASAR JSON header, the ASAR size pickle when the file is large enough, and readArtifactFileBytes.
    • Selection (path): the ASAR container is not a regular file, a positional member has no byte range, an extraction entry is a directory, or a PyInstaller entry has no bytes.
    • Unsupported: a file with no .NET bundle header or no PyInstaller cookie, a dylib root that is not Mach-O, an .asar that classifies as something else, an hdiutil "image not recognized" result, or a SQLite hot journal that needs recovery.
    • Host tool output (hdiutil plists, lipo records): io, because the target's bytes are not at fault.
    • REA defects: InternalInvariantError. Examples: a non-byte ASAR chunk, a PyInstaller non-Error rejection, an invalid expected output size, and an invalid range end. The ASAR fallback no longer turns them into "malformed".
  • Domain vocabularies renamed at the owner. RegionDecodeFailure.kind (hexRecords, uf2, dfuse, ntfsMft) and PyInstallerFailure.reason use malformed (and truncated) instead of format.

  • The adapters use the shared model. Trace, NTFS journal, release exposure, web capture, native macOS and web artifact reads build AnalysisTargetFailureError from the reader's parseFailure. Only path stays invalid_request.

  • One truncated vocabulary. The malformed, truncated, unsupported and cancelled reasons of ArtifactOperationError now take their code from TARGET_FAILURE_PROJECTIONS. A truncated container is therefore unsupported_target with details.failure_kind: "truncated" and format_failure: "truncated" on both the inventory and the selected-file paths. The truncated code means only "result cut short by a limit". This is documented once in docs/reference/target-failures.md.

Design notes

  1. Unrecognised, unsupported, malformed and truncated stay distinct. "No header" or "no cookie" means this reader doesn't recognise the bytes (unsupported reason, unsupported_target), which is not corruption. Truncated is reported only where the owner measured the end. Where it could not tell (for example zip.js's missing end-of-central-directory record), it stays malformed.
  2. Transient is not permanent. A short read inside a measured extent is a changed file (read-coverage), not truncation, so the caller retries on a stable copy instead of discarding the file. Cancellation and I/O paths are unchanged.
  3. One system of record. Facts are set once at the reader, through parseFailure. Consumers test parseFailure !== undefined and never read message text.
  4. Contract evolution. This is a breaking code change, listed in the footer. Detail fields are additive: failure_kind, format_failure, format, offset, field, available_bytes and required_bytes.

Tests

  • Updated stale format expectations in 32 source test files to the owner's new class. They assert reason and parseFailure facts, not message text. Examples: OTA truncated and FIT truncated with extents, ASAR short JSON read as read-coverage, PyInstaller EOF as truncated, DMG and lipo tool output as io, hdiutil "not recognized" as unsupported, and the asset catalog projected as unsupported_target with format: asset-catalog.
  • ArtifactOperationFailure.test.ts now expects inventory and selected-file truncated refusals to share unsupported_target.

Validation

  • npx vitest run passed on src/{artifacts,resources,domain,browser,nuget,sqlite,native,application,electron}: 1158 files, 24102 tests.
  • Boundary tests: the updated tests/boundary/{filesystem,providers/native,sqlite,mcp} files passed. Suites that need the compiled CLI or stdio MCP from dist/ were not run locally: the web capture, codesign, Node SEA and setup-skill tests. CI covers them.
  • Acceptance expectations: the 19 affected tests/acceptance files were copied locally (not committed) and run in-process from source (createCli + serveInProcessCli) to see real CLI output before their expectations were updated. ZIP, Bun, Node SEA, Intel HEX, UF2, iNES, Godot and the JavaScript ASAR cases were checked this way. The keyed-archive, bunPathBudget, dotnetBundleJourney and artifactReaderLimits expectations were updated from the producer code alone, because their fixtures need the compiled workspace or MCP harness. CI must confirm them.
  • A scoped tsc over 408 files (every file that names these error types, plus the changed tests) was clean apart from the pre-existing frida errors. Also clean: oxfmt on all 138 changed files, oxlint (no new errors) and architecture-guards.
  • docs/user-visible-errors.csv was regenerated from source with tsx, because the generator needs dist/. The reason=format row is removed, and reason=truncated becomes unsupported_target.
  • No public-corpus before/after pass was run: no corkami, ImHex or real-archive corpus is available in this environment. NOT_ENOUGH_INFO.

Review fixes

  • A short read inside a range already checked against the measured size is a changed file. It is now reported as integrity/read-coverage, not truncated. This covers readArtifactRange/hashArtifactRange (Node SEA, Deno) and Bun's readExact, and is tested by src/artifacts/ArtifactCarrierRange.test.ts. Mutation check: returning undefined on a short read fails it.
  • DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so the later checks still run.

Test pruning

This PR removes no per-command tests. Inventory refusals do not yet carry details.path, so the conformance registry cannot express container cases. That comes with the inventory-status PR, which moves the container per-command copies into the registry and deletes them there. The changed tests here only replace assertions of the deleted format reason with the owner's class.

Remaining cleanup

  • Inventory ArtifactOperationError details still carry no path, so container cases are not in the conformance registry yet. That lands with the inventory-status PR.
  • asarFailure and the keyed-archive reader still map an unknown non-filesystem cause to malformed. That fallback predates this PR. Removing it needs every ASAR and plist parser to raise typed failures first.
  • SQLite, pwntools, EVM and pwndbg worker replies still use their own reason: "format" reply vocabulary. That is the adapters PR.

…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.
#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.
…cated 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.
@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:50:59.427519Z
We couldn’t complete this review. Comment @codex review to try again.
7aea9b4 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

[High impact] The reviewed changes appear safe to merge with the verified classification fixes in dependent PR #14289.

Summary

Container readers now distinguish malformed bytes, incomplete files, and files that changed during a read. Shared helpers carry the reader’s facts into public errors.

  • Container readers report malformed and truncated bytes as different target failures.
  • Target errors now carry reader facts instead of the ambiguous format reason.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Reader encounters a failure] --> B{What failed?}
  B -->|Bytes break format rules| C[malformed with parseFailure]
  B -->|Declared bytes exceed measured end| D[truncated with parseFailure]
  B -->|Read ends inside measured range| E[integrity / read-coverage]
  B -->|Session digest no longer matches| F[integrity / admitted-identity]
  C --> G[unsupported_target]
  D --> G
  E --> H[artifact_changed / retry with backoff]
  F --> I[Reopen the target / no retry hint]
Loading

Reviews (13) · Last reviewed commit: "test(dylib): expect admitted-identity wh..." · Reviewed by Greptile

Comment thread src/artifacts/DesktopFileInspection.ts Resolved
… 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
…p 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.
…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.
…rget-failures

# Conflicts:
#	docs/reference/target-failures.md
#	src/domain/analysisErrorClassification.ts
#	src/resources/ArtifactOperationFailure.test.ts
#	tests/boundary/cli/artifactZstandardWindow.test.ts
…F 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.
Comment thread src/artifacts/NtfsMftArtifactReader.ts Resolved
…odel

# Conflicts:
#	src/domain/analysisErrorProjection.ts
#	src/domain/parseFailure.ts
#	tests/acceptance/stableArtifactParserFailureCli.test.ts
#	tests/boundary/cli/managedMemberComparisonCli.test.ts
…fix/container-reader-target-failures

# Conflicts:
#	src/resources/AsarHeader.ts
The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling.
…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
…fix/container-reader-target-failures

# Conflicts:
#	src/artifacts/NodeSeaArtifactReader.test.ts
#	src/artifacts/UImageArtifactReader.boundaries.test.ts
#	src/artifacts/UImageArtifactReader.ts
#	src/artifacts/UnityFsArtifactReader.boundaries.test.ts
#	src/artifacts/WxapkgArtifactReader.boundaries.test.ts
#	src/artifacts/inventory/classify.ts
#	src/resources/ZipArtifactReader.ts
#	tests/acceptance/nodeSeaCli.test.ts
#	tests/boundary/filesystem/artifactZipIntegrity.test.ts
#	tests/boundary/mcp/nodeSeaMcp.test.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.
Comment thread src/domain/artifactOperationError.ts Resolved
Comment thread src/domain/artifactOperationError.ts Resolved
…fter 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.
Base automatically changed from feat/target-failure-model to main November 25, 2026 00:39
cursoragent and others added 5 commits November 25, 2026 00:48
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
@morluto
morluto merged commit 6f26702 into main Nov 25, 2026
56 checks passed
@morluto
morluto deleted the fix/container-reader-target-failures branch November 25, 2026 02:17
blankym added a commit to blankym/rea that referenced this pull request Nov 25, 2026
Align decoder failures with the malformed/limit algebra from morluto#14265.
blankym added a commit to blankym/rea that referenced this pull request Nov 25, 2026
Align decoder failures with the malformed/limit algebra from morluto#14265.
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.
2SinceJuly added a commit to 2SinceJuly/rea that referenced this pull request Nov 25, 2026
…re rewrite

main renamed RegionDecodeFailure's `format` kind to `malformed` and dropped the `format` ArtifactReaderFailure reason (morluto#14265), while this branch added an `unsupported` kind for journal layouts it cannot decode. Keep both: widen the kind union, map the decoder's failures through artifactParseFailure so each refusal carries its owner's parse facts, and report a short unsigned file as malformed with a short signed one as truncated — the distinction morluto#14265 asks readers to make.
2SinceJuly added a commit to 2SinceJuly/rea that referenced this pull request Nov 26, 2026
…in merge

Main renamed the region decoder's format kind to malformed (morluto#14265), so the auditd branch's `kind: "format"` no longer compiles. Keep the same behaviour through main's naming: the domain scanner reports `malformed`, and the reader turns it into `malformedArtifact` instead of building a bare `format` failure, matching DecodedRegionArtifactReader.
2SinceJuly added a commit to 2SinceJuly/rea that referenced this pull request Nov 26, 2026
main widened ArtifactOperationError's operation parameter to the public operation name in b7f662b (morluto#14277, morluto#14265) so every reader can raise it with one classification owner. This branch had kept the operation as a per-reader union sitting inside the constructor, so the two could not both stand. The merge takes main's widening: the union only helped the constructor's own type checking, and the reader name still reaches artifactDetailsMessage.

Run: vitest src/domain/evtxArchive (28 pass). A full typecheck still reports two errors in files this merge does not touch (javascriptSemanticExecutionPoints StructBody, releaseProposal release-please path).
@morluto morluto added area: domain Domain logic, errors, and pure functions bug Something isn't working 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 bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants