DEV Community

How to Measure Vector Search Recall@K When Distances Tie

Two vector indexes return the three closest matches to the same query. They agree on just one document. Your recall test reports 33%, so you start tuning the new index.

Before you change a setting, check the distances. Both indexes may have returned an exact answer.

There’s a second trap. Suppose you fix the test by accepting every document within the third neighbor’s distance. Now the new index can leave out the closest document and still score 100%.

You can reproduce both outcomes with six bytes and a few lines of Python. The question that resolves them is simple. How many IDs in this response could appear together in one valid top-three answer?

That question gives you a test you can use when rebuilding a vector index, switching search libraries, or adding a binary candidate stage to a retrieval pipeline.

Build a query with two different correct answers

Imagine a help-center search box that returns three article IDs. Internally, a search stage represents each article with a binary code. For this example, each code is just eight bits. The query is eight zero bits. Hamming distance counts the positions where two codes differ, so you can read each distance by counting the ones.

Article ID Binary code Distance to query
A 00000000 0
B 00000001 1
C 00000010 1
D 00000100 1
E 00001000 1
F 00000011 2

A belongs in every exact top three. Four articles compete for the remaining two places. An exhaustive search that breaks ties by ascending ID gives A, B, C. A second exhaustive search could give A, D, E.

The codes for B and D are different. They tie because they sit the same distance from this query. Removing identical vectors would change nothing here.

Try the reverse case with B, C, D. Every item is within one bit of the query. Yet this response omits the only exact match. In a search box for known items, that missing first result could be the one document a user came to find. You can detect the omission even if you have no human labels for the other four articles.

Decide what a hit means in your benchmark

One common test saves a list of exact IDs, intersects it with the returned IDs, and divides by the requested count. The Sentence Transformers Faiss example uses this approach. It answers a useful question when you need to reproduce a particular set of IDs. With an arbitrary tie-break, a low score can also tell you about insertion order or ID order.

Sentence Transformers search example

Another test counts returned IDs within the distance of the exact kth neighbor. The ANN-Benchmarks paper describes this definition. It answers “How many of our hits are at least this close?” That fits a distance threshold. A move from A, D, E to B, C, D goes undetected because all six positions across the two responses meet the cutoff.

ANN-Benchmarks quality measures

For a top-k membership test, split the eligible records into two groups. Every ID strictly closer than the cutoff owns a place. IDs at the cutoff share the places left over. Give a point for each closer ID returned. Then give a point for each distinct tied ID returned, up to the number of shared places. Divide by the number of places the query can fill.

This computes the best overlap with any valid exact top-k set. Loh and Lee give this interpretation of recall for ties in their work on per-query recall guarantees.

Paper and appendix

Returned IDs Overlap with A, B, C Within distance 1 Best overlap with a valid top three
A, B, C 3/3 3/3 3/3
A, D, E 1/3 3/3 3/3
B, C, D 2/3 3/3 2/3
A, D, F 1/3 2/3 2/3

Read the last two rows together. Both responses earn two points in the final column. One missed A. The other returned a document outside the cutoff. If a release fails, keep the IDs and distances for the failing query. The scalar score alone loses the detail you need to choose a fix.

Write a tie-aware recall test in Python

This example runs on Python 3.10 or later with the standard library. Supply a mapping from every eligible ID to its exact distance. The returned list is in the same order the application received it. Slicing that list before removing duplicate IDs makes each wasted position count.

def top_k_overlap ( exact_distance , returned_ids , k ) :
  if k < 1 :
    raise ValueError ( "k must be positive" )
  target = min ( k , len ( exact_distance ) )
  if target == 0 :
    return None
  cutoff = sorted ( exact_distance . values ( ) ) [ target - 1 ]
  closer = { i for i , d in exact_distance . items ( ) if d < cutoff }
  tied = { i for i , d in exact_distance . items ( ) if d == cutoff }
  hits = set ( returned_ids [ : k ] )
  fixed_hits = len ( hits & closer )
  shared_slots = target - len ( closer )
  shared_hits = min ( shared_slots , len ( hits & tied ) )
  return ( fixed_hits + shared_hits ) / target

codes = { "A" : 0 , "B" : 1 , "C" : 2 , "D" : 4 , "E" : 8 , "F" : 3 }
query = 0
distances = { i : ( query ^ code ) . bit_count ( ) for i , code in codes . items ( ) }
assert top_k_overlap ( distances , [ "A" , "D" , "E" ] , 3 ) == 1
assert top_k_overlap ( distances , [ "B" , "C" , "D" ] , 3 ) == 2 / 3
assert top_k_overlap ( distances , [ "A" , "D" , "F" ] , 3 ) == 2 / 3
assert top_k_overlap ( distances , [ "A" , "A" , "D" , "E" ] , 3 ) == 2 / 3
assert top_k_overlap ( distances , [ "A" ] , 3 ) == 1 / 3
assert top_k_overlap ( { "A" : 0 } , [ "A" ] , 3 ) == 1
assert top_k_overlap ( { } , [ ] , 3 ) is None

The fourth assertion catches an easy mistake in evaluation code. An adapter might remove the second A, pull E into view, and award full credit. A reader who saw the first three positions got A twice. Score the response at the same point where your application promises three results. If the application itself deduplicates and refills before display, capture the list after that operation.

The last two assertions cover small collections. If a tenant has only one eligible document, returning it fills every possible place. If there are none, report an empty-collection case separately. A stream of empty queries can make a broken index look healthy if you assign each one a perfect score. Also count unknown or out-of-scope IDs as contract failures, even if a query has too few eligible records to expose the error through recall alone.

Connect the test to your actual search library

