Spaces:
Build error

trackademi / tests /test_retrieval_fallback_logging.py
anwarKXC
fix(retrieval): only warn about the RAG fallback when it actually ran
b68706b
Raw History Blame Contribute Delete
2.76 kB
# -*- coding: utf-8 -*-
"""The "RAG fallback activated" warning must fire ONLY when the fallback ran.
2026-08-06: the warning sat inside the `if merged:` block that attaches
image_refs, not inside the `if not merged:` fallback block. It therefore fired
on every search that returned anything at all — including searches where hybrid
worked perfectly.
A false alarm on every query is worse than no log line. It trains you to ignore
the message, so the one time hybrid search really does collapse to the relaxed
nearest-neighbour path — which returns lower-quality context — nothing stands
out. That exact degradation has happened before on this corpus (see
RAG_MIN_SIMILARITY in config.py), which is why the warning exists.
"""
import inspect
import re
from app.services.retrieval import RetrievalService
def _search_source() -> str:
return inspect.getsource(RetrievalService.search)
def test_fallback_warning_is_inside_the_fallback_branch():
src = _search_source()
fallback_branch = src.index("if not merged:")
warning = src.index("RAG fallback activated")
assert warning > fallback_branch, (
"the fallback warning must come after `if not merged:` — it fired "
"unconditionally when it lived in the image_refs block"
)
# It must also sit at the fallback block's indentation, not dedented back
# out to the method body (which is how it escaped the branch last time).
line = next(ln for ln in src.splitlines() if "RAG fallback activated" in ln)
indent = len(line) - len(line.lstrip())
assert indent >= 16, f"warning dedented out of the fallback branch (indent={indent})"
def test_fallback_warning_appears_exactly_once():
assert _search_source().count("RAG fallback activated") == 1
def test_image_refs_block_does_not_log_the_fallback():
"""The `if merged:` image_refs block is where the warning wrongly lived."""
src = _search_source()
img = src.index("chunk_ids = [c.id for c in merged]")
tail = src[img:]
# Everything after the image_refs block starts is the summary log only.
assert "RAG fallback activated" not in tail, (
"fallback warning is back inside the image_refs branch"
)
def test_fallback_still_reports_how_many_chunks_it_returned():
"""The count must be read after `merged` is repopulated, or it logs 0."""
src = _search_source()
warning_at = src.index("RAG fallback activated")
before = src[:warning_at]
assert "relaxed_rows.fetchall()" in before, (
"warning must come after the relaxed query populates merged, "
"otherwise it always reports 0 chunks"
)
after = src[warning_at:warning_at + 400]
assert re.search(r"len\(merged\)", after), "warning should report len(merged)"