~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(relevance_filter): tighter prompt, snippet cap 200->800, cap fallback 5->20, dev eval tooling (#3476)
LearningCircuite6a411ffe6d6
diff --git a/src/local_deep_research/config/constants.py b/src/local_deep_research/config/constants.pyindex 92c316b79b..4aca1bfde7 100644--- a/src/local_deep_research/config/constants.py+++ b/src/local_deep_research/config/constants.py@@ -2,3 +2,11 @@DEFAULT_OLLAMA_URL = "http://localhost:11434"DEFAULT_LMSTUDIO_URL = "http://localhost:1234/v1"++# Cap on how many results the LLM relevance filter keeps per search-engine+# call. Must match the ``search.max_filtered_results`` entry in+# ``defaults/default_settings.json``. Used as the fallback whenever an+# engine is constructed without an explicit value (mainly programmatic+# mode) or when the LLM filter itself is unavailable and we slice the+# unfiltered previews.+DEFAULT_MAX_FILTERED_RESULTS = 20diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex cb436c0ab5..2bf3c301a3 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -4,6 +4,7 @@ from loguru import loggerfrom ..web_search_engines.search_engine_factory import (get_search as factory_get_search,)+from .constants import DEFAULT_MAX_FILTERED_RESULTSfrom .llm_config import get_llmfrom .thread_settings import get_setting_from_snapshot@@ -122,7 +123,7 @@ def get_search(),"max_filtered_results": get_setting_from_snapshot("search.max_filtered_results",- 5,+ DEFAULT_MAX_FILTERED_RESULTS,username=username,settings_snapshot=settings_snapshot,),diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.pyindex c73cae23ea..ad5abb310f 100644--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py@@ -143,8 +143,9 @@ class ParallelSearchEngine(BaseSearchEngine):Ignored if the global pool is already initialized.**kwargs: Additional parameters (ignored but accepted for compatibility)"""- # Override max_filtered_results to be much higher for parallel search- # If not explicitly set, use 50 instead of the default 5-20+ # Parallel search aggregates results from multiple engines, so+ # it runs with a higher post-filter cap than a single-engine+ # search would get from DEFAULT_MAX_FILTERED_RESULTS.if max_filtered_results is None:max_filtered_results = 50logger.info(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.pyindex 7f407e6a80..111d2360d7 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py@@ -24,7 +24,7 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):llm: Optional[BaseLLM] = None,language: str = "English",include_full_content: bool = False,- max_filtered_results=5,+ max_filtered_results: Optional[int] = None,settings_snapshot: Optional[Dict[str, Any]] = None,):"""diff --git a/src/local_deep_research/web_search_engines/relevance_filter.py b/src/local_deep_research/web_search_engines/relevance_filter.pyindex b7e73ba14c..05deb995e1 100644--- a/src/local_deep_research/web_search_engines/relevance_filter.py+++ b/src/local_deep_research/web_search_engines/relevance_filter.py@@ -20,17 +20,28 @@ Design notes:reliable on weaker models which struggle to track many indices in asingle context. A failed individual batch is skipped (logged); onlya hard exception falls back to the capped slice.+- Partial success is the common outcome under batching: some batches+ return valid judgments, others raise or time out. Successful batches+ are kept; failed/timed-out batches contribute nothing. The capped+ fallback only fires when *every* batch failed to produce a result."""import reimport time-from concurrent.futures import ThreadPoolExecutor+from concurrent.futures import (+ ThreadPoolExecutor,+ TimeoutError as FuturesTimeoutError,+ as_completed,+)+from datetime import UTC, datetimefrom typing import Any, Dict, List, Optionalfrom loguru import loggerfrom langchain_ollama import ChatOllama+from ..config.constants import DEFAULT_MAX_FILTERED_RESULTS+# Real wrapper chains (RateLimitedLLMWrapper -> ProcessingLLMWrapper -> base)# are at most 2-3 levels deep. A depth limit avoids spurious infinite chains# on test mocks where every getattr produces a new child object.@@ -43,12 +54,39 @@ _MAX_UNWRAP_DEPTH = 10# is robust against prose like "The top 3 results from 2024 are ..."._INT_RE = re.compile(r"(?<![\w.])\d+\b")+# Wall-clock timeout passed to ``as_completed`` when batches run in+# parallel. Note: this bounds the time from iteration start until all+# parallel batches complete, not per-batch. A single batch (≤ 10+# previews on a 9B-class local model) typically completes in 5-15s;+# 120s is generous enough for slow-but-progressing work to finish while+# flagging genuine hangs. The sequential (workers==1) path does not+# apply this — only the parallel branch uses ``as_completed``.+# Without a bound here a stuck Ollama socket would block the pipeline+# indefinitely, because langchain-ollama's httpx client has no default+# socket timeout.+_FILTER_WALL_TIMEOUT_S = 120.0+++# Per-preview snippet character cap. The snippet field often carries the+# paper abstract for academic engines (arxiv, semantic scholar, pubmed).+# 200 was too tight — it truncated abstracts before the judge could tell+# whether a paper's primary topic actually matches the query, leading to+# "paper mentions LLMs in passing" sources leaking past the filter. 800+# comfortably fits a typical abstract opening while keeping total prompt+# size bounded (≈16KB for 20 previews).+_SNIPPET_CHAR_CAP = 800+++_RELEVANCE_PROMPT_TEMPLATE = """This is a relevance-filtering step. Kept results move forward and may be used in the final answer; dropped ones are excluded from further processing.-_RELEVANCE_PROMPT_TEMPLATE = """Query: "{query}"+Query: "{query}"+Current date: {current_date}Search results:{preview_text}+Direct topic match matters more than keyword match — results that just mention the query terms usually don't help.+Output ONLY the 0-based indices of relevant results as a comma-separated list, nothing else.Example: 0, 2, 5""" # noqa: S608@@ -70,24 +108,31 @@ def _unwrap_llm(llm):def _build_batch_prompt(- query: str, batch: List[Dict[str, Any]], total_in_full: int+ query: str,+ batch: List[Dict[str, Any]],+ total_in_full: int,+ prompt_template: str,) -> str:"""Build the relevance prompt for a single batch of previews.Indices in the prompt are local to the batch (0..len(batch)-1).``total_in_full`` is the size of the original full preview list,shown to the model for context — it doesn't affect the index range.+ ``prompt_template`` is passed in (defaulting at the public entry+ point) rather than read from a module global, so eval harnesses can+ test variants without monkey-patching module state."""preview_lines = []for i, preview in enumerate(batch):title = preview.get("title", "Untitled").strip()snippet = preview.get("snippet", "").strip()- if len(snippet) > 200:- snippet = snippet[:200] + "..."+ if len(snippet) > _SNIPPET_CHAR_CAP:+ snippet = snippet[:_SNIPPET_CHAR_CAP] + "..."preview_lines.append(f"[{i}] {title}\n {snippet}")- return _RELEVANCE_PROMPT_TEMPLATE.format(+ return prompt_template.format(query=query,+ current_date=datetime.now(UTC).strftime("%Y-%m-%d"),preview_text="\n\n".join(preview_lines),)@@ -98,13 +143,14 @@ def _run_batch(query: str,total_in_full: int,engine_name: str,+ prompt_template: str,) -> List[int]:"""Invoke the LLM on a single batch and return the parsed local indices.Empty list = "none relevant" (valid judgment). Raises on LLMexceptions; the caller falls back to a capped slice in that case."""- prompt = _build_batch_prompt(query, batch, total_in_full)+ prompt = _build_batch_prompt(query, batch, total_in_full, prompt_template)return _invoke_text(llm, prompt, engine_name)@@ -116,6 +162,7 @@ def filter_previews_for_relevance(engine_name: str = "",batch_size: Optional[int] = None,max_parallel_batches: int = 1,+ prompt_template: Optional[str] = None,) -> List[Dict[str, Any]]:"""Filter search previews for relevance via plain-text LLM output.@@ -135,11 +182,17 @@ def filter_previews_for_relevance(Most providers (Ollama with OLLAMA_NUM_PARALLEL>1, OpenAI,Anthropic) handle concurrent requests fine. Ignored whenthere is only one batch.+ prompt_template: Override the built-in ``_RELEVANCE_PROMPT_TEMPLATE``.+ Used by eval harnesses that want to compare variants without+ mutating module state. None (default) uses the shipping+ template.Returns:Filtered list of preview dicts (subset of input). Order matchesthe original preview order across batches."""+ if prompt_template is None:+ prompt_template = _RELEVANCE_PROMPT_TEMPLATEif not previews:return []@@ -149,7 +202,7 @@ def filter_previews_for_relevance(# Cap used when the filter is unavailable (LLM exception) so we# don't flood downstream processing with unfiltered results.- unavailable_cap = max_filtered_results or 5+ unavailable_cap = max_filtered_results or DEFAULT_MAX_FILTERED_RESULTS# Determine batch boundaries. A batch_size of None or 0 means# "single batch" — process all previews in one LLM call.@@ -166,35 +219,95 @@ def filter_previews_for_relevance()t0 = time.monotonic()- results_per_batch: List[List[int]] = [[] for _ in batches]- try:- if workers == 1:- for i, batch in enumerate(batches):+ # None marks "batch never completed" (exception or timeout). A+ # completed batch is List[int], possibly empty (valid "none relevant"+ # judgment). We distinguish the two so an all-None outcome falls+ # back to the capped-slice while all-[] is kept as a valid decision.+ results_per_batch: List[Optional[List[int]]] = [None for _ in batches]++ if workers == 1:+ for i, batch in enumerate(batches):+ try:results_per_batch[i] = _run_batch(- llm, batch, query, len(previews), engine_name+ llm,+ batch,+ query,+ len(previews),+ engine_name,+ prompt_template,)- else:- with ThreadPoolExecutor(max_workers=workers) as pool:- futures = {- pool.submit(- _run_batch,- llm,- batch,- query,- len(previews),- engine_name,- ): i- for i, batch in enumerate(batches)- }- for fut, i in futures.items():- results_per_batch[i] = fut.result()- except Exception:- logger.exception(- f"[{engine_name}] LLM relevance filter failed — returning "- f"first {unavailable_cap} previews as fallback"+ except Exception:+ logger.exception(+ f"[{engine_name}] batch {i} failed — skipping its results"+ )+ else:+ # Not using ``with ThreadPoolExecutor(...) as pool:`` on purpose.+ # ``__exit__`` calls ``shutdown(wait=True)`` which blocks on any+ # still-running worker — defeating the whole point of the+ # timeout when a worker is stuck on an Ollama HTTP call. We+ # manage the pool lifetime explicitly and always shut down with+ # ``wait=False`` so timed-out batches are orphaned (they'll+ # error out when the socket eventually fails) rather than+ # blocking the caller.+ pool = ThreadPoolExecutor(max_workers=workers)+ try:+ futures_to_idx = {+ pool.submit(+ _run_batch,+ llm,+ batch,+ query,+ len(previews),+ engine_name,+ prompt_template,+ ): i+ for i, batch in enumerate(batches)+ }+ try:+ for fut in as_completed(+ futures_to_idx, timeout=_FILTER_WALL_TIMEOUT_S+ ):+ i = futures_to_idx[fut]+ try:+ results_per_batch[i] = fut.result()+ except Exception:+ logger.exception(+ f"[{engine_name}] batch {i} failed — skipping"+ )+ except FuturesTimeoutError:+ pending = [+ futures_to_idx[f] for f in futures_to_idx if not f.done()+ ]+ logger.warning(+ f"[{engine_name}] {len(pending)} batch(es) still "+ f"running after {_FILTER_WALL_TIMEOUT_S}s — abandoning "+ f"(pending indices: {pending})"+ )+ finally:+ # ``cancel_futures=True`` only cancels queued futures the+ # executor hasn't started yet; already-running workers stay+ # alive until their blocking call returns. We accept that —+ # the alternative is hanging forever.+ pool.shutdown(wait=False, cancel_futures=True)+ total_elapsed = time.monotonic() - t0++ # If no batch even completed, fall back to an unfiltered capped slice+ # — otherwise downstream would receive zero results from a filter+ # outage rather than from a valid "all irrelevant" judgment.+ if all(r is None for r in results_per_batch):+ logger.error(+ f"[{engine_name}] every relevance-filter batch failed — "+ f"returning first {unavailable_cap} previews as fallback")return previews[:unavailable_cap]- total_elapsed = time.monotonic() - t0++ # Normalise None → [] for the aggregation pass below; a batch that+ # was cancelled or errored just contributes nothing. Assign to a+ # new variable with a narrower type so mypy can prove the list+ # elements are no longer Optional.+ completed_batches: List[List[int]] = [+ [] if r is None else r for r in results_per_batch+ ]# Aggregate results in original batch order so the final list# mirrors the input ordering across batches.@@ -202,7 +315,7 @@ def filter_previews_for_relevance(kept_indices: List[int] = []seen: set = set()- for batch_start, batch_result in zip(batch_starts, results_per_batch):+ for batch_start, batch_result in zip(batch_starts, completed_batches):batch_len = min(effective_batch, len(previews) - batch_start)for li in batch_result:if not (0 <= li < batch_len):@@ -238,8 +351,17 @@ def filter_previews_for_relevance(ranked_results = ranked_results[:max_filtered_results]kept_indices = kept_indices[:max_filtered_results]- # Log kept/removed- removed_indices = set(range(len(previews))) - set(kept_indices)+ # Log kept/removed/skipped. A preview is "skipped" when its batch+ # raised or timed out — the judge never saw it — which is distinct+ # from "removed" (judge returned a verdict that dropped it).+ skipped_indices: set = set()+ for i, (batch_start, r) in enumerate(zip(batch_starts, results_per_batch)):+ if r is None:+ batch_len = min(effective_batch, len(previews) - batch_start)+ skipped_indices.update(range(batch_start, batch_start + batch_len))+ removed_indices = (+ set(range(len(previews))) - set(kept_indices) - skipped_indices+ )logger.info(f"[{engine_name}] Relevance filter: "f"kept {len(ranked_results)} of {len(previews)} results"@@ -250,6 +372,9 @@ def filter_previews_for_relevance(for idx in sorted(removed_indices):title = previews[idx].get("title", "Untitled")[:80]logger.debug(f"[{engine_name}] REMOVED [{idx}]: {title}")+ for idx in sorted(skipped_indices):+ title = previews[idx].get("title", "Untitled")[:80]+ logger.debug(f"[{engine_name}] SKIPPED [{idx}]: {title}")return ranked_resultsdiff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex ba9f083284..39a4b2ae07 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -15,6 +15,7 @@ from tenacity import (from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilter+from ..config.constants import DEFAULT_MAX_FILTERED_RESULTSfrom ..config.thread_settings import get_setting_from_snapshotfrom ..utilities.thread_context import clear_search_context, set_search_context@@ -252,7 +253,7 @@ class BaseSearchEngine(ABC):**kwargs: Additional engine-specific parameters"""if max_filtered_results is None:- max_filtered_results = 5+ max_filtered_results = DEFAULT_MAX_FILTERED_RESULTSif max_results is None:max_results = 10self._preview_filters: List[BaseFilter] = (@@ -302,8 +303,10 @@ class BaseSearchEngine(ABC):def max_filtered_results(self, value: int) -> None:"""Set the maximum number of filtered results."""if value is None:- value = 5- logger.warning("Setting max_filtered_results to 5")+ value = DEFAULT_MAX_FILTERED_RESULTS+ logger.warning(+ f"Setting max_filtered_results to {DEFAULT_MAX_FILTERED_RESULTS}"+ )self._max_filtered_results = int(value)@propertydiff --git a/tests/performance/README.md b/tests/performance/README.mdnew file mode 100644index 0000000000..c0375a8391--- /dev/null+++ b/tests/performance/README.md@@ -0,0 +1,67 @@+# tests/performance — live-service tests & eval harnesses++Code here hits **real external services** (arXiv, OpenAlex, Ollama, etc.)+and measures end-to-end behaviour. Everything here is excluded from CI+(`.github/workflows/docker-tests.yml` runs `-m 'not integration'` for+pytest, and the non-`test_*.py` eval scripts aren't collected by+pytest at all).++## Layout++```+tests/performance/+├── _shared/ — general pipeline harnesses, not tied to one subsystem+│ ├── run_full_search.py — thin CLI around quick_summary(); --engine / --model flags+│ └── build_eval_dataset.py — cross-product runner (query × engine × model) over run_full_search.py+└── relevance_filter/ — subsystem: LLM-as-judge relevance filter+ ├── test_live.py — pytest live arXiv + Ollama test (integration + requires_llm + slow)+ ├── eval_prompt.py — human-judgment harness: vary prompt, same judge, same arXiv+ └── eval_models.py — human-judgment harness: vary judge, same prompt, same arXiv+```++**When you add performance tests / harnesses for a new subsystem** (e.g.+embeddings, rate limiting, search-engine latency), create a new sibling+folder alongside `relevance_filter/`. Put anything that's genuinely+subsystem-agnostic in `_shared/`.++## Running the pytest tests++```+LDR_TESTING_WITH_MOCKS=false \+LDR_TEST_OLLAMA_BASE_URL=http://localhost:11434 \+LDR_TEST_OLLAMA_MODEL=qwen3.5:9b \+pdm run pytest tests/performance/ -v -s -m integration+```++`LDR_TESTING_WITH_MOCKS=false` is required — `tests/conftest.py` defaults+it to `true` which auto-skips anything tagged `requires_llm`.++Pytest tests should:+- carry `@pytest.mark.integration` (and usually `@pytest.mark.requires_llm`+ and `@pytest.mark.slow`) so they stay out of CI+- skip cleanly when the required external service is unreachable rather+ than fail+- print their KEPT/REMOVED decisions (or equivalent detail) with `print()`+ — run with `-s` to see them — so humans reviewing output can judge+ quality, not just pass/fail++## Running the eval harnesses++The `eval_*.py`, `run_*.py`, `build_*.py` scripts are human-judgment+tools — success signal is a human reading the output, not a pass/fail+assertion. They're runnable as plain Python:++```+# Swap between prompt variants against the same live arXiv results+pdm run python tests/performance/relevance_filter/eval_prompt.py++# Swap between judge LLMs, same prompt+pdm run python tests/performance/relevance_filter/eval_models.py++# One-shot end-to-end report+pdm run python tests/performance/_shared/run_full_search.py \+ --query "LLM interpretability latest research" --engine arxiv++# Cross-product dataset build+pdm run python tests/performance/_shared/build_eval_dataset.py+```diff --git a/tests/performance/__init__.py b/tests/performance/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/performance/_shared/__init__.py b/tests/performance/_shared/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/performance/_shared/build_eval_dataset.py b/tests/performance/_shared/build_eval_dataset.pynew file mode 100644index 0000000000..fa2ec7e49b--- /dev/null+++ b/tests/performance/_shared/build_eval_dataset.py@@ -0,0 +1,310 @@+"""Build an evaluation dataset: cross-product of queries × search engines × judge LLMs.++For each (query, engine, model) cell, runs `quick_summary` end-to-end and+saves (a) the formatted report and (b) a verbose log capturing the+filter's KEPT/REMOVED decisions. Writes a summary CSV so you can rank+runs by source count, timing, and visually inspect outliers.++Resumable: cells whose report file already exists are skipped unless+--force is passed. Use this to recover from interrupted runs or to+extend an existing dataset with new rows.++Usage (defaults produce a ~12-cell grid ≈ 60-90min total on qwen3.5:9b):+ LDR_BOOTSTRAP_ALLOW_UNENCRYPTED=true LDR_TESTING_WITH_MOCKS=false \\+ pdm run python tests/performance/_shared/build_eval_dataset.py \\+ --output-dir ./ldr_eval_output++Override any axis from the CLI:+ ... --queries "q1|q2" --engines "arxiv,openalex" --models "qwen3.5:9b,gemma3:12b"++Be conservative with --parallel — each parallel slot loads an LLM on the+Ollama endpoint; running 2+ different model tags concurrently may OOM+the server. Same-model parallel is usually fine (Ollama queues).+"""++from __future__ import annotations++import argparse+import csv+import os+import re+import subprocess+import sys+import time+from concurrent.futures import ThreadPoolExecutor, as_completed+from dataclasses import dataclass+from pathlib import Path++DEFAULT_QUERIES = [+ "LLM interpretability latest research",+ "mechanistic interpretability of transformer language models",+ "sparse autoencoders for neural network feature discovery",+ "safety alignment and refusal in large language models",+]+DEFAULT_ENGINES = ["arxiv", "openalex"]+DEFAULT_MODELS = ["qwen3.5:9b", "gemma3:12b", "ministral-3:14b"]+++def slugify(text: str, max_len: int = 50) -> str:+ s = re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")+ return s[:max_len]+++@dataclass+class Cell:+ query: str+ engine: str+ model: str++ def key(self) -> str:+ return f"{self.engine}__{slugify(self.model)}__{slugify(self.query)}"+++def already_done(cell: Cell, out_dir: Path) -> bool:+ return (out_dir / "reports" / f"{cell.key()}.md").exists()+++def run_cell(cell: Cell, out_dir: Path, ollama_url: str) -> dict:+ """Invoke run_full_search.py as a subprocess for isolation between cells."""+ report_path = out_dir / "reports" / f"{cell.key()}.md"+ log_path = out_dir / "logs" / f"{cell.key()}.log"++ script = Path(__file__).parent / "run_full_search.py"+ cmd = [+ sys.executable,+ str(script),+ "--query",+ cell.query,+ "--engine",+ cell.engine,+ "--model",+ cell.model,+ "--ollama-url",+ ollama_url,+ "--verbose",+ "--output",+ str(report_path),+ ]++ env = os.environ.copy()+ env.setdefault("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED", "true")+ env.setdefault("LDR_TESTING_WITH_MOCKS", "false")++ t0 = time.monotonic()+ try:+ with log_path.open("w") as logf:+ proc = subprocess.run(+ cmd,+ env=env,+ stdout=logf,+ stderr=subprocess.STDOUT,+ timeout=60 * 30, # 30-min hard cap per cell+ check=False,+ )+ elapsed = time.monotonic() - t0+ exit_code = proc.returncode+ except subprocess.TimeoutExpired:+ elapsed = time.monotonic() - t0+ exit_code = -1+ # A partially-written report would otherwise cause ``already_done``+ # to skip this cell on the next run even though it never finished.+ report_path.unlink(missing_ok=True)+ except Exception as exc:+ elapsed = time.monotonic() - t0+ exit_code = -2+ log_path.write_text(f"Exception: {exc!r}\n")+ report_path.unlink(missing_ok=True)++ result = {+ "query": cell.query,+ "engine": cell.engine,+ "model": cell.model,+ "elapsed_s": round(elapsed, 1),+ "exit_code": exit_code,+ "report_path": str(report_path) if report_path.exists() else "",+ "sources": 0,+ "log_path": str(log_path),+ }++ if report_path.exists():+ text = report_path.read_text()+ m = re.search(r"^\s*-\s*\*\*Sources:\*\*\s*(\d+)", text, re.M)+ if m:+ result["sources"] = int(m.group(1))++ return result+++def parse_list(+ s: str, sep_primary: str = "|", sep_fallback: str = ","+) -> list[str]:+ """Parse a delimiter-separated list — '|' preferred for queries with commas."""+ sep = sep_primary if sep_primary in s else sep_fallback+ return [x.strip() for x in s.split(sep) if x.strip()]+++def main() -> int:+ p = argparse.ArgumentParser(+ description="Build a cross-product eval dataset (query × engine × model).",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ p.add_argument(+ "--queries",+ default=None,+ help="Queries separated by '|'. Default: a 4-query interpretability set.",+ )+ p.add_argument(+ "--engines",+ default=",".join(DEFAULT_ENGINES),+ help="Comma-separated engine names.",+ )+ p.add_argument(+ "--models",+ default=",".join(DEFAULT_MODELS),+ help="Comma-separated Ollama model tags.",+ )+ p.add_argument(+ "--output-dir",+ default="./ldr_eval_output",+ help="Where reports/, logs/, summary.csv land.",+ )+ p.add_argument(+ "--ollama-url",+ default=os.environ.get(+ "LDR_TEST_OLLAMA_BASE_URL", "http://localhost:11434"+ ),+ )+ p.add_argument(+ "--parallel",+ type=int,+ default=1,+ help="Cells to run concurrently. 1 = sequential. 2+ may OOM Ollama if different models are loaded simultaneously.",+ )+ p.add_argument(+ "--force",+ action="store_true",+ help="Re-run cells even if their report file already exists.",+ )+ args = p.parse_args()++ queries = (+ parse_list(args.queries) if args.queries else list(DEFAULT_QUERIES)+ )+ engines = parse_list(args.engines)+ models = parse_list(args.models)++ out_dir = Path(args.output_dir).resolve()+ (out_dir / "reports").mkdir(parents=True, exist_ok=True)+ (out_dir / "logs").mkdir(parents=True, exist_ok=True)++ cells = [+ Cell(query=q, engine=e, model=m)+ for q in queries+ for e in engines+ for m in models+ ]++ total = len(cells)+ todo = [c for c in cells if args.force or not already_done(c, out_dir)]+ skipped = total - len(todo)++ print(+ f"Grid: {len(queries)} queries × {len(engines)} engines × {len(models)} models = {total} cells",+ file=sys.stderr,+ )+ print(f" {skipped} already done (use --force to re-run)", file=sys.stderr)+ print(f" {len(todo)} to run, parallel={args.parallel}", file=sys.stderr)+ print(f" Output: {out_dir}", file=sys.stderr)++ summary_path = out_dir / "summary.csv"+ summary_rows: list[dict] = []+ if summary_path.exists():+ with summary_path.open() as f:+ summary_rows = list(csv.DictReader(f))++ def run_and_log(cell: Cell) -> dict:+ print(+ f" >>> {cell.engine} | {cell.model} | {cell.query[:60]}",+ file=sys.stderr,+ )+ r = run_cell(cell, out_dir, args.ollama_url)+ status = "ok" if r["exit_code"] == 0 else f"exit={r['exit_code']}"+ print(+ f" {status} {r['elapsed_s']}s sources={r['sources']} {cell.key()}",+ file=sys.stderr,+ )+ return r++ t0 = time.monotonic()+ if args.parallel <= 1:+ for cell in todo:+ summary_rows = _upsert(summary_rows, run_and_log(cell))+ _write_summary(summary_path, summary_rows)+ else:+ with ThreadPoolExecutor(max_workers=args.parallel) as pool:+ futures = {pool.submit(run_and_log, c): c for c in todo}+ for fut in as_completed(futures):+ summary_rows = _upsert(summary_rows, fut.result())+ _write_summary(summary_path, summary_rows)++ elapsed = time.monotonic() - t0+ print(+ f"\nDataset build complete in {elapsed / 60:.1f}min.", file=sys.stderr+ )+ print(f" Summary: {summary_path}", file=sys.stderr)+ _print_table(summary_rows)+ return 0+++def _upsert(rows: list[dict], new: dict) -> list[dict]:+ """Replace a row with the same (query, engine, model) or append."""+ out = [+ r+ for r in rows+ if not (+ r.get("query") == new["query"]+ and r.get("engine") == new["engine"]+ and r.get("model") == new["model"]+ )+ ]+ out.append({k: str(v) for k, v in new.items()})+ return out+++def _write_summary(path: Path, rows: list[dict]) -> None:+ if not rows:+ return+ fieldnames = [+ "query",+ "engine",+ "model",+ "sources",+ "elapsed_s",+ "exit_code",+ "report_path",+ "log_path",+ ]+ with path.open("w", newline="") as f:+ w = csv.DictWriter(f, fieldnames=fieldnames)+ w.writeheader()+ for r in rows:+ w.writerow({k: r.get(k, "") for k in fieldnames})+++def _print_table(rows: list[dict]) -> None:+ if not rows:+ return+ print("\n=== Dataset summary ===")+ print(+ f"{'engine':10s} {'model':20s} {'sources':>8s} {'elapsed_s':>10s} query"+ )+ for r in rows:+ print(+ f"{r.get('engine', ''):10s} {r.get('model', ''):20s} "+ f"{str(r.get('sources', '')):>8s} {str(r.get('elapsed_s', '')):>10s} "+ f"{r.get('query', '')[:60]}"+ )+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/performance/_shared/run_full_search.py b/tests/performance/_shared/run_full_search.pynew file mode 100644index 0000000000..7f60ee0d63--- /dev/null+++ b/tests/performance/_shared/run_full_search.py@@ -0,0 +1,178 @@+"""End-to-end LDR pipeline test — runs a real Quick Summary via programmatic API.++Produces the same style of output as the "Quick Summary" mode in the web UI,+but from a single command so we can diff reports against one another (e.g.+same query with arxiv vs openalex). Useful for evaluating the relevance-+filter prompt and synthesis quality in situ.++Usage:+ LDR_BOOTSTRAP_ALLOW_UNENCRYPTED=true LDR_TESTING_WITH_MOCKS=false \\+ pdm run python tests/performance/_shared/run_full_search.py \\+ --query "LLM interpretability latest research" \\+ --engine openalex \\+ --output /tmp/ldr_report_openalex.md++Default model / URL mirror the other dev scripts so a bare invocation with+just --query also works.+"""++from __future__ import annotations++import argparse+import os+import sys+import tempfile+import time+from pathlib import Path++import requests++PROJECT_ROOT = Path(__file__).resolve().parents[3]+sys.path.insert(0, str(PROJECT_ROOT / "src"))++from local_deep_research.api import quick_summary # noqa: E402+from local_deep_research.api.settings_utils import ( # noqa: E402+ create_settings_snapshot,+)+from local_deep_research.security import safe_get # noqa: E402+from local_deep_research.security.file_write_verifier import ( # noqa: E402+ write_file_verified,+)++DEFAULT_OLLAMA_URL = os.environ.get(+ "LDR_TEST_OLLAMA_BASE_URL", "http://localhost:11434"+)+DEFAULT_OLLAMA_MODEL = os.environ.get("LDR_TEST_OLLAMA_MODEL", "qwen3.5:9b")++VALID_ENGINES = [+ "arxiv",+ "openalex",+ "wikipedia",+ "searxng",+ "parallel",+ "parallel_scientific",+ "auto",+]+++def check_ollama(url: str) -> bool:+ try:+ resp = safe_get(+ f"{url.rstrip('/')}/api/tags",+ timeout=5,+ allow_private_ips=True,+ )+ return resp.status_code == 200+ except requests.RequestException:+ return False+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(+ description="Run a Quick Summary end-to-end against a chosen search engine.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ p.add_argument("--query", required=True, help="Research query.")+ p.add_argument(+ "--engine",+ default="arxiv",+ choices=VALID_ENGINES,+ help="Search engine (search.tool).",+ )+ p.add_argument("--model", default=DEFAULT_OLLAMA_MODEL)+ p.add_argument("--ollama-url", default=DEFAULT_OLLAMA_URL)+ p.add_argument(+ "--iterations",+ type=int,+ default=1,+ help="search.iterations — 1 matches the REST API default for Quick Summary.",+ )+ p.add_argument(+ "--output",+ default=None,+ help="Path for the generated report. Defaults to /tmp/ldr_report_<engine>.md",+ )+ p.add_argument(+ "--verbose",+ action="store_true",+ help="Enable DEBUG logging (LDR_APP_DEBUG=true) — shows filter KEPT/REMOVED decisions.",+ )+ args = p.parse_args()+ if not args.output:+ args.output = str(+ Path(tempfile.gettempdir()) / f"ldr_report_{args.engine}.md"+ )+ return args+++def main() -> int:+ args = parse_args()++ if args.verbose:+ os.environ["LDR_APP_DEBUG"] = "true"++ if not check_ollama(args.ollama_url):+ print(+ f"Ollama endpoint {args.ollama_url} not reachable. Start it or pass --ollama-url.",+ file=sys.stderr,+ )+ return 1++ settings = create_settings_snapshot(+ overrides={+ "llm.provider": "ollama",+ "llm.model": args.model,+ "llm.ollama.url": args.ollama_url,+ "search.tool": args.engine,+ "search.iterations": args.iterations,+ "api.allow_file_output": True,+ }+ )++ print(+ f"Running Quick Summary — engine={args.engine} model={args.model} "+ f"iterations={args.iterations}",+ file=sys.stderr,+ )+ print(f" Query: {args.query!r}", file=sys.stderr)+ print(f" Ollama: {args.ollama_url}", file=sys.stderr)++ t0 = time.monotonic()+ result = quick_summary(+ args.query,+ settings_snapshot=settings,+ programmatic_mode=True,+ )+ elapsed = time.monotonic() - t0++ body = result.get("formatted_findings") or result.get("summary") or ""+ sources = result.get("sources", []) or []++ header = (+ f"# Research Results: {args.query}\n\n"+ f"- **Engine:** {args.engine}\n"+ f"- **Model:** {args.model}\n"+ f"- **Iterations:** {args.iterations}\n"+ f"- **Sources:** {len(sources)}\n"+ f"- **Elapsed:** {elapsed:.1f}s\n"+ f"- **Generated:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"+ "---\n\n"+ )++ write_file_verified(+ args.output,+ header + body,+ "api.allow_file_output",+ context="dev Quick Summary eval",+ settings_snapshot=settings,+ )++ print(+ f"\nDone in {elapsed:.1f}s. {len(sources)} sources. Wrote: {args.output}",+ file=sys.stderr,+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/performance/relevance_filter/__init__.py b/tests/performance/relevance_filter/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/performance/relevance_filter/eval_models.py b/tests/performance/relevance_filter/eval_models.pynew file mode 100644index 0000000000..26670884be--- /dev/null+++ b/tests/performance/relevance_filter/eval_models.py@@ -0,0 +1,210 @@+"""Compare multiple local LLMs as relevance-filter judges on the same arXiv results.++Companion to ``eval_relevance_prompt.py`` — that script varies the prompt+with one model held constant; this one varies the model with the prompt+held constant (the prompt currently on the PR).++Usage:+ LDR_BOOTSTRAP_ALLOW_UNENCRYPTED=true \\+ LDR_TEST_OLLAMA_BASE_URL=http://localhost:11434 \\+ pdm run python tests/performance/relevance_filter/eval_models.py++Override the model list via env var:+ LDR_TEST_OLLAMA_MODELS="qwen3:4b,qwen3.5:9b,gemma3:12b"++Fetches arXiv results once per query and runs the filter with each model.+Prints per-model keep counts and the consensus / disagreement breakdown so+a human can judge whether the prompt generalises across families and sizes.+"""++from __future__ import annotations++import os+import sys+import time+from pathlib import Path+from typing import Dict, List++import arxiv+import requests++PROJECT_ROOT = Path(__file__).resolve().parents[3]+sys.path.insert(0, str(PROJECT_ROOT / "src"))++from local_deep_research.security import safe_get # noqa: E402+from local_deep_research.web_search_engines.relevance_filter import ( # noqa: E402+ filter_previews_for_relevance,+)++OLLAMA_URL = os.environ.get(+ "LDR_TEST_OLLAMA_BASE_URL", "http://localhost:11434"+)+ARXIV_MAX = int(os.environ.get("LDR_TEST_ARXIV_MAX", "40"))++# Default model set — picked for family / size diversity so we can see+# whether prompt quality transfers. Override via LDR_TEST_OLLAMA_MODELS.+DEFAULT_MODELS = [+ "qwen3:4b", # tiny — test the floor+ "qwen3.5:9b", # current default+ "gemma3:12b", # Gemma family+ "ministral-3:14b", # Mistral family+ "gpt-oss:20b", # OpenAI-origin+ "qwen3.5:27b", # larger qwen — does scaling help+]++QUERIES = [+ "LLM interpretability latest research",+ "sparse autoencoders for mechanistic interpretability",+]+++def fetch_previews(query: str, max_results: int) -> List[Dict]:+ client = arxiv.Client(page_size=max_results)+ search = arxiv.Search(+ query=query,+ max_results=max_results,+ sort_by=arxiv.SortCriterion.Relevance,+ )+ return [+ {+ "title": p.title.strip(),+ "snippet": (p.summary or "").strip(),+ "url": p.entry_id,+ }+ for p in client.results(search)+ ]+++def check_ollama(url: str) -> bool:+ try:+ resp = safe_get(+ f"{url.rstrip('/')}/api/tags",+ timeout=3,+ allow_private_ips=True,+ )+ return resp.status_code == 200+ except requests.RequestException:+ return False+++def installed_models(url: str) -> set:+ try:+ resp = safe_get(+ f"{url.rstrip('/')}/api/tags",+ timeout=3,+ allow_private_ips=True,+ )+ return {m["name"] for m in resp.json().get("models", [])}+ except requests.RequestException:+ return set()+++def run_model(model: str, llm, previews, query) -> List[Dict]:+ return filter_previews_for_relevance(+ llm=llm,+ previews=previews,+ query=query,+ max_filtered_results=None,+ engine_name=f"Eval[{model}]",+ batch_size=10,+ max_parallel_batches=4,+ )+++def summarise(+ kept_by_model: Dict[str, List[Dict]],+ previews: List[Dict],+ timings: Dict[str, float],+) -> None:+ all_titles = {p["title"] for p in previews}+ kept_titles = {+ name: {p["title"] for p in kept} for name, kept in kept_by_model.items()+ }++ print("\n=== Per-model keep counts ===")+ for name in kept_by_model:+ n = len(kept_titles[name])+ print(+ f" {name:24s} kept {n:3d} / {len(previews)} ({timings[name]:.1f}s)"+ )++ if len(kept_by_model) < 2:+ return++ consensus = set.intersection(*kept_titles.values())+ print(+ f"\n=== Consensus (kept by ALL {len(kept_by_model)} models): {len(consensus)} ==="+ )+ for t in sorted(consensus):+ print(f" = {t[:110]}")++ rejected_by_all = all_titles - set.union(*kept_titles.values())+ print(f"\n=== Rejected by ALL models: {len(rejected_by_all)} ===")+ for t in sorted(rejected_by_all):+ print(f" × {t[:110]}")++ print("\n=== Disagreements (kept by some, rejected by others) ===")+ for title in sorted(all_titles - consensus - rejected_by_all):+ kept_in = [+ name for name, titles in kept_titles.items() if title in titles+ ]+ tag = ",".join(m.split(":")[0][:6] for m in kept_in)+ print(f" [{tag:40s}] {title[:100]}")+++def main() -> int:+ if not check_ollama(OLLAMA_URL):+ print(f"Ollama endpoint {OLLAMA_URL} not reachable.", file=sys.stderr)+ return 1++ override = os.environ.get("LDR_TEST_OLLAMA_MODELS")+ if override:+ models = [m.strip() for m in override.split(",") if m.strip()]+ else:+ models = list(DEFAULT_MODELS)++ installed = installed_models(OLLAMA_URL)+ missing = [m for m in models if m not in installed]+ if missing:+ print(f"Skipping models not installed on {OLLAMA_URL}: {missing}")+ models = [m for m in models if m in installed]+ if not models:+ print("No models to test.", file=sys.stderr)+ return 1++ from langchain_ollama import ChatOllama++ print(f"Testing {len(models)} models: {models}")++ for query in QUERIES:+ print("\n" + "=" * 78)+ print(f"QUERY: {query!r}")+ print(f"Endpoint: {OLLAMA_URL}")+ print("=" * 78)++ previews = fetch_previews(query, ARXIV_MAX)+ print(f"Fetched {len(previews)} arXiv previews.\n")++ kept_by_model: Dict[str, List[Dict]] = {}+ timings: Dict[str, float] = {}++ for model in models:+ llm = ChatOllama(model=model, base_url=OLLAMA_URL, num_ctx=8192)+ t0 = time.monotonic()+ try:+ kept = run_model(model, llm, previews, query)+ except Exception as exc:+ print(f" {model:24s}: ERROR {exc!r}")+ continue+ elapsed = time.monotonic() - t0+ kept_by_model[model] = kept+ timings[model] = elapsed+ print(f" {model:24s}: kept {len(kept):3d} in {elapsed:.1f}s")++ summarise(kept_by_model, previews, timings)++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/performance/relevance_filter/eval_prompt.py b/tests/performance/relevance_filter/eval_prompt.pynew file mode 100644index 0000000000..b4ac30519d--- /dev/null+++ b/tests/performance/relevance_filter/eval_prompt.py@@ -0,0 +1,214 @@+"""Compare multiple relevance-filter prompt variants on the same arXiv results.++Usage:+ LDR_BOOTSTRAP_ALLOW_UNENCRYPTED=true \\+ LDR_TEST_OLLAMA_BASE_URL=http://localhost:11434 \\+ LDR_TEST_OLLAMA_MODEL=qwen3.5:9b \\+ pdm run python tests/performance/relevance_filter/eval_prompt.py++Fetches arXiv results ONCE per query and then runs the filter with each+candidate prompt variant. Prints a side-by-side comparison so a human can+judge which variant keeps the right papers and drops the right ones.++This is a dev tool — not a pytest test — because the right answer is a+human judgment, not a hard assertion.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path+from typing import Dict, List++import arxiv+import requests++PROJECT_ROOT = Path(__file__).resolve().parents[3]+sys.path.insert(0, str(PROJECT_ROOT / "src"))++from local_deep_research.security import safe_get # noqa: E402+from local_deep_research.web_search_engines.relevance_filter import ( # noqa: E402+ filter_previews_for_relevance,+)++OLLAMA_URL = os.environ.get(+ "LDR_TEST_OLLAMA_BASE_URL", "http://localhost:11434"+)+OLLAMA_MODEL = os.environ.get("LDR_TEST_OLLAMA_MODEL", "qwen3.5:9b")+ARXIV_MAX = int(os.environ.get("LDR_TEST_ARXIV_MAX", "40"))+++QUERIES = [+ "LLM interpretability latest research",+ "sparse autoencoders for mechanistic interpretability",+]+++# The shared scaffolding around the guidance block. The variants below only+# swap the middle paragraph — query block, date, results block, and output+# contract stay identical so the comparison is clean.+def _make_template(guidance: str) -> str:+ return (+ "This is a relevance-filtering step. Kept results move forward and may be used in the final answer; dropped ones are excluded from further processing.\n\n"+ 'Query: "{query}"\n'+ "Current date: {current_date}\n\n"+ "Search results:\n"+ "{preview_text}\n\n"+ f"{guidance}\n\n"+ "Output ONLY the 0-based indices of relevant results as a comma-separated list, nothing else.\n"+ "Example: 0, 2, 5"+ )+++VARIANTS: Dict[str, str] = {+ # V0 — the prompt currently shipping on main after the selectivity-+ # bias fix. Run against this as the baseline to validate new variants.+ "V0_current": _make_template(+ "Direct topic match matters more than keyword match — results that just mention the query terms usually don't help."+ ),+ # V1 — explicit "prefer smaller" selectivity bias (the version that+ # was on an earlier commit of this PR before we dropped it). Kept as+ # a variant so we can quantify the regression if someone re-adds it.+ "V1_prefer_smaller": _make_template(+ "Direct topic match matters more than keyword match — results that just mention the query terms usually don't help. "+ "Prefer a smaller high-confidence selection over a broader one."+ ),+ # V2 — explicitly allow related/adjacent work. Targets the observed+ # false negatives on mech-interp papers that share only one of two query terms.+ "V2_inclusive_adjacent": _make_template(+ "Keep results whose main subject is the query topic or closely relates to it. "+ "Reject results that share keywords with the query but whose main subject is clearly something else."+ ),+ # V3 — flip the framing to emphasise what to keep rather than what to reject.+ "V3_keep_framing": _make_template(+ "A result is relevant if reading it would help someone answering the query. "+ "Borderline-relevant work is often worth keeping; reject only when the main subject is clearly elsewhere."+ ),+ # V4 — terser, closer to the historical "MUST directly address" line.+ "V4_terse": _make_template(+ "Keep results whose main subject directly addresses the query. "+ "Mere keyword overlap with off-topic work is not relevant."+ ),+}+++def fetch_previews(query: str, max_results: int) -> List[Dict]:+ client = arxiv.Client(page_size=max_results)+ search = arxiv.Search(+ query=query,+ max_results=max_results,+ sort_by=arxiv.SortCriterion.Relevance,+ )+ return [+ {+ "title": p.title.strip(),+ "snippet": (p.summary or "").strip(),+ "url": p.entry_id,+ }+ for p in client.results(search)+ ]+++def check_ollama(url: str) -> bool:+ try:+ resp = safe_get(+ f"{url.rstrip('/')}/api/tags",+ timeout=3,+ allow_private_ips=True,+ )+ return resp.status_code == 200+ except requests.RequestException:+ return False+++def run_one(+ variant_name: str, template: str, llm, previews, query+) -> List[Dict]:+ return filter_previews_for_relevance(+ llm=llm,+ previews=previews,+ query=query,+ max_filtered_results=None,+ engine_name=f"Eval[{variant_name}]",+ batch_size=10,+ max_parallel_batches=4,+ prompt_template=template,+ )+++def summarise(+ kept_by_variant: Dict[str, List[Dict]], previews: List[Dict]+) -> None:+ all_titles = {p["title"] for p in previews}+ kept_titles_by_variant = {+ name: {p["title"] for p in kept}+ for name, kept in kept_by_variant.items()+ }++ print("\n=== Per-variant counts ===")+ # Iterate over the collected results rather than VARIANTS so a+ # variant that raised (and was skipped in main) doesn't KeyError.+ for name, titles in kept_titles_by_variant.items():+ print(f" {name:24s} kept {len(titles):3d} / {len(previews)}")++ if len(kept_titles_by_variant) < 2:+ return++ consensus = set.intersection(*kept_titles_by_variant.values())+ print(f"\n=== Consensus (kept by ALL variants): {len(consensus)} ===")+ for t in sorted(consensus):+ print(f" = {t[:110]}")++ rejected_by_all = all_titles - set.union(*kept_titles_by_variant.values())+ print(f"\n=== Rejected by ALL variants: {len(rejected_by_all)} ===")+ for t in sorted(rejected_by_all):+ print(f" × {t[:110]}")++ print("\n=== Disagreements (kept by some, rejected by others) ===")+ for title in sorted(all_titles - consensus - rejected_by_all):+ kept_in = [+ name+ for name, titles in kept_titles_by_variant.items()+ if title in titles+ ]+ print(+ f" [{','.join(v.split('_')[0] for v in kept_in):14s}] {title[:100]}"+ )+++def main() -> int:+ if not check_ollama(OLLAMA_URL):+ print(f"Ollama endpoint {OLLAMA_URL} not reachable.", file=sys.stderr)+ return 1++ from langchain_ollama import ChatOllama++ llm = ChatOllama(model=OLLAMA_MODEL, base_url=OLLAMA_URL, num_ctx=8192)++ for query in QUERIES:+ print("\n" + "=" * 78)+ print(f"QUERY: {query!r}")+ print(f"Judge: {OLLAMA_MODEL} @ {OLLAMA_URL}")+ print("=" * 78)++ previews = fetch_previews(query, ARXIV_MAX)+ print(f"Fetched {len(previews)} arXiv previews.\n")++ kept_by_variant: Dict[str, List[Dict]] = {}+ for name, template in VARIANTS.items():+ try:+ kept = run_one(name, template, llm, previews, query)+ except Exception as exc:+ print(f" {name:24s}: ERROR {exc!r}")+ continue+ kept_by_variant[name] = kept+ print(f" {name:24s}: kept {len(kept)}")++ summarise(kept_by_variant, previews)++ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/performance/relevance_filter/test_live.py b/tests/performance/relevance_filter/test_live.pynew file mode 100644index 0000000000..d5da5d9d3a--- /dev/null+++ b/tests/performance/relevance_filter/test_live.py@@ -0,0 +1,168 @@+"""Live end-to-end check of the LLM relevance filter against real arXiv results.++Hits arXiv for previews and a real Ollama endpoint for the judge, then runs+``filter_previews_for_relevance`` on the pair. Prints KEPT/REMOVED so a human+can eyeball whether the filter is doing the right thing for the chosen local+LLM and prompt.++Excluded from CI via the ``integration`` marker. Skips cleanly if Ollama is+unreachable so running the performance suite locally without a running+endpoint does not fail.++Environment variables (all optional — defaults target a typical local setup):++ LDR_TEST_OLLAMA_BASE_URL Ollama endpoint (default http://localhost:11434)+ LDR_TEST_OLLAMA_MODEL Model tag to load (default qwen3.5:9b)+ LDR_TEST_ARXIV_MAX How many arXiv results to request (default 40)+"""++from __future__ import annotations++import os+from typing import Any, Dict, List+from urllib.parse import urlparse++import pytest+import requests++pytestmark = [+ pytest.mark.integration,+ pytest.mark.requires_llm,+ pytest.mark.slow,+]+++DEFAULT_OLLAMA_URL = "http://localhost:11434"+DEFAULT_OLLAMA_MODEL = "qwen3.5:9b"+++def _ollama_url() -> str:+ return os.environ.get("LDR_TEST_OLLAMA_BASE_URL", DEFAULT_OLLAMA_URL)+++def _ollama_model() -> str:+ return os.environ.get("LDR_TEST_OLLAMA_MODEL", DEFAULT_OLLAMA_MODEL)+++def _ollama_reachable(url: str, timeout: float = 2.0) -> bool:+ # Use safe_get with allow_private_ips=True — the reachability probe+ # targets a user-configured Ollama endpoint on a local/private+ # network, same pattern as the sibling eval scripts.+ from local_deep_research.security import safe_get++ try:+ resp = safe_get(+ f"{url.rstrip('/')}/api/tags",+ timeout=timeout,+ allow_private_ips=True,+ )+ return resp.status_code == 200+ except requests.RequestException:+ return False++[email protected](scope="module")+def ollama_llm():+ """Real ChatOllama bound to the configured endpoint, or skip the test."""+ url = _ollama_url()+ if not _ollama_reachable(url):+ pytest.skip(+ f"Ollama endpoint {url} not reachable. Set "+ "LDR_TEST_OLLAMA_BASE_URL to a running endpoint or run this "+ "test on a machine that can reach it."+ )++ # Import late so the module itself can be collected even if+ # langchain_ollama isn't installed (it is, via the main deps).+ from langchain_ollama import ChatOllama++ host = urlparse(url).netloc or url+ return ChatOllama(model=_ollama_model(), base_url=url, num_ctx=8192), host+++def _arxiv_previews(query: str, max_results: int) -> List[Dict[str, Any]]:+ """Fetch arXiv previews in the dict shape the relevance filter expects.++ Uses the ``arxiv`` package directly (not ArXivSearchEngine) to avoid the+ rate-limiter, journal-reputation-filter, and thread-context machinery —+ we just want raw title+abstract pairs.+ """+ import arxiv++ client = arxiv.Client(page_size=max_results)+ search = arxiv.Search(+ query=query,+ max_results=max_results,+ sort_by=arxiv.SortCriterion.Relevance,+ )+ previews = []+ for paper in client.results(search):+ previews.append(+ {+ "title": paper.title.strip(),+ "snippet": (paper.summary or "").strip(),+ "url": paper.entry_id,+ }+ )+ return previews+++# Queries chosen to exercise the keyword-bait failure mode. Each one has+# plausibly-matching noise on arXiv: papers that share tokens with the query+# but whose primary topic is something else.+_LIVE_QUERIES = [+ "LLM interpretability latest research",+ "sparse autoencoders for mechanistic interpretability",+]++[email protected]("query", _LIVE_QUERIES, ids=lambda q: q.split()[0])+def test_relevance_filter_against_real_arxiv(ollama_llm, query, capsys):+ """Run arXiv → relevance filter → Ollama end-to-end and report decisions."""+ from local_deep_research.web_search_engines.relevance_filter import (+ filter_previews_for_relevance,+ )++ llm, host = ollama_llm+ max_results = int(os.environ.get("LDR_TEST_ARXIV_MAX", "40"))+ previews = _arxiv_previews(query, max_results)+ assert previews, "arXiv returned no results — check connectivity"++ with capsys.disabled():+ print(f"\n=== Query: {query!r} ===")+ print(f" Judge: {_ollama_model()} @ {host}")+ print(f" arXiv previews fetched: {len(previews)}")++ kept = filter_previews_for_relevance(+ llm=llm,+ previews=previews,+ query=query,+ max_filtered_results=None, # let the judge decide+ engine_name="LiveArxivTest",+ batch_size=10,+ max_parallel_batches=4,+ )++ kept_titles = {p["title"] for p in kept}+ removed = [p for p in previews if p["title"] not in kept_titles]++ with capsys.disabled():+ print(f" KEPT ({len(kept)}):")+ for p in kept:+ print(f" + {p['title'][:110]}")+ print(f" REMOVED ({len(removed)}):")+ for p in removed[:25]:+ print(f" - {p['title'][:110]}")+ if len(removed) > 25:+ print(f" ... and {len(removed) - 25} more")++ # Soft sanity checks — the test exists primarily to surface output for+ # a human to read, but fail loudly if the filter collapses entirely.+ assert kept, (+ f"Filter rejected ALL {len(previews)} results for '{query}'. "+ "Either the judge is broken or the prompt over-rejects."+ )+ assert len(kept) < len(previews), (+ f"Filter kept ALL {len(previews)} results for '{query}'. "+ "The prompt is no longer filtering — likely broken."+ )diff --git a/tests/search_engines/test_base_search_engine.py b/tests/search_engines/test_base_search_engine.pyindex 918c9912f2..10a6db4cd9 100644--- a/tests/search_engines/test_base_search_engine.py+++ b/tests/search_engines/test_base_search_engine.py@@ -2,8 +2,11 @@Tests for BaseSearchEngine."""+import json+from pathlib import Pathfrom unittest.mock import Mock+from local_deep_research.config.constants import DEFAULT_MAX_FILTERED_RESULTSfrom local_deep_research.web_search_engines.search_engine_base import (BaseSearchEngine,AdaptiveWait,@@ -13,6 +16,25 @@ from local_deep_research.web_search_engines.rate_limiting import ()+def test_default_max_filtered_results_matches_default_settings_json():+ """``DEFAULT_MAX_FILTERED_RESULTS`` (the Python fallback used when no+ DB is available) must match the shipping value in+ ``defaults/default_settings.json`` — otherwise a user with a seeded+ DB and a programmatic caller without one see different filter caps."""+ defaults_path = (+ Path(__file__).resolve().parents[2]+ / "src"+ / "local_deep_research"+ / "defaults"+ / "default_settings.json"+ )+ settings = json.loads(defaults_path.read_text())+ assert (+ settings["search.max_filtered_results"]["value"]+ == DEFAULT_MAX_FILTERED_RESULTS+ )++def _make_structured_llm(indices):"""Create a mock LLM whose ``invoke()`` returns the given indices asa comma-separated text response (matches the relevance_filter contract)."""@@ -309,7 +331,7 @@ class TestBaseSearchEngineInit:engine = ConcreteSearchEngine(programmatic_mode=True)assert engine.max_results == 10- assert engine.max_filtered_results == 5+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTSassert engine.llm is Noneassert engine.search_snippets_only is Trueassert engine.programmatic_mode is True@@ -339,7 +361,7 @@ class TestBaseSearchEngineInit:)assert engine.max_results == 10- assert engine.max_filtered_results == 5+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTSdef test_init_with_filters(self):"""Test initialization with custom filters."""@@ -419,7 +441,7 @@ class TestMaxFilteredResultsProperty:"""Test max_filtered_results setter with None uses default."""engine = ConcreteSearchEngine(programmatic_mode=True)engine.max_filtered_results = None- assert engine.max_filtered_results == 5+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTSclass TestRunMethod:@@ -609,7 +631,8 @@ class TestFilterForRelevance:def test_filter_with_parse_error_returns_capped_fallback(self):"""Parse errors return a capped slice of the previews so thedownstream pipeline isn't fed empty results when the filter is- unavailable. Cap is ``max_filtered_results or 5``."""+ unavailable. Cap is+ ``max_filtered_results or DEFAULT_MAX_FILTERED_RESULTS``."""mock_llm = _make_error_llm(ValueError("Failed to parse structured output"))@@ -623,7 +646,7 @@ class TestFilterForRelevance:result = engine._filter_for_relevance(previews, "query")- # All 3 previews fit under the default cap of 5+ # All 3 previews fit under DEFAULT_MAX_FILTERED_RESULTSassert result == previewsdef test_filter_limits_to_max_filtered_results(self):@@ -649,7 +672,8 @@ class TestFilterForRelevance:def test_filter_handles_llm_exception(self):"""LLM exceptions return a capped slice of the previews so thedownstream pipeline isn't fed empty results when the filter is- unavailable. Cap is ``max_filtered_results or 5``."""+ unavailable. Cap is+ ``max_filtered_results or DEFAULT_MAX_FILTERED_RESULTS``."""mock_llm = _make_error_llm(Exception("LLM error"))engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)@@ -660,15 +684,19 @@ class TestFilterForRelevance:result = engine._filter_for_relevance(previews, "query")- # Both previews fit under the default cap of 5+ # Both previews fit under DEFAULT_MAX_FILTERED_RESULTSassert result == previewsdef test_filter_truncates_long_snippets(self):- """Test filtering truncates long snippets in prompt."""+ """Filter must not fail on snippets longer than the internal+ snippet cap (``_SNIPPET_CHAR_CAP`` in ``relevance_filter.py``).+ The truncation happens inside the prompt builder, not in the+ returned preview, so we just assert the call succeeds and the+ cap doesn't bleed into the output."""mock_llm = _make_structured_llm([0])engine = ConcreteSearchEngine(llm=mock_llm, programmatic_mode=True)- long_snippet = "x" * 500 # Longer than 300 char limit+ long_snippet = "x" * 2000 # Longer than the 800-char cappreviews = [{"title": "A", "snippet": long_snippet, "url": "https://a.com"},{"title": "B", "snippet": "Short", "url": "https://b.com"},@@ -676,8 +704,11 @@ class TestFilterForRelevance:result = engine._filter_for_relevance(previews, "query")- # Should succeed - just checking it doesn't fail- assert len(result) >= 0+ # Single index returned → one kept. Snippet in the returned+ # preview is NOT truncated — the cap only applies inside the+ # filter's prompt text.+ assert len(result) == 1+ assert result[0]["snippet"] == long_snippetclass TestRateLimiting:diff --git a/tests/web_search_engines/engines/test_meta_search_coverage.py b/tests/web_search_engines/engines/test_meta_search_coverage.pyindex 83784fa40c..e955d02ffd 100644--- a/tests/web_search_engines/engines/test_meta_search_coverage.py+++ b/tests/web_search_engines/engines/test_meta_search_coverage.py@@ -15,6 +15,7 @@ Focuses on:import pytestfrom unittest.mock import Mock, patch+from local_deep_research.config.constants import DEFAULT_MAX_FILTERED_RESULTSfrom local_deep_research.web_search_engines.engines.meta_search_engine import (MetaSearchEngine,)@@ -687,12 +688,12 @@ class TestGetEngineInstanceEdgeCases:assert result is Noneassert "bad_engine" not in engine.engine_cache- def test_max_filtered_results_none_defaults_to_five(self):- """max_filtered_results=None is coerced to 5 by the base class property setter."""+ def test_max_filtered_results_none_defaults_to_constant(self):+ """max_filtered_results=None is coerced to DEFAULT_MAX_FILTERED_RESULTS."""engine = _bypass_init()engine.max_filtered_results = None- # The property setter in BaseSearchEngine converts None -> 5- assert engine.max_filtered_results == 5+ # The property setter in BaseSearchEngine converts None -> DEFAULT_MAX_FILTERED_RESULTS+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTSwith patch("local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",@@ -702,7 +703,7 @@ class TestGetEngineInstanceEdgeCases:_, kwargs = mock_create.call_args# Always passed since the property never returns None- assert kwargs["max_filtered_results"] == 5+ assert kwargs["max_filtered_results"] == DEFAULT_MAX_FILTERED_RESULTSdef test_max_filtered_results_set_is_passed(self):"""max_filtered_results when set is passed to create_search_engine."""@@ -949,9 +950,9 @@ class TestInitIntegration:assert engine.max_filtered_results == 15def test_init_with_max_filtered_results_default(self):- """__init__ defaults max_filtered_results to 5 (base class coerces None to 5)."""+ """__init__ defaults max_filtered_results to DEFAULT_MAX_FILTERED_RESULTS."""engine = _make_engine_with_init(["wikipedia"])- assert engine.max_filtered_results == 5+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTS# ===========================================================================diff --git a/tests/web_search_engines/test_relevance_filter.py b/tests/web_search_engines/test_relevance_filter.pyindex 515cecd25e..0b8a62f1bb 100644--- a/tests/web_search_engines/test_relevance_filter.py+++ b/tests/web_search_engines/test_relevance_filter.py@@ -12,8 +12,11 @@ that are hard to assert through the wrapper:- ``_unwrap_llm`` walks a wrapper chain (locks in Ollama optimization)"""+import threading+import timefrom unittest.mock import Mock+from local_deep_research.web_search_engines import relevance_filterfrom local_deep_research.web_search_engines.relevance_filter import (_unwrap_llm,filter_previews_for_relevance,@@ -274,3 +277,64 @@ def test_batch_parallel_dispatches_concurrently():# 3 batches × 2 kept each = 6 results, in original order.assert result == previewsassert llm.invoke.call_count == 3+++# ---------- 7. parallel-batch timeout ----------+++def _blocking_llm(release_event, max_block_s: float = 3.0):+ """Stub whose ``.invoke()`` blocks on ``release_event`` (bounded).++ Returns ``"0"`` when released. ``max_block_s`` caps how long a stuck+ thread will actually block — enough slack for the filter's timeout+ to trip, short enough that leaked test threads release on their own+ well within any pytest-timeout.+ """+ llm = Mock()++ def _invoke(prompt, **kwargs):+ release_event.wait(timeout=max_block_s)+ return "0"++ llm.invoke.side_effect = _invoke+ return llm+++def test_parallel_batch_timeout_does_not_hang(monkeypatch):+ """A stuck batch must not block the pipeline past the wall timeout.++ Regression for PR #3476: before the fix, ``as_completed(timeout=...)``+ raised correctly but ``ThreadPoolExecutor.__exit__`` called+ ``shutdown(wait=True)`` which waited for the stuck worker, so the+ advertised timeout was unenforced. With the ``shutdown(wait=False,+ cancel_futures=True)`` fix this test returns promptly.+ """+ monkeypatch.setattr(relevance_filter, "_FILTER_WALL_TIMEOUT_S", 0.5)++ release = threading.Event()+ previews = _previews(4)+ llm = _blocking_llm(release)++ t0 = time.monotonic()+ try:+ result = filter_previews_for_relevance(+ llm,+ previews,+ "q",+ batch_size=2,+ max_parallel_batches=2,+ max_filtered_results=3,+ )+ elapsed = time.monotonic() - t0+ finally:+ # Let stuck worker threads exit cleanly regardless of what+ # happened in the call — otherwise pytest's global teardown+ # blocks on them.+ release.set()++ # Must return within a small multiple of the patched timeout.+ # Slack accounts for thread-pool teardown and CI jitter.+ assert elapsed < 3.0, f"filter did not honor timeout: took {elapsed:.2f}s"++ # All batches timed out → capped fallback slice.+ assert result == previews[:3]diff --git a/tests/web_search_engines/test_search_engine_base.py b/tests/web_search_engines/test_search_engine_base.pyindex 446bb70cf8..f85c62b05a 100644--- a/tests/web_search_engines/test_search_engine_base.py+++ b/tests/web_search_engines/test_search_engine_base.py@@ -12,6 +12,8 @@ Tests cover:from unittest.mock import Mock+from local_deep_research.config.constants import DEFAULT_MAX_FILTERED_RESULTS+class TestBaseSearchEngineInit:"""Tests for BaseSearchEngine initialization."""@@ -33,7 +35,7 @@ class TestBaseSearchEngineInit:engine = TestEngine()assert engine.max_results == 10- assert engine.max_filtered_results == 5+ assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTSassert engine.search_snippets_only is Trueassert engine.llm is Noneassert engine.programmatic_mode is False