Repository navigation
fix(patch): review pass — removal trust, hunk isolation, file boundaries - #63
Conversation
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>
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
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>
…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>
| 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; |
There was a problem hiding this comment.
🔴 혼합 들여쓰기 블록의 대체 호출이 조건문 밖에 저장됨
탭과 공백을 함께 쓰는 Python 블록은 기존 접두사에 공백만 추가돼도 이동을 계산하지 않습니다. 대체 호출이 원래 깊이에 남아 조건과 무관하게 실행됩니다.
Learn more
퍼지 패치는 들여쓰기가 달라도 토큰이 일치하는 호출을 찾을 수 있습니다. 현재 이동 계산은 첫 공백 문자와 다른 문자가 접두사에 하나라도 있으면 보정을 포기합니다. 접두사가 완전히 보존되고 한 단계만 추가된 경우에도 그렇습니다. 추가 줄 렌더링은 이동 정보가 없으면 원래 들여쓰기를 그대로 쓰므로, 구문상 유효하지만 실행 범위가 다른 파일이 만들어집니다.
Example: 함수 본문의 접두사가 탭 하나와 공백 4개이고, 대상 파일이 store()를 새 if 아래로 옮겨 공백을 4개 더 붙였습니다. store()를 persist()로 바꾸는 패치는 기존 접두사로 persist()를 씁니다. if 안에 log()가 남아 있으므로 파싱은 성공하지만 persist()는 조건문 밖에 놓입니다.
Recommended fix: 공통 이동 폭을 비교하는 방식은 유지하되, 기존 접두사가 그대로 보존된 이동은 접두사의 문자 종류가 섞여 있어도 처리하세요. 탭과 공백을 임의로 환산하지 말고 실제 접두사 차이를 사용하세요.
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>
| 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()..])) |
There was a problem hiding this comment.
🔴 JavaScript 패치가 템플릿 문자열에 공백을 삽입함
공백으로 들여쓴 코드가 더 깊이 이동하면, 패치 엔진은 탭으로 시작하는 템플릿 문자열 본문에도 길이만 보고 공백을 추가합니다. 구문 검사를 통과해 패치와 다른 문자열 값이 저장됩니다.
Learn more
들여쓰기 계산은 원래 접두사의 내용이 아니라 바이트 길이만 추가 줄에 전달합니다. 따라서 탭으로 시작하는 문자열 본문도 공백으로 들여쓴 코드와 길이가 비슷하면 같은 이동을 적용받습니다. JavaScript 템플릿 문자열 안에서는 그 공백이 값의 일부이므로 구문 검사로 잡히지 않습니다.
Example: 공백 4칸으로 들여쓴 const text = 선언이 대상 파일에서 8칸으로 이동했다고 가정합니다. 문맥 없는 교체 패치가 이 선언을 여러 줄 템플릿 문자열로 바꾸고, 두 번째 줄을 탭 1개와 공백 4칸으로 시작하면 렌더러는 그 줄에 공백을 4칸 더 넣습니다.
Recommended fix: Shift에 매칭된 블록의 실제 패치 접두사를 보관하고, 추가 줄이 그 접두사로 시작할 때만 이동을 적용하세요. 이렇게 하면 공통 접두사 뒤에서 탭과 공백을 섞는 코드도 지원하면서, 접두사가 다른 템플릿 본문의 바이트는 보존할 수 있습니다.
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>
| // Multi-line delimiters: Python's two triple quotes, and the backtick | ||
| // that spans lines in JavaScript/TypeScript templates. | ||
| const DELIMITERS: [&str; 3] = ["\"\"\"", "'''", "`"]; |
There was a problem hiding this comment.
🔴 백틱이 든 파이썬 문자열 뒤에서 조건문 밖으로 빠지는 코드
파이썬의 일반 문자열에 백틱이 하나 있으면 렌더러가 여러 줄 문자열이 시작됐다고 판단합니다. 이동한 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 템플릿 내부의 공백은 보존하는 렌더링 테스트를 추가하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| // 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, | ||
| }; |
There was a problem hiding this comment.
🔴 파이썬 정수 나눗셈 뒤의 여러 줄 문자열 공백 손상
파이썬에서 // 정수 나눗셈 뒤에 여러 줄 문자열이 시작되면, 렌더러가 //를 주석으로 오인해 여는 따옴표를 놓칩니다. 이동한 블록에 패치를 적용할 때 문자열 본문까지 들여쓰기를 보정해 값이 달라집니다.
Learn more
indent_shift는 문맥이 더 깊은 블록으로 이동하면 새 코드도 함께 옮기도록 들여쓰기 차이를 계산합니다. 여러 줄 문자열의 본문은 코드가 아니라 값이므로 추가 줄 렌더링이 이 보정을 건너뛰어야 합니다. 하지만 tokenize는 언어와 무관하게 //에서 줄 주석이 시작된다고 보고합니다. 그 뒤의 여는 따옴표가 검사 대상에서 빠져 본문에도 들여쓰기 보정이 적용됩니다. 출력은 여전히 유효한 파이썬이므로 구문 검사가 값의 변화를 발견하지 못합니다.
Example: 문맥이 if 안으로 공백 4칸 이동한 곳에 return count // page_size, """로 시작하는 여러 줄 문자열을 추가합니다. 패치에서 문자열 본문이 Page라면 반환값에도 공백 4칸이 있어야 하지만, 렌더러는 공백을 8칸으로 늘립니다.
Recommended fix: 유사도 점수용 토크나이저의 범용 주석 규칙을 그대로 쓰지 말고, 파일 언어를 렌더러에 전달해 그 언어의 주석과 문자열 문법으로 구분자를 추적하세요. 파이썬에서는 // 뒤의 문자열도 추적하고, 회귀 테스트에서 적용 후 문자열의 공백을 바이트 단위로 비교하세요.
Was this helpful? React with 👍 or 👎 to provide feedback.
| // 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, | ||
| }; |
There was a problem hiding this comment.
🔍 들여쓰기 보정이 없는 패치도 렌더링 중 다시 토큰화
들여쓰기 보정이 필요 없는 헝크도 주석 위치를 찾기 위해 tokenize를 호출합니다. 렌더러는 위치만 쓰므로, 이 경로에서 계산한 토큰과 인접 쌍 해시, 정렬 결과는 모두 버려집니다.
Was this helpful? React with 👍 or 👎 to provide feedback.
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
-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 newRemovalMissing. Context may still drift. This also makes re-applying an applied patch fail instead of deleting its replacement.search_boundscollapsed 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 nowNone→NotAnchored; a file shorter than the hunk isNonetoo.diff -umulti-file patch is refused. Onlydiff --gitwas 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 nowMultiFile. A body line that merely starts with--(removing a SQL/Lua comment) is unaffected; both directions are tested.Wrong-target anchoring
best - runner < 0) and skipped itself. Ranking is now similarity-first with distance as the tie-break, and the margin compares the absolute gap.let elapsed = end - start;andlet 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
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 fileis 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 (+hellomeanshello\n).#trailing comment is not code.return result # read from diskandreturn result # use cachenow compare as the same line instead of failing a one-line hunk.Hardening
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:
ifwas read as the whole block moving, pushing the replacement call inside"""/'''literal changed the string's datadiff -U0hunk whose body is--- old note/+++ new notewas refused as multi-fileNew 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)"""in a comment switched rebasing off, and a closing quote on a kept line did not end ita_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)block's shift; only added lines at least as deep as the matched block move.
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.
close inside an open literal regardless of
#; the comment start is nowstring-aware, and backticks (JS/TS template literals) are tracked too.
Left as documented behaviour
ambiguity_margin: 0.0disables the rule for fuzzy anchors only; two byte-exact blocks at equal distance are still two edits and are still refused.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 warningsEvery 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.