deepset-ai/haystack · error · ValueError
top_k must be greater than 0.
Error message
top_k must be greater than 0.
What it means
DocumentJoiner.__init__ rejects a top_k that is not None and not > 0. top_k bounds how many documents are kept after joining; zero or negative values are invalid at construction time.
Source
Thrown at haystack/components/joiners/document_joiner.py:120
- `reciprocal_rank_fusion`: Merges and assigns scores based on reciprocal rank fusion.
- `distribution_based_rank_fusion`: Merges and assigns scores based on scores
distribution in each Retriever.
:param weights:
Assign importance to each list of documents to influence how they're joined.
This parameter is ignored for
`concatenate` or `distribution_based_rank_fusion` join modes.
Weight for each list of documents must match the number of inputs.
:param top_k:
The maximum number of documents to return. Must be `None` or greater than 0.
:param sort_by_score:
If `True`, sorts the documents by score in descending order.
If a document has no score, it is handled as if its score is -infinity.
:raises ValueError:
If `top_k` is not `None` and is less than or equal to 0.
"""
if top_k is not None and top_k <= 0:
raise ValueError("top_k must be greater than 0.")
if isinstance(join_mode, str):
join_mode = JoinMode.from_str(join_mode)
join_mode_functions = {
JoinMode.CONCATENATE: DocumentJoiner._concatenate,
JoinMode.MERGE: self._merge,
JoinMode.RECIPROCAL_RANK_FUSION: self._rrf,
JoinMode.DISTRIBUTION_BASED_RANK_FUSION: DocumentJoiner._distribution_based_rank_fusion,
}
self.join_mode_function = join_mode_functions[join_mode]
self.join_mode = join_mode
if weights:
weight_sum = sum(weights)
if weight_sum == 0:
raise ValueError("The provided `weights` must not sum to zero.")
self.weights: list[float] | None = [float(i) / weight_sum for i in weights]
else:
self.weights = None
self.top_k = top_kView on GitHub (pinned to e318778c9b)
Solutions
- Pass a positive integer for top_k.
- Pass top_k=None to skip truncation at init time and control it in run().
- Validate config-sourced values before constructing: top_k must be int > 0 or None.
Example fix
// before DocumentJoiner(join_mode="merge", top_k=0) // after DocumentJoiner(join_mode="merge", top_k=None) # or a positive int like 10
Defensive patterns
Strategy: validation
Validate before calling
if top_k is not None and (not isinstance(top_k, int) or top_k <= 0):
raise ValueError("DocumentJoiner top_k must be a positive int or None")
joiner = DocumentJoiner(top_k=top_k) Type guard
def is_valid_init_top_k(v: int | None) -> bool:
return v is None or (isinstance(v, int) and not isinstance(v, bool) and v > 0) Try / catch
try:
joiner = DocumentJoiner(join_mode=mode, top_k=top_k)
except ValueError as e:
logger.warning("invalid top_k %r, using None", top_k)
joiner = DocumentJoiner(join_mode=mode, top_k=None) Prevention
- Treat 0 as invalid at init; use None for 'no init-level limit'
- Sanitize config defaults that use 0
- Coerce strings from YAML/JSON configs to int before constructing
When it happens
Trigger: DocumentJoiner(top_k=0) or DocumentJoiner(top_k=-5). Note None is allowed and means 'use the runtime top_k only'.
Common situations: Config defaults of 0 mistaken for 'no limit'; computing top_k from an empty/zero-valued variable; confusion with the runtime run() check which allows 0.
Understand the failure class
Background: "must be positive", "Invalid value": how libraries reject invalid parameter values (ValueError, ArgumentError, INVALID_PARAMETER_VALUE) — this error's family across 28 libraries.
Related errors
- 'response_fn' must return an assistant ChatMessage, got '{re
- Cannot stream multiple responses, please set n=1.
- A `ChatMessage` must contain at least one `TextContent`, `To
- top_k must be greater than 0.
- top_k must not be negative.
AI-assisted analysis of deepset-ai/haystack@e318778c9b (2026-08-30).
Data as JSON: /api/errors/a07a50c857752bc0.
Report an issue: GitHub.