fix(label): keep labels already named when a nested retry fails to parse

_label_batch_with_retry retried the ids a truncated reply left out (#3671)
inside the try that guards the batch's own parse. A retry that still would
not parse therefore landed in this batch's except branch, which re-split the
whole batch, asking the backend again for ids it had already named, and when
that failed the same way the error discarded every name of the batch, the
ones already parsed included. Likewise, once a parse failure split a batch,
one half failing at the base case discarded the names the other half got.

Parse the batch's own reply inside the try, then retry the missing ids (all
of them after a parse failure, the plain #1278 split) outside it, one half at
a time: a half that still won't parse is recorded and the other half still
runs. A batch re-raises only when none of it could be named, so
label_communities still skips a batch that yields nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 24055dabfc)
This commit is contained in:
VikramLex authored and safishamsi committed 2026-09-30 20:41:10 +01:00
1 parent bab648b0c3
commit 18d834f771
2 files changed
+110 -46

No files matched your search

+35 -46
View File
@@ -3337,9 +3337,10 @@ def _label_batch_with_retry(
can't be split further (a single community, or ``depth >= max_depth``) and
still won't parse, the parse error is **re-raised**: ``label_communities``
catches it per batch and skips that batch (its communities stay unlabeled),
re-raising only if every batch fails. Any non-parse exception (network,
missing config, programming bug) propagates unchanged — those are never
split-retried.
re-raising only if every batch fails. A batch that was split keeps every
name it and its halves obtained, and re-raises only when none of it could
be labeled. Any non-parse exception (network, missing config, programming
bug) propagates unchanged — those are never split-retried.
"""
prompt = (
"You are naming clusters in a knowledge graph. For each community below, "
@@ -3365,37 +3366,6 @@ def _label_batch_with_retry(
try:
text = _call_llm(prompt, **call_kwargs)
parsed = _parse_label_response(text, batch_cids)
if len(parsed) == len(batch_cids):
return parsed
# Salvage can produce a valid partial map from a truncated JSON object.
# Keep those names, but retry only the missing ids in smaller batches so a
# reasoning model's completion cap cannot silently turn 3/16 labels into
# an apparent success (#3671).
missing = [cid for cid in batch_cids if cid not in parsed]
if len(batch_cids) <= 1 or depth >= max_depth:
return parsed
missing_lines = [
line for cid, line in zip(batch_cids, batch_lines) if cid in missing
]
if len(missing) == 1:
recovered = _label_batch_with_retry(
missing, missing_lines,
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
return parsed | recovered
mid = len(missing) // 2
left = _label_batch_with_retry(
missing[:mid], missing_lines[:mid],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
right = _label_batch_with_retry(
missing[mid:], missing_lines[mid:],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
return parsed | left | right
except (json.JSONDecodeError, ValueError) as exc:
# Parse failure. If we can still split, retry each half on a smaller
# prompt (smaller output → less likely to truncate/mangle). At the base
@@ -3408,18 +3378,37 @@ def _label_batch_with_retry(
file=sys.stderr,
)
raise
mid = len(batch_cids) // 2
left = _label_batch_with_retry(
batch_cids[:mid], batch_lines[:mid],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
right = _label_batch_with_retry(
batch_cids[mid:], batch_lines[mid:],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
return left | right
parsed = {}
if len(parsed) == len(batch_cids) or len(batch_cids) <= 1 or depth >= max_depth:
return parsed
# Salvage can produce a valid partial map from a truncated JSON object.
# Keep those names, but retry only the missing ids in smaller batches so a
# reasoning model's completion cap cannot silently turn 3/16 labels into
# an apparent success (#3671). After a parse failure nothing was kept, so
# every id is missing and this is the plain split-and-retry (#1278).
missing = [
(cid, line) for cid, line in zip(batch_cids, batch_lines) if cid not in parsed
]
mid = max(1, len(missing) // 2)
failure: Exception | None = None
for half in (missing[:mid], missing[mid:]):
if not half:
continue
# The retries run outside the try above: a half that still won't parse
# must neither re-split this whole batch (asking again for the ids it
# already named) nor discard what this batch and the other half named.
try:
parsed |= _label_batch_with_retry(
[cid for cid, _ in half], [line for _, line in half],
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
usage_out=usage_out,
)
except (json.JSONDecodeError, ValueError) as exc:
failure = failure or exc
# Nothing named at all: re-raise, so the caller still skips the batch.
if not parsed and failure is not None:
raise failure
return parsed
def label_communities(
+75
View File
@@ -6,6 +6,8 @@ from __future__ import annotations
import json
import re
import pytest
from graphify import llm as llm_mod
@@ -69,3 +71,76 @@ def test_label_batch_recovers_when_json_is_valid_but_incomplete(monkeypatch):
assert result == {cid: f"Label {cid}" for cid in batch_cids}
assert call_count["n"] == 2
def _labels_for(prompt: str, unparseable: set[int]) -> str:
"""Label every community in ``prompt``; garbage if any id is unparseable."""
cids_in_prompt = [int(m) for m in re.findall(r"Community (\d+):", prompt)]
if unparseable & set(cids_in_prompt):
return "{this is not valid json, missing quotes"
return json.dumps({str(cid): f"Label {cid}" for cid in cids_in_prompt})
def test_a_missing_id_that_never_parses_keeps_the_labels_already_had(monkeypatch):
"""A truncated reply labels part of the batch; retrying a missing id that
still won't parse must not discard those labels or ask for them again.
The nested retry used to run inside the try that guards this batch's own
parse, so its failure re-split the whole batch (re-requesting 42 and 99)
and the re-split failed the same way, dropping every label of the batch.
"""
batch_cids = [42, 99, 137, 201]
batch_lines = [f"Community {cid}: node_{cid}" for cid in batch_cids]
prompts: list[list[int]] = []
def fake_call_llm(prompt: str, **_kwargs) -> str:
prompts.append([int(m) for m in re.findall(r"Community (\d+):", prompt)])
if len(prompts) == 1:
return '{"42":"Label 42","99":"Label 99"'
return _labels_for(prompt, unparseable={137})
monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)
result = llm_mod._label_batch_with_retry(
batch_cids, batch_lines, backend="gemini", model=None,
)
assert result == {42: "Label 42", 99: "Label 99", 201: "Label 201"}
assert prompts == [batch_cids, [137], [201]]
def test_a_half_that_never_parses_does_not_discard_the_other_half(monkeypatch):
"""After a split, one half failing at the base case must not take the
other half's labels down with it; only the unparseable id stays unlabeled."""
batch_cids = [42, 99, 137, 201]
batch_lines = [f"Community {cid}: node_{cid}" for cid in batch_cids]
prompts: list[list[int]] = []
def fake_call_llm(prompt: str, **_kwargs) -> str:
prompts.append([int(m) for m in re.findall(r"Community (\d+):", prompt)])
if len(prompts) == 1:
return "{this is not valid json, missing quotes"
return _labels_for(prompt, unparseable={137})
monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)
result = llm_mod._label_batch_with_retry(
batch_cids, batch_lines, backend="gemini", model=None,
)
assert result == {42: "Label 42", 99: "Label 99", 201: "Label 201"}
assert prompts == [batch_cids, [42, 99], [137, 201], [137], [201]]
def test_a_batch_that_never_parses_still_raises(monkeypatch):
"""With nothing labeled anywhere, the parse error still reaches the caller,
which skips the batch (label_communities)."""
monkeypatch.setattr(
llm_mod, "_call_llm", lambda prompt, **_kwargs: "{not json at all",
)
with pytest.raises(ValueError):
llm_mod._label_batch_with_retry(
[1, 2, 3], ["Community 1: a", "Community 2: b", "Community 3: c"],
backend="gemini", model=None,
)