Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(search): treat an empty relevance-filter completion as a failure (#7336)

Ehsane254d675763e
diff --git a/changelog.d/5932.bugfix.md b/changelog.d/5932.bugfix.md
new file mode 100644
index 0000000000..c4ed1cab50
--- /dev/null
+++ b/changelog.d/5932.bugfix.md
@@ -0,0 +1 @@
+The LLM relevance filter now retries an empty completion (an empty or whitespace-only string response) once before reading it as "none of these results are relevant". The retry is skipped when it cannot help: when the model stopped on its output token limit, when its output went to `reasoning_content`, or when less time is left before the filter's 300 s deadline than the first attempt took. If the retry raises (a rate limit, a client read timeout) or has not been collected when that deadline passes, the batch keeps the first attempt's "none relevant" judgment instead of being counted as failed, so an empty completion never brings back the unfiltered fallback. If the retry is also empty the batch is still treated as "none relevant", not as an LLM failure, so the filter does not fall back to unfiltered previews. A response that contains text but no indices is a "none relevant" judgment as before. The warning for an empty completion now records the provider's finish reason (`finish_reason`, Ollama's `done_reason` or Anthropic's `stop_reason`), the attempt's duration, token usage and the names of any extra message fields (such as `reasoning_content`), so these runs can be diagnosed from the log.
diff --git a/src/local_deep_research/web_search_engines/relevance_filter.py b/src/local_deep_research/web_search_engines/relevance_filter.py
index e4e5f8045d..6fae18aa05 100644
--- a/src/local_deep_research/web_search_engines/relevance_filter.py
+++ b/src/local_deep_research/web_search_engines/relevance_filter.py
@@ -7,10 +7,20 @@ or "[0, 2, 5]" and dodges all the structured-output provider quirks
(qwen prose-mode, function_calling latency, schema bikeshedding).
Design notes:
-- An empty LLM response is treated as a valid judgment ("none of these
- results are relevant"). We do not second-guess the model — if the
- filter says reject all, we reject all, and log a warning so users
- can notice if their chosen model is misbehaving.
+- A response with no integers in it is treated as a valid judgment
+ ("none of these results are relevant"). We do not second-guess the
+ model: if the filter says reject all, we reject all, and log a
+ warning so users can notice if their chosen model is misbehaving.
+- An empty completion (a string that is empty or whitespace only) is
+ retried once. If it is still empty it is read as "none relevant",
+ like a response with no integers, rather than as a failure: falling
+ back to unfiltered previews would fill the context with results the
+ filter was meant to remove. The warning records the provider's
+ finish reason and extra message fields so these runs can be told
+ apart in the log. A list of content blocks is read through its text
+ blocks, so a reply whose blocks hold no text (thinking only) counts
+ as empty and gets the same retry. If the retry raises, the first
+ attempt's empty judgment is kept.
- On exception (network error, parse failure, provider outage) the
filter is considered unavailable, not "reject all". In that case we
fall back to a capped slice of the original previews so downstream
@@ -34,7 +44,7 @@ from concurrent.futures import (
as_completed,
)
from datetime import UTC, datetime
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from langchain_ollama import ChatOllama
@@ -70,6 +80,13 @@ _INT_RE = re.compile(r"(?<![\w.])\d+\b")
# socket timeout.
_FILTER_WALL_TIMEOUT_S = 300.0
+# Calls made before an empty completion is read as "none relevant".
+_EMPTY_COMPLETION_ATTEMPTS = 2
+
+# Finish reasons meaning the model ran out of output tokens. Re-sending
+# the same prompt with the same limit cannot produce an answer.
+_TOKEN_LIMIT_FINISH_REASONS = frozenset({"length", "max_tokens"})
+
# Per-preview snippet character cap. The snippet field often carries the
# paper abstract for academic engines (arxiv, semantic scholar, pubmed).
@@ -111,6 +128,50 @@ def _unwrap_llm(llm):
return probe
+def _finish_reason(result):
+ """Return the provider's finish reason, or None.
+
+ OpenAI-compatible providers report ``finish_reason``, Ollama reports
+ ``done_reason`` and Anthropic reports ``stop_reason``.
+ """
+ metadata = getattr(result, "response_metadata", None)
+ if not isinstance(metadata, dict):
+ return None
+ for key in ("finish_reason", "done_reason", "stop_reason"):
+ if metadata.get(key) is not None:
+ return metadata[key]
+ return None
+
+
+def _empty_completion_is_deterministic(result) -> bool:
+ """Whether a retry of this empty completion cannot succeed.
+
+ True when the model hit its output token limit, or when it put its
+ output in ``reasoning_content`` instead of the message content.
+ """
+ if _finish_reason(result) in _TOKEN_LIMIT_FINISH_REASONS:
+ return True
+ extra = getattr(result, "additional_kwargs", None)
+ return isinstance(extra, dict) and bool(extra.get("reasoning_content"))
+
+
+def _describe_empty_completion(result) -> str:
+ """Summarise why a completion may be empty, without logging any text.
+
+ Reports the provider's finish reason, token usage, and the names of
+ any extra message fields (e.g. ``reasoning_content``, where some
+ OpenAI-compatible endpoints put the whole answer).
+ """
+ usage = getattr(result, "usage_metadata", None)
+ extra = getattr(result, "additional_kwargs", None)
+ finish_reason = _finish_reason(result)
+ return (
+ f"finish_reason={finish_reason!r}, "
+ f"usage={usage if isinstance(usage, dict) else None!r}, "
+ f"extra_fields={sorted(extra, key=str) if isinstance(extra, dict) else []}"
+ )
+
+
def _build_batch_prompt(
query: str,
batch: List[Dict[str, Any]],
@@ -148,14 +209,23 @@ def _run_batch(
total_in_full: int,
engine_name: str,
prompt_template: str,
+ deadline: Optional[float] = None,
+ on_empty_completion: Optional[Callable[[], None]] = None,
) -> List[int]:
"""Invoke the LLM on a single batch and return the parsed local indices.
Empty list = "none relevant" (valid judgment). Raises on LLM
exceptions; the caller falls back to a capped slice in that case.
+ ``deadline`` and ``on_empty_completion`` are passed to ``_invoke_text``.
"""
prompt = _build_batch_prompt(query, batch, total_in_full, prompt_template)
- return _invoke_text(llm, prompt, engine_name)
+ return _invoke_text(
+ llm,
+ prompt,
+ engine_name,
+ deadline=deadline,
+ on_empty_completion=on_empty_completion,
+ )
def filter_previews_for_relevance(
@@ -254,6 +324,24 @@ def filter_previews_for_relevance(
# ``wait=False`` so timed-out batches are orphaned (they'll
# error out when the socket eventually fails) rather than
# blocking the caller.
+ #
+ # A batch whose first completion was empty already has a valid
+ # "none relevant" judgment; its retry is optional. If that retry
+ # is still running at the wall timeout, the batch keeps the
+ # empty judgment instead of being counted as failed, so an
+ # abandoned retry cannot bring back the unfiltered fallback.
+ # Retries are also not started when they would not fit before
+ # the shared deadline.
+ deadline = t0 + _FILTER_WALL_TIMEOUT_S
+ judged_empty = [False for _ in batches]
+ collected: set = set()
+
+ def _mark_judged_empty(i: int) -> Callable[[], None]:
+ def _mark() -> None:
+ judged_empty[i] = True
+
+ return _mark
+
pool = ThreadPoolExecutor(max_workers=workers)
try:
futures_to_idx = {
@@ -265,6 +353,8 @@ def filter_previews_for_relevance(
len(previews),
engine_name,
prompt_template,
+ deadline,
+ _mark_judged_empty(i),
): i
for i, batch in enumerate(batches)
}
@@ -273,6 +363,7 @@ def filter_previews_for_relevance(
futures_to_idx, timeout=_FILTER_WALL_TIMEOUT_S
):
i = futures_to_idx[fut]
+ collected.add(i)
try:
results_per_batch[i] = fut.result()
except Exception as e:
@@ -281,14 +372,29 @@ def filter_previews_for_relevance(
f"[{engine_name}] batch {i} failed — skipping ({type(e).__name__}): {safe_msg}"
)
except FuturesTimeoutError:
- pending = [
- futures_to_idx[f] for f in futures_to_idx if not f.done()
- ]
+ # A future can finish between the iterator timing out and
+ # this scan. Take the result of any that did, then treat
+ # every batch that is still unresolved the same way,
+ # whether or not its future has finished since.
+ for f, i in futures_to_idx.items():
+ if i in collected or not f.done() or f.exception():
+ continue
+ collected.add(i)
+ results_per_batch[i] = f.result()
+ pending = [i for i in range(len(batches)) if i not in collected]
logger.warning(
- f"[{engine_name}] {len(pending)} batch(es) still "
- f"running after {_FILTER_WALL_TIMEOUT_S}s — abandoning "
+ f"[{engine_name}] {len(pending)} batch(es) unresolved "
+ f"after {_FILTER_WALL_TIMEOUT_S}s, abandoning them "
f"(pending indices: {pending})"
)
+ for i in pending:
+ if judged_empty[i]:
+ results_per_batch[i] = []
+ logger.warning(
+ f"[{engine_name}] batch {i}: retry of an empty "
+ f"completion abandoned; keeping the first "
+ f"attempt's empty judgment (no relevant results)"
+ )
finally:
# ``cancel_futures=True`` only cancels queued futures the
# executor hasn't started yet; already-running workers stay
@@ -391,12 +497,29 @@ def filter_previews_for_relevance(
return ranked_results
-def _invoke_text(llm, prompt: str, engine_name: str) -> List[int]:
+def _invoke_text(
+ llm,
+ prompt: str,
+ engine_name: str,
+ deadline: Optional[float] = None,
+ on_empty_completion: Optional[Callable[[], None]] = None,
+) -> List[int]:
"""Invoke the LLM with a plain text prompt and parse out integer indices.
Returns the list of parsed ints (empty list = "no integers found",
treated as a valid "none relevant" judgment by the caller).
Range/dedup validation happens in ``filter_previews_for_relevance``.
+
+ An empty completion is retried once; if every attempt is empty the
+ result is an empty list, the same "none relevant" judgment. The retry
+ is skipped when it cannot succeed (token limit reached, or the output
+ went to ``reasoning_content``), or when ``deadline`` (a
+ ``time.monotonic()`` value) leaves less time than the empty attempt
+ took. If the retry raises, the first attempt's empty judgment is kept
+ and the result is an empty list; an exception on the first attempt is
+ raised. ``on_empty_completion`` is called once the first empty
+ completion has been read, before any retry: from then on the batch has
+ an empty judgment even if the retry never finishes.
"""
# Ollama thinking-by-default models (qwen3 dense variants, etc.)
# burn 30-60s on CoT before emitting the answer. Index selection does
@@ -406,24 +529,68 @@ def _invoke_text(llm, prompt: str, engine_name: str) -> List[int]:
if isinstance(base_llm, ChatOllama):
invoke_kwargs["reasoning"] = False
- try:
- result = llm.invoke(prompt, **invoke_kwargs)
- except Exception as exc:
- safe_msg = scrub_error(exc)
+ for attempt in range(1, _EMPTY_COMPLETION_ATTEMPTS + 1):
+ started = time.monotonic()
+ try:
+ result = llm.invoke(prompt, **invoke_kwargs)
+ except Exception as exc:
+ safe_msg = scrub_error(exc)
+ if attempt == 1:
+ logger.warning(
+ f"[{engine_name}] LLM invocation failed ({type(exc).__name__}): {safe_msg}"
+ )
+ raise
+ # Only the retry of an empty completion gets here, so the first
+ # attempt already judged the batch empty; keep that judgment.
+ # logger.exception() keeps the traceback the batch failure
+ # handlers used to log for this case, behind the same gate.
+ logger.exception(
+ f"[{engine_name}] the retry of an empty completion failed "
+ f"({type(exc).__name__}): {safe_msg}; treating it as no "
+ f"relevant results"
+ )
+ return []
+
+ # LangChain chat models return a Message; LLMs return a string. A
+ # thinking-capable model (Anthropic extended-thinking, some Ollama
+ # reasoning models) can return ``.content`` as a list of blocks
+ # (``[{"type": "thinking", ...}, {"type": "text", "text": "0, 2"}]``)
+ # rather than a plain string. get_llm_response_text() handles both
+ # shapes, joining text blocks and dropping thinking/tool_use ones,
+ # so a reply with no text block counts as an empty completion.
+ text = get_llm_response_text(result)
+ if text.strip():
+ break
+ elapsed = time.monotonic() - started
logger.warning(
- f"[{engine_name}] LLM invocation failed ({type(exc).__name__}): {safe_msg}"
+ f"[{engine_name}] LLM returned an empty completion "
+ f"(attempt {attempt} of {_EMPTY_COMPLETION_ATTEMPTS}, "
+ f"{elapsed:.1f}s; {_describe_empty_completion(result)})"
)
- raise
-
- # LangChain chat models return a Message; LLMs return a string. A
- # thinking-capable model (Anthropic extended-thinking, some Ollama
- # reasoning models) can return ``.content`` as a list of blocks
- # (``[{"type": "thinking", ...}, {"type": "text", "text": "0, 2"}]``)
- # rather than a plain string. get_llm_response_text() handles both
- # shapes — joining text blocks and dropping thinking/tool_use ones —
- # the same way the rest of the codebase extracts LLM output, instead
- # of only accepting a bare string and discarding the whole response.
- text = get_llm_response_text(result)
+ if _empty_completion_is_deterministic(result):
+ logger.warning(
+ f"[{engine_name}] not retrying: the same prompt and token "
+ f"limit cannot produce an answer; treating it as no "
+ f"relevant results"
+ )
+ return []
+ if on_empty_completion is not None and attempt == 1:
+ on_empty_completion()
+ if deadline is not None and time.monotonic() + elapsed > deadline:
+ logger.warning(
+ f"[{engine_name}] not retrying: the attempt took "
+ f"{elapsed:.1f}s and less than that is left before the "
+ f"{_FILTER_WALL_TIMEOUT_S:.0f}s filter deadline; treating "
+ f"it as no relevant results"
+ )
+ return []
+ else:
+ logger.warning(
+ f"[{engine_name}] LLM returned an empty completion "
+ f"{_EMPTY_COMPLETION_ATTEMPTS} times; treating it as no "
+ f"relevant results"
+ )
+ return []
logger.info(f"[{engine_name}] LLM call returned {len(text)} chars")
diff --git a/tests/web_search_engines/test_relevance_filter.py b/tests/web_search_engines/test_relevance_filter.py
index 6f2d4859f4..1de2f48416 100644
--- a/tests/web_search_engines/test_relevance_filter.py
+++ b/tests/web_search_engines/test_relevance_filter.py
@@ -16,8 +16,12 @@ that are hard to assert through the wrapper:
import threading
import time
+from concurrent.futures import TimeoutError as FuturesTimeoutError
+from concurrent.futures import wait
from unittest.mock import Mock
+import pytest
+
from local_deep_research.web_search_engines import relevance_filter
from local_deep_research.web_search_engines.relevance_filter import (
_unwrap_llm,
@@ -153,6 +157,28 @@ def test_content_block_list_with_only_thinking_is_empty_judgment():
assert result == []
+def test_content_block_list_with_only_thinking_is_retried():
+ """A content-block list with no text block is an empty completion, so
+ it gets the one retry, and an answer on the retry is used."""
+ previews = _previews(3)
+ thinking_only = Mock(spec=["content"])
+ thinking_only.content = [
+ {"type": "thinking", "thinking": "Still reasoning..."}
+ ]
+ answer = Mock(spec=["content"])
+ answer.content = [
+ {"type": "thinking", "thinking": "Done."},
+ {"type": "text", "text": "0, 2"},
+ ]
+ mock_llm = Mock()
+ mock_llm.invoke.side_effect = [thinking_only, answer]
+
+ result = filter_previews_for_relevance(mock_llm, previews, "q")
+
+ assert result == [previews[0], previews[2]]
+ assert mock_llm.invoke.call_count == 2
+
+
# ---------- 5. LLM exception → capped fallback ----------
@@ -169,6 +195,28 @@ def test_llm_exception_returns_capped_fallback():
assert result == previews[:4]
+def test_llm_exception_is_raised_without_retry():
+ """An exception from the LLM is raised on the first call: it does not
+ consume the empty-completion retry and is not reclassified as one."""
+ llm = _llm_raising(ConnectionError("network down"))
+
+ with pytest.raises(ConnectionError):
+ relevance_filter._invoke_text(llm, "prompt", "test_engine")
+ assert llm.invoke.call_count == 1
+
+
+def test_empty_completion_then_exception_keeps_the_empty_judgment():
+ """An exception on the retry does not undo the first attempt's empty
+ judgment: the result is an empty list, not a raised error."""
+ llm = Mock()
+ llm.invoke.side_effect = ["", ConnectionError("network down")]
+
+ result = relevance_filter._invoke_text(llm, "prompt", "test_engine")
+
+ assert result == []
+ assert llm.invoke.call_count == 2
+
+
# ---------- 6. max_filtered_results=None ----------
@@ -497,8 +545,11 @@ def test_relevance_filter_preview_neutralizes_control_chars(loguru_caplog):
assert "\\x1b" in loguru_caplog.text
-def test_relevance_filter_empty_response_does_not_crash(loguru_caplog):
- """An empty/whitespace unparsable response is handled without raising."""
+def test_relevance_filter_empty_response_is_none_relevant_after_retry(
+ loguru_caplog,
+):
+ """An empty/whitespace completion is retried once, then read as a
+ "none relevant" judgment."""
from local_deep_research.web_search_engines.relevance_filter import (
_invoke_text,
)
@@ -508,4 +559,415 @@ def test_relevance_filter_empty_response_does_not_crash(loguru_caplog):
with loguru_caplog.at_level("DEBUG"):
result = _invoke_text(llm, "prompt", "test_engine")
assert result == []
- assert "Parser found no integers in LLM response." in loguru_caplog.text
+ assert llm.invoke.call_count == 2
+ assert "treating it as no relevant results" in loguru_caplog.text
+ assert "Parser found no integers" not in loguru_caplog.text
+
+
+# ---------- 8. empty completion (#5932) ----------
+
+
+def test_empty_completion_is_retried_once():
+ """A single empty completion is retried and the retry's answer is used."""
+ previews = _previews(4)
+ llm = Mock()
+ llm.invoke.side_effect = ["", "0, 2"]
+
+ result = filter_previews_for_relevance(llm, previews, "q")
+
+ assert result == [previews[0], previews[2]]
+ assert llm.invoke.call_count == 2
+
+
+def test_empty_completion_twice_returns_no_results():
+ """Two empty completions are read as "none relevant": the unfiltered
+ fallback slice is not returned."""
+ previews = _previews(8)
+ llm = _llm_returning("")
+
+ result = filter_previews_for_relevance(
+ llm, previews, "q", max_filtered_results=4
+ )
+
+ assert result == []
+ assert llm.invoke.call_count == 2
+
+
+def test_empty_completion_batch_is_judged_none_relevant(loguru_caplog):
+ """In batched mode an empty batch's previews are removed after the
+ retry, and the other batches' judgments are kept."""
+ previews = _previews(4)
+ llm = Mock()
+ llm.invoke.side_effect = ["0, 1", "", ""]
+
+ with loguru_caplog.at_level("DEBUG"):
+ result = filter_previews_for_relevance(
+ llm, previews, "q", batch_size=2, max_parallel_batches=1
+ )
+
+ assert result == [previews[0], previews[1]]
+ assert llm.invoke.call_count == 3
+ assert "REMOVED [2]" in loguru_caplog.text
+ assert "SKIPPED [2]" not in loguru_caplog.text
+
+
+def test_content_block_text_is_not_retried():
+ """A content-block list that carries text is an answer, not an empty
+ completion: it is parsed without a second call."""
+ message = Mock()
+ message.content = [{"type": "text", "text": "0"}]
+ llm = _llm_returning(message)
+
+ assert relevance_filter._invoke_text(llm, "prompt", "test_engine") == [0]
+ assert llm.invoke.call_count == 1
+
+
+def test_empty_completion_logs_response_structure(loguru_caplog):
+ """The empty-completion warning names the finish reason and any extra
+ message fields, without logging their contents."""
+ from langchain_core.messages import AIMessage
+
+ message = AIMessage(
+ content="",
+ response_metadata={"finish_reason": "length"},
+ additional_kwargs={"reasoning_content": "secret reasoning 0, 1"},
+ usage_metadata={
+ "input_tokens": 120,
+ "output_tokens": 0,
+ "total_tokens": 120,
+ },
+ )
+ llm = _llm_returning(message)
+
+ with loguru_caplog.at_level("WARNING"):
+ result = relevance_filter._invoke_text(llm, "prompt", "test_engine")
+
+ assert result == []
+ assert llm.invoke.call_count == 1
+ assert "finish_reason='length'" in loguru_caplog.text
+ assert "extra_fields=['reasoning_content']" in loguru_caplog.text
+ assert "usage={'input_tokens': 120" in loguru_caplog.text
+ assert "secret reasoning" not in loguru_caplog.text
+
+
+def test_empty_completion_description_tolerates_mixed_key_types():
+ """Extra-field names of mixed types do not break the diagnostic."""
+ message = Mock()
+ message.response_metadata = {}
+ message.usage_metadata = None
+ message.additional_kwargs = {"b": 1, 2: "a"}
+
+ description = relevance_filter._describe_empty_completion(message)
+
+ assert "extra_fields=[2, 'b']" in description
+
+
+# ---------- 9. empty completion retry is skipped when it cannot help ----------
+
+
+ "metadata",
+ [
+ {"finish_reason": "length"},
+ {"done_reason": "length"},
+ {"stop_reason": "max_tokens"},
+ ],
+)
+def test_empty_completion_at_token_limit_is_not_retried(metadata):
+ """An empty completion that stopped on the output token limit is not
+ re-sent: the same prompt and limit cannot produce an answer."""
+ from langchain_core.messages import AIMessage
+
+ llm = _llm_returning(AIMessage(content="", response_metadata=metadata))
+
+ assert relevance_filter._invoke_text(llm, "prompt", "test_engine") == []
+ assert llm.invoke.call_count == 1
+
+
+def test_empty_completion_with_reasoning_content_is_not_retried():
+ """An empty completion whose output went to ``reasoning_content`` is
+ not re-sent, whatever the finish reason."""
+ from langchain_core.messages import AIMessage
+
+ message = AIMessage(
+ content="",
+ response_metadata={"finish_reason": "stop"},
+ additional_kwargs={"reasoning_content": "0, 1"},
+ )
+ llm = _llm_returning(message)
+
+ assert relevance_filter._invoke_text(llm, "prompt", "test_engine") == []
+ assert llm.invoke.call_count == 1
+
+
+def test_empty_completion_with_normal_stop_is_retried():
+ """An empty completion that stopped normally is still retried."""
+ from langchain_core.messages import AIMessage
+
+ llm = Mock()
+ llm.invoke.side_effect = [
+ AIMessage(content="", response_metadata={"done_reason": "stop"}),
+ AIMessage(content="0"),
+ ]
+
+ assert relevance_filter._invoke_text(llm, "prompt", "test_engine") == [0]
+ assert llm.invoke.call_count == 2
+
+
+ ("metadata", "expected"),
+ [
+ ({"done_reason": "length"}, "finish_reason='length'"),
+ ({"stop_reason": "max_tokens"}, "finish_reason='max_tokens'"),
+ ({}, "finish_reason=None"),
+ ],
+)
+def test_empty_completion_description_reads_provider_finish_keys(
+ metadata, expected
+):
+ """Ollama's ``done_reason`` and Anthropic's ``stop_reason`` are reported
+ as the finish reason."""
+ message = Mock()
+ message.response_metadata = metadata
+ message.usage_metadata = None
+ message.additional_kwargs = {}
+
+ assert expected in relevance_filter._describe_empty_completion(message)
+
+
+def test_slow_empty_completion_is_not_retried_past_the_wall_timeout(
+ monkeypatch,
+):
+ """A slow empty completion is not retried when the retry would run
+ past the wall timeout. Retrying would get every batch abandoned as
+ failed and return the unfiltered fallback slice (#5932)."""
+ monkeypatch.setattr(relevance_filter, "_FILTER_WALL_TIMEOUT_S", 0.6)
+ previews = _previews(4)
+ llm = Mock()
+
+ def _slow_empty(prompt, **kwargs):
+ threading.Event().wait(timeout=0.4)
+ return ""
+
+ llm.invoke.side_effect = _slow_empty
+
+ result = filter_previews_for_relevance(
+ llm,
+ previews,
+ "q",
+ batch_size=2,
+ max_parallel_batches=2,
+ max_filtered_results=3,
+ )
+
+ assert result == []
+ assert llm.invoke.call_count == 2
+
+
+def test_abandoned_retry_keeps_the_first_empty_judgment(monkeypatch):
+ """A first empty completion that is quick enough to be retried, followed
+ by a retry that runs past the wall timeout, keeps the first attempt's
+ empty judgment. Counting the batch as failed would return the
+ unfiltered fallback slice, which main never did for an empty reply."""
+ monkeypatch.setattr(relevance_filter, "_FILTER_WALL_TIMEOUT_S", 0.6)
+ previews = _previews(4)
+ release = threading.Event()
+ calls = []
+ lock = threading.Lock()
+
+ def _empty_then_stuck(prompt, **kwargs):
+ with lock:
+ calls.append(prompt)
+ first = calls.count(prompt) == 1
+ if first:
+ threading.Event().wait(timeout=0.1)
+ return ""
+ release.wait(timeout=5)
+ return "0"
+
+ llm = Mock()
+ llm.invoke.side_effect = _empty_then_stuck
+
+ try:
+ result = filter_previews_for_relevance(
+ llm,
+ previews,
+ "q",
+ batch_size=2,
+ max_parallel_batches=2,
+ max_filtered_results=3,
+ )
+ finally:
+ release.set()
+
+ assert result == []
+ assert llm.invoke.call_count == 4
+
+
+def test_failing_retry_keeps_the_empty_judgment_sequential():
+ """Single-batch path: an empty completion whose retry raises (a 429, a
+ client read timeout) returns no results, not the unfiltered fallback."""
+ llm = Mock()
+ llm.invoke.side_effect = ["", ConnectionError("429 Too Many Requests")]
+
+ result = filter_previews_for_relevance(
+ llm, _previews(4), "q", max_filtered_results=3
+ )
+
+ assert result == []
+ assert llm.invoke.call_count == 2
+
+
+def test_failing_retry_keeps_the_empty_judgment_parallel():
+ """Parallel path: every batch gets an empty completion and a retry that
+ raises. The result is no results, not the unfiltered fallback."""
+ calls = []
+ lock = threading.Lock()
+
+ def _empty_then_raise(prompt, **kwargs):
+ with lock:
+ calls.append(prompt)
+ first = calls.count(prompt) == 1
+ if first:
+ return ""
+ raise ConnectionError("429 Too Many Requests")
+
+ llm = Mock()
+ llm.invoke.side_effect = _empty_then_raise
+
+ result = filter_previews_for_relevance(
+ llm,
+ _previews(4),
+ "q",
+ batch_size=2,
+ max_parallel_batches=2,
+ max_filtered_results=3,
+ )
+
+ assert result == []
+ assert llm.invoke.call_count == 4
+
+
+def _timeout_then_release(monkeypatch, release):
+ """Make ``as_completed`` time out, then let the blocked calls finish
+ before the caller scans for pending batches."""
+ real_as_completed = relevance_filter.as_completed
+
+ def _as_completed(fs, timeout=None):
+ try:
+ yield from real_as_completed(fs, timeout=timeout)
+ except FuturesTimeoutError:
+ release.set()
+ wait(fs, timeout=5)
+ raise
+
+ monkeypatch.setattr(relevance_filter, "as_completed", _as_completed)
+
+
+def test_retry_finishing_after_the_timeout_keeps_the_empty_judgment(
+ monkeypatch,
+):
+ """A retry that finishes after ``as_completed`` has timed out but before
+ the pending scan leaves its future done and uncollected. The batch still
+ keeps the first attempt's empty judgment instead of being counted as
+ failed and bringing back the unfiltered fallback."""
+ monkeypatch.setattr(relevance_filter, "_FILTER_WALL_TIMEOUT_S", 0.6)
+ release = threading.Event()
+ _timeout_then_release(monkeypatch, release)
+ calls = []
+ lock = threading.Lock()
+
+ def _empty_then_late_empty(prompt, **kwargs):
+ with lock:
+ calls.append(prompt)
+ first = calls.count(prompt) == 1
+ if first:
+ threading.Event().wait(timeout=0.1)
+ return ""
+ release.wait(timeout=5)
+ return ""
+
+ llm = Mock()
+ llm.invoke.side_effect = _empty_then_late_empty
+
+ try:
+ result = filter_previews_for_relevance(
+ llm,
+ _previews(4),
+ "q",
+ batch_size=2,
+ max_parallel_batches=2,
+ max_filtered_results=3,
+ )
+ finally:
+ release.set()
+
+ assert result == []
+ assert llm.invoke.call_count == 4
+
+
+def test_first_call_finishing_after_the_timeout_still_falls_back(
+ monkeypatch,
+):
+ """Control for the test above: a batch whose first call fails after the
+ timeout never judged anything, so it is still a failure and the capped
+ fallback is returned."""
+ monkeypatch.setattr(relevance_filter, "_FILTER_WALL_TIMEOUT_S", 0.6)
+ release = threading.Event()
+ _timeout_then_release(monkeypatch, release)
+
+ def _late_failure(prompt, **kwargs):
+ release.wait(timeout=5)
+ raise ConnectionError("provider went away")
+
+ llm = Mock()
+ llm.invoke.side_effect = _late_failure
+ previews = _previews(4)
+
+ try:
+ result = filter_previews_for_relevance(
+ llm,
+ previews,
+ "q",
+ batch_size=2,
+ max_parallel_batches=2,
+ max_filtered_results=3,
+ )
+ finally:
+ release.set()
+
+ assert result == previews[:3]
+ assert llm.invoke.call_count == 2
+
+
+def test_empty_completion_is_not_retried_after_the_deadline():
+ """No retry is started when less time is left before the deadline than
+ the empty attempt took."""
+ llm = _llm_returning("")
+
+ deadline = time.monotonic() - 1.0
+ result = relevance_filter._invoke_text(
+ llm, "prompt", "test_engine", deadline=deadline
+ )
+
+ assert result == []
+ assert llm.invoke.call_count == 1
+
+
+def test_empty_completion_is_retried_before_the_deadline():
+ """A retry that fits before the deadline is still made."""
+ llm = Mock()
+ llm.invoke.side_effect = ["", "1"]
+ marked = []
+
+ result = relevance_filter._invoke_text(
+ llm,
+ "prompt",
+ "test_engine",
+ deadline=time.monotonic() + 60,
+ on_empty_completion=lambda: marked.append(True),
+ )
+
+ assert result == [1]
+ assert llm.invoke.call_count == 2
+ assert marked == [True]