Skip to content

fix: copy_from_slice panic when k > number of indexed elements#40

Open
npiesco wants to merge 1 commit intorust-cv:mainfrom
npiesco:fix/copy-from-slice-panic
Open

fix: copy_from_slice panic when k > number of indexed elements#40
npiesco wants to merge 1 commit intorust-cv:mainfrom
npiesco:fix/copy-from-slice-panic

Conversation

@npiesco
Copy link
Copy Markdown

@npiesco npiesco commented Mar 9, 2026

Bug

search_layer in hnsw_const.rs panics with a copy_from_slice length mismatch when the requested number of neighbors (k / ef) exceeds the number of elements in the index.

Root cause

Two sites in search_layer (lines 309 and 321) use:

let found = core::cmp::min(dest.len(), searcher.nearest.len());
dest.copy_from_slice(&searcher.nearest[..found]);

copy_from_slice requires src.len() == dest.len(). When found < dest.len() (fewer elements in the index than requested), the source slice is shorter than dest → panic.

Fix

dest[..found].copy_from_slice(&searcher.nearest[..found]);

Slices dest to match found, which is what the next line (return &mut dest[..found]) already expects.

MRE

See tests/simple.rs::nearest_k_greater_than_index_size — inserts 8 vectors, searches with k=100:

#[test]
fn nearest_k_greater_than_index_size() {
    let (hnsw, mut searcher, _) = test_hnsw(); // 8 vectors
    let mut neighbors = vec![Neighbor { index: !0, distance: !0 }; 100];
    let found = hnsw.nearest(&&[0.0, 0.0, 0.0, 1.0][..], 100, &mut searcher, &mut neighbors);
    assert_eq!(found.len(), 8);
}

Before: panics with copy_from_slice: source slice length (8) does not match destination slice length (100)
After: returns 8 results

This surfaces whenever a caller passes k larger than the index size, or when filtered searches reduce the effective candidate set below k.

search_layer used dest.copy_from_slice(&src[..found]) where found < dest.len(),
causing a length mismatch panic. Fixed to dest[..found].copy_from_slice(&src[..found]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant