{"record":{"id":"e04c9ed488826da3","repo":"mastra-ai/mastra","slug":"topk-must-be-a-positive-integer","errorCode":null,"errorMessage":"topK must be a positive integer","messagePattern":"topK must be a positive integer","errorType":"error_code","errorClass":"MastraError","httpStatus":null,"severity":"error","filePath":"packages/core/src/vector/validation.ts","lineNumber":76,"sourceCode":"      details: {\n        message: 'IDs array length must match vectors array length',\n        vectorsLength: vectors.length,\n        idsLength: ids.length,\n      },\n    });\n  }\n}\n\n/**\n * Validates topK parameter for queries\n *\n * @param storeName - Name of the vector store (e.g., 'PG', 'CHROMA')\n * @param topK - Number of results to return\n * @throws MastraError if topK is not a positive integer\n */\nexport function validateTopK(storeName: string, topK: number): void {\n  if (!Number.isInteger(topK) || topK <= 0) {\n    throw new MastraError({\n      id: createVectorErrorId(storeName, 'QUERY', 'INVALID_TOP_K'),\n      domain: ErrorDomain.MASTRA_VECTOR,\n      category: ErrorCategory.USER,\n      details: {\n        message: 'topK must be a positive integer',\n        topK,\n      },\n    });\n  }\n}\n\n/**\n * Validates vector components for NaN/Infinity values\n *\n * @param storeName - Name of the vector store (e.g., 'PG', 'CHROMA')\n * @param vectors - Array of vectors to validate\n * @throws MastraError if any vector contains NaN, Infinity, null, or undefined\n */","sourceCodeStart":58,"sourceCodeEnd":94,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/vector/validation.ts#L58-L94","documentation":"validateTopK rejects any topK that is not a positive integer. topK is the number of nearest neighbors a query() should return, so 0, negatives, floats, NaN, or non-numbers are all invalid.","triggerScenarios":"Calling query({ indexName, queryVector, topK: 0 }), topK from parseInt of a bad string producing NaN, a float like 2.5, or a negative limit computed from pagination math.","commonSituations":"User-supplied limit passed through unvalidated; pagination page*size arithmetic going negative; config value loaded from env as a string then coerced incorrectly.","solutions":["Pass a positive integer, e.g. topK: 10","Clamp/round user input: topK = Math.max(1, Math.floor(Number(input) || 10))","Validate the value before calling query instead of relying on the store to throw"],"exampleFix":"// before\nconst results = await store.query({ indexName: 'docs', queryVector, topK: Number(req.query.limit) });\n// after\nconst topK = Math.max(1, Math.floor(Number(req.query.limit) || 10));\nconst results = await store.query({ indexName: 'docs', queryVector, topK });","handlingStrategy":"validation","validationCode":"const topK = Math.max(1, Math.floor(Number(rawTopK)));\nif (!Number.isInteger(topK) || topK <= 0) throw new Error('topK must be a positive integer');","typeGuard":"function isValidTopK(v: unknown): v is number {\n  return typeof v === 'number' && Number.isInteger(v) && v > 0;\n}","tryCatchPattern":"try {\n  return await store.query({ indexName, queryVector, topK });\n} catch (e) {\n  if (e instanceof MastraError && e.id.includes('INVALID_TOP_K')) {\n    return store.query({ indexName, queryVector, topK: 10 });\n  }\n  throw e;\n}","preventionTips":["Coerce and clamp user-provided limits at the API boundary","Never pass NaN from failed Number()/parseInt calls straight through","Keep pagination arithmetic guarded with Math.max(1, ...)"],"tags":["validation","vector-store","query","topk"],"backgroundTag":"invalid-parameter-value","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}