{"record":{"id":"50c1700925542f49","repo":"mem0ai/mem0","slug":"invalid-topk-topk-must-be-a-non-negative-inte","errorCode":null,"errorMessage":"Invalid topK: ${topK}. Must be a non-negative integer.","messagePattern":"Invalid topK: (.+?)\\. Must be a non-negative integer\\.","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mem0-ts/src/oss/src/memory/index.ts","lineNumber":200,"sourceCode":" * @throws Error if threshold or topK are invalid\n */\nfunction validateSearchParams(threshold?: number, topK?: number): void {\n  if (threshold !== undefined) {\n    if (typeof threshold !== \"number\" || isNaN(threshold)) {\n      throw new Error(\"threshold must be a valid number\");\n    }\n    if (threshold < 0 || threshold > 1) {\n      throw new Error(\n        `Invalid threshold: ${threshold}. Must be between 0 and 1 (inclusive).`,\n      );\n    }\n  }\n  if (topK !== undefined) {\n    if (typeof topK !== \"number\" || isNaN(topK) || !Number.isInteger(topK)) {\n      throw new Error(\"topK must be a valid integer\");\n    }\n    if (topK < 0) {\n      throw new Error(`Invalid topK: ${topK}. Must be a non-negative integer.`);\n    }\n  }\n}\n\nexport class Memory {\n  private config: MemoryConfig;\n  private customInstructions: string | undefined;\n  private embedder: Embedder;\n  private vectorStore!: VectorStore;\n  private llm: LLM;\n  private reranker: Reranker | null = null;\n  private db: HistoryManager;\n  private collectionName: string | undefined;\n  private apiVersion: string;\n  telemetryId: string;\n  private _initPromise: Promise<void>;\n  private _initError?: Error;\n  private _entityStore?: VectorStore;","sourceCodeStart":182,"sourceCodeEnd":218,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0-ts/src/oss/src/memory/index.ts#L182-L218","documentation":"Thrown by validateSearchParams when topK is an integer but negative. A negative result count is nonsensical, so the SDK rejects it up front with a message echoing the value; zero is allowed (returns no results) but -1, -5, etc. throw.","triggerScenarios":"Calling memory.search('q', { topK: -1 }); or computing topK from subtraction that can go negative, e.g. topK: requested - offset where offset exceeds requested.","commonSituations":"Pagination arithmetic bugs (limit - page*size underflowing), signaling 'no limit' with -1 as some APIs allow, or defaults built from env vars that contain '-5'.","solutions":["Use a positive integer or omit topK to use the SDK default.","Clamp pagination math: topK: Math.max(0, limit - offset).","If -1 was meant as 'unlimited', pass a large positive integer instead or leave topK undefined.","Add boundary tests on your pagination code for the last page where counts can go negative."],"exampleFix":"// before\nconst topK = limit - offset; // can be negative on the last page\nawait memory.search('q', { topK });\n\n// after\nconst topK = Math.max(0, limit - offset);\nif (topK === 0) return []; // nothing left on this page\nawait memory.search('q', { topK });","handlingStrategy":"validation","validationCode":"function safeTopK(computed: number): number {\n  return Math.max(0, Math.floor(computed));\n}","typeGuard":"function isNonNegativeIntegerTopK(k: unknown): k is number {\n  return typeof k === 'number' && Number.isInteger(k) && k >= 0;\n}","tryCatchPattern":null,"preventionTips":["Clamp pagination-derived counts with Math.max(0, ...).","Don't use -1 as an 'unlimited' sentinel — this API doesn't support it.","Unit-test the last-page case of any pagination code producing topK."],"tags":["validation","search","topk","pagination","typescript"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}