{"record":{"id":"1c5c28be969a0619","repo":"deepset-ai/haystack","slug":"top-k-must-not-be-negative-1c5c28","errorCode":null,"errorMessage":"top_k must not be negative.","messagePattern":"top_k must not be negative\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"haystack/components/joiners/document_joiner.py","lineNumber":174,"sourceCode":"        :raises ValueError:\n            If `top_k` is negative.\n        \"\"\"\n        documents = list(documents)\n        output_documents = self.join_mode_function(documents)\n\n        if self.sort_by_score:\n            output_documents = sorted(\n                output_documents, key=lambda doc: doc.score if doc.score is not None else -inf, reverse=True\n            )\n            if any(doc.score is None for doc in output_documents):\n                logger.info(\n                    \"Some of the Documents DocumentJoiner got have score=None. It was configured to sort Documents by \"\n                    \"score, so those with score=None were sorted as if they had a score of -infinity.\"\n                )\n\n        if top_k is not None:\n            if top_k < 0:\n                raise ValueError(\"top_k must not be negative.\")\n            output_documents = output_documents[:top_k]\n        elif self.top_k is not None:\n            output_documents = output_documents[: self.top_k]\n\n        return {\"documents\": output_documents}\n\n    @staticmethod\n    def _concatenate(document_lists: list[list[Document]]) -> list[Document]:\n        \"\"\"\n        Concatenate multiple lists of Documents and return only the Document with the highest score for duplicates.\n        \"\"\"\n        output = []\n        docs_per_id = defaultdict(list)\n        for doc in itertools.chain.from_iterable(document_lists):\n            docs_per_id[doc.id].append(doc)\n        for docs in docs_per_id.values():\n            doc_with_best_score = max(docs, key=lambda doc: doc.score if doc.score is not None else -inf)\n            output.append(doc_with_best_score)","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/deepset-ai/haystack/blob/e318778c9bf60a1963e3b5f451359655dd696c30/haystack/components/joiners/document_joiner.py#L156-L192","documentation":"DocumentJoiner.run raises ValueError when the runtime top_k argument is negative. top_k truncates the joined document list; negative values are rejected before slicing. (Runtime top_k may be 0, unlike the init check which requires > 0.)","triggerScenarios":"document_joiner.run(documents=..., top_k=-1) or any negative int at runtime.","commonSituations":"Using -1 as a 'no limit' sentinel; deriving top_k from user input or config without validation; confusing the stricter init rule (must be > 0) with the looser runtime rule (>= 0).","solutions":["Pass top_k=None in run() to use the init-time top_k or keep all documents.","Ensure the runtime top_k is >= 0.","Clamp with max(0, top_k) before calling run()."],"exampleFix":"// before\njoiner.run(documents=docs, top_k=-1)\n// after\njoiner.run(documents=docs, top_k=None)  # or a non-negative int","handlingStrategy":"validation","validationCode":"if run_top_k is not None and run_top_k < 0:\n    raise ValueError(f\"runtime top_k must be >= 0 or None, got {run_top_k}\")\njoiner.run(documents=docs, top_k=run_top_k)","typeGuard":"def is_valid_run_top_k(v: int | None) -> bool:\n    return v is None or (isinstance(v, int) and v >= 0)","tryCatchPattern":"try:\n    out = joiner.run(documents=docs, top_k=k)\nexcept ValueError as e:\n    logger.warning(\"bad runtime top_k: %s\", e)\n    out = joiner.run(documents=docs, top_k=None)","preventionTips":["Use None, not -1, to mean 'no limit' at runtime","Clamp values from external input: max(0, k)","Distinguish the init rule (>0) from the runtime rule (>=0)"],"tags":["validation","python","haystack"],"backgroundTag":"invalid-parameter-value","analyzedSha":"e318778c9bf60a1963e3b5f451359655dd696c30","analyzedAt":"2026-08-30T11:45:20.711Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}