{"record":{"id":"6050a30f12148467","repo":"mastra-ai/mastra","slug":"topk-must-be-greater-than-0","errorCode":null,"errorMessage":"TopK must be greater than 0","messagePattern":"TopK must be greater than 0","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/rag/src/graph-rag/index.ts","lineNumber":354,"sourceCode":"  // Retrieve relevant nodes using hybrid approach\n  query({\n    query,\n    topK = 10,\n    randomWalkSteps = 100,\n    restartProb = 0.15,\n    filter,\n  }: {\n    query: number[];\n    topK?: number;\n    randomWalkSteps?: number;\n    restartProb?: number;\n    filter?: Partial<GraphMetadata>;\n  }): RankedNode[] {\n    if (!query || query.length !== this.dimension) {\n      throw new Error(`Query embedding must have dimension ${this.dimension}`);\n    }\n    if (topK < 1) {\n      throw new Error('TopK must be greater than 0');\n    }\n    if (randomWalkSteps < 1) {\n      throw new Error('Random walk steps must be greater than 0');\n    }\n    if (restartProb <= 0 || restartProb >= 1) {\n      throw new Error('Restart probability must be between 0 and 1');\n    }\n\n    const filterEntries = Object.entries(filter ?? {});\n    const matchesFilter = (node: GraphNode) =>\n      filterEntries.length === 0 ? true : filterEntries.every(([key, value]) => node.metadata?.[key] === value);\n\n    const nodesToSearch = Array.from(this.nodes.values()).filter(matchesFilter);\n\n    // Retrieve nodes and calculate similarity\n    const similarities = nodesToSearch.map(node => ({\n      node,\n      similarity: this.cosineSimilarity(query, node.embedding!),","sourceCodeStart":336,"sourceCodeEnd":372,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/rag/src/graph-rag/index.ts#L336-L372","documentation":"query() validates its options and throws 'TopK must be greater than 0' when topK < 1 (including 0, NaN treated by comparison, or negatives). topK controls how many top results are returned, so a non-positive value is meaningless.","triggerScenarios":"graph.query({ query, topK: 0 }) or topK negative — typically topK computed from a variable like `results.length - n`, a misparsed CLI/config value, or `topK: limit` where limit defaulted to 0.","commonSituations":"Pagination math yielding 0 on the first page; user-supplied limit parsed from an empty string (Number('') === 0); config that sets topK to 0 to 'disable' reranking instead of omitting it.","solutions":["Pass topK >= 1, or omit it to use the default of 10.","Clamp computed values: Math.max(1, requestedTopK) before calling query().","Fix the parsing/config path that produced 0 or a negative number.","Validate options in a wrapper around query() to fail with a clearer app-level message."],"exampleFix":"// before\nconst res = graph.query({ query, topK: limit });\n// after\nconst res = graph.query({ query, topK: Math.max(1, limit ?? 10) });","handlingStrategy":"validation","validationCode":"const safeTopK = Math.max(1, topK ?? 10);\nif (!Number.isInteger(safeTopK)) throw new Error(`topK must be a positive integer, got ${topK}`);","typeGuard":"const isValidTopK = (n: unknown): n is number =>\n  typeof n === 'number' && Number.isInteger(n) && n >= 1;","tryCatchPattern":"try {\n  const results = graph.query({ query, topK });\n} catch (e) {\n  if ((e as Error).message === 'TopK must be greater than 0') {\n    // fall back to the default: graph.query({ query })\n  } else throw e;\n}","preventionTips":["Omit topK to use the built-in default of 10","Clamp computed/dynamic values with Math.max(1, n)","Beware Number('') === 0 when parsing limits from config or CLI input","To disable reranking effects, tune randomWalkSteps/restartProb instead of setting topK to 0"],"tags":["rag","invalid-argument","query","validation"],"backgroundTag":"invalid-parameter-value","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}