BestOfN.forward() and Refine.forward() mutate self.fail_count as shared instance state, not a per-call counter
BestOfN.forward() (dspy/predict/best_of_n.py) and Refine.forward() (dspy/predict/refine.py) both use self.fail_count as a per-call retry budget, but they decrement the instance attribute directly instead of a local counter. Since fail_count is set once in __init__ and never reset in forward(), repeated calls to the same module instance carry over (and can go negative) the decremented value from earlier calls.
Current code, dspy/predict/best_of_n.py:
def __init__(
self,
module: Module,
N: int, # noqa: N803
reward_fn: Callable[[dict, Prediction], float],
threshold: float,
fail_count: int | None = None,
):
self.module = module
self.reward_fn = lambda *args: reward_fn(*args) # to prevent this from becoming a parameter
self.threshold = threshold
self.N = N
self.fail_count = fail_count or N # default to N if fail_count is not providedand in forward():
except Exception as e:
print(f"BestOfN: Attempt {idx + 1} failed with rollout id {rid}: {e}")
if idx > self.fail_count:
raise e
self.fail_count -= 1dspy/predict/refine.py has the identical pattern:
except Exception as e:
print(f"Refine: Attempt failed with rollout id {rid}: {e}")
if idx > self.fail_count:
raise e
self.fail_count -= 1Why this happens: self.fail_count is instance state, not a loop-local variable. Each failed attempt inside forward() permanently lowers it, and nothing restores it once forward() returns. A BestOfN/Refine module is normally built once (e.g. best_of_3 = dspy.BestOfN(module=qa, N=3, reward_fn=..., threshold=1.0)) and then called many times as part of a pipeline, exactly the pattern shown in the class docstring's own example.
Steps to reproduce (conceptually, for BestOfN, Refine behaves the same way):
- Create
bo = dspy.BestOfN(module=some_module, N=5, reward_fn=reward_fn, threshold=1.0, fail_count=2). - Call
bo(**kwargs)once where 2 of the attempts raise exceptions (allowed, sincefail_count=2).self.fail_countis now0. - Call
bo(**kwargs)again on the same instance. Any single attempt that raises now immediately triggersidx > self.fail_count(0 > 0is False on the very first failure, butself.fail_countgoes negative from there), so the module tolerates fewer and fewer failures than thefail_countthe caller configured, with no error or warning that the budget has been silently exhausted by a previous, unrelated call.
There is also an off-by-one at fail_count=0: the intent (per the docstring, "Number of allowed failures before raising an exception") is that 0 allowed failures means the first failure should raise immediately, but idx > self.fail_count evaluates 0 > 0 → False on the first failure, so one failure is incorrectly tolerated before self.fail_count goes negative.
Expected: fail_count should behave as a fixed, per-call budget: the same instance called twice with the same inputs and same failure pattern should behave identically both times. This requires tracking the remaining budget in a local variable inside forward() (e.g. remaining_failures = self.fail_count) rather than mutating self.fail_count.
Actual: the failure budget silently erodes (and can go negative) across repeated calls to the same BestOfN/Refine instance, since the same self.fail_count attribute is shared and decremented on every call.
Verified by reading the current main branch source in both files; both forward() methods share this exact bug.
Source: stanfordnlp/dspy