Skip to content

fix(verify): reject anchorless, submodule, non-UTF-8 diffs; lock shadow immunity - #82

Merged
omsherikar merged 6 commits into
mainfrom
fix/r3-input-hardening
Jul 29, 2026
Merged

omsherikar merged 6 commits into
mainfrom
fix/r3-input-hardening

Conversation

@omsherikar

@omsherikar omsherikar commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

What

Round-3 input hardening: three new loud rejections for diff shapes that could silently misverify, all probe-confirmed before implementation, plus adversarial-review fixes.

Changes

  1. Zero-context anchorless hunks are rejected (diff has a zero-context hunk in <file>; regenerate the diff with context (e.g. git diff -U3)). Probe proof: a pure-insertion -U0 hunk silently applied at the wrong location on a drifted base. Review then bypassed the guard itself via a --- /dev/null claim against an existing file; the exemption now trusts the disk, not the diff's claim.
  2. Submodule pointer diffs are rejected, gated on the gitlink mode 160000 discriminator so an innocent content line reading Subproject commit <sha> can never false-reject (review-proven false positive, fixed with lock tests both ways).
  3. Non-UTF-8 base files are rejected loudly (probe proof: latin-1 sources corrupt through a UTF-8 read with no byte round-trip). Implemented with fatal TextDecoder including the ignoreBOM subtlety.
  4. Whitespace-mangled patches: existing loud failure locked with a regression test.
  5. Shadow-tree __pycache__ handling: an interim redesign (hardlink + prune) was REVERTED after review measured the perf win at ~1.9s per 500-module verify against giving up structural immunity to stale-bytecode false SAFEs. Blanket skip is restored and locked by a structural-immunity test (no bytecode anywhere in any shadow).
  6. Docs: honest notes on subprocess-coverage blindness and on SAFE meaning suite-approved, not proven correct (SWE-bench audit context).

Proof

Red-first on every behavioral change including the two review findings; full suite 860/860 in an isolated worktree; typecheck, lint, build clean.

Summary by CodeRabbit

  • Documentation
    • Clarified verification result meanings (SAFE vs UNPROVEN) and reiterated coverage’s Python-only limitations, including gaps for subprocesses/multiprocessing execution.
  • Bug Fixes
    • Verification now flags additional unverifiable/unsafe diff scenarios, including submodule pointer changes, non-UTF-8 base content, and mismatched/unsafe patch application (avoiding misleading results).
    • Shadow environments now exclude build caches and Python bytecode caches (__pycache__).
  • Tests
    • Expanded unit coverage for unsafe patch rejection, encoding handling, and shadow-tree cache exclusion behavior.

Three diff-input hardenings that each closed a silent false-SAFE path:

R3.1: a hunk with no context and no deletions has no anchor, so applyPatch inserts it at the header line even on a drifted base and fabricates content. Reject such hunks unless the file is brand new (base absent).

R3.5: a git submodule pointer bump renders as Subproject commit hunk content. A gitlink cannot be applied or covered, so refuse it explicitly instead of failing later with a confusing did-not-apply.

R3.6: reading a non-UTF-8 base as utf8 substitutes replacement chars that do not round-trip, corrupting unchanged bytes in the shadow. Read the base as a Buffer and reject it when it fails a byte-for-byte round-trip, in both editsFromUnifiedDiff and changedLinesForEdits.

R3.7: added a regression test locking the loud failure on a whitespace-mangled context line so a future fuzz-tolerant parser cannot misapply silently.
Python validates a .pyc against its source's mtime (1s granularity) plus size. Overlaying a changed .py of identical byte length within the same mtime second as the original can validate a STALE .pyc, so the shadow executes old bytecode and reads as a false SAFE.

Stop skipping __pycache__ wholesale (hardlinked bytecode for UNCHANGED files stays valid, since the source is hardlinked with the same inode) and instead prune the sibling __pycache__ of every overlaid change in the shadow, forcing Python to recompile the changed source. Pruning is shadow-only: unlinking a hardlinked .pyc leaves the source inode intact, so the source tree is never touched. .pytest_cache stays skipped.
Two honest limitations in the verdict docs: coverage.py cannot see code that runs only in a subprocess or multiprocessing worker without COVERAGE_PROCESS_START wiring, so such changes read UNPROVEN until subprocess coverage lands; and SAFE means suite-approved, not proven correct, since it inherits whatever a possibly-weak suite checks (SWE-bench audits find many test-passing agent patches are still wrong), which is why UNPROVEN and the missing-tests hints exist. Also adds the one-line subprocess caveat to the verify-diff coverage warning.
C1: the anchorless-hunk (R3.1) guard trusted the diff's `--- /dev/null`
old side to mean "new file". A diff can lie: claim /dev/null while the
victim path already exists on disk, and its anchorless hunk then skipped
the zero-context rejection and spliced content in at a raw line number on
the live file. Derive isNewFile from the disk base instead; the one safe
relaxation is a recreate-into-empty (claimed /dev/null AND base is empty),
where an all-insertion hunk cannot misapply onto drift.

