{"record":{"id":"77125e6712a7f22e","repo":"deepset-ai/haystack","slug":"top-k-must-be-0-but-got-top-k-77125e","errorCode":null,"errorMessage":"top_k must be > 0, but got {top_k}","messagePattern":"top_k must be > 0, but got (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"haystack/components/rankers/lost_in_the_middle.py","lineNumber":57,"sourceCode":"\n    def __init__(self, word_count_threshold: int | None = None, top_k: int | None = None) -> None:\n        \"\"\"\n        Initialize the LostInTheMiddleRanker.\n\n        If 'word_count_threshold' is specified, this ranker includes all documents up until the point where adding\n        another document would exceed the 'word_count_threshold'. The last document that causes the threshold to\n        be breached will be included in the resulting list of documents, but all subsequent documents will be\n        discarded.\n\n        :param word_count_threshold: The maximum total number of words across all documents selected by the ranker.\n        :param top_k: The maximum number of documents to return.\n        \"\"\"\n        if isinstance(word_count_threshold, int) and word_count_threshold <= 0:\n            raise ValueError(\n                f\"Invalid value for word_count_threshold: {word_count_threshold}. word_count_threshold must be > 0.\"\n            )\n        if isinstance(top_k, int) and top_k <= 0:\n            raise ValueError(f\"top_k must be > 0, but got {top_k}\")\n\n        self.word_count_threshold = word_count_threshold\n        self.top_k = top_k\n\n    @component.output_types(documents=list[Document])\n    def run(\n        self, documents: list[Document], top_k: int | None = None, word_count_threshold: int | None = None\n    ) -> dict[str, list[Document]]:\n        \"\"\"\n        Reranks documents based on the \"lost in the middle\" order.\n\n        Before ranking, documents are deduplicated by their id, retaining only the document with the highest score\n        if a score is present.\n\n        :param documents: List of Documents to reorder.\n        :param top_k: The maximum number of documents to return.\n        :param word_count_threshold: The maximum total number of words across all documents selected by the ranker.\n        :returns:","sourceCodeStart":39,"sourceCodeEnd":75,"githubUrl":"https://github.com/deepset-ai/haystack/blob/e318778c9bf60a1963e3b5f451359655dd696c30/haystack/components/rankers/lost_in_the_middle.py#L39-L75","documentation":"LostInTheMiddleRanker's __init__ rejects a top_k that is an int <= 0. top_k caps how many documents the ranker returns, so zero or negative values cannot produce a valid result set. Raised as ValueError at construction time.","triggerScenarios":"Calling LostInTheMiddleRanker(top_k=0) or a negative int; the check only applies when the value is an int instance (None or floats bypass it).","commonSituations":"top_k computed from a variable (e.g. user input or len() of an empty list) that is 0; config templates with 0 placeholders; off-by-one in subtraction logic.","solutions":["Pass a positive integer for top_k, e.g. LostInTheMiddleRanker(top_k=10).","Guard the source variable: only construct the ranker when top_k > 0.","Use the default top_k by omitting the parameter if no explicit limit is needed."],"exampleFix":"// before\nranker = LostInTheMiddleRanker(top_k=0)\n// after\nranker = LostInTheMiddleRanker(top_k=10)","handlingStrategy":"validation","validationCode":"def ensure_valid_top_k(v):\n    if isinstance(v, int) and v <= 0:\n        raise ValueError(f\"top_k must be > 0, got {v}\")\n    return v","typeGuard":"def is_positive_int(v) -> bool:\n    return isinstance(v, int) and v > 0","tryCatchPattern":"try:\n    ranker = LostInTheMiddleRanker(top_k=k)\nexcept ValueError:\n    ranker = LostInTheMiddleRanker(top_k=10)  # safe default","preventionTips":["Compute top_k defensively: max(1, computed_k).","Never derive top_k from len() of a possibly empty list without a guard.","Centralize top_k validation in a shared helper for all rankers."],"tags":["python","validation","ranker","constructor-argument"],"backgroundTag":"invalid-parameter-value","analyzedSha":"e318778c9bf60a1963e3b5f451359655dd696c30","analyzedAt":"2026-08-30T11:45:20.711Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}