Skip to content

Commit 39527f8

Browse files
tlongwell-blockDawn (sprout agent)
andcommitted
fix(cli/mem patch): enforce strict positional context, not just content
Max caught this on review of PR #627: diffy::apply is strict on context *content* but will slide a hunk forward/backward through the file to find a position where the preimage matches. With our advertised "no fuzz, no offset" semantics that's a real correctness gap — a patch generated against `zero\nalpha\nbeta\ngamma\n` claiming to modify line 1 would silently land at line 2 instead of refusing. Add `verify_hunks_at_declared_position` which, before calling diffy::apply, checks that each hunk's preimage (Context + Delete lines) matches the current value byte-for-byte at the line number the hunk declares. Drift in line numbers means the file changed structurally since the patch was generated; the strict mode wants the operator to regenerate the patch rather than risk a silent off-target apply. Test coverage: - Max's exact case (offset-slide rejected; diffy would have accepted) - Exact-position match (still accepted) - Pure insertion into empty value (`@@ -0,0 +1,N @@`) - No-trailing-newline value (matches diffy's strip-newline behavior on `\\ No newline at end of file` marker) E2E verified against the live relay: offset-slide patch is rejected with a precise diagnostic ("hunk #1 preimage mismatch at line 1: patch expects ... but value has ..."), and the correctly-positioned patch applies cleanly. Signed-off-by: tlongwell-block <[email protected]> Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
1 parent b10a459 commit 39527f8

1 file changed

Lines changed: 182 additions & 1 deletion

File tree

  • crates/sprout-cli/src/commands

‎crates/sprout-cli/src/commands/mem.rs‎

Lines changed: 182 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,94 @@ fn sha256_hex(s: &str) -> String {
339339
hex::encode(h.finalize())
340340
}
341341

