Skip to content

refactor(parsers): report format failures through one ParseFailure algebra - #10593

Merged
morluto merged 2 commits into
mainfrom
refactor/parse-failure-algebra
Nov 14, 2026
Merged

morluto merged 2 commits into
mainfrom
refactor/parse-failure-algebra

Conversation

@morluto

@morluto morluto commented Nov 14, 2026

Copy link
Copy Markdown
Owner

Summary

Byte-format parsers each invented their own failure class (BinaryFormatFailure, V8CodeCacheFormatFailure, WindowsShortcutFormatFailure, ElectronFuseFormatFailure, and about ten more), and each provider re-derived the public category with its own instanceof ladder. This adds one tagged failure algebra in the domain, makes BinaryReader produce it, projects it to analysis errors in one place, migrates three per-format classes onto it, and adds counted guards so new raw reads and plain throws in parser folders cannot return.

First slice of the parser-kernel workstream (W7). No issue is fixed outright; this is the owner later format migrations build on.

Problem and expected behavior

  • BinaryReader.range() reported a structure that runs past end of file as malformed, with no offset or field. Expected: truncated, with the format, the offset and the field it was reading.
  • Nine providers repeated the same 15-line BinaryFormatFailure ladder. Five of them (inspect_kernel_module, inspect_elf_notes, inspect_elf_unwind_ranges, inspect_devicetree, inspect_v8_code_cache) left the selected path out of the invalid_format message, while the others prefixed Selected artifact <path>:. Expected: one projection with one message form.
  • A provider whose ladder matched only its own class let any other format failure fall through to a generic failure. For example, ElectronFuseFailures matched ElectronFuseFormatFailure but not a BinaryFormatFailure thrown by a shared header reader. Expected: every parser format failure projects the same way.

