Skip to content

Commit 50fbff4

Browse files
committed
deduplicate search results before assigning RRF ranks
1 parent bb30185 commit 50fbff4

2 files changed

Lines changed: 93 additions & 5 deletions

File tree

‎serviette/server/ranking.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,20 @@ def rrf_merge(
2222
) -> list[dict[str, Any]]:
2323
"""Fuse ranked result lists with reciprocal-rank fusion.
2424
25-
A hit appearing in several lists (same ``text``) sums its 1/(RRF_K + rank)
26-
contributions, so chunks that answer *several* sub-queries rise. The fused
27-
RRF value replaces ``score`` — original per-query similarities are not
28-
comparable across lists.
25+
Each list votes once per distinct ``text``, ranked in first-occurrence
26+
order after duplicates are removed. A text appearing in several lists
27+
sums its 1/(RRF_K + rank) contributions, rewarding agreement between
28+
searches. The fused RRF value replaces ``score`` — original scores are
29+
not comparable across lists.
2930
"""
3031

3132
fused: dict[str, dict[str, Any]] = {}
3233
scores: dict[str, float] = {}
3334
for hits in result_lists:
34-
for rank, hit in enumerate(hits):
35+
unique: dict[str, dict[str, Any]] = {}
36+
for hit in hits:
37+
unique.setdefault(hit["text"], hit)
38+
for rank, hit in enumerate(unique.values()):
3539
key = hit["text"]
3640
scores[key] = scores.get(key, 0.0) + 1.0 / (RRF_K + rank + 1)
3741
# Keep the first-seen dict (embedding included when present).

‎tests/test_rag_quality.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,90 @@ def test_rrf_merge_rewards_presence_in_multiple_lists():
473473
assert {m["text"] for m in merged} == {"x", "y", "z"}
474474

475475

476+
@pytest.mark.parametrize("copies", [1, 2, 10])
477+
def test_rrf_merge_ranks_unique_texts_within_each_list(copies):
478+
a = {"text": "a", "score": 0.9}
479+
b = {"text": "b", "score": 0.8}
480+
c = {"text": "c", "score": 0.7}
481+
merged = rrf_merge([[a, *([b] * copies), c], [a, b]], 3)
482+
assert [hit["text"] for hit in merged] == ["a", "b", "c"]
483+
assert [hit["score"] for hit in merged] == pytest.approx([2 / 61, 2 / 62, 1 / 63])
484+
485+
486+
@pytest.mark.parametrize("copies", [1, 3, 10])
487+
@pytest.mark.parametrize("limit", [0, 1, 3, 10])
488+
@pytest.mark.parametrize("placement", ["adjacent", "at_end"])
489+
def test_rrf_merge_is_unchanged_when_copies_are_inserted(copies, limit, placement):
490+
lists = [
491+
[{"text": text, "score": 0.9} for text in ("a", "b", "c")],
492+
[],
493+
[{"text": text, "score": 0.1} for text in ("d", "b", "e", "a")],
494+
]
495+
repeated = (
496+
[[hit for hit in hits for _ in range(copies + 1)] for hits in lists]
497+
if placement == "adjacent"
498+
else [hits * (copies + 1) for hits in lists]
499+
)
500+
assert rrf_merge(repeated, limit) == rrf_merge(lists, limit)
501+
502+
503+
def test_rrf_merge_preserves_the_first_hits_metadata_and_embedding():
504+
import copy
505+
506+
first = {"text": "same text", "metadata": {"path": "first.txt"},
507+
"embedding": [1.0, 0.0], "score": 0.5}
508+
other = {"text": "same text", "metadata": {"path": "other.txt"},
509+
"embedding": [0.0, 1.0], "score": 99.0}
510+
lists = [[first, other], [other]]
511+
original = copy.deepcopy(lists)
512+
merged = rrf_merge(lists, 3)
513+
assert merged == [{**first, "score": 2 / 61}]
514+
assert lists == original
515+
516+
517+
def test_rrf_merge_does_not_evict_an_answer_for_repeated_boilerplate():
518+
hits = {text: {"text": text, "score": 0.5} for text in ("a", "b", "c", "d", "e")}
519+
merged = rrf_merge(
520+
[[hits[text] for text in ("c", "a", "e")],
521+
[hits[text] for text in ("d", "b", "b")]],
522+
3,
523+
)
524+
assert [hit["text"] for hit in merged] == ["c", "d", "a"]
525+
526+
527+
def test_hybrid_retrieval_is_unchanged_by_a_duplicate_text(tmp_path, mock_server_embedder):
528+
import json
529+
530+
import duckdb
531+
532+
path = tmp_path / "duplicates.duckdb"
533+
texts = [
534+
"payment term is thirty days",
535+
"payment term conditions",
536+
"payment term annual invoice and notice details",
537+
]
538+
rows = [{"id": str(i), "text": text, "metadata": {"path": f"{i}.txt"},
539+
"embedding": fake_embedding(text)} for i, text in enumerate(texts)]
540+
write_duckdb_rows(path, rows)
541+
542+
def retrieve():
543+
with TestClient(_app(path, mock_server_embedder, hybrid=True)) as client:
544+
response = client.post("/api/v1/retrieve", json={"query": texts[0], "k": 10})
545+
assert response.status_code == 200
546+
return [(hit["text"], hit["score"]) for hit in response.json()["results"]]
547+
548+
before = retrieve()
549+
with duckdb.connect(str(path)) as conn:
550+
conn.execute(
551+
"INSERT INTO serviette_embeddings VALUES (?, ?, ?, ?)",
552+
["duplicate", texts[1], json.dumps({"path": "duplicate.txt"}),
553+
fake_embedding(texts[1])],
554+
)
555+
after = retrieve()
556+
assert len(before) == 3
557+
assert after == before
558+
559+
476560
# ---------------------------------------------------------------------------
477561
# LLM reranker
478562
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)