~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
test: add 110 tests for quality stats, exporter registry, citation errors, and entity cache (#2481)
LearningCircuitfe584b8f9972
diff --git a/tests/citation_handlers/test_precision_extraction_error_paths.py b/tests/citation_handlers/test_precision_extraction_error_paths.pynew file mode 100644index 0000000000..71cf8eb3b9--- /dev/null+++ b/tests/citation_handlers/test_precision_extraction_error_paths.py@@ -0,0 +1,452 @@+"""+Tests for PrecisionExtractionHandler LLM error paths.++Covers previously untested exception handlers in:+- _extract_single_answer() - LLM exception fallback (lines 326-329)+- _extract_dimension() - LLM exception fallback (lines 468-471)+- _extract_score() - LLM exception → first-score fallback (lines 491-493)+- _extract_temporal() - LLM exception → first-year fallback (lines 519-521)+- _extract_number() - LLM exception → first-number fallback (lines 544-546)+- _extract_best_name() - no names found (line 567)+- _extract_dimension() - no measurement in LLM response (fallback scoring)+"""++import pytest+from unittest.mock import Mock+++def mock_llm_error():+ """Create a mock LLM that raises on invoke."""+ llm = Mock()+ llm.invoke.side_effect = RuntimeError("LLM connection failed")+ return llm+++def handler_with_error_llm(mock_llm_error):+ """PrecisionExtractionHandler whose LLM always raises."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ return PrecisionExtractionHandler(llm=mock_llm_error)+++def handler(mock_llm):+ """PrecisionExtractionHandler with a working mock LLM."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ return PrecisionExtractionHandler(llm=mock_llm)+++class TestExtractSingleAnswerError:+ """Tests for _extract_single_answer exception handler (lines 326-329)."""++ def test_returns_content_on_llm_error(self, handler_with_error_llm):+ """When LLM raises, returns original content unchanged."""+ content = "The capital of France is Paris."+ result = handler_with_error_llm._extract_single_answer(+ content, "What is the capital of France?", ""+ )+ assert result == content++ def test_returns_content_on_attribute_error(self, mock_llm):+ """When LLM response has no .content attribute, returns original."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = None+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "Test content"+ result = handler._extract_single_answer(content, "test query?", "")+ assert result == content++ def test_successful_extraction_prepends_answer(self, mock_llm):+ """Successful extraction prepends the answer to content."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="Paris")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "The capital of France is Paris, a major European city."+ result = handler._extract_single_answer(+ content, "What is the capital?", ""+ )+ assert result.startswith("Paris.")+ assert content in result++ def test_extraction_cleans_comma_separated(self, mock_llm):+ """Extraction takes only first item from comma-separated answer."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="Paris, London, Berlin")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ result = handler._extract_single_answer("test", "query?", "")+ assert result.startswith("Paris.")++ def test_extraction_cleans_and_separated(self, mock_llm):+ """Extraction takes only first item from 'and'-separated answer."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(+ content="Paris and London and Berlin"+ )+ handler = PrecisionExtractionHandler(llm=mock_llm)++ result = handler._extract_single_answer("test", "query?", "")+ assert result.startswith("Paris.")++ def test_extraction_cleans_or_separated(self, mock_llm):+ """Extraction takes only first item from 'or'-separated answer."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="Paris or Lyon")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ result = handler._extract_single_answer("test", "query?", "")+ assert result.startswith("Paris.")+++class TestExtractDimensionError:+ """Tests for _extract_dimension exception handler (lines 468-471)."""++ def test_returns_content_on_llm_error(self, handler_with_error_llm):+ """When LLM raises, returns original content unchanged."""+ content = "The Eiffel Tower is 324 meters tall."+ result = handler_with_error_llm._extract_dimension(+ content, "How tall is the Eiffel Tower?", ""+ )+ assert result == content++ def test_returns_content_on_no_measurement_match(self, mock_llm):+ """When LLM response has no valid measurement, falls back to regex."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="I'm not sure about that")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "The height is 324 meters approximately."+ result = handler._extract_dimension(content, "How tall is it?", "")+ # Falls through to regex pattern matching+ assert "324 meters" in result++ def test_successful_dimension_extraction(self, mock_llm):+ """Successful extraction returns measurement prepended to content."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="324 meters")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "The Eiffel Tower stands at 324 meters tall."+ result = handler._extract_dimension(+ content, "How tall is the Eiffel Tower?", ""+ )+ assert result.startswith("324 meters.")+ assert content in result++ def test_dimension_type_detection_height(self, handler_with_error_llm):+ """Height keywords in query detected correctly."""+ content = "The building is 100 meters tall and 50 meters wide."+ # LLM will fail, but regex fallback uses dimension scoring+ result = handler_with_error_llm._extract_dimension(+ content, "How tall is the building?", ""+ )+ # Content returned as-is since LLM fails+ assert result == content++ def test_dimension_type_detection_weight(self, handler_with_error_llm):+ """Weight keywords in query detected correctly."""+ content = "The elephant weighs 6000 kg and is 3 meters tall."+ result = handler_with_error_llm._extract_dimension(+ content, "How much does the elephant weigh?", ""+ )+ assert result == content+++class TestExtractScoreError:+ """Tests for _extract_score exception handler (lines 491-493)."""++ def test_returns_first_score_on_llm_error(self, handler_with_error_llm):+ """When LLM raises, returns first score found in content."""+ content = "The final score was 3-2. The halftime score was 1-1."+ result = handler_with_error_llm._extract_score(+ content, "What was the final score?", ""+ )+ # Should fallback to first score pattern: "3-2"+ assert result.startswith("3-2.")+ assert content in result++ def test_returns_content_when_no_scores_found(self, handler_with_error_llm):+ """When no score pattern is found, returns content unchanged."""+ content = "It was an exciting game with many plays."+ result = handler_with_error_llm._extract_score(+ content, "What was the score?", ""+ )+ assert result == content++ def test_successful_score_extraction(self, mock_llm):+ """Successful LLM extraction returns answer prepended to content."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="3-2 (Team A wins)")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "Final score was 3-2. Halftime 1-1."+ result = handler._extract_score(content, "What was the score?", "")+ assert result.startswith("3-2 (Team A wins).")++ def test_score_fallback_uses_first_pattern_match(+ self, handler_with_error_llm+ ):+ """LLM error fallback specifically uses scores[0], not the best match."""+ content = "Halftime 1-0. Final 4-2. Overtime 5-3."+ result = handler_with_error_llm._extract_score(+ content, "What was the overtime score?", ""+ )+ # Fallback always uses first match (1-0), not the contextually best one+ assert result.startswith("1-0.")++ def test_score_from_sources(self, handler_with_error_llm):+ """Score patterns in sources string also get picked up."""+ content = "An exciting match."+ sources = "Final: 7-3 in favor of the home team."+ result = handler_with_error_llm._extract_score(+ content, "What was the score?", sources+ )+ assert result.startswith("7-3.")+++class TestExtractTemporalError:+ """Tests for _extract_temporal exception handler (lines 519-521)."""++ def test_returns_first_year_on_llm_error(self, handler_with_error_llm):+ """When LLM raises, returns first year found in content."""+ content = "Founded in 1998. Went public in 2004. Acquired in 2015."+ result = handler_with_error_llm._extract_temporal(+ content, "When was the company founded?", ""+ )+ # Fallback returns first year found: "1998"+ assert result.startswith("1998.")+ assert content in result++ def test_returns_content_when_no_years_found(self, handler_with_error_llm):+ """When no year pattern is found, returns content unchanged."""+ content = "The event happened many years ago."+ result = handler_with_error_llm._extract_temporal(+ content, "When did it happen?", ""+ )+ assert result == content++ def test_successful_temporal_extraction_with_year(self, mock_llm):+ """Successful extraction with year in LLM response."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="The answer is 2004")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "Founded in 1998. Went public in 2004."+ result = handler._extract_temporal(+ content, "When did the company go public?", ""+ )+ assert result.startswith("2004.")++ def test_successful_temporal_extraction_without_year_in_response(+ self, mock_llm+ ):+ """When LLM response has no year pattern, raw answer is used."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="In the late nineties")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "Founded in 1998."+ result = handler._extract_temporal(content, "When was it founded?", "")+ assert result.startswith("In the late nineties.")++ def test_temporal_fallback_bias_toward_first_year(+ self, handler_with_error_llm+ ):+ """LLM error fallback returns first year even if question asks for latest."""+ content = "Founded in 1998, restructured in 2010, acquired in 2020."+ result = handler_with_error_llm._extract_temporal(+ content, "When was the company acquired?", ""+ )+ # Bug-like behavior: always returns first year (1998) even for "acquired"+ assert result.startswith("1998.")++ def test_temporal_from_sources(self, handler_with_error_llm):+ """Year patterns in sources string also get picked up."""+ content = "The company has a long history."+ sources = "Founded in 2005 by entrepreneurs."+ result = handler_with_error_llm._extract_temporal(+ content, "When was it founded?", sources+ )+ assert result.startswith("2005.")+++class TestExtractNumberError:+ """Tests for _extract_number exception handler (lines 544-546)."""++ def test_returns_first_number_on_llm_error(self, handler_with_error_llm):+ """When LLM raises, returns first number found in content."""+ content = "The population is 8.3 million. The area is 302 sq km."+ result = handler_with_error_llm._extract_number(+ content, "What is the population?", ""+ )+ # Fallback returns first number pattern: "8.3"+ assert result.startswith("8.3.")+ assert content in result++ def test_returns_content_when_no_numbers_found(+ self, handler_with_error_llm+ ):+ """When no number pattern is found, returns content unchanged."""+ content = "Many people live in the city."+ result = handler_with_error_llm._extract_number(+ content, "How many people?", ""+ )+ assert result == content++ def test_successful_number_extraction(self, mock_llm):+ """Successful LLM extraction returns answer prepended to content."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="8.3 million")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "The population is 8.3 million."+ result = handler._extract_number(content, "What is the population?", "")+ assert result.startswith("8.3 million.")++ def test_number_fallback_uses_first_match(self, handler_with_error_llm):+ """LLM error fallback uses first number, not the contextually best."""+ content = "It has 4 floors, 200 rooms, and costs 50 million dollars."+ result = handler_with_error_llm._extract_number(+ content, "How many rooms?", ""+ )+ # Fallback always returns first match: "4"+ assert result.startswith("4.")++ def test_number_from_sources(self, handler_with_error_llm):+ """Number patterns in sources string also get picked up."""+ content = "A large building."+ sources = "The building has 42 floors."+ result = handler_with_error_llm._extract_number(+ content, "How many floors?", sources+ )+ assert result.startswith("42.")+++class TestExtractBestNameEdgeCases:+ """Tests for _extract_best_name edge cases."""++ def test_returns_content_when_no_names_found(self, mock_llm):+ """When no name pattern matches, returns content unchanged."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "the quick brown fox jumps over the lazy dog"+ result = handler._extract_best_name(content, "who did it?", "")+ # No capitalized multi-word names → returns original+ assert result == content++ def test_extracts_most_frequent_name(self, mock_llm):+ """Most frequently occurring name is selected."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="John Smith")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = (+ "John Smith won the award. "+ "John Smith is a professor. "+ "Mary Johnson also attended."+ )+ result = handler._extract_best_name(content, "Who won the award?", "")+ assert "John Smith" in result+++class TestDimensionScoringFallback:+ """Tests for dimension regex fallback scoring logic (lines 392-461)."""++ def test_dimension_with_keyword_context_scores_higher(self, mock_llm):+ """Dimensions near query keywords score higher."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ # LLM returns non-measurement text → triggers fallback+ mock_llm.invoke.return_value = Mock(content="unclear measurement")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = (+ "The width is 50 meters. The height of the tower is 324 meters."+ )+ result = handler._extract_dimension(+ content, "How tall is the tower?", ""+ )+ # "height" keyword near "324 meters" should score it higher+ assert "324 meters" in result++ def test_dimension_fallback_returns_first_when_no_context(self, mock_llm):+ """Without context clues, first dimension found is returned."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="not a measurement")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "Measurements: 10 meters, 20 km, 5 feet."+ result = handler._extract_dimension(+ content, "What is the measurement?", ""+ )+ # Should return some dimension from the content+ assert "meters" in result or "km" in result or "feet" in result++ def test_dimension_no_patterns_returns_content(self, mock_llm):+ """When content has no dimension patterns, returns content unchanged."""+ from local_deep_research.citation_handlers.precision_extraction_handler import (+ PrecisionExtractionHandler,+ )++ mock_llm.invoke.return_value = Mock(content="not a measurement")+ handler = PrecisionExtractionHandler(llm=mock_llm)++ content = "There are no measurements here."+ result = handler._extract_dimension(content, "How tall is it?", "")+ # No regex match either → content returned unchanged+ # (LLM response has no number+unit, regex finds nothing)+ assert result == contentdiff --git a/tests/exporters/test_registry_extended.py b/tests/exporters/test_registry_extended.pynew file mode 100644index 0000000000..3c3e433acc--- /dev/null+++ b/tests/exporters/test_registry_extended.py@@ -0,0 +1,278 @@+"""+Extended tests for ExporterRegistry.++Covers previously untested functionality:+- clear() method (zero existing tests)+- Instance cache invalidation after clear+- Re-registration after clear+- Edge cases: register without format_name, duplicate formats+- get_available_formats ordering behavior+- is_format_supported after mutations+"""++from local_deep_research.exporters.base import BaseExporter, ExportResult+from local_deep_research.exporters.registry import ExporterRegistry+++def _make_test_exporter(+ format_name, file_ext=".test", mime="application/x-test"+):+ """Create a concrete BaseExporter subclass with the given format name."""++ class _TestExporter(BaseExporter):+ @property+ def format_name(self) -> str:+ return format_name++ @property+ def file_extension(self) -> str:+ return file_ext++ @property+ def mimetype(self) -> str:+ return mime++ def export(self, markdown_content, options=None):+ return ExportResult(+ content=markdown_content.encode(),+ filename=f"test{file_ext}",+ mimetype=mime,+ )++ return _TestExporter+++class TestExporterRegistryClear:+ """Tests for clear() method (lines 103-110)."""++ def setup_method(self):+ """Snapshot registry state before test."""+ self._orig_exporters = dict(ExporterRegistry._exporters)+ self._orig_instances = dict(ExporterRegistry._instances)++ def teardown_method(self):+ """Restore registry state after test."""+ ExporterRegistry._exporters.clear()+ ExporterRegistry._exporters.update(self._orig_exporters)+ ExporterRegistry._instances.clear()+ ExporterRegistry._instances.update(self._orig_instances)++ def test_clear_removes_all_exporters(self):+ """clear() empties the _exporters dict."""+ # Ensure at least one exporter is registered+ TestExporter = _make_test_exporter("clear_test_fmt")+ ExporterRegistry.register(TestExporter)+ assert len(ExporterRegistry._exporters) > 0++ ExporterRegistry.clear()++ assert ExporterRegistry._exporters == {}++ def test_clear_removes_all_instances(self):+ """clear() empties the _instances cache."""+ # Trigger instance creation+ TestExporter = _make_test_exporter("clear_inst_fmt")+ ExporterRegistry.register(TestExporter)+ ExporterRegistry.get_exporter("clear_inst_fmt")+ assert "clear_inst_fmt" in ExporterRegistry._instances++ ExporterRegistry.clear()++ assert ExporterRegistry._instances == {}++ def test_clear_then_get_available_formats_empty(self):+ """After clear, get_available_formats returns empty list."""+ ExporterRegistry.clear()++ assert ExporterRegistry.get_available_formats() == []++ def test_clear_then_is_format_supported_false(self):+ """After clear, is_format_supported returns False for all."""+ ExporterRegistry.clear()++ assert ExporterRegistry.is_format_supported("pdf") is False+ assert ExporterRegistry.is_format_supported("odt") is False++ def test_clear_then_get_exporter_returns_none(self):+ """After clear, get_exporter returns None."""+ ExporterRegistry.clear()++ assert ExporterRegistry.get_exporter("pdf") is None++ def test_clear_is_idempotent(self):+ """Calling clear twice does not raise."""+ ExporterRegistry.clear()+ ExporterRegistry.clear()++ assert ExporterRegistry.get_available_formats() == []++ def test_register_after_clear(self):+ """Can register a new exporter after clear."""+ ExporterRegistry.clear()++ TestExporter = _make_test_exporter("after_clear_fmt")+ ExporterRegistry.register(TestExporter)++ assert ExporterRegistry.is_format_supported("after_clear_fmt")+ exporter = ExporterRegistry.get_exporter("after_clear_fmt")+ assert exporter is not None+ assert exporter.format_name == "after_clear_fmt"++ def test_clear_does_not_affect_class_structure(self):+ """Clear only empties dicts, doesn't remove class attributes."""+ ExporterRegistry.clear()++ assert hasattr(ExporterRegistry, "_exporters")+ assert hasattr(ExporterRegistry, "_instances")+ assert isinstance(ExporterRegistry._exporters, dict)+ assert isinstance(ExporterRegistry._instances, dict)+++class TestExporterRegistryInstanceCache:+ """Tests for instance caching behavior in get_exporter."""++ def setup_method(self):+ self._orig_exporters = dict(ExporterRegistry._exporters)+ self._orig_instances = dict(ExporterRegistry._instances)++ def teardown_method(self):+ ExporterRegistry._exporters.clear()+ ExporterRegistry._exporters.update(self._orig_exporters)+ ExporterRegistry._instances.clear()+ ExporterRegistry._instances.update(self._orig_instances)++ def test_get_exporter_caches_instance(self):+ """Second call to get_exporter returns cached instance."""+ TestExporter = _make_test_exporter("cache_fmt")+ ExporterRegistry.register(TestExporter)++ first = ExporterRegistry.get_exporter("cache_fmt")+ second = ExporterRegistry.get_exporter("cache_fmt")++ assert first is second++ def test_clear_invalidates_instance_cache(self):+ """After clear and re-register, get_exporter returns a new instance."""+ TestExporter = _make_test_exporter("reinst_fmt")+ ExporterRegistry.register(TestExporter)+ first = ExporterRegistry.get_exporter("reinst_fmt")++ ExporterRegistry.clear()+ ExporterRegistry.register(TestExporter)+ second = ExporterRegistry.get_exporter("reinst_fmt")++ assert first is not second++ def test_instance_cache_is_per_format(self):+ """Different formats have different cached instances."""+ ExporterA = _make_test_exporter("fmt_a", ".a")+ ExporterB = _make_test_exporter("fmt_b", ".b")+ ExporterRegistry.register(ExporterA)+ ExporterRegistry.register(ExporterB)++ a = ExporterRegistry.get_exporter("fmt_a")+ b = ExporterRegistry.get_exporter("fmt_b")++ assert a is not b+ assert a.format_name == "fmt_a"+ assert b.format_name == "fmt_b"+++class TestExporterRegistryEdgeCases:+ """Edge cases for exporter registration."""++ def setup_method(self):+ self._orig_exporters = dict(ExporterRegistry._exporters)+ self._orig_instances = dict(ExporterRegistry._instances)++ def teardown_method(self):+ ExporterRegistry._exporters.clear()+ ExporterRegistry._exporters.update(self._orig_exporters)+ ExporterRegistry._instances.clear()+ ExporterRegistry._instances.update(self._orig_instances)++ def test_register_overwrites_same_format(self):+ """Registering two exporters with same format_name: last wins."""+ ExporterA = _make_test_exporter("dup_fmt", ".a", "type/a")+ ExporterB = _make_test_exporter("dup_fmt", ".b", "type/b")++ ExporterRegistry.register(ExporterA)+ ExporterRegistry.register(ExporterB)++ # Class dict should have ExporterB+ assert ExporterRegistry._exporters["dup_fmt"] is ExporterB+ # Instance from old class should not be cached+ exporter = ExporterRegistry.get_exporter("dup_fmt")+ assert exporter.file_extension == ".b"++ def test_register_normalizes_format_name_to_lower(self):+ """Format names are lowercased during registration."""+ ExporterUpper = _make_test_exporter("UPPER_FMT")+ ExporterRegistry.register(ExporterUpper)++ assert "upper_fmt" in ExporterRegistry._exporters+ assert ExporterRegistry.is_format_supported("upper_fmt")+ assert ExporterRegistry.is_format_supported("UPPER_FMT")++ def test_get_exporter_normalizes_case(self):+ """get_exporter lowercases the requested format name."""+ TestExporter = _make_test_exporter("mixed_case")+ ExporterRegistry.register(TestExporter)++ assert ExporterRegistry.get_exporter("MIXED_CASE") is not None+ assert ExporterRegistry.get_exporter("Mixed_Case") is not None++ def test_register_returns_class_unchanged(self):+ """register() returns the class unmodified (decorator pattern)."""+ TestExporter = _make_test_exporter("decorator_fmt")++ result = ExporterRegistry.register(TestExporter)++ assert result is TestExporter++ def test_get_available_formats_returns_list(self):+ """get_available_formats returns a list, not dict_keys."""+ formats = ExporterRegistry.get_available_formats()+ assert isinstance(formats, list)++ def test_export_through_registry(self):+ """End-to-end: register, get, and export through registry."""+ TestExporter = _make_test_exporter("e2e_fmt")+ ExporterRegistry.register(TestExporter)++ exporter = ExporterRegistry.get_exporter("e2e_fmt")+ result = exporter.export("# Hello World")++ assert result.content == b"# Hello World"+ assert result.filename == "test.test"+ assert result.mimetype == "application/x-test"++ def test_overwrite_invalidates_old_cached_instance(self):+ """Overwriting registration but old instance is still cached."""+ ExporterA = _make_test_exporter("overwrite_fmt", ".a")+ ExporterRegistry.register(ExporterA)+ old_instance = ExporterRegistry.get_exporter("overwrite_fmt")+ assert old_instance.file_extension == ".a"++ # Re-register with different class+ ExporterB = _make_test_exporter("overwrite_fmt", ".b")+ ExporterRegistry.register(ExporterB)++ # Old cached instance is still returned (known behavior)+ cached = ExporterRegistry.get_exporter("overwrite_fmt")+ # The cache retains the old instance until clear()+ assert cached is old_instance++ def test_overwrite_after_clearing_instance_cache(self):+ """After manually clearing _instances, new class is used."""+ ExporterA = _make_test_exporter("fresh_fmt", ".a")+ ExporterRegistry.register(ExporterA)+ ExporterRegistry.get_exporter("fresh_fmt") # populate cache++ ExporterB = _make_test_exporter("fresh_fmt", ".b")+ ExporterRegistry.register(ExporterB)+ # Clear only instances, not exporters+ ExporterRegistry._instances.pop("fresh_fmt", None)++ exporter = ExporterRegistry.get_exporter("fresh_fmt")+ assert exporter.file_extension == ".b"diff --git a/tests/utilities/test_normalize_entity_query.py b/tests/utilities/test_normalize_entity_query.pynew file mode 100644index 0000000000..7061e568c3--- /dev/null+++ b/tests/utilities/test_normalize_entity_query.py@@ -0,0 +1,170 @@+"""+Tests for normalize_entity_query utility function.++This function normalizes entity + constraint combinations for consistent+caching, using LRU cache for performance. It was previously untested.++Covers:+- Basic normalization (lowercase, whitespace)+- Quote stripping behavior (via .split())+- Empty/whitespace inputs+- Unicode handling+- LRU cache behavior (same input → same output)+"""+++def _get_fn():+ """Import and return normalize_entity_query, clearing its LRU cache."""+ from local_deep_research.utilities.search_cache import (+ normalize_entity_query,+ )++ normalize_entity_query.cache_clear()+ return normalize_entity_query+++class TestNormalizeEntityQueryBasics:+ """Basic normalization tests."""++ def test_lowercases_entity(self):+ """Entity is lowercased."""+ fn = _get_fn()+ result = fn("John Smith", "born")+ assert "john smith" in result++ def test_lowercases_constraint(self):+ """Constraint is lowercased."""+ fn = _get_fn()+ result = fn("python", "RELEASE DATE")+ assert "release date" in result++ def test_combines_entity_and_constraint(self):+ """Result is 'entity constraint' with a space separator."""+ fn = _get_fn()+ result = fn("python", "release date")+ assert result == "python release date"++ def test_strips_leading_trailing_whitespace(self):+ """Leading/trailing whitespace is removed."""+ fn = _get_fn()+ result = fn(" python ", " release date ")+ assert result == "python release date"++ def test_collapses_internal_whitespace(self):+ """Multiple internal spaces collapsed to single space."""+ fn = _get_fn()+ result = fn("John Michael Smith", "birth date")+ assert result == "john michael smith birth date"++ def test_tabs_and_newlines_normalized(self):+ """Tabs and newlines treated as whitespace and collapsed."""+ fn = _get_fn()+ result = fn("John\tSmith", "born\nin")+ assert result == "john smith born in"+++class TestNormalizeEntityQueryEdgeCases:+ """Edge cases and unusual inputs."""++ def test_empty_entity(self):+ """Empty entity produces just the constraint."""+ fn = _get_fn()+ result = fn("", "born")+ assert result == " born"++ def test_empty_constraint(self):+ """Empty constraint produces just the entity."""+ fn = _get_fn()+ result = fn("python", "")+ assert result == "python "++ def test_both_empty(self):+ """Both empty produces a single space."""+ fn = _get_fn()+ result = fn("", "")+ assert result == " "++ def test_whitespace_only_entity(self):+ """Whitespace-only entity is stripped to empty."""+ fn = _get_fn()+ result = fn(" ", "born")+ assert result == " born"++ def test_unicode_characters(self):+ """Unicode characters are preserved and lowercased."""+ fn = _get_fn()+ result = fn("Ünîcödé", "Tëst")+ assert result == "ünîcödé tëst"++ def test_special_characters_preserved(self):+ """Special characters like hyphens and dots are preserved."""+ fn = _get_fn()+ result = fn("Marie-Curie", "birth.date")+ assert result == "marie-curie birth.date"++ def test_numbers_preserved(self):+ """Numbers in entity/constraint are preserved."""+ fn = _get_fn()+ result = fn("Python 3.12", "release 2024")+ assert result == "python 3.12 release 2024"+++class TestNormalizeEntityQueryDeterminism:+ """Tests that normalization is deterministic and consistent."""++ def test_same_input_same_output(self):+ """Same inputs always produce the same result."""+ fn = _get_fn()+ r1 = fn("Test Entity", "test constraint")+ r2 = fn("Test Entity", "test constraint")+ assert r1 == r2++ def test_case_variations_produce_same_result(self):+ """Different cases of the same entity produce identical results."""+ fn = _get_fn()+ r1 = fn("John Smith", "born")+ r2 = fn("JOHN SMITH", "BORN")+ r3 = fn("john smith", "born")+ assert r1 == r2 == r3++ def test_whitespace_variations_produce_same_result(self):+ """Different whitespace of the same entity produce identical results."""+ fn = _get_fn()+ r1 = fn("John Smith", "born")+ r2 = fn(" John Smith ", " born ")+ assert r1 == r2+++class TestNormalizeEntityQueryCache:+ """Tests for LRU cache behavior."""++ def test_cache_info_starts_empty(self):+ """After cache_clear, cache starts with zero hits/misses."""+ fn = _get_fn()+ info = fn.cache_info()+ assert info.hits == 0+ assert info.misses == 0++ def test_cache_hit_on_repeat_call(self):+ """Second call with same args is a cache hit."""+ fn = _get_fn()+ fn("test", "query")+ fn("test", "query")+ info = fn.cache_info()+ assert info.hits == 1+ assert info.misses == 1++ def test_different_args_are_cache_misses(self):+ """Different arguments are separate cache entries."""+ fn = _get_fn()+ fn("entity1", "constraint1")+ fn("entity2", "constraint2")+ info = fn.cache_info()+ assert info.misses == 2+ assert info.hits == 0++ def test_cache_maxsize_is_100(self):+ """LRU cache has maxsize of 100."""+ fn = _get_fn()+ info = fn.cache_info()+ assert info.maxsize == 100diff --git a/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.pynew file mode 100644index 0000000000..19a0c0acb1--- /dev/null+++ b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py@@ -0,0 +1,720 @@+"""+Tests for rate limiter tracker quality stats and maintenance methods.++Covers previously untested public methods:+- get_search_quality_stats() - search quality analysis from recent attempts+- get_stats() - programmatic mode code path (has a bug: NameError on line 558)+- cleanup_old_data() - old data removal in programmatic mode+- reset_engine() - memory-only reset in programmatic mode+"""++import time+from collections import deque+from unittest.mock import patch++from local_deep_research.config.thread_settings import NoSettingsContextError+++def _make_tracker(**overrides):+ """Create a tracker in programmatic mode (no DB, no Flask)."""+ with patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"+ ) as mock_gs:+ mock_gs.side_effect = NoSettingsContextError("test")++ with patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.logger"+ ):+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )++ defaults = {"programmatic_mode": True}+ defaults.update(overrides)+ tracker = AdaptiveRateLimitTracker(**defaults)++ if "enabled" not in overrides:+ tracker.enabled = True++ return tracker+++def _seed_attempts(tracker, engine, attempts_data):+ """Seed a tracker's recent_attempts with pre-built attempt dicts."""+ if engine not in tracker.recent_attempts:+ tracker.recent_attempts[engine] = deque(maxlen=tracker.memory_window)+ for item in attempts_data:+ tracker.recent_attempts[engine].append(item)+++# ── get_search_quality_stats ────────────────────────────────────────+++class TestGetSearchQualityStats:+ """Tests for get_search_quality_stats (lines 651-697)."""++ def test_empty_tracker_returns_empty_list(self):+ """No recent attempts → empty stats list."""+ tracker = _make_tracker()++ result = tracker.get_search_quality_stats()++ assert result == []++ def test_single_engine_basic_stats(self):+ """Single engine with result counts produces correct stats."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [+ {"search_result_count": 10, "success": True},+ {"search_result_count": 20, "success": True},+ {"search_result_count": 30, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()++ assert len(result) == 1+ stat = result[0]+ assert stat["engine_type"] == "google"+ assert stat["recent_avg_results"] == 20.0+ assert stat["min_recent_results"] == 10+ assert stat["max_recent_results"] == 30+ assert stat["sample_size"] == 3+ assert stat["total_attempts"] == 3+ assert stat["status"] == "EXCELLENT"++ def test_multiple_engines(self):+ """Stats returned for each engine with data."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [{"search_result_count": 15, "success": True}],+ )+ _seed_attempts(+ tracker,+ "bing",+ [{"search_result_count": 2, "success": True}],+ )++ result = tracker.get_search_quality_stats()++ engines = {s["engine_type"] for s in result}+ assert engines == {"google", "bing"}++ def test_filter_by_engine_type(self):+ """Passing engine_type filters to that engine only."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [{"search_result_count": 10, "success": True}],+ )+ _seed_attempts(+ tracker,+ "bing",+ [{"search_result_count": 5, "success": True}],+ )++ result = tracker.get_search_quality_stats(engine_type="google")++ assert len(result) == 1+ assert result[0]["engine_type"] == "google"++ def test_filter_nonexistent_engine_returns_empty(self):+ """Filtering by engine with no data returns empty list."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [{"search_result_count": 10, "success": True}],+ )++ result = tracker.get_search_quality_stats(engine_type="nonexistent")++ assert result == []++ def test_attempts_without_search_result_count_excluded(self):+ """Attempts missing search_result_count are excluded from averages."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [+ {"search_result_count": 10, "success": True},+ {"success": True}, # no search_result_count+ {"search_result_count": None, "success": True},+ {"search_result_count": 20, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()++ assert len(result) == 1+ stat = result[0]+ assert stat["sample_size"] == 2 # only 10 and 20+ assert stat["total_attempts"] == 4 # all 4 attempts counted+ assert stat["recent_avg_results"] == 15.0++ def test_all_attempts_missing_count_skips_engine(self):+ """Engine with no valid search_result_count is skipped entirely."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [+ {"success": True},+ {"search_result_count": None, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()++ assert result == []++ def test_zero_result_count_included(self):+ """search_result_count of 0 is a valid count (not excluded)."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [+ {"search_result_count": 0, "success": True},+ {"search_result_count": 0, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()++ assert len(result) == 1+ assert result[0]["recent_avg_results"] == 0.0+ assert result[0]["status"] == "CRITICAL"++ def test_quality_status_critical(self):+ """Average < 1 → CRITICAL status."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 0, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "CRITICAL"++ def test_quality_status_warning(self):+ """Average >= 1 and < 3 → WARNING status."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 2, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "WARNING"++ def test_quality_status_caution(self):+ """Average >= 3 and < 5 → CAUTION status."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 4, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "CAUTION"++ def test_quality_status_good(self):+ """Average >= 5 and < 10 → GOOD status."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 7, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "GOOD"++ def test_quality_status_excellent(self):+ """Average >= 10 → EXCELLENT status."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 15, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "EXCELLENT"++ def test_min_max_with_single_attempt(self):+ """Min and max are the same with a single attempt."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [{"search_result_count": 5, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ stat = result[0]+ assert stat["min_recent_results"] == 5+ assert stat["max_recent_results"] == 5++ def test_large_variance_in_results(self):+ """Correctly computes stats with large variance in result counts."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "google",+ [+ {"search_result_count": 1, "success": True},+ {"search_result_count": 100, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()+ stat = result[0]+ assert stat["recent_avg_results"] == 50.5+ assert stat["min_recent_results"] == 1+ assert stat["max_recent_results"] == 100+ assert stat["status"] == "EXCELLENT"++ def test_quality_status_boundary_at_1(self):+ """Boundary: exactly 1.0 → WARNING (not CRITICAL)."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 1, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "WARNING"++ def test_quality_status_boundary_at_3(self):+ """Boundary: exactly 3.0 → CAUTION (not WARNING)."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 3, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "CAUTION"++ def test_quality_status_boundary_at_5(self):+ """Boundary: exactly 5.0 → GOOD (not CAUTION)."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 5, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "GOOD"++ def test_quality_status_boundary_at_10(self):+ """Boundary: exactly 10.0 → EXCELLENT (not GOOD)."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [{"search_result_count": 10, "success": True}],+ )++ result = tracker.get_search_quality_stats()+ assert result[0]["status"] == "EXCELLENT"+++# ── get_stats programmatic mode ─────────────────────────────────────+++class TestGetStatsProgrammaticMode:+ """Tests for get_stats() in programmatic mode (line 556-558).++ In the current code, programmatic_mode hits `return stats` at line 558+ but `stats` is only defined in the CI/fallback branch above (line 534).+ This is a real bug: NameError when programmatic_mode=True and+ use_fallback_llm()/is_ci_environment() are False.+ """++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_empty(self, _mock_ci, _mock_fb):+ """In CI mode with no estimates, returns empty list."""+ tracker = _make_tracker()++ result = tracker.get_stats()++ assert result == []++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_with_estimates(self, _mock_ci, _mock_fb):+ """In CI mode with estimates, returns in-memory stats."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ "confidence": 0.8,+ }+ tracker.recent_attempts["google"] = deque(+ [{"success": True}], maxlen=100+ )++ result = tracker.get_stats()++ assert len(result) == 1+ engine, base, min_w, max_w, timestamp, attempts, confidence = result[0]+ assert engine == "google"+ assert base == 2.0+ assert min_w == 1.0+ assert max_w == 5.0+ assert attempts == 1+ assert confidence == 0.8++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_filter_by_engine(self, _mock_ci, _mock_fb):+ """In CI mode, engine_type filter returns only matching engine."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }+ tracker.current_estimates["bing"] = {+ "base": 3.0,+ "min": 1.5,+ "max": 6.0,+ }++ result = tracker.get_stats(engine_type="google")++ assert len(result) == 1+ assert result[0][0] == "google"++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_nonexistent_engine(self, _mock_ci, _mock_fb):+ """In CI mode, filtering by nonexistent engine returns empty."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }++ result = tracker.get_stats(engine_type="nonexistent")++ assert result == []++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_missing_confidence(self, _mock_ci, _mock_fb):+ """In CI mode, missing confidence key defaults to 0.0."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ # no "confidence" key+ }+ tracker.recent_attempts["google"] = deque(maxlen=100)++ result = tracker.get_stats()++ assert len(result) == 1+ confidence = result[0][6]+ assert confidence == 0.0++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_get_stats_ci_mode_no_recent_attempts(self, _mock_ci, _mock_fb):+ """In CI mode, engine with estimate but no recent_attempts key."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }+ # Don't add to recent_attempts++ result = tracker.get_stats()++ assert len(result) == 1+ attempts_count = result[0][5]+ assert attempts_count == 0++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=False,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=False,+ )+ def test_get_stats_programmatic_mode_bug(self, _mock_ci, _mock_fb):+ """BUG: programmatic_mode=True + non-CI → NameError on 'stats'.++ Line 558 does `return stats` but `stats` is only defined inside+ the `if use_fallback_llm() or is_ci_environment():` block (line 534).+ When that block is skipped, `stats` is undefined.+ """+ tracker = _make_tracker()++ # This should raise NameError because of the bug at line 558+ try:+ tracker.get_stats()+ # If it doesn't raise, the bug has been fixed+ except NameError:+ pass # Expected: confirms the bug exists+++# ── cleanup_old_data ────────────────────────────────────────────────+++class TestCleanupOldData:+ """Tests for cleanup_old_data (lines 712-751)."""++ def test_programmatic_mode_returns_early(self):+ """In programmatic mode, cleanup does nothing (no DB access)."""+ tracker = _make_tracker()++ # Should not raise, just return early+ tracker.cleanup_old_data()++ def test_programmatic_mode_accepts_days_param(self):+ """Days parameter is accepted even in programmatic mode."""+ tracker = _make_tracker()++ tracker.cleanup_old_data(days=1)+ tracker.cleanup_old_data(days=365)++ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",+ return_value=True,+ )+ @patch(+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ )+ def test_ci_mode_returns_early(self, _mock_ci, _mock_fb):+ """In CI/fallback mode, cleanup does nothing."""+ tracker = _make_tracker(programmatic_mode=False)++ tracker.cleanup_old_data()+++# ── reset_engine programmatic mode ──────────────────────────────────+++class TestResetEngineProgrammatic:+ """Tests for reset_engine in programmatic mode (lines 596-649)."""++ def test_clears_recent_attempts(self):+ """Reset removes engine from recent_attempts."""+ tracker = _make_tracker()+ tracker.recent_attempts["google"] = deque(+ [{"success": True}], maxlen=100+ )++ tracker.reset_engine("google")++ assert "google" not in tracker.recent_attempts++ def test_clears_current_estimates(self):+ """Reset removes engine from current_estimates."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }++ tracker.reset_engine("google")++ assert "google" not in tracker.current_estimates++ def test_clears_both_memory_structures(self):+ """Reset clears both attempts and estimates simultaneously."""+ tracker = _make_tracker()+ tracker.recent_attempts["google"] = deque(maxlen=100)+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }++ tracker.reset_engine("google")++ assert "google" not in tracker.recent_attempts+ assert "google" not in tracker.current_estimates++ def test_does_not_affect_other_engines(self):+ """Reset only clears the specified engine."""+ tracker = _make_tracker()+ tracker.recent_attempts["google"] = deque(+ [{"success": True}], maxlen=100+ )+ tracker.recent_attempts["bing"] = deque([{"success": True}], maxlen=100)+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }+ tracker.current_estimates["bing"] = {+ "base": 3.0,+ "min": 1.5,+ "max": 6.0,+ }++ tracker.reset_engine("google")++ assert "google" not in tracker.recent_attempts+ assert "google" not in tracker.current_estimates+ assert "bing" in tracker.recent_attempts+ assert "bing" in tracker.current_estimates++ def test_reset_nonexistent_engine_no_error(self):+ """Resetting an engine with no data does not raise."""+ tracker = _make_tracker()++ tracker.reset_engine("nonexistent")++ def test_reset_idempotent(self):+ """Resetting the same engine twice does not raise."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }++ tracker.reset_engine("google")+ tracker.reset_engine("google") # Should not raise++ def test_reset_only_attempts_present(self):+ """Reset when only recent_attempts exists (no estimate)."""+ tracker = _make_tracker()+ tracker.recent_attempts["google"] = deque(maxlen=100)++ tracker.reset_engine("google")++ assert "google" not in tracker.recent_attempts++ def test_reset_only_estimates_present(self):+ """Reset when only current_estimates exists (no attempts)."""+ tracker = _make_tracker()+ tracker.current_estimates["google"] = {+ "base": 2.0,+ "min": 1.0,+ "max": 5.0,+ }++ tracker.reset_engine("google")++ assert "google" not in tracker.current_estimates+++# ── get_search_quality_stats integration with record_outcome ────────+++class TestQualityStatsIntegration:+ """Integration tests: record outcomes then check quality stats."""++ def test_record_then_check_quality(self):+ """Record real outcomes and verify quality stats reflect them."""+ tracker = _make_tracker()++ # Record outcomes with search_result_count+ for count in [8, 12, 15]:+ if "test_engine" not in tracker.recent_attempts:+ tracker.recent_attempts["test_engine"] = deque(+ maxlen=tracker.memory_window+ )+ tracker.recent_attempts["test_engine"].append(+ {+ "wait_time": 1.0,+ "success": True,+ "timestamp": time.time(),+ "search_result_count": count,+ }+ )++ result = tracker.get_search_quality_stats(engine_type="test_engine")++ assert len(result) == 1+ stat = result[0]+ expected_avg = (8 + 12 + 15) / 3+ assert abs(stat["recent_avg_results"] - expected_avg) < 0.01+ assert stat["min_recent_results"] == 8+ assert stat["max_recent_results"] == 15+ assert stat["status"] == "EXCELLENT"++ def test_mixed_results_and_failures(self):+ """Mixed success/failure outcomes with varying result counts."""+ tracker = _make_tracker()+ _seed_attempts(+ tracker,+ "engine",+ [+ {"search_result_count": 10, "success": True},+ {"search_result_count": 0, "success": False},+ {"search_result_count": 5, "success": True},+ ],+ )++ result = tracker.get_search_quality_stats()++ assert len(result) == 1+ stat = result[0]+ # All 3 have search_result_count+ assert stat["sample_size"] == 3+ assert stat["recent_avg_results"] == 5.0