{"record":{"id":"0d24b063d51fb20f","repo":"mem0ai/mem0","slug":"invalid-top-k-top-k-must-be-a-non-negative-int","errorCode":null,"errorMessage":"Invalid top_k: {top_k}. Must be a non-negative integer.","messagePattern":"Invalid top_k: (.+?)\\. Must be a non-negative integer\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mem0/memory/main.py","lineNumber":234,"sourceCode":"    Args:\n        threshold: Similarity threshold (must be between 0 and 1)\n        top_k: Number of results to return (must be non-negative integer)\n\n    Raises:\n        ValueError: If threshold or top_k are invalid\n    \"\"\"\n    if threshold is not None:\n        if not isinstance(threshold, (int, float)):\n            raise ValueError(\"threshold must be a valid number\")\n        if threshold < 0 or threshold > 1:\n            raise ValueError(\n                f\"Invalid threshold: {threshold}. Must be between 0 and 1 (inclusive).\"\n            )\n    if top_k is not None:\n        if not isinstance(top_k, int) or isinstance(top_k, bool):\n            raise ValueError(\"top_k must be a valid integer\")\n        if top_k < 0:\n            raise ValueError(\n                f\"Invalid top_k: {top_k}. Must be a non-negative integer.\"\n            )\n\n\ndef _validate_and_trim_search_query(query: str) -> str:\n    \"\"\"\n    Validates and normalizes a search query before embedding/vector search.\n\n    Raises:\n        ValueError: If query is not a string or is empty/whitespace-only.\n    \"\"\"\n    if not isinstance(query, str):\n        raise ValueError(\"Invalid query: must be a non-empty string.\")\n    trimmed = query.strip()\n    if not trimmed:\n        raise ValueError(\"Invalid query: cannot be empty or whitespace-only.\")\n    return trimmed\n","sourceCodeStart":216,"sourceCodeEnd":252,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/memory/main.py#L216-L252","documentation":"Raised by _validate_search_params when top_k is an int but negative (top_k < 0). Requesting a negative number of results is meaningless, so the SDK rejects it with a ValueError before touching the vector store. Zero is allowed and simply returns no results.","triggerScenarios":"m.search(query, filters={'user_id':'u1'}, top_k=-1); top_k computed as a subtraction that underflows (e.g. top_k = limit - offset where offset > limit); a loop decrementing top_k below zero; parsing a negative number from user input without clamping.","commonSituations":"Pagination arithmetic bugs (limit - page*size going negative on the last page); passing -1 as an 'all results' sentinel that worked in another API but is invalid here; sign errors in config.","solutions":["Clamp the value: top_k = max(0, top_k).","Fix the pagination arithmetic that produced a negative count.","Use a large positive number (e.g. 100) or the SDK default instead of -1 to mean 'many results'.","Add an assert or pre-check in your own wrapper before calling mem0."],"exampleFix":"# before\ntop_k = limit - offset  # can go negative\nm.search(q, filters=f, top_k=top_k)\n\n# after\ntop_k = max(0, limit - offset)\nif top_k == 0:\n    return []\nm.search(q, filters=f, top_k=top_k)","handlingStrategy":"validation","validationCode":"top_k = max(0, int(top_k))\nif top_k == 0:\n    return []  # nothing to fetch","typeGuard":"def is_valid_top_k(k) -> bool:\n    return k is None or (isinstance(k, int) and not isinstance(k, bool) and k >= 0)","tryCatchPattern":null,"preventionTips":["Clamp pagination arithmetic: top_k = max(0, limit - offset).","Never use -1 as an 'unlimited' sentinel; pick a large positive bound instead.","Assert invariants on computed counts in debug builds."],"tags":["validation","search","top-k","pagination"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}