I1: a bare `Subproject commit <hex>` content line false-rejected innocent
prose (a docs file editing that literal line). A real gitlink change
always carries mode 160000 on the enclosing entry, so scanRawDiff now
tracks whether the current `diff --git` entry declared that mode and only
then treats a Subproject line as a pointer bump. The parsePatch-hunk
fallback in findSubmodule (which cannot see the mode and was the false-
positive source) is dropped.

Minor: replace the readUtf8Base Buffer round-trip with a single fatal
TextDecoder pass (ignoreBOM keeps the base byte-exact) and state the
gate's scope honestly: it catches invalid UTF-8 bytes; byte-valid UTF-8
that is really another encoding fails loudly downstream at applyPatch.
Reverts the branch's __pycache__ redesign (removed it from SKIP_DIRS and
pruned the changed file's sibling cache post-overlay) back to blanket
skipping the directory at copy time.

The measured win of the redesign was ~1.9s per verify on a 500-module
tree — low single-digit % of a gate that runs the full suite — while
blanket-skip buys two structural properties that matter more than that:
stale-bytecode false SAFEs become impossible (Python cannot validate a
.pyc that was never copied in), and we avoid ENOENT races from hardlinking
the most volatile directory in a Python repo. A shared content-hash
bytecode cache is the right perf design if this ever becomes a bottleneck.

Tests: replace the prune test with a structural-immunity lock (a source
tree with populated __pycache__ in a changed and an unchanged dir yields a
shadow with no __pycache__ anywhere), and restore __pycache__ coverage to
the build-caches skip test alongside dist.
Copilot AI review requested due to automatic review settings July 23, 2026 17:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 66074077-17ab-43fa-b908-eb3a1d539f31

📥 Commits

Reviewing files that changed from the base of the PR and between c49318a and 2142b36.

📒 Files selected for processing (2)
  • docs/styles/config/vocabularies/Mintlify/accept.txt
  • docs/verification/verdicts.mdx
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/verification/verdicts.mdx

📝 Walkthrough

Walkthrough

Diff verification now rejects unsafe submodule, invalid UTF-8, anchorless, spoofed-new-file, and mismatched patches. Tests cover these cases and shadow-tree cache exclusions. Documentation clarifies subprocess coverage limits and verification verdict semantics.

Changes

Verification safety

Layer / File(s) Summary
Diff input validation
src/verify/diff-input.ts
Diff scanning and application now detect submodule pointers, validate base files as UTF-8, and reject unsafe anchorless hunks.
Diff validation coverage
tests/unit/verify/diff-input.test.ts
Tests cover malformed bases, submodule diffs, spoofed new-file headers, anchorless hunks, deletion mismatches, and whitespace-mangled patches.
Shadow-tree cache exclusions
tests/unit/verify/shadow-tree.test.ts
Tests verify that dist and __pycache__ are absent from shadow trees while changed overlays remain present.
Verification result documentation
docs/verification/verdicts.mdx, docs/verification/verify-diff.mdx, docs/styles/config/vocabularies/Mintlify/accept.txt
Documentation explains Python-only and subprocess coverage limitations, clarifies SAFE, UNPROVEN, and missingTests semantics, and updates accepted terminology.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main verification hardening changes and the shadow-tree immunity update.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/r3-input-hardening

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

docs/verification/verdicts.mdx

Parsing error: ESLint was configured to run on <tsconfigRootDir>/docs/verification/verdicts.mdx using parserOptions.project: /tsconfig.eslint.json
The extension for the file (.mdx) is non-standard. You should add parserOptions.extraFileExtensions to your config.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mintlify

mintlify Bot commented Jul 23, 2026

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
refactron 🟢 Ready View Preview Jul 23, 2026, 5:55 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@omsherikar
omsherikar merged commit bee3694 into main Jul 29, 2026
16 checks passed
@omsherikar
omsherikar deleted the fix/r3-input-hardening branch July 29, 2026 07:02

This branch was successfully deployed

1 active deployment
staging - docs — 2142b366 Deployed Jul 29, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants