Skip to content

fix(patch): review pass — removal trust, hunk isolation, file boundaries - #63

Merged
developjik merged 5 commits into
mainfrom
fix/patch-review-pass
Nov 30, 2026
Merged

developjik merged 5 commits into
mainfrom
fix/patch-review-pass

Conversation

@developjik

@developjik developjik commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Follow-up to #62 (merged as 56fc5c9, closes #31).

#62's engine is in main. While it was being merged, Devin Review's findings on it landed; each was reproduced as a failing case and fixed here. The file-on-disk guarantee (any failure leaves the file byte-identical) is unchanged and re-tested.

Nothing here changes the API: same apply_patch_file / render_patch / ApplyOptions, one new error variant.

Data loss / corruption

  • A - line must be in the file. The alignment paired a changed line with the nearest one (a mismatch cost less than skipping both), and the renderer then deleted it — so a hunk whose deleted line had been replaced still applied (0.625 with one of four lines missing) and removed content the patch never saw. Removals are now verified against their pair (>= MATCH_FLOOR); a missing or weakly-matched removal fails as the new RemovalMissing. Context may still drift. This also makes re-applying an applied patch fail instead of deleting its replacement.
  • Two hunks can no longer share lines. When the previous hunk ended past the whole search window, search_bounds collapsed the empty range to a single point at the window's edge, so the next hunk could anchor back inside the previous one. An empty range is now None → NotAnchored; a file shorter than the hunk is None too.
  • A plain diff -u multi-file patch is refused. Only diff --git was recognized as a file boundary, so a concatenated ---/+++ header let the second file's hunks apply to the first file. A ---/+++ pair followed by @@ inside a hunk body is now MultiFile. A body line that merely starts with -- (removing a SQL/Lua comment) is unaffected; both directions are tested.

Wrong-target anchoring

  • Similarity decides before distance. The distance term was subtracted from the score before ranking, so a nearer 0.96 candidate could outrank the true 1.00 target; the ambiguity check then saw that inversion as a tie (best - runner < 0) and skipped itself. Ranking is now similarity-first with distance as the tie-break, and the margin compares the absolute gap.
  • Token order counts. A bag-of-tokens Dice score rated let elapsed = end - start; and let elapsed = start - end; identical. The similarity now blends the bag score with the same measure over adjacent token pairs (0.6/0.4): similar, not the same line.

Rendering

  • Added lines follow their block. A hunk whose matched context had moved into a deeper block kept the patch's old indentation — in Python that can move a statement out of its if: valid syntax, different program. The indentation shift now comes from the first indented matched line and is applied when the patch's prefix matches.
  • \ No newline at end of file is read per side. A marker on the removed line means the patch is adding the missing newline; it was treated as "preserve the old shape" and the newline was dropped. An empty file no longer inherits a no-trailing-newline shape it never had (+hello means hello\n).
  • A Python # trailing comment is not code. return result # read from disk and return result # use cache now compare as the same line instead of failing a one-line hunk.

Hardening

  • The temp file is opened with create_new (O_EXCL) and named with a random UUID: a predictable name in a directory another local user can write to let a planted symlink redirect the write with the patching process's privileges.

Second pass (commit a82d1ca)

A second review round on the first pass found five more; each is reproduced and fixed:

finding fix
a stale patch overwrote a line whose argument also changed (similarity alone let it through) a removal now requires identical code tokens; comments and indentation may differ, tokens may not
a comment that moved into an if was read as the whole block moving, pushing the replacement call inside the shift comes from matched code lines only, and every one of them must agree
reindenting an added line inside an open """/''' literal changed the string's data lines inside an open triple-quoted literal are never rebased
a diff -U0 hunk whose body is --- old note/+++ new note was refused as multi-file the boundary check also requires the current hunk's declared counts to be met
an EOF-marker test no longer had a body line after the marker test corrected to actually exercise it

New regression tests: a_removal_whose_code_changed_is_refused_even_with_a_good_score, a_moved_comment_does_not_rebase_the_code_beside_it, a_multiline_string_value_is_not_reindented, a_diff_u_zero_hunk_that_looks_like_a_header_is_still_body.

Third pass (commit 24e77d7)

finding fix
a miscounted hunk header let the next file's header parse as body (two files mixed) the boundary test now needs only a started hunk body, not exact counts — refusing a strange patch beats mixing files; the per-line recount that made parsing quadratic is gone too
a nested block that moved by the same width was read as a conflict and never rebased the shift compares the move (+4 / −4), not the absolute prefix
a """ in a comment switched rebasing off, and a closing quote on a kept line did not end it the quote tracker walks every line the renderer sees and ignores comment-only lines

a_nested_block_that_moved_as_a_whole_still_rebases, triple_quotes_in_a_comment_do_not_switch_off_rebasing, a_second_file_is_detected_even_when_the_first_hunk_miscounted.

Fourth and fifth passes (e9501f0, 0550f85)

  • A statement the patch adds outside a moved block no longer takes the
    block's shift; only added lines at least as deep as the matched block move.
  • A prefix that merely grew or shrank by a run of one whitespace character
    counts as a move, and the pad is applied after the line's own indent, so a
    tab-indented block that gained four spaces still rebases.
  • The triple-quote state follows only lines that reach the output and finds a
    close inside an open literal regardless of #; the comment start is now
    string-aware, and backticks (JS/TS template literals) are tracked too.

Left as documented behaviour

  • ambiguity_margin: 0.0 disables the rule for fuzzy anchors only; two byte-exact blocks at equal distance are still two edits and are still refused.
  • The fuzzy search is O(hunk × window) per candidate: a 500-line hunk over the default ±250 window repeats comparisons (~10⁸ line comparisons in the pathological case). Worth a benchmark before tuning for very large hunks; not addressed here.

Verified

  • cargo test --lib — 355 passed (68 patch)
  • cargo test --test patch_engine — 31 passed (all green in CI on 3 OSes)
  • cargo fmt --check, cargo clippy --lib --tests -- -D warnings

Every finding above has a regression test: a_removal_of_a_line_the_file_does_not_have_is_refused, a_second_hunk_never_edits_the_lines_the_first_one_took, a_plain_diff_u_multi_file_patch_is_refused, the_ambiguity_margin_boundary, a_wider_margin_makes_a_close_call_ambiguous, token_order_counts, a_python_statement_that_moved_into_a_block_keeps_the_blocks_indent, an_empty_file_gains_the_newline_the_patch_asks_for, a_patch_can_add_the_final_newline_the_file_was_missing, a_python_trailing_comment_is_not_code.

Addresses the actionable findings from Devin Review on this PR. Each one
was reproduced as a test before the fix; the file-on-disk guarantee (any
failure leaves the file byte-identical) is unchanged and re-tested.

Data loss / corruption:
- **A `-` line must be in the file.** The alignment paired a changed line
  with the nearest one (a mismatch cost less than skipping both) and the
  renderer then deleted it, so a hunk whose deleted line had been replaced
  still applied — at a score of 0.625 with one of four lines missing —
  and removed content the patch never saw. Removals are now verified
  against their pair (`>= MATCH_FLOOR`); a missing or weakly-matched
  removal fails as `RemovalMissing`. Context may still drift. This also
  makes re-applying an applied patch fail instead of deleting its
  replacement.
- **Two hunks can no longer share lines.** When the previous hunk ended
  past the whole search window, `search_bounds` collapsed the empty range
  to a single point at the window's edge, so the next hunk could anchor
  back inside the previous one. An empty range now returns `None` and the
  hunk fails as `NotAnchored`. A file shorter than the hunk is `None` too.
- **A plain `diff -u` multi-file patch is refused.** Only `diff --git`
  was recognized as a file boundary; a concatenated `---`/`+++` header
  let the second file's hunks apply to the first file. A `---`/`+++` pair
  followed by `@@` inside a hunk body is now `MultiFile`. A body line
  that merely starts with `--` (removing a SQL/Lua comment) is unaffected,
  and both directions have tests.

Wrong-target anchoring:
- **Similarity decides before distance.** The distance term was subtracted
  from the score before ranking, so a nearer 0.96 candidate could outrank
  the true 1.00 target and the ambiguity check then saw the inversion as a
  tie (`best - runner < 0`) and skipped itself. Ranking is now
  similarity-first with distance as the tie-break, and the margin compares
  the absolute gap.
- **Token order counts.** A bag-of-tokens Dice score rated
  `let elapsed = end - start;` and `let elapsed = start - end;` identical;
  the similarity now blends the bag score with the same measure over
  adjacent token pairs (0.6 / 0.4), so a reordered line is similar but not
  the same line.

