Skip to content

Commit 18d834f

Browse files
VikramLexclaude
authored andcommitted
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 <[email protected]> (cherry picked from commit 24055da)
1 parent bab648b commit 18d834f

2 files changed

Lines changed: 110 additions & 46 deletions

File tree

‎graphify/llm.py‎

Lines changed: 35 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -3337,9 +3337,10 @@ def _label_batch_with_retry(
33373337
can't be split further (a single community, or ``depth >= max_depth``) and
33383338
still won't parse, the parse error is **re-raised**: ``label_communities``
33393339
catches it per batch and skips that batch (its communities stay unlabeled),
3340-
re-raising only if every batch fails. Any non-parse exception (network,
3341-
missing config, programming bug) propagates unchanged — those are never
3342-
split-retried.
3340+
re-raising only if every batch fails. A batch that was split keeps every
3341+
name it and its halves obtained, and re-raises only when none of it could
3342+
be labeled. Any non-parse exception (network, missing config, programming
3343+
bug) propagates unchanged — those are never split-retried.
33433344
"""
33443345
prompt = (
33453346
"You are naming clusters in a knowledge graph. For each community below, "
@@ -3365,37 +3366,6 @@ def _label_batch_with_retry(
33653366
try:
33663367
text = _call_llm(prompt, **call_kwargs)
33673368
parsed = _parse_label_response(text, batch_cids)
3368-
if len(parsed) == len(batch_cids):
3369-
return parsed
3370-
# Salvage can produce a valid partial map from a truncated JSON object.
3371-
# Keep those names, but retry only the missing ids in smaller batches so a
3372-
# reasoning model's completion cap cannot silently turn 3/16 labels into
3373-
# an apparent success (#3671).
3374-
missing = [cid for cid in batch_cids if cid not in parsed]
3375-
if len(batch_cids) <= 1 or depth >= max_depth:
3376-
return parsed
3377-
missing_lines = [
3378-
line for cid, line in zip(batch_cids, batch_lines) if cid in missing
3379-
]
3380-
if len(missing) == 1:
3381-
recovered = _label_batch_with_retry(
3382-
missing, missing_lines,
3383-
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3384-
usage_out=usage_out,
3385-
)
3386-
return parsed | recovered
3387-
mid = len(missing) // 2
3388-
left = _label_batch_with_retry(
3389-
missing[:mid], missing_lines[:mid],
3390-
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3391-
usage_out=usage_out,
3392-
)
3393-
right = _label_batch_with_retry(
3394-
missing[mid:], missing_lines[mid:],
3395-
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3396-
usage_out=usage_out,
3397-
)
3398-
return parsed | left | right
33993369
except (json.JSONDecodeError, ValueError) as exc:
34003370
# Parse failure. If we can still split, retry each half on a smaller
34013371
# prompt (smaller output → less likely to truncate/mangle). At the base
@@ -3408,18 +3378,37 @@ def _label_batch_with_retry(
34083378
file=sys.stderr,
34093379
)
34103380
raise
3411-
mid = len(batch_cids) // 2
3412-
left = _label_batch_with_retry(
3413-
batch_cids[:mid], batch_lines[:mid],
3414-
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3415-
usage_out=usage_out,
3416-
)
3417-
right = _label_batch_with_retry(
3418-
batch_cids[mid:], batch_lines[mid:],
3419-
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3420-
usage_out=usage_out,
3421-
)
3422-
return left | right
3381+
parsed = {}
3382+
if len(parsed) == len(batch_cids) or len(batch_cids) <= 1 or depth >= max_depth:
3383+
return parsed
3384+
# Salvage can produce a valid partial map from a truncated JSON object.
3385+
# Keep those names, but retry only the missing ids in smaller batches so a
3386+
# reasoning model's completion cap cannot silently turn 3/16 labels into
3387+
# an apparent success (#3671). After a parse failure nothing was kept, so
3388+
# every id is missing and this is the plain split-and-retry (#1278).
3389+
missing = [
3390+
(cid, line) for cid, line in zip(batch_cids, batch_lines) if cid not in parsed
3391+
]
3392+
mid = max(1, len(missing) // 2)
3393+
failure: Exception | None = None
3394+
for half in (missing[:mid], missing[mid:]):
3395+
if not half:
3396+
continue
3397+
# The retries run outside the try above: a half that still won't parse
3398+
# must neither re-split this whole batch (asking again for the ids it
3399+
# already named) nor discard what this batch and the other half named.
3400+
try:
3401+
parsed |= _label_batch_with_retry(
3402+
[cid for cid, _ in half], [line for _, line in half],
3403+
backend=backend, model=model, depth=depth + 1, max_depth=max_depth,
3404+
usage_out=usage_out,
3405+
)
3406+
except (json.JSONDecodeError, ValueError) as exc:
3407+
failure = failure or exc
3408+
# Nothing named at all: re-raise, so the caller still skips the batch.
3409+
if not parsed and failure is not None:
3410+
raise failure
3411+
return parsed
34233412

34243413

34253414
def label_communities(

‎tests/test_label_retry.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import json
77
import re
88

9+
import pytest
10+
911
from graphify import llm as llm_mod
1012

1113

@@ -69,3 +71,76 @@ def fake_call_llm(prompt: str, **_kwargs) -> str:
6971

7072
assert result == {cid: f"Label {cid}" for cid in batch_cids}
7173
assert call_count["n"] == 2
74+
75+
76+
def _labels_for(prompt: str, unparseable: set[int]) -> str:
77+
"""Label every community in ``prompt``; garbage if any id is unparseable."""
78+
cids_in_prompt = [int(m) for m in re.findall(r"Community (\d+):", prompt)]
79+
if unparseable & set(cids_in_prompt):
80+
return "{this is not valid json, missing quotes"
81+
return json.dumps({str(cid): f"Label {cid}" for cid in cids_in_prompt})
82+
83+
84+
def test_a_missing_id_that_never_parses_keeps_the_labels_already_had(monkeypatch):
85+
"""A truncated reply labels part of the batch; retrying a missing id that
86+
still won't parse must not discard those labels or ask for them again.
87+
88+
The nested retry used to run inside the try that guards this batch's own
89+
parse, so its failure re-split the whole batch (re-requesting 42 and 99)
90+
and the re-split failed the same way, dropping every label of the batch.
91+
"""
92+
batch_cids = [42, 99, 137, 201]
93+
batch_lines = [f"Community {cid}: node_{cid}" for cid in batch_cids]
94+
prompts: list[list[int]] = []
95+
96+
def fake_call_llm(prompt: str, **_kwargs) -> str:
97+
prompts.append([int(m) for m in re.findall(r"Community (\d+):", prompt)])
98+
if len(prompts) == 1:
99+
return '{"42":"Label 42","99":"Label 99"'
100+
return _labels_for(prompt, unparseable={137})
101+
102+
monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)
103+
104+
result = llm_mod._label_batch_with_retry(
105+
batch_cids, batch_lines, backend="gemini", model=None,
106+
)
107+
108+
assert result == {42: "Label 42", 99: "Label 99", 201: "Label 201"}
109+
assert prompts == [batch_cids, [137], [201]]
110+
111+
112+
def test_a_half_that_never_parses_does_not_discard_the_other_half(monkeypatch):
113+
"""After a split, one half failing at the base case must not take the
114+
other half's labels down with it; only the unparseable id stays unlabeled."""
115+
batch_cids = [42, 99, 137, 201]
116+
batch_lines = [f"Community {cid}: node_{cid}" for cid in batch_cids]
117+
prompts: list[list[int]] = []
118+
119+
def fake_call_llm(prompt: str, **_kwargs) -> str:
120+
prompts.append([int(m) for m in re.findall(r"Community (\d+):", prompt)])
121+
if len(prompts) == 1:
122+
return "{this is not valid json, missing quotes"
123+
return _labels_for(prompt, unparseable={137})
124+
125+
monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)
126+
127+
result = llm_mod._label_batch_with_retry(
128+
batch_cids, batch_lines, backend="gemini", model=None,
129+
)
130+
131+
assert result == {42: "Label 42", 99: "Label 99", 201: "Label 201"}
132+
assert prompts == [batch_cids, [42, 99], [137, 201], [137], [201]]
133+
134+
135+
def test_a_batch_that_never_parses_still_raises(monkeypatch):
136+
"""With nothing labeled anywhere, the parse error still reaches the caller,
137+
which skips the batch (label_communities)."""
138+
monkeypatch.setattr(
139+
llm_mod, "_call_llm", lambda prompt, **_kwargs: "{not json at all",
140+
)
141+
142+
with pytest.raises(ValueError):
143+
llm_mod._label_batch_with_retry(
144+
[1, 2, 3], ["Community 1: a", "Community 2: b", "Community 3: c"],
145+
backend="gemini", model=None,
146+
)

0 commit comments

Comments
 (0)