fix(llm): retry rate-limited (429) requests instead of dropping the chunk (#1523)

On strict per-org concurrency/RPM caps (notably Moonshot/kimi), a parallel
`graphify extract --force` 429'd, and because the provider SDKs default to only
max_retries=2, the chunk gave up after two attempts, logged `chunk N failed`, and
was silently dropped — an incomplete graph plus the screen full of
rate_limit_reached_error spam in the report. The SDKs already back off
exponentially and honor Retry-After; they just need more attempts to outlast the
rate window.

The OpenAI-compatible, Azure, and Anthropic clients are now built with
max_retries=_resolve_max_retries() (default 6, override via GRAPHIFY_MAX_RETRIES;
0 disables). For very tight accounts, --max-concurrency 1 further cuts the
concurrency that trips org-level limits.

Reported by @bercedev (#1523). Tests: _resolve_max_retries default/env/invalid,
and the OpenAI-compatible client is constructed with retries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
safishamsi
2026-06-28 20:11:18 +01:00
co-authored by Claude Opus 4.8
parent 22a5afb251
commit 64c1f21070
3 changed files with 73 additions and 4 deletions
+2
View File
@@ -4,6 +4,8 @@ Full release notes with details on each version: [GitHub Releases](https://githu
## Unreleased
- Fix: rate-limited (HTTP 429) extraction chunks are now retried instead of dropped (#1523, thanks @bercedev). The provider SDKs back off and honor `Retry-After`, but the SDK default of 2 retries was too low for strict per-org concurrency/RPM caps (e.g. Moonshot/kimi), so a parallel `extract` 429'd, each chunk logged `chunk N failed`, and was silently lost (incomplete graph + console spam). The OpenAI-compatible, Azure, and Anthropic clients are now built with a higher `max_retries` (default 6, override via `GRAPHIFY_MAX_RETRIES`). For very tight accounts, `--max-concurrency 1` further reduces the concurrency that triggers org-level limits.
- Fix: `graphify update` now prunes the edges a re-extracted file no longer produces (#1521, thanks @UltronOfSpace). Old edges were preserved by endpoint-node membership alone, so a deleted import's edge survived forever as long as both endpoints still existed — driving phantom circular-dependency findings (and `--force` didn't help). Edges owned by a re-extracted file (`source_file`) are dropped before merging the fresh extraction; cross-file edges that merely point at the file are untouched.
- Fix: residual node-ID collisions after the 0.9.0 full-path change (#1522, thanks @sub4biz). `normalize_id` collapses every separator to `_`, so distinct paths that differ only by a separator-vs-punctuation swap (`foo/bar_baz.py` vs `foo_bar/baz.py`) still merged. Colliders are now salted with a short stable path hash so they stay distinct; non-colliding IDs are byte-identical to 0.9.0 (no re-migration).
- Fix: Java record component types now emit `references` edges (#1519, thanks @oleksii-tumanov) — a record's data dependencies (`record Order(Payload p, List<Item> items, …)`) were invisible; primitives and the record's own type parameters are skipped.
+26 -4
View File
@@ -369,6 +369,25 @@ def _resolve_api_timeout(default: float = 600.0) -> float:
pass
return default
def _resolve_max_retries(default: int = 6) -> int:
"""How many times the provider SDK retries a transient error (notably HTTP 429
rate limits) before giving up. The OpenAI/Anthropic/Azure SDKs already back off
exponentially and honour ``Retry-After``; the SDK default of 2 is too low for
strict per-org concurrency/RPM caps (e.g. Moonshot/kimi), where a parallel run
429s and the chunk is then dropped — incomplete graph plus console spam (#1523).
A higher cap lets a rate-limited chunk wait out the window instead of failing.
Honour GRAPHIFY_MAX_RETRIES; 0 is allowed (disable retries)."""
raw = os.environ.get("GRAPHIFY_MAX_RETRIES", "").strip()
if raw:
try:
v = int(raw)
if v >= 0:
return v
except ValueError:
pass
return default
_EXTRACTION_SYSTEM = """\
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
@@ -904,7 +923,8 @@ def _call_openai_compat(
# default. Honour GRAPHIFY_API_TIMEOUT (seconds) for explicit override;
# default to 600s, which is long enough for a 31B model on a 16k chunk
# but still bounds runaway connections (issue #792 addendum).
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout())
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout(),
max_retries=_resolve_max_retries())
kwargs: dict = {
"model": model,
"messages": [
@@ -1024,6 +1044,7 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
api_key=api_key,
base_url=BACKENDS["claude"]["base_url"],
timeout=_resolve_api_timeout(),
max_retries=_resolve_max_retries(),
)
resp = client.messages.create(
model=model,
@@ -1213,7 +1234,8 @@ def _azure_client(api_key: str, endpoint: str):
timeout_s = v
except ValueError:
pass
return AzureOpenAI(api_key=api_key, azure_endpoint=endpoint, api_version=api_version, timeout=timeout_s)
return AzureOpenAI(api_key=api_key, azure_endpoint=endpoint, api_version=api_version, timeout=timeout_s,
max_retries=_resolve_max_retries())
def _call_azure(
@@ -1883,7 +1905,7 @@ def _call_llm(
import anthropic
except ImportError as exc:
raise ImportError(_backend_pkg_hint("anthropic", "anthropic")) from exc
client = anthropic.Anthropic(api_key=key, base_url=cfg["base_url"])
client = anthropic.Anthropic(api_key=key, base_url=cfg["base_url"], max_retries=_resolve_max_retries())
resp = client.messages.create(
model=mdl,
max_tokens=max_tokens,
@@ -1966,7 +1988,7 @@ def _call_llm(
from openai import OpenAI
except ImportError as exc:
raise ImportError(_backend_pkg_hint("openai", "openai")) from exc
client = OpenAI(api_key=key, base_url=cfg["base_url"])
client = OpenAI(api_key=key, base_url=cfg["base_url"], max_retries=_resolve_max_retries())
kwargs: dict = {
"model": mdl,
"messages": [{"role": "user", "content": prompt}],
+45
View File
@@ -983,3 +983,48 @@ def test_call_claude_cli_tolerates_non_utf8_in_stderr():
patch("subprocess.run", return_value=mock_proc):
with pytest.raises(RuntimeError, match="claude -p exited 1"):
llm._call_claude_cli("test prompt")
def test_resolve_max_retries_default_and_env(monkeypatch):
"""Default retry count is generous (so 429s are absorbed, #1523); env overrides."""
monkeypatch.delenv("GRAPHIFY_MAX_RETRIES", raising=False)
assert llm._resolve_max_retries() >= 5
monkeypatch.setenv("GRAPHIFY_MAX_RETRIES", "10")
assert llm._resolve_max_retries() == 10
monkeypatch.setenv("GRAPHIFY_MAX_RETRIES", "0")
assert llm._resolve_max_retries() == 0 # disable is allowed
monkeypatch.setenv("GRAPHIFY_MAX_RETRIES", "bogus")
assert llm._resolve_max_retries() >= 5 # invalid -> default
def test_openai_compat_client_built_with_retries(monkeypatch):
"""The OpenAI-compatible client (kimi/openai/gemini/deepseek/ollama) is built with
max_retries so rate-limited (429) chunks are retried with backoff instead of being
dropped — the kimi rate-limit failure in #1523."""
import sys
import types
ctor_kwargs = {}
class _FakeOpenAI:
def __init__(self, *_, **kwargs):
ctor_kwargs.update(kwargs)
self.chat = self
self.completions = self
def create(self, **_):
return _fake_openai_response(
'{"nodes":[],"edges":[],"hyperedges":[]}', finish_reason="stop",
completion_tokens=10,
)
fake_module = types.ModuleType("openai")
fake_module.OpenAI = _FakeOpenAI
monkeypatch.setitem(sys.modules, "openai", fake_module)
monkeypatch.delenv("GRAPHIFY_MAX_RETRIES", raising=False)
llm._call_openai_compat(
"https://api.moonshot.ai/v1", "fake-key", "kimi-k2",
"user msg", temperature=0, max_completion_tokens=4096, backend="kimi",
)
assert ctor_kwargs.get("max_retries", 0) >= 5, ctor_kwargs