From 8420a1782db796bac738336e36275c07f41cc2df Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:05:43 +0100 Subject: [PATCH] Split oversized UTF-8 diff lines using byte boundaries Architecture-Review: unchanged; oversized diff chunks still use the same budget and preserve review fallback behavior. Co-Authored-By: Codex --- src/loopzero/runners.py | 16 ++++++++++------ tests/test_runners.py | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index d03855ec..6ddc57fd 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -1411,16 +1411,20 @@ def _split_bytes(text: str, budget: int) -> list[str]: pieces: list[str] = [] current = "" for line in text.splitlines(keepends=True): - if len(line.encode()) > budget: + encoded = line.encode() + if len(encoded) > budget: if current: pieces.append(current) current = "" - while line: - cut = min(len(line), budget) - while len(line[:cut].encode()) > budget: + start = 0 + while start < len(encoded): + cut = min(len(encoded), start + budget) + while cut < len(encoded) and encoded[cut] & 0xC0 == 0x80: cut -= 1 - pieces.append(line[:cut]) - line = line[cut:] + if cut <= start: + raise ValueError("diff chunk budget cannot fit one UTF-8 character") + pieces.append(encoded[start:cut].decode()) + start = cut elif current and len((current + line).encode()) > budget: pieces.append(current) current = line diff --git a/tests/test_runners.py b/tests/test_runners.py index 9e07d096..8291928d 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -1188,6 +1188,28 @@ def test_split_diff_respects_budget_and_summarizes_deleted_file() -> None: assert any("gone.py: deleted, 3 lines" in chunk for chunk in chunks) +def test_split_diff_encodes_long_utf8_line_in_linear_work() -> None: + diff = "diff --git a/new.txt b/new.txt\n+" + "aé€😀" * 1500 + "\n" + budget = 511 + encoded_chars = 0 + + def count_encodes(frame, event, arg): + nonlocal encoded_chars + if event == "c_call" and arg.__name__ == "encode" and isinstance(arg.__self__, str): + encoded_chars += len(arg.__self__) + + previous = sys.getprofile() + sys.setprofile(count_encodes) + try: + chunks = split_diff(diff, budget) + finally: + sys.setprofile(previous) + + assert "".join(chunks) == diff + assert all(len(chunk.encode()) <= budget for chunk in chunks) + assert encoded_chars <= 5 * len(diff) + + # ----------------------------------------------------------------- family detection