Rendering:
- **Added lines follow their block.** A hunk whose context had moved into
  a deeper block kept the patch's old indentation, which in Python could
  move a statement out of its `if` — valid syntax, different program. The
  indentation shift is taken from the first indented matched line and
  applied when the patch's prefix matches.
- **`\ No newline at end of file` is read per side.** A marker on the
  removed line means the patch is *adding* the missing newline; it was
  being treated as "preserve the old shape" and the newline was dropped.
  An empty file no longer inherits a no-trailing-newline shape it never
  had (`+hello` now means `hello\n`).

Hardening:
- The temp file is opened with `create_new` (`O_EXCL`) and named with a
  random UUID: a predictable name in a shared directory let a planted
  symlink redirect the write with the patching process's privileges.

Documented rather than changed:
- `ambiguity_margin: 0.0` disables the rule for *fuzzy* anchors only; two
  byte-exact blocks at equal distance are still two edits and are still
  refused.

Tests: 67 unit (patch), 27 end-to-end — each finding above has a
regression test, plus the existing acceptance-criteria suite.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>
@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-30T05:00:38.208983Z
We couldn’t complete this review. Comment @codex review to try again.
6dd26d8 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.

devin-ai-integration[bot]

This comment was marked as resolved.

Follow-up findings on #63, each reproduced as a test.

- **A removed line's *code* must match, not just its similarity.** The
  previous 0.5 similarity floor let a stale patch overwrite a line whose
  argument also changed, because the comment term is normalized away. A
  removal now requires identical code tokens (comments and indentation may
  differ); anything else is `RemovalMissing`.
- **Indentation is rebased only from code lines, and only when they
  agree.** A comment that someone moved into an `if` was read as the block
  having moved, and the replacement call was pushed inside with it. Blank
  and comment lines no longer decide the shift, and conflicting shifts
  disable rebasing.
- **Multi-line string contents are never rebased.** Reindenting an added
  line inside an open triple-quoted literal changed data. A small tracker
  skips lines while a `"""`/`'''` literal is open.
- **A `diff -U0` hunk that looks like a file header is body.** The
  multi-file boundary check now also requires the current hunk to have
  taken everything its header declared, so a one-file patch whose hunk body
  is `--- old note` / `+++ new note` parses as one file.
- Test corrected: `a_marker_followed_by_another_line_*` now actually has a
  body line after the marker.

Tests: 66 unit (patch), 29 end-to-end.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>
devin-ai-integration[bot]

This comment was marked as resolved.

…ote state

- A `---`/`+++`/`@@` triple after the hunk body has started is a file
  boundary even when the hunk header miscounted its lines. Reading a header
  pair as body is still allowed while the body is empty (`diff -U0` of a
  one-file comment swap), but once body lines exist the boundary wins:
  refusing a strange patch beats mixing two files. Also drops the
  per-line recount that made parsing quadratic on huge insert hunks.
- Indentation rebasing compares the *move* (+4, -4), not the absolute
  prefix, so a block header and its nested body that moved by the same
  width still rebase — and tab/space mixing or disagreeing moves disable it.
- The triple-quote tracker walks every line the renderer sees (kept,
  removed, added) and ignores comment-only lines, so a `"""` in a comment
  does not switch rebasing off and a closing quote on a kept line ends it.

Tests: nested-shift and comment-quote cases end to end; miscounted
multi-file parse case; 67 unit + 31 end-to-end.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 4 new potential issues.

Devin Review

Comment thread src/patch/render.rs Resolved
Comment thread src/patch/render.rs Resolved
Comment thread src/patch/render.rs Resolved
Comment thread src/patch/render.rs Outdated
Comment on lines +215 to +220
let pad = patch_prefix.chars().next()?;
if !patch_prefix.chars().all(|c| c == pad)
|| !file_prefix.chars().all(|c| c == pad)
|| patch_prefix.len() == file_prefix.len()
{
return None;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 혼합 들여쓰기 블록의 대체 호출이 조건문 밖에 저장됨

탭과 공백을 함께 쓰는 Python 블록은 기존 접두사에 공백만 추가돼도 이동을 계산하지 않습니다. 대체 호출이 원래 깊이에 남아 조건과 무관하게 실행됩니다.

Learn more

퍼지 패치는 들여쓰기가 달라도 토큰이 일치하는 호출을 찾을 수 있습니다. 현재 이동 계산은 첫 공백 문자와 다른 문자가 접두사에 하나라도 있으면 보정을 포기합니다. 접두사가 완전히 보존되고 한 단계만 추가된 경우에도 그렇습니다. 추가 줄 렌더링은 이동 정보가 없으면 원래 들여쓰기를 그대로 쓰므로, 구문상 유효하지만 실행 범위가 다른 파일이 만들어집니다.

Example: 함수 본문의 접두사가 탭 하나와 공백 4개이고, 대상 파일이 store()를 새 if 아래로 옮겨 공백을 4개 더 붙였습니다. store()를 persist()로 바꾸는 패치는 기존 접두사로 persist()를 씁니다. if 안에 log()가 남아 있으므로 파싱은 성공하지만 persist()는 조건문 밖에 놓입니다.

Recommended fix: 공통 이동 폭을 비교하는 방식은 유지하되, 기존 접두사가 그대로 보존된 이동은 접두사의 문자 종류가 섞여 있어도 처리하세요. 탭과 공백을 임의로 환산하지 말고 실제 접두사 차이를 사용하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

- Only added lines at least as deep as the matched block take the shift: a
  statement the patch adds above or below a block that moved stays where
  the patch put it.
- The prefix comparison accepts a prefix that merely grew or shrank by a
  run of one whitespace character, and the pad is applied after the line's
  own indent, so a tab-indented block that gained four spaces still moves.
- The triple-quote state tracks only lines that reach the output (kept
  context and added lines) and looks for delimiters inside an open literal
  regardless of `#`; a `#` comment's quotes are prose only outside one.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 2 new potential issues.

Devin Review

Comment thread src/patch/render.rs Resolved
Comment thread src/patch/render.rs
Comment on lines +295 to +299
if shift.delta >= 0 {
// Extend the line's own prefix, so mixed tab/space styles keep their
// shape ("\t " gains four spaces rather than becoming " \t ").
let extra: String = std::iter::repeat_n(shift.pad, shift.delta as usize).collect();
Cow::Owned(format!("{indent}{extra}{}", &line[indent.len()..]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 JavaScript 패치가 템플릿 문자열에 공백을 삽입함

공백으로 들여쓴 코드가 더 깊이 이동하면, 패치 엔진은 탭으로 시작하는 템플릿 문자열 본문에도 길이만 보고 공백을 추가합니다. 구문 검사를 통과해 패치와 다른 문자열 값이 저장됩니다.

Learn more

들여쓰기 계산은 원래 접두사의 내용이 아니라 바이트 길이만 추가 줄에 전달합니다. 따라서 탭으로 시작하는 문자열 본문도 공백으로 들여쓴 코드와 길이가 비슷하면 같은 이동을 적용받습니다. JavaScript 템플릿 문자열 안에서는 그 공백이 값의 일부이므로 구문 검사로 잡히지 않습니다.

Example: 공백 4칸으로 들여쓴 const text = 선언이 대상 파일에서 8칸으로 이동했다고 가정합니다. 문맥 없는 교체 패치가 이 선언을 여러 줄 템플릿 문자열로 바꾸고, 두 번째 줄을 탭 1개와 공백 4칸으로 시작하면 렌더러는 그 줄에 공백을 4칸 더 넣습니다.

Recommended fix: Shift에 매칭된 블록의 실제 패치 접두사를 보관하고, 추가 줄이 그 접두사로 시작할 때만 이동을 적용하세요. 이렇게 하면 공통 접두사 뒤에서 탭과 공백을 섞는 코드도 지원하면서, 접두사가 다른 템플릿 본문의 바이트는 보존할 수 있습니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

- The triple-quote tracker cut the line at its first `#`, which is data
  inside a string; the comment start now comes from the tokenizer, so a
  `"""` after a `#` inside a literal is still seen as the literal's close.
- Backticks are tracked as multi-line delimiters too: a JavaScript/TypeScript
  template literal's interior must not be reindented either.

Refs #31

Signed-off-by: 정인권 <developjik@gmail.com>

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 3 new potential issues.

Devin Review

Comment thread src/patch/render.rs
Comment on lines +253 to +255
// Multi-line delimiters: Python's two triple quotes, and the backtick
// that spans lines in JavaScript/TypeScript templates.
const DELIMITERS: [&str; 3] = ["\"\"\"", "'''", "`"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 백틱이 든 파이썬 문자열 뒤에서 조건문 밖으로 빠지는 코드

파이썬의 일반 문자열에 백틱이 하나 있으면 렌더러가 여러 줄 문자열이 시작됐다고 판단합니다. 이동한 if 블록에 문장을 추가할 때 들여쓰기가 보정되지 않아, 조건이 거짓이어도 문장이 실행됩니다.

Learn more

indent_shift는 패치의 문맥 줄과 현재 파일의 줄을 비교해 블록이 얼마나 이동했는지 계산합니다. 렌더링 루프는 문맥 줄을 읽다가 여러 줄 문자열이 열렸다고 판단하면 이후 추가 줄의 들여쓰기를 보정하지 않습니다. multiline_quote는 백틱이 일반 따옴표로 둘러싸여 있는지 확인하지 않고 raw 문자열에서 개수를 셉니다. 조건문 밖으로 빠진 문장도 유효한 파이썬이라 구문 검사를 통과하고 apply_patch_file이 그대로 저장합니다.

Example: 패치의 문맥 줄 marker = "\u0060"이 현재 파일에서 공백 4칸에서 8칸으로 이동해 if ok: 안에 있습니다. 그 뒤에 공백 4칸으로 notify()를 추가하는 패치를 적용하면, 기대와 달리 호출은 8칸으로 이동하지 않아 ok가 거짓이어도 실행됩니다.

Recommended fix: 파일 언어에 맞는 구분자만 사용하고, 다른 문자열 내부의 백틱을 여는 구분자로 취급하지 마세요. 파이썬 일반 문자열 뒤의 추가 줄은 재배치하면서 JS/TS 템플릿 내부의 공백은 보존하는 렌더링 테스트를 추가하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/render.rs
Comment on lines +319 to +324
// The tokenizer knows where the comment starts without being
// fooled by a `#` inside a string literal.
let code = match score::tokenize(line).comment_at {
Some(at) => &line[..at],
None => line,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 파이썬 정수 나눗셈 뒤의 여러 줄 문자열 공백 손상

파이썬에서 // 정수 나눗셈 뒤에 여러 줄 문자열이 시작되면, 렌더러가 //를 주석으로 오인해 여는 따옴표를 놓칩니다. 이동한 블록에 패치를 적용할 때 문자열 본문까지 들여쓰기를 보정해 값이 달라집니다.

Learn more

indent_shift는 문맥이 더 깊은 블록으로 이동하면 새 코드도 함께 옮기도록 들여쓰기 차이를 계산합니다. 여러 줄 문자열의 본문은 코드가 아니라 값이므로 추가 줄 렌더링이 이 보정을 건너뛰어야 합니다. 하지만 tokenize는 언어와 무관하게 //에서 줄 주석이 시작된다고 보고합니다. 그 뒤의 여는 따옴표가 검사 대상에서 빠져 본문에도 들여쓰기 보정이 적용됩니다. 출력은 여전히 유효한 파이썬이므로 구문 검사가 값의 변화를 발견하지 못합니다.

Example: 문맥이 if 안으로 공백 4칸 이동한 곳에 return count // page_size, """로 시작하는 여러 줄 문자열을 추가합니다. 패치에서 문자열 본문이 Page라면 반환값에도 공백 4칸이 있어야 하지만, 렌더러는 공백을 8칸으로 늘립니다.

Recommended fix: 유사도 점수용 토크나이저의 범용 주석 규칙을 그대로 쓰지 말고, 파일 언어를 렌더러에 전달해 그 언어의 주석과 문자열 문법으로 구분자를 추적하세요. 파이썬에서는 // 뒤의 문자열도 추적하고, 회귀 테스트에서 적용 후 문자열의 공백을 바이트 단위로 비교하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/patch/render.rs
Comment on lines +319 to +324
// The tokenizer knows where the comment starts without being
// fooled by a `#` inside a string literal.
let code = match score::tokenize(line).comment_at {
Some(at) => &line[..at],
None => line,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 들여쓰기 보정이 없는 패치도 렌더링 중 다시 토큰화

들여쓰기 보정이 필요 없는 헝크도 주석 위치를 찾기 위해 tokenize를 호출합니다. 렌더러는 위치만 쓰므로, 이 경로에서 계산한 토큰과 인접 쌍 해시, 정렬 결과는 모두 버려집니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@developjik
developjik merged commit 2990dfb into main Nov 30, 2026
10 checks passed
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.

feat(patch): resilient fuzzy diff engine with AST syntax pre-validation

1 participant