mastra-ai/mastra · error
TopK must be greater than 0
Error message
TopK must be greater than 0
What it means
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.
Source
Thrown at packages/rag/src/graph-rag/index.ts:354
// Retrieve relevant nodes using hybrid approach
query({
query,
topK = 10,
randomWalkSteps = 100,
restartProb = 0.15,
filter,
}: {
query: number[];
topK?: number;
randomWalkSteps?: number;
restartProb?: number;
filter?: Partial<GraphMetadata>;
}): RankedNode[] {
if (!query || query.length !== this.dimension) {
throw new Error(`Query embedding must have dimension ${this.dimension}`);
}
if (topK < 1) {
throw new Error('TopK must be greater than 0');
}
if (randomWalkSteps < 1) {
throw new Error('Random walk steps must be greater than 0');
}
if (restartProb <= 0 || restartProb >= 1) {
throw new Error('Restart probability must be between 0 and 1');
}
const filterEntries = Object.entries(filter ?? {});
const matchesFilter = (node: GraphNode) =>
filterEntries.length === 0 ? true : filterEntries.every(([key, value]) => node.metadata?.[key] === value);
const nodesToSearch = Array.from(this.nodes.values()).filter(matchesFilter);
// Retrieve nodes and calculate similarity
const similarities = nodesToSearch.map(node => ({
node,
similarity: this.cosineSimilarity(query, node.embedding!),View on GitHub (pinned to 75dd419e61)
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.
Example fix
// before
const res = graph.query({ query, topK: limit });
// after
const res = graph.query({ query, topK: Math.max(1, limit ?? 10) }); Defensive patterns
Strategy: validation
Validate before calling
const safeTopK = Math.max(1, topK ?? 10);
if (!Number.isInteger(safeTopK)) throw new Error(`topK must be a positive integer, got ${topK}`); Type guard
const isValidTopK = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 1;
Try / catch
try {
const results = graph.query({ query, topK });
} catch (e) {
if ((e as Error).message === 'TopK must be greater than 0') {
// fall back to the default: graph.query({ query })
} else throw e;
} Prevention
- 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
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: "must be positive", "Invalid value": how libraries reject invalid parameter values (ValueError, ArgumentError, INVALID_PARAMETER_VALUE) — this error's family across 28 libraries.
Related errors
- Invalid signal type: ${input.type}. Use a supported signal t
- topK must be a positive integer
- Unknown strategy: ${strategy}
- HTML chunking requires either headers or sections to be spec
- JSON chunking requires maxSize to be specified
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/6050a30f12148467.
Report an issue: GitHub.