@@ -389,7 +389,8 @@ void HNSWIndex<DataType, DistType>::removeExtraLinks(
389389 size_t removed_idx = 0 ;
390390 size_t link_idx = 0 ;
391391
392- while (orig_candidates.size () > 0 ) {
392+ // candidates <= orig_candidates
393+ while (candidates.size () > 0 ) {
393394 if (orig_candidates.top ().second != candidates.top ().second ) {
394395 if (neighbors_bitmap[orig_candidates.top ().second ]) {
395396 removed_links[removed_idx++] = orig_candidates.top ().second ;
@@ -401,6 +402,15 @@ void HNSWIndex<DataType, DistType>::removeExtraLinks(
401402 orig_candidates.pop ();
402403 }
403404 }
405+
406+ assert (candidates.empty () && " candidates should be empty" );
407+ // Handle remaining elements in orig_candidates that were rejected by heuristic
408+ while (orig_candidates.size () > 0 ) {
409+ if (neighbors_bitmap[orig_candidates.top ().second ]) {
410+ removed_links[removed_idx++] = orig_candidates.top ().second ;
411+ }
412+ orig_candidates.pop ();
413+ }
404414 setListCount (node_ll, link_idx);
405415 *removed_links_num = removed_idx;
406416}
@@ -466,7 +476,10 @@ DistType HNSWIndex<DataType, DistType>::processCandidate(
466476 }
467477 // Pre-fetch the neighbours list of the top candidate (the one that is going
468478 // to be processed in the next iteration) into memory cache, to improve performance.
469- __builtin_prefetch (get_linklist_at_level (candidate_set.top ().second , layer));
479+ if (!candidate_set.empty ()) {
480+ assert (links_num);
481+ __builtin_prefetch (get_linklist_at_level (candidate_set.top ().second , layer));
482+ }
470483
471484 return lowerBound;
472485}
@@ -515,7 +528,10 @@ void HNSWIndex<DataType, DistType>::processCandidate_RangeSearch(
515528 }
516529 // Pre-fetch the neighbours list of the top candidate (the one that is going
517530 // to be processed in the next iteration) into memory cache, to improve performance.
518- __builtin_prefetch (get_linklist_at_level (candidate_set.top ().second , layer));
531+ if (!candidate_set.empty ()) {
532+ assert (links_num);
533+ __builtin_prefetch (get_linklist_at_level (candidate_set.top ().second , layer));
534+ }
519535}
520536
521537template <typename DataType, typename DistType>
0 commit comments