fix(llm): write a held sliced file in chunk order, not completion order

Review follow-up. With max_concurrency > 1, slices finish in any order, and
the held results were joined in that order, so the cached entry's node
order changed from run to run and a cache-served build churned graph.json
(the #1632 problem). Join them by chunk index.

(cherry picked from commit 299fc1a36f)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-11-02 18:02:01 +00:00
1 parent f2ef7024fe
commit f3cdf6b651
2 files changed
+41 -6

No files matched your search

+8 -6
View File
@@ -2874,9 +2874,9 @@ def extract_corpus_parallel(
for _unit in _chunk:
if isinstance(_unit, FileSlice):
slices_left[unit_path(_unit)] = slices_left.get(unit_path(_unit), 0) + 1
held_results: dict[Path, list[dict]] = {}
held_results: dict[Path, list[tuple[int, dict]]] = {}
def _checkpoint_chunk(result: dict, chunk: "list[Path | FileSlice]") -> None:
def _checkpoint_chunk(idx: int, result: dict, chunk: "list[Path | FileSlice]") -> None:
sliced = [unit_path(u) for u in chunk if isinstance(u, FileSlice)]
for parent in sliced:
slices_left[parent] -= 1
@@ -2884,9 +2884,11 @@ def extract_corpus_parallel(
if whole:
_save_checkpoint(result, whole)
for parent in dict.fromkeys(sliced):
held_results.setdefault(parent, []).append(result)
held_results.setdefault(parent, []).append((idx, result))
if slices_left[parent] == 0:
held = held_results.pop(parent)
# Chunk order, not completion order, so the entry is the same
# whichever slice returned first (#1632).
held = [r for _, r in sorted(held_results.pop(parent), key=lambda p: p[0])]
combined: dict = {
bucket: [item for r in held for item in r.get(bucket, [])]
for bucket in ("nodes", "edges", "hyperedges")
@@ -2951,7 +2953,7 @@ def extract_corpus_parallel(
continue
assert result is not None
_merge_into(merged, result)
_checkpoint_chunk(result, chunk)
_checkpoint_chunk(idx, result, chunk)
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
else:
@@ -2977,7 +2979,7 @@ def extract_corpus_parallel(
continue
assert result is not None
results_by_idx[idx] = result
_checkpoint_chunk(result, chunks[idx])
_checkpoint_chunk(idx, result, chunks[idx])
if callable(on_chunk_done):
on_chunk_done(idx, total, result)
for idx in sorted(results_by_idx):
@@ -96,3 +96,36 @@ def test_unsliced_file_is_still_checkpointed_before_an_interrupt(tmp_path):
with pytest.raises(KeyboardInterrupt):
_run(tmp_path, [note, doc], endpoint)
assert _uncached(tmp_path, [note, doc]) == ["guide.md"]
def test_held_slices_are_cached_in_chunk_order_under_parallel_completion(tmp_path):
import json
import threading
doc = _big_doc(tmp_path)
first_may_return = threading.Event()
calls: list[int] = []
lock = threading.Lock()
def endpoint(files, **kwargs):
with lock:
calls.append(1)
n = len(calls)
text = llm.read_slice_text(files[0]) if isinstance(files[0], llm.FileSlice) else ""
if "# Early" in text:
first_may_return.wait(timeout=10)
else:
first_may_return.set()
return {"nodes": [{"id": f"s{100 - n}", "label": "early" if "# Early" in text else f"later{n}",
"source_file": str(doc), "source_location": "L1"}],
"edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1,
"finish_reason": "stop", "model": "fixture"}
with patch.object(llm, "extract_files_direct", endpoint):
llm.extract_corpus_parallel(
[doc], backend="openai", root=tmp_path, cache_root=tmp_path / "out",
max_concurrency=4, token_budget=1, max_retry_depth=0,
)
entries = list((tmp_path / "out/graphify-out/cache/semantic").rglob("*.json"))
assert len(entries) == 1
labels = [n["label"] for n in json.loads(entries[0].read_text())["nodes"]]
assert labels[0] == "early"