Skip to content

Commit 2b21aa6

Browse files
fix: raise a clear error for zero-sum weights in DocumentJoiner (#11629)
Co-authored-by: bogdankostic <bogdankostic@web.de>
1 parent 9c9fbd7 commit 2b21aa6

3 files changed

Lines changed: 18 additions & 1 deletion

File tree

haystack/components/joiners/document_joiner.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,13 @@ def __init__(
123123
}
124124
self.join_mode_function = join_mode_functions[join_mode]
125125
self.join_mode = join_mode
126-
self.weights = [float(i) / sum(weights) for i in weights] if weights else None
126+
if weights:
127+
weight_sum = sum(weights)
128+
if weight_sum == 0:
129+
raise ValueError("The provided `weights` must not sum to zero.")
130+
self.weights: list[float] | None = [float(i) / weight_sum for i in weights]
131+
else:
132+
self.weights = None
127133
self.top_k = top_k
128134
self.sort_by_score = sort_by_score
129135

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
fixes:
3+
- |
4+
``DocumentJoiner`` now raises a clear ``ValueError`` when the provided ``weights``
5+
sum to zero, instead of failing with an opaque ``ZeroDivisionError`` while
6+
normalizing them.

test/components/joiners/test_document_joiner.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ def test_init_with_custom_parameters(self):
2626
assert joiner.top_k == 5
2727
assert not joiner.sort_by_score
2828

29+
def test_init_with_zero_sum_weights_raises(self):
30+
# weights that sum to zero would divide by zero during normalization
31+
with pytest.raises(ValueError, match="must not sum to zero"):
32+
DocumentJoiner(join_mode="merge", weights=[0.0, 0.0, 0.0])
33+
2934
def test_to_dict(self):
3035
joiner = DocumentJoiner()
3136
data = joiner.to_dict()

0 commit comments

Comments
 (0)