Start with one query for which your exact and approximate paths disagree. Save its vector, metric, requested count, eligible corpus revision and returned IDs. If your SDK uses internal row numbers, resolve those numbers through the ID map from that same index build. A rebuild can change row positions while leaving every document and every distance intact.

Make the reference independent of the result

For a small fixture, score every eligible vector directly. Faiss offers an exhaustive Hamming search through IndexBinaryFlat for packed binary codes. An exact search for just three IDs tells you the third distance, but its response can omit other IDs tied there. Recompute distances for the full fixture, or store the cutoff, the number of strictly closer IDs, and enough reference data to score each returned ID. Using only the approximate results to discover the cutoff makes a missing nearest neighbor hard to detect.

Faiss binary indexes

Check your score direction before porting the code. Hamming and squared L2 distances reward smaller values. Inner product rewards larger ones. For a similarity score, sort descending and treat values strictly above the kth score as required. A quick check is to run one query whose closest document you know, replace that ID with a distant one, and verify that the score falls.

Freeze the eligibility rules

Suppose the help center offers English and French editions, and the caller asks for French only. Compute the exact distances on French records accessible to that caller. Taking three neighbors from the entire collection and filtering afterward might leave one French result even though hundreds qualify. That shortened list makes a poor baseline.

Keep the same language, access rules and deletion snapshot on both sides of the comparison. An especially revealing check is to add a closer record outside the test tenant. The expected top three for the tenant should stay the same. If an adapter returns the new record, fail the access test immediately. Keep that failure visible even when retrieval metrics are averaged over thousands of queries.

Evaluate a binary candidate stage and a dense reranker

Consider a system that retrieves 50 binary candidates, rescoring them with the original dense vectors before showing three documents. You have two useful questions. Did the candidate search preserve the nearest binary codes? And did those 50 IDs include the documents the dense scorer would choose? Answering the first one gives no guarantee about the second.

Take the six articles again. Suppose a dense reference ranks E first, A second and F third, with distinct scores. A binary candidate list containing A, B, C has perfect binary top-three membership. A dense reranker working with those candidates can recover only A from the dense reference. Increasing the reranker’s precision cannot recover E or F from a list that excluded them.

Measure candidate coverage by comparing all candidate IDs with the target dense top three. In this example, coverage is one third. If the next experiment retrieves A, B, C, E, F, coverage rises to three thirds. With the same dense scoring function and distinct scores, sorting that second list puts the correct three on screen.

Record the actual candidate count alongside coverage. A metadata filter can leave you with fewer candidates than you requested. When dense scores also tie, apply the same shared-place cap to matches from the entire candidate pool. Keep the denominator at the final display count, and inspect all 50 candidates. The Python function above slices to the display count because it scores final responses. Passing an unsorted candidate pool straight into it would silently discard 47 chances to recover a winner.

Read a failing release check

Start the investigation with the first query where fixed-ID overlap and the tie-aware result disagree. Write down the cutoff, the IDs closer than it, and how many places remain open. If the new list contains every required ID and fills the open places, the nearest-neighbor membership check passes. You can then decide whether a stable display order matters to this surface.

If a required ID is missing, look for it in the candidate list before reranking. An absent ID points you toward candidate depth, index search settings, eligibility rules or stale data. An ID present before reranking but missing afterward points you toward score direction, vector versions or final selection. Keep the query as a regression example once you know which change restores it.

For a release review, pair each query from the old build with the same query on the new one. Separate queries with more tied IDs than open places from queries with a unique membership set. A change in ID overlap confined to the first group has a different explanation from a drop on both. Keep a small table of individual losses next to the averages. A team can tolerate a change in the order of several equally close glossary entries and still care deeply about losing the exact match for a product code.

To test the scorer itself, shuffle the order of the six input records and repeat the assertions. The fixture should keep the same scores in every order. Then change A’s code from zero to a one-bit value. Now all five nearby records tie for all three places, and B, C, D should earn full credit. These two edits test different assumptions about what the scorer treats as interchangeable.

If both retrieval stages pass and the answer still cites the wrong paragraph, move the investigation downstream or upstream as the evidence warrants. Inspect what the encoder saw for the missing passage and which retrieved passages actually reached the prompt. A nearest-neighbor test ends at the ranked IDs.

Test for embedding truncation · Inspect the RAG context budget

FAQ

When should I keep strict ID overlap? Keep it when a client depends on a specific identity. For example, a search API might promise to prefer the current edition of a manual when distances tie. Encode edition priority and a stable final ID in the reference sort. Check order separately if the first item is part of the promise. Set overlap gives a reversed list full credit.

Should I round cosine scores to detect ties? Use the precision and scoring rule that define your reference. Two scores that both display as 0.812 can differ enough to rank consistently at full precision. If your application intentionally groups scores into buckets, define those buckets before the test and report them. For a numerical tolerance experiment, keep a second result under the original precision so readers can see which decisions changed.

How can I tell whether ties affect my corpus? For each sampled query, count the IDs at the cutoff and the places available to them. A boundary with three IDs for three places allows different ordering, but it has only one valid membership set. A boundary with four IDs for two places allows six sets. Report the fraction of queries where the first count exceeds the second.

Does tie-aware recall measure whether the passage answers the question? That requires relevance evidence. Ask a reviewer to mark which passages support the answer, or use a query set with known supporting documents. An index can reproduce every exact neighbor of an embedding and still surface an irrelevant paragraph. Track neighbor membership for index fidelity and judged retrieval for the reader’s task.

What should a small team keep as a regression fixture? Keep the short binary example for the metric itself. Add one real query with its eligible IDs and reference distances, one query that returns too few results, and one query where the caller can access only a single record. Together they exercise the scoring rule, your ID mapping, the denominator and the filter path. A failure then tells the next en

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.