fix(llm): bisect splittable documents below char cap on output truncation (#5072)

This commit is contained in:
marq committed 2026-11-07 22:50:10 +05:30
1 parent 16218bfc80
commit 3d06d10849
4 files changed
+140 -4

No files matched your search

+16
View File
@@ -41,6 +41,7 @@ _SPLITTABLE_TEXT_SUFFIXES = frozenset({
".md", ".mdx", ".markdown", ".txt", ".rst",
".qmd", ".skill", ".html",
".j2", ".jinja", ".jinja2",
".yaml", ".yml",
})
# Document types whose BYTES are not what the model is shown. `llm._file_to_text`
@@ -248,3 +249,18 @@ def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
left = FileSlice(fs.path, fs.start, cut, fs.index, fs.total)
right = FileSlice(fs.path, cut, fs.end, fs.index, fs.total)
return left, right
def make_full_slice(path: Path) -> FileSlice | None:
"""Create a full-range ``FileSlice`` for an eligible splittable text file (#5072).
Returns None for non-splittable files (code, binary, unreadable).
"""
if not is_splittable_text(path):
return None
try:
text = unit_source_text(path)
except Exception:
return None
return FileSlice(path=path, start=0, end=len(text), index=0, total=1)
+12 -4
View File
@@ -22,6 +22,7 @@ from graphify.file_slice import (
FileSlice,
bisect_slice,
expand_oversized_files,
make_full_slice,
read_slice_text,
unit_path,
)
@@ -2575,10 +2576,17 @@ def _extract_with_adaptive_retry(
}
def _split_lone_slice() -> "tuple[FileSlice, FileSlice] | None":
# When a single-unit chunk is a slice, bisect the slice so we can retry
# on a smaller range rather than give up (#1369).
if len(chunk) == 1 and isinstance(chunk[0], FileSlice) and _depth < max_depth:
return bisect_slice(chunk[0])
# When a single-unit chunk is a slice (or an eligible splittable text file
# below the char cap), bisect the slice so we can retry on a smaller
# range rather than give up (#1369, #5072).
if len(chunk) == 1 and _depth < max_depth:
unit = chunk[0]
if isinstance(unit, FileSlice):
return bisect_slice(unit)
if isinstance(unit, (Path, str)):
fs = make_full_slice(Path(unit))
if fs is not None:
return bisect_slice(fs)
return None
try:
@@ -0,0 +1,93 @@
"""Splittable documents below character cap can bisect after output truncation (#5072)."""
from pathlib import Path
from unittest.mock import patch
import pytest
import graphify.llm as llm
from graphify.file_slice import (
FileSlice,
is_splittable_text,
read_slice_text,
unit_source_text,
)
@pytest.mark.parametrize("ext", [".yaml", ".yml", ".md", ".txt", ".rst"])
def test_splittable_document_under_cap_bisects_on_truncation(tmp_path, ext):
"""When a splittable document below _FILE_CHAR_CAP truncates (finish_reason='length'),
adaptive retry should promote the raw Path unit to a full-range FileSlice and bisect it,
completing without being marked partial (#5072).
"""
path = tmp_path / f"dense{ext}"
if ext in (".yaml", ".yml"):
content = "records:\n" + "".join(f" item{i}: value{i}\n" for i in range(80))
else:
content = "# Title\n\n" + "".join(f"Paragraph {i} with some content.\n\n" for i in range(40))
path.write_text(content, encoding="utf-8")
text = unit_source_text(path)
assert len(text) < llm._FILE_CHAR_CAP
raw = llm.expand_oversized_files([path], llm._FILE_CHAR_CAP)
assert raw == [path], "File below cap must initially stay a raw Path"
calls = []
def mock_extract(chunk, **kwargs):
calls.append(chunk)
chunk_text = "".join(
read_slice_text(u) if isinstance(u, FileSlice) else unit_source_text(u)
for u in chunk
)
if len(chunk_text) > 700:
return {
"nodes": [{"id": f"node_{len(calls)}", "label": "n", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "length",
}
return {
"nodes": [{"id": f"leaf_{len(calls)}", "label": "leaf", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "stop",
}
with patch.object(llm, "extract_files_direct", side_effect=mock_extract):
result = llm._extract_with_adaptive_retry(
raw, "kimi", "offline", "offline", path.parent, max_depth=3
)
is_partial = bool(result.get("partial") or result.get("_partial_files"))
assert not is_partial, "Splittable document under cap should bisect and recover from truncation"
assert result["finish_reason"] == "stop"
assert len(calls) >= 3, f"Expected at least 1 root truncated call + bisected slice calls, got {len(calls)}"
for subcall in calls[1:]:
assert isinstance(subcall[0], FileSlice), "Bisected unit must be a FileSlice"
def test_code_file_under_cap_does_not_bisect_on_truncation(tmp_path):
"""Code files must never be sliced or bisected; they remain whole and partial on truncation."""
path = tmp_path / "dense.py"
path.write_text("x = 1\n" * 100, encoding="utf-8")
raw = [path]
calls = []
def mock_extract(chunk, **kwargs):
calls.append(chunk)
return {
"nodes": [{"id": "code_node", "label": "n", "source_file": str(path)}],
"edges": [],
"hyperedges": [],
"finish_reason": "length",
}
with patch.object(llm, "extract_files_direct", side_effect=mock_extract):
result = llm._extract_with_adaptive_retry(
raw, "kimi", "offline", "offline", path.parent, max_depth=3
)
is_partial = bool(result.get("partial") or result.get("_partial_files"))
assert is_partial, "Code file must stay partial when truncated"
assert len(calls) == 1, "Code file must not be bisected"
+19
View File
@@ -10,6 +10,7 @@ from graphify.file_slice import (
bisect_slice,
expand_oversized_files,
is_splittable_text,
make_full_slice,
read_slice_text,
slice_boundaries,
unit_path,
@@ -163,3 +164,21 @@ def test_bisect_slice_splits_at_newline(tmp_path):
def test_bisect_slice_returns_none_for_tiny(tmp_path):
f = _write(tmp_path / "a.md", "ab")
assert bisect_slice(FileSlice(f, 0, 1, 0, 1)) is None
def test_make_full_slice(tmp_path):
f_md = _write(tmp_path / "doc.md", "# Hello\n\nWorld\n")
fs = make_full_slice(f_md)
assert fs is not None
assert fs.path == f_md
assert fs.start == 0
assert fs.end == len(f_md.read_text(encoding="utf-8"))
assert fs.index == 0
assert fs.total == 1
f_py = _write(tmp_path / "code.py", "x = 1\n")
assert make_full_slice(f_py) is None
f_none = tmp_path / "nonexistent.md"
assert make_full_slice(f_none) is None