tech-trans-rag / tests /test_retrieval.py
phaethon-order's picture
feat: add embedding normalization utility and corresponding test
179360e
Raw History Blame Contribute Delete
22.4 kB
"""Regression tests for hybrid retrieval and grounded context handling."""
from __future__ import annotations
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Self
import pytest
from flask import Flask
from pgvector import Vector
from infrastructure import chunker, database, vector_search
from infrastructure.database import Chunk, Document
from infrastructure.retrieval_text import (
EMBEDDING_INPUT_VERSION,
build_embedding_input,
count_tokens,
embedding_input_sha256,
pack_context,
)
from routes import api
from scripts import evaluate_retrieval, reindex_embeddings
from services import gpt_service
def _candidate(
chunk_id: int,
text: str,
vector: list[float] | None,
*,
doc_id: int = 1,
) -> dict[str, Any]:
return {
"chunk_id": chunk_id,
"doc_id": doc_id,
"chunk_index": chunk_id - 1,
"text": text,
"embedding": vector,
"document_sha256": f"{doc_id:064x}",
}
def test_candidate_hydration_accepts_pgvector_wrapper() -> None:
candidate = database._candidate_from_row(
{
"chunk_id": 7,
"doc_id": 3,
"chunk_index": 1,
"text": "License grant",
"embedding": Vector([0.25, 0.75]),
}
)
assert candidate["embedding"] == pytest.approx([0.25, 0.75])
def test_rrf_and_mmr_are_deterministic_and_remove_exact_duplicates() -> None:
"""Hybrid agreement wins while duplicate chunk text is returned once."""
vector = [
_candidate(1, "Confidentiality obligations", [1.0, 0.0]),
_candidate(2, "Confidentiality obligations", [0.99, 0.01]),
_candidate(3, "Defined term Confidential Information", [0.0, 1.0]),
]
lexical = [
_candidate(3, "Defined term Confidential Information", [0.0, 1.0]),
_candidate(1, "Confidentiality obligations", [1.0, 0.0]),
]
first = vector_search.fuse_and_select(vector, lexical, top_k=3)
second = vector_search.fuse_and_select(vector, lexical, top_k=3)
assert [item["id"] for item in first] == ["1", "3"]
assert first == second
assert first[0]["selection_reason"] == "hybrid"
assert first[0]["vector_rank"] == 1
assert first[0]["lexical_rank"] == 2
assert "embedding" not in first[0]
def test_rrf_equal_scores_use_chunk_id_tie_breaking() -> None:
vector = [
_candidate(2, "Second chunk", [1.0, 0.0]),
_candidate(1, "First chunk", [0.0, 1.0]),
]
lexical = [
_candidate(1, "First chunk", [0.0, 1.0]),
_candidate(2, "Second chunk", [1.0, 0.0]),
]
selected = vector_search.fuse_and_select(vector, lexical, top_k=1)
assert selected[0]["id"] == "1"
def test_query_embedding_failure_falls_back_to_lexical_candidates(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""An embedding outage does not discard exact legal-term matches."""
lexical = [_candidate(7, "Affiliate means...", None)]
calls: dict[str, Any] = {}
monkeypatch.setattr(vector_search, "generate_embedding", lambda *_a, **_k: [])
monkeypatch.setattr(
vector_search,
"search_lexical_candidates",
lambda query, *, limit, filters: (
calls.update(query=query, limit=limit, filters=filters) or lexical
),
)
monkeypatch.setattr(
vector_search,
"search_vector_candidates",
lambda *_a, **_k: pytest.fail("vector search should not run"),
)
results = vector_search.find_nearest_neighbors(
"Define Affiliate", 5, where={"jurisdiction": "US-DE"}
)
assert [item["id"] for item in results] == ["7"]
assert results[0]["selection_reason"] == "lexical"
assert calls == {
"query": "Define Affiliate",
"limit": 20,
"filters": {"jurisdiction": "US-DE"},
}
def test_embedding_input_is_deterministic_and_keeps_original_text() -> None:
text = "The Licensee shall keep the source code confidential."
enriched = build_embedding_input(
text,
section_number="8.2",
section_title="Confidentiality",
clause_type="Nondisclosure",
definition_terms="Confidential Information",
)
assert "Section title: Confidentiality" in enriched
assert enriched.endswith(text)
assert embedding_input_sha256(enriched) == embedding_input_sha256(enriched)
def test_new_upload_does_not_write_partial_embedding_batch(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(chunker, "get_chunk_info", lambda *_args: {})
monkeypatch.setattr(
chunker,
"add_chunk",
lambda **values: Chunk(
chunk_id=int(values["chunk_index"]) + 1,
doc_id=int(values["doc_id"]),
chunk_index=int(values["chunk_index"]),
text=str(values["text"]),
),
)
monkeypatch.setattr(
chunker,
"generate_embeddings",
lambda *_args, **_kwargs: [[0.1, 0.2]],
)
monkeypatch.setattr(
chunker,
"upsert_embeddings",
lambda _records: pytest.fail("an incomplete batch must not be persisted"),
)
chunk_ids = chunker.chunk_doc("one\n\ntwo", doc_id=4, max_chars=5, overlap=0)
assert chunk_ids == [1, 2]
def test_context_packing_skips_lower_ranked_chunks_and_truncates_only_first() -> None:
first = {"chunk_id": 1, "text": "A" * 900}
second = {"chunk_id": 2, "text": "short but cannot fit after the first"}
packed = pack_context([first, second], max_tokens=100)
assert len(packed) == 1
assert packed[0]["chunk_id"] == 1
assert packed[0]["truncated"] is True
assert count_tokens(str(packed[0])) <= 110
def test_query_payload_validation_and_filter_allowlist(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("TOP_K_RESULTS", "6")
monkeypatch.setenv("MAX_QUERY_LENGTH", "20")
query, top_k, filters = api._parse_query_payload(
{
"query": " Define Affiliate ",
"filters": {"doc_id": 9, "jurisdiction": " us-de "},
}
)
assert (query, top_k) == ("Define Affiliate", 6)
assert filters == {"doc_id": 9, "jurisdiction": "us-de"}
with pytest.raises(ValueError, match="unsupported filters"):
api._parse_query_payload({"query": "test", "filters": {"title": "NDA"}})
with pytest.raises(ValueError, match="top_k"):
api._parse_query_payload({"query": "test", "top_k": 21})
with pytest.raises(TypeError, match="top_k"):
api._parse_query_payload({"query": "test", "top_k": 5.0})
with pytest.raises(TypeError, match="filters"):
api._parse_query_payload({"query": "test", "filters": None})
with pytest.raises(ValueError, match="doc_id"):
api._parse_query_payload({"query": "test", "filters": {"doc_id": "9"}})
with pytest.raises(ValueError, match="at most 20"):
api._parse_query_payload({"query": "x" * 21})
def test_query_endpoint_sends_rich_bounded_context(
monkeypatch: pytest.MonkeyPatch,
) -> None:
document = Document(
doc_id=4,
sha256="a" * 64,
title="NDA",
doc_type="NDA",
jurisdiction="US-DE",
governing_law="US-DE",
)
chunk = Chunk(
chunk_id=9,
doc_id=4,
chunk_index=2,
text="Affiliate means an entity under common control.",
token_count=12,
page_start=3,
page_end=3,
section_number="1.1",
section_title="Definitions",
clause_type="Definitions",
definition_terms="Affiliate",
document=document,
)
neighbor = {
"id": "9",
"rank": 1,
"distance": 0.1,
"vector_rank": 2,
"lexical_rank": 1,
"rrf_score": 0.03,
"selection_reason": "hybrid",
}
captured: dict[str, Any] = {}
monkeypatch.setattr(api, "find_nearest_neighbors", lambda **_kwargs: [neighbor])
monkeypatch.setattr(api, "get_chunks_by_ids", lambda _ids: [chunk])
monkeypatch.setattr(
api,
"refine_query_response",
lambda query, context: (
captured.update(query=query, context=context)
or {"response": "An Affiliate is...", "sources": []}
),
)
monkeypatch.setenv("MAX_CONTEXT_LENGTH", "4000")
app = Flask(__name__)
app.register_blueprint(api.api_bp)
response = app.test_client().post(
"/api/query",
json={
"query": "Define Affiliate",
"top_k": 5,
"filters": {"jurisdiction": "US-DE"},
},
)
assert response.status_code == 200
body = response.get_json()
assert body["retrieval"]["method"] == "hybrid_rrf_mmr_v1"
assert body["results"][0]["section_title"] == "Definitions"
assert body["results"][0]["lexical_rank"] == 1
assert captured["context"] == body["results"]
def test_query_endpoint_keeps_full_result_text_when_prompt_copy_is_truncated(
monkeypatch: pytest.MonkeyPatch,
) -> None:
full_text = "A" * 1200
chunk = Chunk(chunk_id=9, doc_id=4, chunk_index=0, text=full_text)
neighbor = {
"id": "9",
"rank": 1,
"vector_rank": 1,
"rrf_score": 0.02,
"selection_reason": "vector",
}
captured: dict[str, Any] = {}
monkeypatch.setattr(api, "find_nearest_neighbors", lambda **_kwargs: [neighbor])
monkeypatch.setattr(api, "get_chunks_by_ids", lambda _ids: [chunk])
monkeypatch.setattr(
api,
"refine_query_response",
lambda _query, context: (
captured.update(context=context) or {"response": "answer", "sources": []}
),
)
monkeypatch.setenv("MAX_CONTEXT_LENGTH", "250")
app = Flask(__name__)
app.register_blueprint(api.api_bp)
response = app.test_client().post(
"/api/query", json={"query": "Summarize", "top_k": 1}
)
body = response.get_json()
assert response.status_code == 200
assert body["results"][0]["text"] == full_text
assert body["results"][0]["context_truncated"] is True
assert len(captured["context"][0]["text"]) < len(full_text)
def test_query_endpoint_rejects_malformed_top_k() -> None:
app = Flask(__name__)
app.register_blueprint(api.api_bp)
response = app.test_client().post(
"/api/query", json={"query": "test", "top_k": "many"}
)
assert response.status_code == 400
assert "top_k" in response.get_json()["error"]
def test_model_citations_are_rebuilt_from_supplied_context() -> None:
context = [
{
"chunk_id": 9,
"doc_id": 4,
"section_number": "1.1",
"section_title": "Definitions",
"document": {"doc_type": "NDA", "jurisdiction": "US-DE"},
}
]
sources = [
{
"doc_id": 999,
"chunks": [
{"chunk_id": 9, "section_title": "Invented"},
{"chunk_id": 12345},
],
}
]
validated = gpt_service._validated_sources(sources, context)
assert validated == [
{
"doc_id": 4,
"doc_type": "NDA",
"jurisdiction": "US-DE",
"chunks": [
{
"chunk_id": 9,
"section_number": "1.1",
"section_title": "Definitions",
}
],
}
]
def test_unsupported_model_citation_uses_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Completions:
@staticmethod
def create(**_kwargs: object) -> SimpleNamespace:
content = json.dumps(
{
"response": "An Affiliate is under common control.",
"sources": [{"chunks": [{"chunk_id": 999}]}],
}
)
return SimpleNamespace(
choices=[SimpleNamespace(message=SimpleNamespace(content=content))]
)
client = SimpleNamespace(chat=SimpleNamespace(completions=Completions()))
monkeypatch.setattr(gpt_service, "OPENAI_API_KEY", "test-key")
monkeypatch.setattr(gpt_service.openai, "OpenAI", lambda **_kwargs: client)
response = gpt_service.refine_query_response(
"Define Affiliate", [{"chunk_id": 1, "doc_id": 2, "text": "context"}]
)
assert response == {
"response": "Insufficient information to provide an answer.",
"sources": [],
}
def test_malformed_model_json_uses_insufficient_information_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Completions:
@staticmethod
def create(**_kwargs: object) -> SimpleNamespace:
message = SimpleNamespace(content="not json")
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
client = SimpleNamespace(chat=SimpleNamespace(completions=Completions()))
monkeypatch.setattr(gpt_service, "OPENAI_API_KEY", "test-key")
monkeypatch.setattr(gpt_service.openai, "OpenAI", lambda **_kwargs: client)
response = gpt_service.refine_query_response(
"Define Affiliate", [{"chunk_id": 1, "doc_id": 2, "text": "context"}]
)
assert response == {
"response": "Insufficient information to provide an answer.",
"sources": [],
}
def test_backfill_is_dry_run_by_default_and_resumable(
monkeypatch: pytest.MonkeyPatch,
) -> None:
chunk = Chunk(
chunk_id=12,
doc_id=3,
chunk_index=0,
text="A license grant.",
embedding_input_version=1,
)
calls = 0
def batches(*, after_chunk_id: int, limit: int) -> list[Chunk]:
nonlocal calls
calls += 1
return [chunk] if calls == 1 else []
monkeypatch.setattr(reindex_embeddings, "get_embedding_backfill_batch", batches)
monkeypatch.setattr(
reindex_embeddings,
"generate_embeddings",
lambda *_a, **_k: pytest.fail("dry-run must not call OpenAI"),
)
monkeypatch.setattr(
reindex_embeddings,
"upsert_embeddings",
lambda *_a, **_k: pytest.fail("dry-run must not mutate Neon"),
)
summary = reindex_embeddings.backfill_embeddings(apply=False, batch_size=10)
assert summary == {
"scanned": 1,
"stale": 1,
"updated": 0,
"failed": 0,
"last_chunk_id": 12,
}
def test_backfill_skips_current_compatible_embedding(
monkeypatch: pytest.MonkeyPatch,
) -> None:
text = "A current license grant."
embedding_input = build_embedding_input(text)
chunk = Chunk(
chunk_id=12,
doc_id=3,
chunk_index=0,
text=text,
embedding_input_version=EMBEDDING_INPUT_VERSION,
embedding_input_sha256=embedding_input_sha256(embedding_input),
embedding_model=reindex_embeddings.DEFAULT_MODEL,
embedding_dim=2,
has_embedding=True,
)
batches = iter([[chunk], []])
monkeypatch.setattr(
reindex_embeddings,
"get_embedding_backfill_batch",
lambda **_kwargs: next(batches),
)
monkeypatch.setattr(
reindex_embeddings,
"generate_embeddings",
lambda *_a, **_k: pytest.fail("current embeddings must not be regenerated"),
)
summary = reindex_embeddings.backfill_embeddings(apply=True)
assert summary["stale"] == 0
assert summary["updated"] == 0
assert summary["last_chunk_id"] == 12
def test_backfill_replaces_vectors_only_after_complete_generation(
monkeypatch: pytest.MonkeyPatch,
) -> None:
chunk = Chunk(chunk_id=2, doc_id=1, chunk_index=0, text="License grant")
batches = iter([[chunk], []])
written: list[dict[str, Any]] = []
monkeypatch.setattr(
reindex_embeddings,
"get_embedding_backfill_batch",
lambda **_kwargs: next(batches),
)
monkeypatch.setattr(
reindex_embeddings, "generate_embeddings", lambda *_a, **_k: [[0.1, 0.2]]
)
monkeypatch.setattr(
reindex_embeddings,
"upsert_embeddings",
lambda records: written.extend(records) or len(records),
)
summary = reindex_embeddings.backfill_embeddings(apply=True)
assert summary["updated"] == 1
assert written[0]["input_version"] == EMBEDDING_INPUT_VERSION
assert written[0]["chunk_id"] == 2
def test_backfill_failure_preserves_safe_resume_checkpoint(
monkeypatch: pytest.MonkeyPatch,
) -> None:
chunk = Chunk(chunk_id=12, doc_id=3, chunk_index=0, text="License grant")
monkeypatch.setattr(
reindex_embeddings,
"get_embedding_backfill_batch",
lambda **_kwargs: [chunk],
)
monkeypatch.setattr(reindex_embeddings, "generate_embeddings", lambda *_a, **_k: [])
monkeypatch.setattr(
reindex_embeddings,
"upsert_embeddings",
lambda _records: pytest.fail("failed generation must not replace vectors"),
)
summary = reindex_embeddings.backfill_embeddings(
apply=True,
after_chunk_id=5,
)
assert summary == {
"scanned": 1,
"stale": 1,
"updated": 0,
"failed": 1,
"last_chunk_id": 5,
}
def test_search_candidate_filters_are_bound_in_both_queries(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Result:
def fetchall(self) -> list[dict[str, Any]]:
return []
class Connection:
def __init__(self) -> None:
self.calls: list[tuple[str, list[Any]]] = []
def __enter__(self) -> Self:
return self
def __exit__(self, *_args: object) -> None:
return None
def execute(self, statement: Any, parameters: list[Any]) -> Result:
self.calls.append((statement.as_string(), parameters))
return Result()
connection = Connection()
monkeypatch.setattr(database, "_connect", lambda **_kwargs: connection)
filters = {"doc_id": 4, "jurisdiction": "US-DE"}
database.search_vector_candidates(
[0.1, 0.2], model="embedding-test", limit=20, filters=filters
)
database.search_lexical_candidates("Affiliate", limit=20, filters=filters)
vector_sql, vector_params = connection.calls[0]
lexical_sql, lexical_params = connection.calls[1]
assert "c.doc_id = %s" in vector_sql and "jurisdiction" in vector_sql
assert "lower(trim" in vector_sql
assert vector_params[1:5] == ["embedding-test", 2, 4, "us-de"]
assert "websearch_to_tsquery" in lexical_sql and "jurisdiction" in lexical_sql
assert lexical_params == ["Affiliate", 4, "us-de", 20]
def test_schema_initialization_statements_are_idempotent(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Cursor:
def __init__(self) -> None:
self.statements: list[str] = []
def __enter__(self) -> Self:
return self
def __exit__(self, *_args: object) -> None:
return None
def execute(self, statement: str) -> None:
self.statements.append(statement)
class Connection:
def __init__(self) -> None:
self.db_cursor = Cursor()
def __enter__(self) -> Self:
return self
def __exit__(self, *_args: object) -> None:
return None
def cursor(self) -> Cursor:
return self.db_cursor
def commit(self) -> None:
return None
connections: list[Connection] = []
def connect(**_kwargs: object) -> Connection:
connection = Connection()
connections.append(connection)
return connection
monkeypatch.setattr(database, "_connect", connect)
database.init_db()
database.init_db()
for connection in connections:
sql_text = "\n".join(connection.db_cursor.statements)
assert "ADD COLUMN IF NOT EXISTS search_tsv" in sql_text
assert "CREATE INDEX IF NOT EXISTS chunks_search_tsv_idx" in sql_text
assert "embedding_input_version" in sql_text
assert "{TOK_VER}" not in sql_text
def test_retrieval_metrics_use_stable_document_and_chunk_identity() -> None:
relevant = [
{"document_sha256": "a" * 64, "chunk_index": 2, "grade": 3},
{"document_sha256": "b" * 64, "chunk_index": 0, "grade": 1},
]
results = [
{"document_sha256": "a" * 64, "chunk_index": 2},
{"document_sha256": "c" * 64, "chunk_index": 4},
]
metrics = evaluate_retrieval.retrieval_metrics(results, relevant, k=5)
assert metrics["recall"] == 0.5
assert metrics["mrr"] == 1.0
assert 0.0 < metrics["ndcg"] < 1.0
def test_acceptance_comparison_enforces_quality_filter_and_latency_gates() -> None:
baseline = {
"overall": {"ndcg": 0.50, "recall": 0.60, "mrr": 0.70},
"categories": {"paraphrase": {"ndcg": 0.50}},
"latency_ms": {"p95": 300.0},
}
candidate = {
"overall": {"ndcg": 0.56, "recall": 0.61, "mrr": 0.70},
"categories": {"paraphrase": {"ndcg": 0.51}},
"latency_ms": {"p95": 500.0},
"filter_leaks": 0,
"deterministic": True,
}
acceptance = evaluate_retrieval.compare(candidate, baseline)
assert acceptance["passed"] is True
assert all(acceptance["checks"].values())
def test_benchmark_loader_requires_reviewed_rows_and_acceptance_size(
tmp_path: Path,
) -> None:
row = {
"benchmark_version": 1,
"query_id": "defined-term-1",
"category": "defined_term",
"query": "Define Affiliate",
"filters": {},
"relevant": [{"document_sha256": "a" * 64, "chunk_index": 2, "grade": 3}],
"review_status": "approved",
"reviewed_by": "legal-reviewer",
}
benchmark = tmp_path / "benchmark.jsonl"
benchmark.write_text(json.dumps(row) + "\n", encoding="utf-8")
loaded = evaluate_retrieval.load_benchmark(benchmark, allow_small=True)
assert loaded == [row]
with pytest.raises(ValueError, match="at least 40"):
evaluate_retrieval.load_benchmark(benchmark)
repeated_rows = []
for index in range(40):
repeated = dict(row)
repeated["query_id"] = f"defined-term-{index}"
repeated_rows.append(json.dumps(repeated))
benchmark.write_text("\n".join(repeated_rows) + "\n", encoding="utf-8")
with pytest.raises(ValueError, match="missing categories"):
evaluate_retrieval.load_benchmark(benchmark)