KNN(k=0) returns the entire trainset instead of zero neighbors (argsort()[-self.k:] negative-zero slicing bug)
What happens
dspy.predict.knn.KNN.__call__ uses scores.argsort()[-self.k :] to take the top-k nearest neighbors:
def __call__(self, **kwargs) -> list:
input_example_vector = self.embedding([" | ".join([f"{key}: {val}" for key, val in kwargs.items()])])
scores = np.dot(self.trainset_vectors, input_example_vector.T).squeeze()
nearest_samples_idxs = scores.argsort()[-self.k :][::-1]
return [self.trainset[cur_idx] for cur_idx in nearest_samples_idxs]When self.k == 0, -self.k evaluates to 0 (Python integers have no distinct negative zero), so scores.argsort()[-self.k:] is exactly scores.argsort()[0:], i.e. the entire array, not an empty slice. KNN(k=0, ...) therefore returns every example in the trainset (in reverse similarity order) instead of zero examples.
Repro
Tested directly against the current main source of dspy/predict/knn.py (verified byte-identical to the installed dspy 3.4.0 package):
import numpy as np
import dspy
from dspy.predict.knn import KNN
def fake_embed(texts):
return np.array([[len(t), sum(map(ord, t)) % 97] for t in texts], dtype=float)
trainset = [dspy.Example(input=f"item{i}", output=str(i)).with_inputs("input") for i in range(5)]
for k in (0, 1, 2):
knn = KNN(k=k, trainset=trainset, vectorizer=fake_embed)
result = knn(input="item0")
print(f"k={k}: requested {k} neighbors, got {len(result)}: {[r.output for r in result]}")Output:
k=0: requested 0 neighbors, got 5: ['4', '3', '2', '1', '0']
k=1: requested 1 neighbors, got 1: ['4']
k=2: requested 2 neighbors, got 2: ['4', '3']k=1 and k=2 behave as expected (a fixed stand-in embedding function is used here only to make the repro deterministic and dependency-free; the slicing bug does not depend on the embedding quality). Only k=0 breaks, and it breaks by returning everything, the opposite of "zero neighbors."
Expected vs actual
Expected: KNN(k=0, ...) returns an empty list (or __init__ rejects k=0 outright as invalid), consistent with k meaning "number of neighbors to retrieve."
Actual: KNN(k=0, ...) silently returns the full trainset.
Why this matters
k is commonly a tunable/computed parameter (grid search, config value, or derived from a fraction of trainset size). A computed or misconfigured k that lands on 0 does not raise or warn, it silently returns the entire training set as "nearest neighbors," which would quietly balloon the few-shot prompt built from this selection, or break any downstream logic assuming len(result) <= k.
Suggested fix
Guard the k == 0 (and k < 0) case explicitly, e.g.:
nearest_samples_idxs = scores.argsort()[-self.k :][::-1] if self.k > 0 else np.array([], dtype=int)or validate k > 0 in __init__.
This is on the current main branch, dspy/predict/knn.py, KNN.__call__.
Duplicate check
I searched existing issues and PRs for KNN, argsort, and k=0 first. The only currently open PR touching this file, #10424, fixes an unrelated TypeError in KNN.__init__ when an example never called with_inputs(); it does not touch __call__ or this slicing logic. No existing issue covers the k=0 behavior.
Source: stanfordnlp/dspy