342+
/// Verify that each hunk's preimage lines (Context + Delete) match the
343+
/// current value byte-for-byte starting at the line number the hunk declares.
344+
///
345+
/// Diffy's `apply` is strict on context content but will *slide* a hunk
346+
/// forward or backward through the file to find a position where the
347+
/// preimage matches. For memory-edit safety we want the stronger property:
348+
/// the patch must apply at exactly the line number it was generated against.
349+
/// Drift in line numbers usually means lines were inserted or deleted before
350+
/// the hunk — at which point regenerating the patch is the correct response,
351+
/// not silently landing the change at a different position.
352+
///
353+
/// Returns `Ok(())` on a clean match, `Err(message)` otherwise.
354+
///
355+
/// Line-number convention: unified-diff `@@ -N,M @@` uses 1-based line
356+
/// numbers. A pure-insertion hunk against an empty file is encoded as
357+
/// `@@ -0,0 +1,M @@` (`start == 0`, `len == 0`), which we treat as
358+
/// "apply at index 0 of an empty preimage."
359+
fn verify_hunks_at_declared_position(
360+
current: &str,
361+
patch: &diffy::Patch<'_, str>,
362+
) -> Result<(), String> {
363+
// `split_inclusive('\n')` preserves the trailing newline on each line,
364+
// matching diffy's own line representation. A value with no trailing
365+
// newline produces a last segment with no `\n`, which also matches how
366+
// diffy stores the "no newline at EOF" case (parser strips the `\n`).
367+
let current_lines: Vec<&str> = current.split_inclusive('\n').collect();
368+
369+
for (i, hunk) in patch.hunks().iter().enumerate() {
370+
let preimage: Vec<&str> = hunk
371+
.lines()
372+
.iter()
373+
.filter_map(|l| match l {
374+
diffy::Line::Context(s) | diffy::Line::Delete(s) => Some(*s),
375+
diffy::Line::Insert(_) => None,
376+
})
377+
.collect();
378+
379+
// Pure insertion at start of empty file: `@@ -0,0 +1,M @@`.
380+
if preimage.is_empty() {
381+
if hunk.old_range().start() == 0 {
382+
continue;
383+
}
384+
return Err(format!(
385+
"hunk #{} has empty preimage but declared start line {} \
386+
(expected 0 for pure insertion)",
387+
i + 1,
388+
hunk.old_range().start()
389+
));
390+
}
391+
392+
// Convert 1-based line number to 0-based index.
393+
let declared_start = hunk
394+
.old_range()
395+
.start()
396+
.checked_sub(1)
397+
.ok_or_else(|| format!("hunk #{} has invalid line number 0", i + 1))?;
398+
399+
let end = declared_start
400+
.checked_add(preimage.len())
401+
.ok_or_else(|| format!("hunk #{} line range overflows", i + 1))?;
402+
if end > current_lines.len() {
403+
return Err(format!(
404+
"hunk #{} expects {} preimage line(s) starting at line {}, \
405+
but the value only has {} line(s)",
406+
i + 1,
407+
preimage.len(),
408+
declared_start + 1,
409+
current_lines.len()
410+
));
411+
}
412+
413+
for (offset, expected) in preimage.iter().enumerate() {
414+
let actual = current_lines[declared_start + offset];
415+
if *expected != actual {
416+
return Err(format!(
417+
"hunk #{} preimage mismatch at line {}: \
418+
patch expects {:?} but value has {:?}",
419+
i + 1,
420+
declared_start + offset + 1,
421+
expected,
422+
actual
423+
));
424+
}
425+
}
426+
}
427+
Ok(())
428+
}
429+
342430
/// Extract the current slug value as a `String` (or return `NotFound`).
343431
/// Used by `mem hash` and `mem patch` — they both need "the value or fail".
344432
/// Returns `(head_event, value)` so the caller can preserve monotonic ordering.
@@ -483,10 +571,26 @@ pub async fn cmd_patch(
483571

484572
let patch = diffy::Patch::from_str(&diff_text)
485573
.map_err(|e| CliError::Usage(format!("malformed unified diff: {e}")))?;
574+
575+
// Strict positional check — diffy's `apply` allows the hunk to slide
576+
// forward/backward in the file if it finds the preimage elsewhere. For
577+
// memory edits we want the stronger guarantee: the hunk must apply at
578+
// exactly the line number it claims. If the file has drifted enough that
579+
// the hunk's declared position no longer matches, we'd rather refuse and
580+
// make the operator regenerate the patch than risk landing the change
581+
// somewhere unintended.
582+
verify_hunks_at_declared_position(&current, &patch).map_err(|msg| {
583+
CliError::Usage(format!(
584+
"patch did not apply cleanly to slug `{slug}`: {msg}. \
585+
Context must match the current value verbatim at the declared \
586+
line numbers — no fuzz, no offset."
587+
))
588+
})?;
589+
486590
let new_value = diffy::apply(&current, &patch).map_err(|e| {
487591
CliError::Usage(format!(
488592
"patch did not apply cleanly to slug `{slug}`: {e}. \
489-
Context must match the current value verbatim — no fuzz, no offset on content."
593+
Context must match the current value verbatim — no fuzz, no offset."
490594
))
491595
})?;
492596

@@ -701,6 +805,83 @@ mod tests {
701805
assert_eq!(applied, new);
702806
}
703807

808+
// Max's offset-search case: a hunk declaring `@@ -1,3 @@ alpha/-beta/+delta/gamma`
809+
// against `zero\nalpha\nbeta\ngamma\n` must be rejected. Diffy's `apply`
810+
// would happily slide the hunk forward and land it at line 2; the
811+
// positional check refuses.
812+
#[test]
813+
fn strict_position_rejects_offset_slide() {
814+
let current = "zero\nalpha\nbeta\ngamma\n";
815+
let patch_text = "\
816+
--- a/x
817+
+++ b/x
818+
@@ -1,3 +1,3 @@
819+
alpha
820+
-beta
821+
+delta
822+
gamma
823+
";
824+
let patch = diffy::Patch::from_str(patch_text).unwrap();
825+
// Sanity: diffy's apply *would* slide and produce a result.
826+
let diffy_result = diffy::apply(current, &patch).unwrap();
827+
assert_eq!(diffy_result, "zero\nalpha\ndelta\ngamma\n");
828+
// Our positional check rejects.
829+
let err = verify_hunks_at_declared_position(current, &patch).unwrap_err();
830+
assert!(err.contains("preimage mismatch"), "got: {err}");
831+
}
832+
833+
#[test]
834+
fn strict_position_accepts_exact_match() {
835+
let current = "alpha\nbeta\ngamma\n";
836+
let patch_text = "\
837+
--- a/x
838+
+++ b/x
839+
@@ -1,3 +1,3 @@
840+
alpha
841+
-beta
842+
+delta
843+
gamma
844+
";
845+
let patch = diffy::Patch::from_str(patch_text).unwrap();
846+
verify_hunks_at_declared_position(current, &patch).unwrap();
847+
}
848+
849+
// Pure insertion against an empty value: `@@ -0,0 +1,N @@`.
850+
#[test]
851+
fn strict_position_accepts_pure_insertion_into_empty() {
852+
let current = "";
853+
let patch_text = "\
854+
--- a/x
855+
+++ b/x
856+
@@ -0,0 +1,2 @@
857+
+first
858+
+second
859+
";
860+
let patch = diffy::Patch::from_str(patch_text).unwrap();
861+
verify_hunks_at_declared_position(current, &patch).unwrap();
862+
}
863+
864+
// Value with no trailing newline must still round-trip. `split_inclusive`
865+
// produces a final segment without `\n`; diffy strips `\n` from the last
866+
// hunk line when the patch carries `\\ No newline at end of file`. Both
867+
// representations must match here.
868+
#[test]
869+
fn strict_position_handles_no_trailing_newline() {
870+
let current = "alpha\nbeta\ngamma"; // no trailing \n
871+
let patch_text = "\
872+
--- a/x
873+
+++ b/x
874+
@@ -1,3 +1,3 @@
875+
alpha
876+
-beta
877+
+delta
878+
gamma
879+
\\ No newline at end of file
880+
";
881+
let patch = diffy::Patch::from_str(patch_text).unwrap();
882+
verify_hunks_at_declared_position(current, &patch).unwrap();
883+
}
884+
704885
// Lock the multi-file detection. The check is a simple count of lines
705886
// starting with `--- ` because diffy's `parse()` will only consume the
706887
// first patch and silently treat everything after the last hunk as

0 commit comments

Comments
 (0)