4 of 5 Document*Evaluators crash with ZeroDivisionError on empty input
4 of 5 Document*Evaluators crash with ZeroDivisionError on empty input
Bug
The 5 retrieval/answer evaluators in haystack/components/evaluators/ aggregate per-question scores into one overall score with a mean. Four of them divide by len(ground_truth_documents) or len(retrieved_documents) without first checking that the list is non-empty, so an empty input raises ZeroDivisionError: division by zero instead of returning a clean 0.0 mean (or raising a helpful ValueError).
DocumentNDCGEvaluator already has its own empty-input guard (document_ndcg.py:148) — the other four do not.
Affected evaluators (all in haystack/components/evaluators/):
| Evaluator | File | Aggregation line |
|---|---|---|
DocumentMAPEvaluator |
document_map.py |
144: score = sum(individual_scores) / len(ground_truth_documents) |
DocumentMRREvaluator |
document_mrr.py |
128: same shape |
DocumentRecallEvaluator |
document_recall.py |
186: sum(scores) / len(retrieved_documents) |
AnswerExactMatchEvaluator |
answer_exact_match.py |
67: sum(matches) / len(predicted_answers) |
DocumentNDCGEvaluator is already correct and is the model to follow.
Reproduction
from haystack import Document
from haystack.components.evaluators import (
DocumentMAPEvaluator, DocumentMRREvaluator, DocumentNDCGEvaluator,
DocumentRecallEvaluator, AnswerExactMatchEvaluator,
)
for name, ev, kwargs in [
("DocumentMAPEvaluator", DocumentMAPEvaluator(), {"ground_truth_documents": [], "retrieved_documents": []}),
("DocumentMRREvaluator", DocumentMRREvaluator(), {"ground_truth_documents": [], "retrieved_documents": []}),
("DocumentNDCGEvaluator", DocumentNDCGEvaluator(), {"ground_truth_documents": [], "retrieved_documents": []}),
("DocumentRecallEvaluator", DocumentRecallEvaluator(), {"ground_truth_documents": [], "retrieved_documents": []}),
("AnswerExactMatchEvaluator", AnswerExactMatchEvaluator(), {"ground_truth_answers": [], "predicted_answers": []}),
]:
try:
print(name, ev.run(**kwargs))
except Exception as e:
print(f"{name}: {type(e).__name__}: {e}")
Output on main (2.31.0):
DocumentMAPEvaluator: ZeroDivisionError: division by zero
DocumentMRREvaluator: ZeroDivisionError: division by zero
DocumentNDCGEvaluator: ValueError: ground_truth_documents and retrieved_documents must be provided.
DocumentRecallEvaluator: ZeroDivisionError: division by zero
AnswerExactMatchEvaluator: ZeroDivisionError: division by zero
The per-question case ([[]] — one question with no documents) returns 0.0 for the retrieval evaluators and 1.0 for AnswerExactMatchEvaluator (one empty list, the answer is "matching" because both are missing). Only the top-level empty case breaks.
Why this matters
- Evaluator components are commonly run inside pipelines that iterate over a dataset. A pipeline that filters down to zero questions (e.g. all filtered out) crashes instead of returning a clean
0.0mean. - The inconsistency with
DocumentNDCGEvaluator(which has the right guard) is a footgun: users add a second evaluator to a pipeline, the pipeline's first run with a non-empty subset works, and a later run with an empty subset unexpectedly crashes only on the new evaluator. ZeroDivisionErroris not a useful signal for a caller that already passed the explicit shape contract ("same-length lists"). The intent is clearly a "no questions" case, not a math error.
Proposed fix
Mirror DocumentNDCGEvaluator.validate_inputs in each of the four evaluators. The recommended path is to raise ValueError, for the same reason DocumentNDCGEvaluator does: an empty list of questions is almost certainly a data-pipeline bug (filter dropped everything, wrong input path, etc.) and surfacing it is more useful than silently returning a clean 0.0 mean that downstream dashboards will average into unrelated scores. Returning 0.0 would also create a new inconsistency between four evaluators and the NDCG one; raising keeps all five behaviorally identical.
For the per-question [[]] case the existing semantics stay as they are (the four retrieval evaluators return 0.0; AnswerExactMatchEvaluator returns 1.0 because two empty answers are treated as "matching" by the answer-comparison code). Only the top-level empty case needs the new guard.
Acceptance criteria
- All 5 evaluators handle
ground_truth_documents=[](and equivalent forAnswerExactMatchEvaluator) withoutZeroDivisionError. - The behavior matches
DocumentNDCGEvaluator—ValueErrorwith a clear message naming the offending argument. (See Proposed fix for the rationale.) - New unit tests cover the empty case for all four evaluators that lack it today.
- The mismatch between the
len(...) == 0check and the score aggregation line is fixed in all four files in the same PR.
Backward compatibility
Pure bug fix. No public API change. Pipelines that today crash on empty input will either get a ValueError (the loud-fail option) or a clean zero mean (the silent option). Either is strictly better than the current ZeroDivisionError.
Risks
Low. The aggregation is a simple mean. A test pinning the exact error type/message should be added in case the maintainer chooses the "raise" path.
Hi, I'd like to work on this issue. I can align the empty-input behavior of the affected evaluators with DocumentNDCGEvaluator, add focused regression tests for the four missing cases, and keep the change limited to the validation path. Please let me know if this is open for an external contribution.
Hi, I'd like to take this if it's still free. Quick check before I start: for empty input, do you want the evaluators to return 0.0 (matching the issue suggestion) or raise a helpful ValueError? I'll mirror DocumentNDCGEvaluator's guard style plus regression tests for the four cases. Could you assign it to me if that sounds right?
Update: I see #12572 and #12706 already cover this (both currently draft on unsigned CLA). I won't open a duplicate — happy to step back here. If #12572 goes stale, I'm glad to pick this up; otherwise, if you have another unclaimed starter suitable for a first contribution, I'd appreciate a pointer.
haystack/components/evaluators/answer_exact_match.py:56-67
if not len(ground_truth_answers) == len(predicted_answers):
raise ValueError("The length of ground_truth_answers and predicted_answers must be the same.")
matches = []
for truth, extracted in zip(ground_truth_answers, predicted_answers, strict=True):
if truth == extracted:
matches.append(1)
else:
matches.append(0)
# The proportion of questions where any predicted answer matched one of the ground truth answers
average = sum(matches) / len(predicted_answers)
return {"individual_scores": matches, "score": average}
The match check is bare truth == extracted with no guard on either side being empty. When a ground_truth_answers entry is "" (a missing/blank reference — a common shape for gaps in eval data) and the corresponding predicted_answers entry is also "" (an empty or refusal-shaped reply), "" == "" is True and that row is counted as a full match, even though no real answer was ever compared to anything.
Measured
Verbatim copy of the function body above, run in plain Python (target not installed — classifier-gated package):
| Case | Input | individual_scores | score | Note |
|---|---|---|---|---|
| Control (must fail) | ["Berlin"] vs ["Munich"] |
[0] |
0.0 |
genuine mismatch, correct |
| Control (must pass) | ["Berlin"] vs ["Berlin"] |
[1] |
1.0 |
genuine match, correct |
| Degenerate | [""] vs [""] |
[1] |
1.0 |
blank reference + blank reply scored as a full match |
| Batch | ["Berlin","Paris",""] vs ["Munich","Lyon",""] |
[0,0,1] |
0.333 |
0/2 real questions answered correctly, but the composite score is nonzero because of the blank/blank filler row |
Why this is worth fixing alongside #12543
This is the exact per-row case #12543 measured directly ("one empty list, the answer is 'matching' because both are missing") and explicitly scoped out ("the existing semantics stay as they are... only the top-level empty case needs the new guard"). Extending that with what a mid-batch blank row does to a composite score: a 3-row run with 2 genuine wrong answers and 1 blank/blank filler row scores 0.333 instead of 0.0 — the blank row isn't just individually miscounted, it pulls the whole batch's mean toward "correct."
The rest of this evaluator family already treats a no-signal row this way: FaithfulnessEvaluator
and ContextRelevanceEvaluator (faithfulness.py:230-237, context_relevance.py:231-237) exclude
a no-signal row from the mean with a logged warning rather than crediting it, and
DocumentNDCGEvaluator.validate_inputs raises up front rather than silently scoring. Either
of those two patterns applied to a blank ground-truth/prediction pair in AnswerExactMatchEvaluator
would close this without touching the top-level-empty-list fix #12543 is already tracking.