Skip to content

Official Codebase of 3DCodeVerse

Python

retry: stop manufacturing exceptions that are their own cause

gaoypeng1a10e167928f
diff --git a/harness/codeverse/models/retry.py b/harness/codeverse/models/retry.py
index 58075639..feedd830 100644
--- a/harness/codeverse/models/retry.py
+++ b/harness/codeverse/models/retry.py
@@ -591,6 +591,21 @@ log = logging.getLogger(__name__)
OnRetry = Callable[[int, BaseException, float], None]
+
+def _cause(err: BaseException, exc: BaseException | None) -> BaseException | None:
+ """The cause to raise ``err`` from — ``None`` when it would be ``err`` itself.
+
+ Every adapter's ``classify()`` returns an already-classified ``ModelError``
+ unchanged (gemini.py, openai.py, anthropic.py), so ``raise err from exc`` below is
+ often ``raise e from e``, and CPython's ``raise ... from ...`` does NOT check for a
+ cycle the way it does for ``__context__``. The result — ``e.__cause__ is e`` — is a
+ chain no naive walker survives: on 2026-08-27 it took ``bench/_infra.py`` to a
+ RecursionError inside ``run_cell``'s except handler and a compare matrix lost 11
+ finished cells. Dropping the self-cause is invisible otherwise: none of these
+ raises sits inside an ``except`` block, and ``__suppress_context__`` is already set.
+ """
+ return None if exc is err else exc
+
#: per-round-trip hook of :func:`rotate_with_retries`: ``(try, attempt_no, discarded)``.
#: ``attempt_no`` is the 1-based issue order within the logical call; ``discarded``
#: is True for every round-trip that is not the winning one (hedge losers included).
@@ -853,7 +868,7 @@ def rotate_with_retries[T](
# sleeps: a free rotation must not out-live the caller's budget
log.warning("%s giving up after %.0f s of retrying (%s)",
label, max_total_s, last_err)
- raise last_err from last_exc
+ raise last_err from _cause(last_err, last_exc)
attempt += 1
# never go back to a key that looked dead this call; throttled keys are
# excluded while an untried one remains, else acquire() waits for a cooldown
@@ -865,8 +880,9 @@ def rotate_with_retries[T](
# cannot cover this: a worker parked at a gate ANOTHER thread closed
# has no last_err, and would go on to spend a full round-trip.
log.warning("%s budget of %.0f s spent waiting at the storm gate", label, max_total_s)
- raise (last_err or classify(TimeoutError(
- f"{label}: retry budget spent waiting for capacity"))) from last_exc
+ gate_err = last_err or classify(TimeoutError(
+ f"{label}: retry budget spent waiting for capacity"))
+ raise gate_err from _cause(gate_err, last_exc)
budget_left = None if deadline == float("inf") else max(0.0, deadline - monotonic())
try:
# the key/slot wait must fit the remaining budget, never outlive it
@@ -919,11 +935,11 @@ def rotate_with_retries[T](
if out_of_time():
log.warning("%s giving up after %.0f s of retrying (%s)",
label, max_total_s, err)
- raise err from exc
+ raise err from _cause(err, exc)
log.warning("%s key …%s looks dead (%s); rotating", label, key[-4:], err)
attempt -= 1
continue
- raise err from exc # every key failed the same way: not the keys' fault
+ raise err from _cause(err, exc) # every key failed the same way: not the keys' fault
if is_storm(err) and storm < storm_attempts and not out_of_time():
failed_keys.update(t.key for t in tries)
if len(failed_keys) < len(pool):
@@ -964,7 +980,7 @@ def rotate_with_retries[T](
if out_of_time():
log.warning("%s giving up after %.0f s of retrying (%s)",
label, max_total_s, err)
- raise err from exc
+ raise err from _cause(err, exc)
# an untried key remains: rotation is free, only a courtesy pause
attempt -= 1
log.warning(
@@ -974,10 +990,10 @@ def rotate_with_retries[T](
continue
if not err.retryable or attempt >= max_attempts:
bench()
- raise err from exc
+ raise err from _cause(err, exc)
if out_of_time():
log.warning("%s giving up after %.0f s of retrying (%s)", label, max_total_s, err)
- raise err from exc
+ raise err from _cause(err, exc)
delay = backoff_delay(attempt, base_delay=base_delay, max_delay=max_delay)
log.warning(
"%s attempt %d/%d failed (%s); retrying in %.1fs",
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index fd7dda2c..4383f7f0 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -681,6 +681,39 @@ def test_a_broken_on_attempt_hook_never_breaks_the_call():
assert _rotate(pool, lambda key: "ok", on_attempt=hook) == "ok"
+def test_the_error_it_gives_up_with_is_never_its_own_cause():
+ """`classify()` returns an already-classified ModelError unchanged, so the give-up
+ `raise err from exc` was `raise e from e` — and CPython does not check `from` for a
+ cycle. bench/_infra.py had to grow a seen-set after that chain took run_cell to a
+ RecursionError and a compare matrix lost 11 finished cells (2026-08-27)."""
+ def call(key):
+ raise ModelError("structured output unavailable (finish_reason=MAX_TOKENS)",
+ retryable=False, status=None)
+
+ with pytest.raises(ModelError) as ei:
+ _rotate(_pool(), call, max_attempts=1)
+ err = ei.value
+ assert err.__cause__ is not err, "the classified error became its own __cause__"
+
+ # walk the whole chain: no link may repeat, whatever the branch
+ seen, node = set(), err
+ while node is not None and id(node) not in seen:
+ seen.add(id(node))
+ node = node.__cause__ if node.__cause__ is not None else node.__context__
+ assert node is None, "the cause chain closes into a cycle"
+
+
+def test_a_real_wrapped_cause_still_survives_the_self_cause_guard():
+ """The guard drops the cause only when it IS the error — a genuine wrapped cause
+ (the classifier built a NEW ModelError) must still reach the caller."""
+ def call(key):
+ raise TimeoutError("read timed out")
+
+ with pytest.raises(ModelError) as ei:
+ _rotate(_pool(), call, max_attempts=1)
+ assert isinstance(ei.value.__cause__, TimeoutError)
+
+
def test_a_budget_spent_at_the_storm_gate_issues_no_round_trip():
"""A worker parked at a gate ANOTHER thread closed carries no ``last_err``, so the
guard at the top of the loop (which requires one) let it through: it woke past its