{"record":{"id":"2b56090dd4d12642","repo":"chroma-core/chroma","slug":"number-of-requested-results-n-results-cannot-be","errorCode":null,"errorMessage":"Number of requested results {n_results}, cannot be negative, or zero.","messagePattern":"Number of requested results (.+?), cannot be negative, or zero\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"chromadb/api/types.py","lineNumber":1366,"sourceCode":"            raise ValueError(\n                f\"Expected include item to be one of {', '.join(valid_items)}, got {item}\"\n            )\n\n        if dissalowed is not None and any(item == e for e in dissalowed):\n            raise ValueError(\n                f\"Include item cannot be one of {', '.join(dissalowed)}, got {item}\"\n            )\n\n\ndef validate_n_results(n_results: int) -> int:\n    \"\"\"Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative.\"\"\"\n    # Check Number of requested results\n    if not isinstance(n_results, int):\n        raise ValueError(\n            f\"Expected requested number of results to be a int, got {n_results}\"\n        )\n    if n_results <= 0:\n        raise TypeError(\n            f\"Number of requested results {n_results}, cannot be negative, or zero.\"\n        )\n    return n_results\n\n\ndef validate_embeddings(embeddings: Embeddings) -> Embeddings:\n    \"\"\"Validates embeddings to ensure it is a list of numpy arrays of ints, or floats\"\"\"\n    if not isinstance(embeddings, (list, np.ndarray)):\n        raise ValueError(\n            f\"Expected embeddings to be a list, got {type(embeddings).__name__}\"\n        )\n    if len(embeddings) == 0:\n        raise ValueError(\n            f\"Expected embeddings to be a list with at least one item, got {len(embeddings)} embeddings\"\n        )\n    if not all([isinstance(e, np.ndarray) for e in embeddings]):\n        raise ValueError(\n            \"Expected each embedding in the embeddings to be a numpy array, got \"","sourceCodeStart":1348,"sourceCodeEnd":1384,"githubUrl":"https://github.com/chroma-core/chroma/blob/aecdd12c8a891610db8653630b066b32ceb678b5/chromadb/api/types.py#L1348-L1384","documentation":"validate_n_results raises a TypeError (not ValueError) when n_results <= 0, because the underlying HNSW index cannot serve zero or negative result counts. This fires after the int-type check passes, so the value is a genuine int that is 0 or negative.","triggerScenarios":"collection.query(query_texts=..., n_results=0) — commonly a computed top-k that evaluated to 0, e.g. min(len(collection), user_k) with an empty collection, max(0, something), or a default of 0 meaning 'not set'.","commonSituations":"top_k = min(user_k, collection.count()) returning 0 on a fresh collection; config defaults of 0; pagination math floor-dividing to 0; user-supplied limit=0 intended to mean 'no limit'.","solutions":["Clamp before the call: n_results=max(1, k)","Skip the query entirely when the computed top-k is 0 instead of calling with n_results=0","Treat 0 as a sentinel and substitute a sensible default (e.g. 10)"],"exampleFix":"# before\nk = min(user_top_k, collection.count())  # 0 when collection is empty\nresults = collection.query(query_embeddings=[q], n_results=k)\n\n# after\nk = min(user_top_k, collection.count())\nif k <= 0:\n    results = {\"ids\": [[]], \"documents\": [[]]}\nelse:\n    results = collection.query(query_embeddings=[q], n_results=k)","handlingStrategy":"validation","validationCode":"def safe_n_results(k, default=10) -> int:\n    try:\n        k = int(k)\n    except (TypeError, ValueError):\n        k = default\n    return max(1, k)\n\nres = collection.query(query_embeddings=[q], n_results=safe_n_results(min(user_k, collection.count())))","typeGuard":"def is_valid_n_results(n) -> bool:\n    return isinstance(n, int) and not isinstance(n, bool) and n >= 1","tryCatchPattern":"try:\n    res = collection.query(query_texts=[q], n_results=k)\nexcept TypeError as e:  # note: this check raises TypeError, not ValueError\n    if \"cannot be negative, or zero\" in str(e):\n        res = collection.query(query_texts=[q], n_results=1)\n    else:\n        raise","preventionTips":["Clamp computed top-k: max(1, min(user_k, collection.count()))","Skip querying empty collections (count() == 0) instead of relying on the error","Catch TypeError as well as ValueError around query calls — this specific check raises TypeError"],"tags":["chromadb","n-results","top-k","type-error"],"backgroundTag":"invalid-limit-parameter","analyzedSha":"aecdd12c8a891610db8653630b066b32ceb678b5","analyzedAt":"2026-08-16T21:53:27.228Z","schemaVersion":2},"datasetVersion":"2026-08-16T23:17:17.608Z"}