Change and scope

  • src/domain/parseFailure.ts: ParseFailure = {kind: malformed | truncated | unsupported | limit, format, detail, offset?, field?}. unsupported carries undecodedContent and limit carries {name, maximum}. ParseFailureError<Kind> is the one throwable carrier. malformedInput and unsupportedInput are constructors.

  • src/domain/parseFailureAnalysisError.ts: the one projection. Malformed or truncated input becomes AnalysisInputError (invalid_format, Selected artifact <path>: …). Unsupported input becomes AnalysisUnsupportedTargetError, which keeps undecodedContent. A limit returns undefined because only its producer knows the budget to name in the recovery.

  • BinaryReader takes its native format (elf, pe, macho, cuda-nv-info, or the Go container's format). Out-of-file starts are malformed and spans that end past EOF are truncated, both with field and offset. BinaryFormatFailure and BinaryResourceFailure are now ParseFailureError subclasses. They keep their class names, messages and accessors for the 39 existing catch sites, with an alias-first migration. The two positional undecodedContent arguments became { undecodedContent: true }.

  • The provider ladders in Go, kernel module, binary hardening, native initializers, ELF notes, ELF unwind ranges, devicetree, native exports, PE (PeBinaryFailure), V8 code cache, Windows Shortcut and Electron fuses now call parseFailureAnalysisError.

  • Migrated and deleted: V8CodeCacheFormatFailure, WindowsShortcutFormatFailure, ElectronFuseFormatFailure. The Shortcut header checks now name HeaderSize and LinkCLSID with their offsets.

  • Three consumers that copied BinaryFormatFailure.kind into a narrower union now map truncated explicitly: AndroidJniLibrary, RustBinaryImage, and MachoHardening/AppleDispatchMetadata (kind !== "unsupported"). The compiler found them.

  • Guard 2.5 in scripts/verify/architecture-guards.mjs uses counted baselines in scripts/verify/architecture-guard-baselines.json. A file may not exceed its count, and --shrink-baselines only lowers counts. Baselines measured on this branch:

    • raw Buffer.read* / DataView.get* numeric reads anywhere in src/ outside BinaryContainer.ts: 956 in 134 files
    • throw new Error|TypeError|RangeError( in parser folders: 211 in 52 files
    • JSON.parse( in parser folders: 17 in 15 files

    The counted-baseline helper is the same code as in open PR refactor(errors): require a reason for every analysis cancellation #10566 (checkCounted, same baseline file), so whichever lands second rebases mechanically.

  • docs/development/tool-design.md gains a paragraph on the owner, the projection and the guard.

Intentionally not included (later slices):

  • The RangeError channel: classifyHostRangeError and the 17 instanceof RangeError sites. That is the next PR.
  • The recognizer registry, MachoSliceSelection, and the other per-format classes (Il2cpp*, PythonPyc*, Model*, RustAuditable*, AppleIps*, SourceMap*, Capture*). The resource classes (V8CodeCacheBudgetFailure, WindowsShortcutResourceFailure, ElectronFuseResourceFailure) are also left: their recovery needs a typed, provider-specific boundary.
  • GpuCodeObjectsProvider still maps a malformed container to BinaryTargetError(file_format_rejected). That is a different public category, so it needs its own decision.

Contribution scope: ordinary refactor within existing boundaries; maintainer scope decision not applicable.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/parseFailure.ts owns the failure facts. BinaryReader is the earliest producer changed. parseFailureAnalysisError is the one projection. Twelve provider ladders and three format classes are removed.

  • Contribution scope fit and linked maintainer decision: not applicable (refactor).

  • CLI and MCP/tool-catalog contract: no schema change. The invalid_format message for the five providers listed above now carries the Selected artifact <path>: prefix the other providers already used. Public error tags and categories are unchanged.

  • Provider, bridge, target-format, or platform compatibility: none.

  • Evidence, artifact, provenance, or reconstruction contract: none.

  • Target selection, authority, upstream behavior, and cleanup details: not applicable.

  • Generated metadata, package, or installation impact: none.

  • Read existing files or captured data.

Evidence and regression coverage

  • Tests added or updated:
    • src/native/metadata/BinaryContainer.test.ts: an ELF PT_LOAD running past EOF fails as {kind: "truncated", format: "elf", offset: 0, field: "ELF load segment"}, while the same segment inside the file is admitted.
    • src/domain/parseFailureAnalysisError.test.ts: malformed and truncated project to invalid_format with the path; unsupported projects to an unsupported target that keeps undecodedContent; a limit or an unrelated RangeError is left to the producer.
    • V8CodeCacheParser.test.ts and WindowsShortcutParser.test.ts now assert the algebra's facts instead of the deleted class names.
  • Base reproduction: with src/native/metadata/BinaryContainer.ts restored from origin/main, the new truncation test fails (1 failed, 23 passed). With this change it passes.
  • Remaining proof gaps: no real-provider or Windows run. The guard counts are textual (comments stripped), not a type-aware audit.

Validation performed

  • node scripts/run-typescript.mjs --noEmit — passed
  • npm run check:fast — passed (typecheck + lint)
  • npx knip --cache — no findings
  • node scripts/verify/architecture-guards.mjs — passed across 2786 source files
  • npm run test:local -- 48 test files under src/native/{elf,hardening,initializers,exports,pe,windows,metadata,android}, src/native/AppleDispatchMetadata*, src/firmware/devicetree, src/go, src/v8, src/electron, src/gpu, src/rust — 48 files passed, 1327 tests passed, 2 skipped
  • npm run test:focused -- 48 CLI acceptance, MCP boundary, provider finalization and application-service test files for the touched providers (for example tests/acceptance/kernelModuleCli.test.ts, tests/boundary/mcp/elfNotesMcp.test.ts, tests/boundary/go/goBinaryProvider.test.ts, tests/process-global/electronFuseCleanup.test.ts) — 48 files passed, 851 tests passed
  • npm run test:local -- src/domain/parseFailureAnalysisError.test.ts — 4 passed
  • npx oxfmt on changed files — clean

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; macOS host only.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new reads, processes or network access.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

…gebra

Add ParseFailure (malformed, truncated, unsupported, limit, with format,
offset and field) and its one carrier, ParseFailureError, in the domain.
BinaryReader now names truncation and the field it read, and its native
format and resource failures are ParseFailureError subclasses.

Providers projected a format failure with their own instanceof ladder,
and some dropped the selected path from the invalid_format message.
parseFailureAnalysisError now owns that projection for the native,
Go, devicetree, V8, Windows Shortcut and Electron fuse providers.
The V8 code cache, Windows Shortcut and Electron fuse format classes
are removed in favour of the algebra.

The architecture guard counts raw Buffer and DataView reads, plain
Error throws in parser folders and plain JSON.parse of parser input
against baselines that can only shrink.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T18:33:26.507623Z ed80e64 New commits
ℹ️ 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.

@greptile-apps

greptile-apps Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge; the previous offset finding is fixed and no new actionable issue was found.

Summary

This PR gives parsers one shared failure type and one way to turn format failures into public errors.

  • Byte parsers report shared failure kinds with format and location details.
  • Parser failures use one provider mapping across binary inspection workflows.
  • Parser checks track raw reads and plain failure shortcuts.

No new security issue was identified. Checks were source-based; no tests were run during this review. Whether another PR supersedes this one could not be checked because GitHub authentication was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Parser or BinaryReader] --> B[ParseFailureError]
  B --> C{Failure kind}
  C -->|malformed or truncated| D[AnalysisInputError]
  C -->|unsupported| E[AnalysisUnsupportedTargetError]
  C -->|limit| F[Producer chooses recovery]
Loading

Reviews (3) · Last reviewed commit: "fix(parsers): retain malformed range off..." · Reviewed by Greptile

Comment thread src/native/metadata/BinaryContainer.ts Resolved
@morluto
morluto merged commit a0d9025 into main Nov 14, 2026
53 checks passed
@morluto
morluto deleted the refactor/parse-failure-algebra branch November 14, 2026 19:35
@morluto morluto added the area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior label Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant