fix(diff): keep combined-diff changes made against a later parent (#4318)

## Description

In a merge diff (`git show -c`, `git diff --cc`) every line has one +/-
column per parent, so a change against the second parent is written `
-old` / ` +new`. `DiffCompressor` only treated lines starting with `+`
or `-` as changes. These lines were counted as context and trimmed
whenever they sat more than `max_context_lines` from a first-column
change. A hunk holding only such a change lost the change entirely, and
the footer under-counted additions and deletions.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `parse_diff` and `reduce_context` classify combined-diff lines by all
of their parent columns (the parent count comes from the `@@@` header).
- Regular `@@` diffs are classified exactly as before.
- New test `combined_diff_second_parent_changes_survive_context_trim`.

## Testing

- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ cargo test -p headroom-core --lib
test result: ok. 976 passed; 0 failed; 1 ignored

# new test against the old code:
" -old_from_p2" dropped as context:
test result: FAILED. 0 passed; 1 failed

$ cargo clippy -p headroom-core --lib --tests -- -D warnings   # clean
$ pytest tests/test_transforms/test_diff_compressor.py tests/test_transforms/test_diff_compressor_rust_parity.py tests/test_transforms_content_router.py tests/test_transforms/test_content_router.py tests/parity
212 passed, 2 skipped
```

## Real Behavior Proof

- Environment: Ubuntu, Python 3.12, headroom-ai 0.41.0 from PyPI vs this
branch built with `pip install -e .`
- Exact command / steps: a 400-line file changed on two branches,
merged, then one more line changed in the merge. `git show -c HEAD` (120
lines) passed through `DiffCompressor().compress(...)`, and the +/-
lines in all parent columns counted before and after.
- Observed result:
  ```text
0.41.0: changed lines in: 28 out: 26 lost: [' -line 200', ' +line 200
main']
  branch:  changed lines in: 28 out: 28 lost: []
  ```
On 0.41.0 the `@@@ -197,7 -197,7 +197,7 @@@` hunk comes out as two
context lines and nothing else. The footer goes from `+12 -12 lines` to
`+13 -15 lines`, which matches a count of the input.
- Not tested: octopus merges (`@@@@`); the same code path handles them.

## Runtime Rollout Safety

N/A: no rollout-managed feature, no config change.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

The existing combined-diff tests build their input with `\` string
continuations, which strip each line's leading whitespace, so their `
-...` lines were really `-...` lines. The new test builds its lines
explicitly.

The hunk headers are still not updated after trimming. That is a
separate PR on top of this one.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4318"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Jay Hemnani
2026-11-03 22:58:03 -06:00
committed by GitHub
co-authored by JD Davis
parent 35ca9b8356
commit 4b788fd04d
@@ -802,7 +802,18 @@ fn parse_diff(lines: &[&str]) -> ParsedDiff {
// Hunk content.
if let Some(h) = current_hunk.as_mut() {
if line.starts_with('+') && !line.starts_with("+++") {
let parents = hunk_parents(&h.header);
if parents > 1 && !line.starts_with('\\') {
let (added, deleted) = combined_change(line, parents);
if deleted {
h.deletions += 1;
} else if added {
h.additions += 1;
} else {
h.context_lines += 1;
}
h.lines.push(line.to_string());
} else if line.starts_with('+') && !line.starts_with("+++") {
h.additions += 1;
h.lines.push(line.to_string());
} else if line.starts_with('-') && !line.starts_with("---") {
@@ -996,6 +1007,24 @@ fn select_hunks(hunks: Vec<DiffHunk>, max_per_file: usize) -> (Vec<DiffHunk>, Ve
)
}
/// Number of `+`/`-` prefix columns on a hunk's lines: one per parent, so 1
/// for `@@` and N for a combined-diff `@@@…` header with N parents.
fn hunk_parents(header: &str) -> usize {
header
.bytes()
.take_while(|&b| b == b'@')
.count()
.saturating_sub(1)
.max(1)
}
/// `(is_addition, is_deletion)` for a combined-diff hunk line. A change can
/// sit in any parent column, e.g. ` -old` / ` +new` against the second parent.
fn combined_change(line: &str, parents: usize) -> (bool, bool) {
let cols = &line.as_bytes()[..parents.min(line.len())];
(cols.contains(&b'+'), cols.contains(&b'-'))
}
fn extract_line_number(header: &str) -> usize {
// Use the dedicated `+N` regex — works for both `@@` and `@@@` headers.
// The previous implementation captured group(1) of the hunk-header
@@ -1014,13 +1043,23 @@ fn extract_line_number(header: &str) -> usize {
// ─── Context trimming ──────────────────────────────────────────────────────
fn reduce_context(hunk: &DiffHunk, max_context: usize) -> DiffHunk {
let parents = hunk_parents(&hunk.header);
let change_kind = |l: &str| -> (bool, bool) {
if parents > 1 {
combined_change(l, parents)
} else {
(l.starts_with('+'), l.starts_with('-'))
}
};
// Indices of `+`/`-` lines.
let change_positions: Vec<usize> = hunk
.lines
.iter()
.enumerate()
.filter_map(|(i, l)| {
if l.starts_with('+') || l.starts_with('-') {
let (added, deleted) = change_kind(l);
if added || deleted {
Some(i)
} else {
None
@@ -1075,10 +1114,11 @@ fn reduce_context(hunk: &DiffHunk, max_context: usize) -> DiffHunk {
for &i in &keep {
let line = &hunk.lines[i];
new_lines.push(line.clone());
if line.starts_with('+') {
additions += 1;
} else if line.starts_with('-') {
let (added, deleted) = change_kind(line);
if deleted {
deletions += 1;
} else if added {
additions += 1;
} else {
context_lines += 1;
}
@@ -1744,6 +1784,56 @@ mod tests {
assert!(r.compressed.contains("++merge_added"));
}
/// A combined-diff change against the second parent (` -old` / ` +new`)
/// starts with a space, like context. It must still count as a change
/// and survive the context trim, wherever it sits in the hunk.
#[test]
fn combined_diff_second_parent_changes_survive_context_trim() {
let lines = [
"diff --combined merge.py",
"--- a/merge.py",
"+++ b/merge.py",
"@@@ -1,7 -1,7 +1,7 @@@",
" ctx_1",
" ctx_2",
" ctx_3",
" -old_from_p2",
" +new_from_p1",
" ctx_4",
" ctx_5",
" ctx_6",
"@@@ -20,8 -20,8 +20,8 @@@",
"- old_p1",
" -old_p2",
"++merged",
" ctx_a",
" ctx_b",
" ctx_c",
" ctx_d",
" -far_old_from_p2",
" +far_new_from_p1",
];
let input = lines.join("\n");
let cfg = DiffCompressorConfig {
min_lines_for_ccr: 5,
..Default::default()
};
let r = DiffCompressor::new(cfg).compress(&input, "");
for change in [
" -old_from_p2",
" +new_from_p1",
" -far_old_from_p2",
" +far_new_from_p1",
] {
assert!(
r.compressed.lines().any(|l| l == change),
"{change:?} dropped as context:\n{}",
r.compressed
);
}
assert_eq!((r.additions, r.deletions), (3, 4));
}
/// Bug-fix test: pre-diff content (commit headers, email-style
/// metadata) is preserved verbatim before the diff sections. Before
/// the fix, anything before the first `diff --git` was silently