@HamzaM to AI & LLMEnglish • 4 days ago

What is the most reliable way to ask an LLM to return diffs or unified patches for large source code files?

message-square
0
1
What is the most reliable way to ask an LLM to return diffs or unified patches for large source code files?
@HamzaM to AI & LLMEnglish • 4 days ago

Overview

Asking an LLM to generate raw standard unified diffs (@@ -start,count +start,count @@) for large source files frequently breaks git apply or patch because LLMs struggle with exact line counting, hunk length math, and strict whitespace/prefix (+/-/�) alignment. In production coding agents and orchestration layers, the most reliable pattern is line-number-free SEARCH/REPLACE blocks (or context-anchored unified diff hunks where your harness ignores the LLM’s @@ line counts and resolves spans via fuzzy/context matching).

  • Eliminate line-number arithmetic: Models excel at copying verbatim code spans from context but routinely miscount line offsets and hunk line totals in multi-hundred-line files. Removing line-number requirements—or treating @@ ... @@ strictly as a section separator rather than an exact offset—eliminates the #1 cause of corrupt patches.
  • Require unique surrounding context anchors (oldCode -> newCode): Having the model output exact contiguous blocks (search + replace) with 3–5 lines of unchanged surrounding context lets your applier locate the unique target span deterministically, verify uniqueness (rejecting ambiguous multi-matches), and generate a true unified diff locally for review or git apply.
  • Layered fallback matching + structured retry feedback: Apply edits in tiers—(1) exact string match, (2) trailing-whitespace / CRLF-normalized match, (3) indentation-realigned match—and if a block still fails to match uniquely, return a structured error with nearby context lines so the model can self-correct on the next turn.

Steps

  1. Prompt or define a structured tool schema for SEARCH/REPLACE edits: Ask the model to emit an ordered list of { search, replace } blocks (or fenced <<<<<<< SEARCH / ======= / >>>>>>> REPLACE blocks) containing enough unchanged surrounding lines to uniquely identify each edit site in the file.
  2. Validate uniqueness and apply edits with tiered normalization: For each block, search the source file for search; if it matches zero times, retry with normalized line endings/trailing spaces or indentation offset; if it matches more than once, fail fast with an ambiguity error requiring more surrounding context.
  3. Apply edits atomically in memory before touching disk: Stage all hunks on an in-memory buffer first so a failure on hunk 3 never leaves a half-patched file on disk.
  4. Compute a valid unified diff locally if needed: Once the updated buffer passes syntax/lint checks, run a deterministic diff generator (diff / git diff) between the original file and patched buffer whenever downstream tooling expects a strict RFC-compliant unified patch.

Example

export interface SearchReplaceEdit {
  search: string;
  replace: string;
}

export interface PatchApplyResult {
  ok: boolean;
  updatedContent?: string;
  error?: string;
  failedEditIndex?: number;
}

function normalizeLineEndings(text: string): string {
  return text.replace(/\r\n/g, "\n");
}

function trimTrailingLineWhitespace(text: string): string {
  return text
    .split("\n")
    .map((line) => line.replace(/[ \t]+$/g, ""))
    .join("\n");
}

/**
 * Finds a unique occurrence of `search` in `content` using exact matching first,
 * then falling back to trailing-whitespace-normalized line matching.
 */
function locateUniqueSpan(
  content: string,
  search: string
): { start: number; end: number } | { error: string } {
  if (!search.trim()) {
    return { error: "Search block cannot be empty." };
  }

  // Tier 1: Exact substring match
  const firstExact = content.indexOf(search);
  if (firstExact !== -1) {
    const secondExact = content.indexOf(search, firstExact + 1);
    if (secondExact !== -1) {
      return {
        error:
          "Ambiguous search block: matched multiple locations. Include more surrounding context lines.",
      };
    }
    return { start: firstExact, end: firstExact + search.length };
  }

  // Tier 2: Line-by-line match ignoring trailing whitespace differences
  const contentLines = content.split("\n");
  const searchLines = search.split("\n");
  const normContentLines = contentLines.map((l) => l.replace(/[ \t]+$/g, ""));
  const normSearchLines = searchLines.map((l) => l.replace(/[ \t]+$/g, ""));

  const matchedStartLines: number[] = [];
  for (let i = 0; i <= normContentLines.length - normSearchLines.length; i++) {
    let allMatch = true;
    for (let j = 0; j < normSearchLines.length; j++) {
      if (normContentLines[i + j] !== normSearchLines[j]) {
        allMatch = false;
        break;
      }
    }
    if (allMatch) {
      matchedStartLines.push(i);
    }
  }

  if (matchedStartLines.length > 1) {
    return {
      error: `Ambiguous normalized match at lines \${matchedStartLines.map((l) => l + 1).join(", ")}. Add more context.`,
    };
  }

  if (matchedStartLines.length === 1) {
    const startLine = matchedStartLines[0];
    const endLine = startLine + searchLines.length;

    let startChar = 0;
    for (let i = 0; i < startLine; i++) {
      startChar += contentLines[i].length + 1;
    }

    let endChar = startChar;
    for (let i = startLine; i < endLine; i++) {
      endChar += contentLines[i].length + (i < endLine - 1 ? 1 : 0);
    }

    return { start: startChar, end: endChar };
  }

  return {
    error:
      "Search block not found in file. Ensure all lines, comments, and indentation match the source file verbatim.",
  };
}

/**
 * Applies a sequence of SEARCH/REPLACE edits atomically in memory.
 */
export function applySearchReplaceEdits(
  originalContent: string,
  edits: SearchReplaceEdit[]
): PatchApplyResult {
  const usesCrlf = originalContent.includes("\r\n");
  let working = normalizeLineEndings(originalContent);

  for (let idx = 0; idx < edits.length; idx++) {
    const edit = edits[idx];
    const searchNorm = normalizeLineEndings(edit.search);
    const replaceNorm = normalizeLineEndings(edit.replace);

    const located = locateUniqueSpan(working, searchNorm);
    if ("error" in located) {
      return {
        ok: false,
        error: `Edit #${idx + 1} failed:${located.error}`,
        failedEditIndex: idx,
      };
    }

    working =
      working.slice(0, located.start) + replaceNorm + working.slice(located.end);
  }

  const finalContent = usesCrlf ? working.replace(/\n/g, "\r\n") : working;
  return {
    ok: true,
    updatedContent: finalContent,
  };
}

Tips

  • Include line numbers in the input prompt even when omitting them from the edit output: Passing the source file with 120 | const x = ... prefixes helps the LLM orient itself across large files without forcing the model to compute @@ -120,14 +120,18 @@ headers on output.
  • Forbid placeholder comments like // ... existing code ... inside search or replace: Explicitly instruct the model that every character inside search and replace must be complete, literal code—any ellipsis shortcut will break exact matching or delete code.
  • Fall back to whole-file or function-level rewrites for small files or heavy refactors: If a file is under ~200 lines or more than ~40% of the file is changing, a full file/function rewrite avoids multi-hunk drift and merges faster than juggling dozens of small patches.