Milestone 3 of 8
Find ordered neighbors for one query
Order every reference by squared distance and original row position, then retain the first k with a complete trace.
Neighbor selection is a traceable ordering step. Save the full decision for one query before attaching a label to it.
Goal
Calculate distances for one query, apply the exact distance-and-row-position
tie rule, and save the first k reference records with a complete trace.
Inputs
Use one validated query, all validated reference rows, their original row
positions, the squared-distance function, and a valid k. Order candidates by:
- smaller squared distance;
- earlier row position in the reference file when distances are equal.
Each selected neighbor must retain record_id, label, squared distance, and
original row position. Do not use a nearest-neighbor library, a tree, an
approximate index, or an unstable sort with undocumented tie behavior.
Deliverables
Implement src/neighbors.py to return the ordered first k neighbors for one
query. Save a trace containing the query ID, every selected neighbor's fields,
and the candidate order or enough evidence to reconstruct it.
The trace must be independent of any later label vote. A reader should be able to inspect which records were selected before seeing the predicted label.
Checks
Use a public fixture with an equal-distance tie and confirm that the earlier
reference row wins. Check that exactly k neighbors are returned, all belong to
the validated reference set, distances are non-decreasing, and equal-distance
rows follow original row order.
Recompute the complete distance vector and compare each selected record's distance and row position. Check that the query, reference arrays, and source ordering are not mutated.
Workspace
Keep ordering and neighbor records in src/neighbors.py; use distance
calculation from src/distance.py and validated rows from src/data.py. Write
the initial trace under output/neighbor_traces.json when the project runner
orchestrates this milestone.
Hints
HintKeep the original position
HintTrace before vote
Review
Read one trace from top to bottom and map every neighbor back to its source row. Explain why a deterministic tie rule makes a later vote reproducible.
How to check your work
Checks compare the selected records, tie behavior, and trace schema with the supplied fixture. The supplied fixture keeps ordering separate from prediction.