Skip to content

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

test: add 185 high-value tests across 7 under-tested modules (round 5) (#2547)

LearningCircuit5a761f6018bb
diff --git a/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py b/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py
new file mode 100644
index 0000000000..b14971ae87
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py
@@ -0,0 +1,486 @@
+"""
+High-value tests for ConcurrentDualConfidenceStrategy.
+
+Covers pure logic paths:
+- SearchState dataclass defaults and field types
+- _classify_constraint_difficulty: keyword matching, constraint type adjustment, sorting
+- _build_combined_query: multi-word quoting, already-quoted passthrough, concatenation
+- _should_stop_search: all 7 stopping criteria
+- _is_candidate_evaluated: thread-safe duplicate check
+"""
+
+import threading
+import time
+from unittest.mock import MagicMock, Mock
+
+
+from local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
+ ConcurrentDualConfidenceStrategy,
+ SearchState,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_strategy(**kwargs):
+ """Create a ConcurrentDualConfidenceStrategy with mocked dependencies."""
+ model = MagicMock()
+ search = MagicMock()
+ defaults = dict(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ )
+ defaults.update(kwargs)
+ return ConcurrentDualConfidenceStrategy(**defaults)
+
+
+def _make_constraint(value="test", type_name="PROPERTY"):
+ """Create a mock Constraint with a ConstraintType."""
+ from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ )
+
+ constraint = Mock()
+ constraint.value = value
+ constraint.type = ConstraintType[type_name]
+ return constraint
+
+
+def _make_candidate(name="Candidate"):
+ """Create a mock Candidate."""
+ c = Mock()
+ c.name = name
+ return c
+
+
+# ---------------------------------------------------------------------------
+# SearchState dataclass
+# ---------------------------------------------------------------------------
+
+
+class TestSearchState:
+ """Tests for SearchState dataclass defaults."""
+
+ def test_default_good_candidates_empty(self):
+ state = SearchState()
+ assert state.good_candidates == []
+
+ def test_default_total_evaluated_zero(self):
+ state = SearchState()
+ assert state.total_evaluated == 0
+
+ def test_start_time_is_float(self):
+ state = SearchState()
+ assert isinstance(state.start_time, float)
+
+ def test_remaining_constraints_empty(self):
+ state = SearchState()
+ assert state.remaining_constraints == []
+
+ def test_candidates_lock_is_lock(self):
+ state = SearchState()
+ assert isinstance(state.candidates_lock, type(threading.Lock()))
+
+ def test_stop_search_is_event(self):
+ state = SearchState()
+ assert isinstance(state.stop_search, threading.Event)
+ assert not state.stop_search.is_set()
+
+ def test_evaluation_futures_empty(self):
+ state = SearchState()
+ assert state.evaluation_futures == []
+
+ def test_each_instance_gets_unique_lock(self):
+ s1 = SearchState()
+ s2 = SearchState()
+ assert s1.candidates_lock is not s2.candidates_lock
+
+ def test_each_instance_gets_unique_event(self):
+ s1 = SearchState()
+ s2 = SearchState()
+ assert s1.stop_search is not s2.stop_search
+
+
+# ---------------------------------------------------------------------------
+# _build_combined_query
+# ---------------------------------------------------------------------------
+
+
+class TestBuildCombinedQuery:
+ """Tests for query construction from constraints."""
+
+ def test_single_word_no_quotes(self):
+ strategy = _make_strategy()
+ c = _make_constraint(value="Netflix")
+ result = strategy._build_combined_query([c])
+ assert result == "Netflix"
+
+ def test_multi_word_gets_quoted(self):
+ strategy = _make_strategy()
+ c = _make_constraint(value="TV series")
+ result = strategy._build_combined_query([c])
+ assert result == '"TV series"'
+
+ def test_already_quoted_not_double_quoted(self):
+ strategy = _make_strategy()
+ c = _make_constraint(value='"Breaking Bad"')
+ result = strategy._build_combined_query([c])
+ assert result == '"Breaking Bad"'
+
+ def test_multiple_constraints_joined_with_space(self):
+ strategy = _make_strategy()
+ c1 = _make_constraint(value="HBO")
+ c2 = _make_constraint(value="TV show")
+ c3 = _make_constraint(value="2019")
+ result = strategy._build_combined_query([c1, c2, c3])
+ assert result == 'HBO "TV show" 2019'
+
+ def test_empty_constraints_list(self):
+ strategy = _make_strategy()
+ result = strategy._build_combined_query([])
+ assert result == ""
+
+ def test_constraint_with_existing_quotes_preserved(self):
+ strategy = _make_strategy()
+ c = _make_constraint(value='aired on "HBO Max"')
+ result = strategy._build_combined_query([c])
+ # Contains a quote already, so it should NOT be additionally quoted
+ assert result == 'aired on "HBO Max"'
+
+
+# ---------------------------------------------------------------------------
+# _classify_constraint_difficulty
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyConstraintDifficulty:
+ """Tests for constraint difficulty rating and sorting."""
+
+ def test_abstract_keyword_gets_high_difficulty_with_event_type(self):
+ """EVENT type doesn't cap, so keyword difficulty of 0.9 is preserved."""
+ strategy = _make_strategy()
+ c = _make_constraint(
+ value="complex emotional narrative", type_name="EVENT"
+ )
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty >= 0.9
+
+ def test_specific_keyword_with_event_type(self):
+ """'episode aired' has keyword difficulty ~0.2 but EVENT raises to 0.7."""
+ strategy = _make_strategy()
+ c = _make_constraint(value="episode aired in 2020", type_name="EVENT")
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty >= 0.7
+
+ def test_default_difficulty_is_0_5(self):
+ strategy = _make_strategy()
+ c = _make_constraint(value="something generic xyz")
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ # PROPERTY type caps at 0.6, so 0.5 default stays as 0.5
+ assert c.search_difficulty == 0.5
+
+ def test_named_entity_with_property_type(self):
+ """PROPERTY type caps at 0.6; 'netflix' keyword gives 0.1 -> min(0.5, 0.6) = 0.5."""
+ strategy = _make_strategy()
+ c = _make_constraint(value="netflix original")
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ # Default 0.5 with 'netflix' keyword max = max(0.5, 0.1) = 0.5
+ # Then PROPERTY: min(0.5, 0.6) = 0.5
+ assert c.search_difficulty == 0.5
+
+ def test_property_type_caps_difficulty(self):
+ """PROPERTY constraint type caps difficulty at 0.6."""
+ strategy = _make_strategy()
+ c = _make_constraint(
+ value="complex deep emotional", type_name="PROPERTY"
+ )
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty <= 0.6
+
+ def test_event_type_raises_difficulty(self):
+ """EVENT constraint type raises difficulty to at least 0.7."""
+ strategy = _make_strategy()
+ c = _make_constraint(value="something simple", type_name="EVENT")
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty >= 0.7
+
+ def test_sorted_by_difficulty_descending(self):
+ """Constraints are sorted hardest-first after classification."""
+ strategy = _make_strategy()
+ easy = _make_constraint(value="episode aired")
+ hard = _make_constraint(value="complex emotional narrative")
+ strategy.state = SearchState(remaining_constraints=[easy, hard])
+ strategy._classify_constraint_difficulty()
+ assert strategy.state.remaining_constraints[0] is hard
+ assert strategy.state.remaining_constraints[1] is easy
+
+ def test_multiple_keywords_max_difficulty_wins(self):
+ """When multiple keywords match, the highest keyword difficulty wins.
+ But PROPERTY type caps at 0.6."""
+ strategy = _make_strategy()
+ # 'complex' = 0.9, 'released' = 0.2 -> max keyword = 0.9
+ # PROPERTY type: min(0.9, 0.6) = 0.6
+ c = _make_constraint(
+ value="complex movie released", type_name="PROPERTY"
+ )
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty == 0.6
+
+ def test_multiple_keywords_max_difficulty_with_event_type(self):
+ """EVENT type: keyword max 0.9 -> max(0.9, 0.7) = 0.9."""
+ strategy = _make_strategy()
+ c = _make_constraint(value="complex movie released", type_name="EVENT")
+ strategy.state = SearchState(remaining_constraints=[c])
+ strategy._classify_constraint_difficulty()
+ assert c.search_difficulty >= 0.9
+
+
+# ---------------------------------------------------------------------------
+# _should_stop_search
+# ---------------------------------------------------------------------------
+
+
+class TestShouldStopSearch:
+ """Tests for the 7 stopping criteria."""
+
+ def _setup_strategy(self, **overrides):
+ defaults = dict(
+ max_candidates=10,
+ target_candidates=5,
+ min_good_candidates=3,
+ exceptional_score=0.95,
+ max_search_time=30.0,
+ max_evaluations=30,
+ quality_plateau_threshold=0.1,
+ )
+ defaults.update(overrides)
+ strategy = _make_strategy(**defaults)
+ strategy.state = SearchState(start_time=time.time())
+ return strategy
+
+ def test_returns_false_when_no_criteria_met(self):
+ strategy = self._setup_strategy()
+ assert strategy._should_stop_search() is False
+
+ def test_criterion_1_stop_flag_set(self):
+ """Respects the stop_search Event."""
+ strategy = self._setup_strategy()
+ strategy.state.stop_search.set()
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_2_max_candidates_reached(self):
+ """Stops when good_candidates >= max_candidates."""
+ strategy = self._setup_strategy(max_candidates=2)
+ strategy.state.good_candidates = [
+ (_make_candidate("A"), 0.8),
+ (_make_candidate("B"), 0.7),
+ ]
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_3_target_with_high_quality(self):
+ """Stops when target_candidates reached with avg score >= 0.8."""
+ strategy = self._setup_strategy(target_candidates=2)
+ strategy.state.good_candidates = [
+ (_make_candidate("A"), 0.85),
+ (_make_candidate("B"), 0.90),
+ ]
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_3_target_with_low_quality_continues(self):
+ """Does not stop when target reached but avg score < 0.8."""
+ strategy = self._setup_strategy(target_candidates=2)
+ strategy.state.good_candidates = [
+ (_make_candidate("A"), 0.6),
+ (_make_candidate("B"), 0.7),
+ ]
+ assert strategy._should_stop_search() is False
+
+ def test_criterion_4_exceptional_candidate(self):
+ """Stops when min_good met and one candidate >= exceptional_score."""
+ strategy = self._setup_strategy(
+ min_good_candidates=2, exceptional_score=0.95
+ )
+ strategy.state.good_candidates = [
+ (_make_candidate("A"), 0.7),
+ (_make_candidate("B"), 0.96),
+ ]
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_4_no_exceptional(self):
+ """Does not stop when min_good met but no candidate >= exceptional_score,
+ and target not yet reached with high quality."""
+ strategy = self._setup_strategy(
+ min_good_candidates=2,
+ exceptional_score=0.95,
+ target_candidates=10, # High target so criterion 3 doesn't trigger
+ )
+ strategy.state.good_candidates = [
+ (_make_candidate("A"), 0.7),
+ (_make_candidate("B"), 0.7),
+ ]
+ strategy.state.remaining_constraints = [
+ _make_constraint()
+ ] # Prevent criterion 7
+ assert strategy._should_stop_search() is False
+
+ def test_criterion_5_time_limit(self):
+ """Stops when elapsed time exceeds max_search_time."""
+ strategy = self._setup_strategy(max_search_time=0.001)
+ strategy.state.start_time = time.time() - 1.0 # 1 second ago
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_6_evaluation_limit(self):
+ """Stops when total_evaluated >= max_evaluations."""
+ strategy = self._setup_strategy(max_evaluations=5)
+ strategy.state.total_evaluated = 5
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_7_no_remaining_constraints_with_min_candidates(self):
+ """Stops when no constraints remain and min candidates found."""
+ strategy = self._setup_strategy(min_good_candidates=1)
+ strategy.state.remaining_constraints = []
+ strategy.state.good_candidates = [(_make_candidate("A"), 0.7)]
+ assert strategy._should_stop_search() is True
+
+ def test_criterion_7_no_constraints_but_no_candidates(self):
+ """Does not stop when no constraints but also no candidates."""
+ strategy = self._setup_strategy(min_good_candidates=1)
+ strategy.state.remaining_constraints = []
+ strategy.state.good_candidates = []
+ assert strategy._should_stop_search() is False
+
+ def test_criterion_8_quality_plateau(self):
+ """Stops when last 5 scores are within plateau threshold."""
+ strategy = self._setup_strategy(quality_plateau_threshold=0.1)
+ strategy.state.good_candidates = [
+ (_make_candidate(f"C{i}"), score)
+ for i, score in enumerate([0.80, 0.81, 0.82, 0.83, 0.84])
+ ]
+ assert strategy._should_stop_search() is True
+
+ def test_no_plateau_with_wide_score_range(self):
+ """Does not trigger plateau when score range is wide."""
+ strategy = self._setup_strategy(
+ quality_plateau_threshold=0.1,
+ target_candidates=20, # Prevent criterion 3
+ max_candidates=20, # Prevent criterion 2
+ )
+ strategy.state.good_candidates = [
+ (_make_candidate(f"C{i}"), score)
+ for i, score in enumerate([0.50, 0.60, 0.70, 0.80, 0.90])
+ ]
+ strategy.state.remaining_constraints = [
+ _make_constraint()
+ ] # Prevent criterion 7
+ assert strategy._should_stop_search() is False
+
+ def test_plateau_not_checked_under_5_candidates(self):
+ """Plateau detection requires at least 5 candidates."""
+ strategy = self._setup_strategy(
+ quality_plateau_threshold=0.1,
+ target_candidates=20, # Prevent criterion 3
+ max_candidates=20, # Prevent criterion 2
+ )
+ strategy.state.good_candidates = [
+ (_make_candidate(f"C{i}"), 0.8) for i in range(4)
+ ]
+ strategy.state.remaining_constraints = [
+ _make_constraint()
+ ] # Prevent criterion 7
+ assert strategy._should_stop_search() is False
+
+
+# ---------------------------------------------------------------------------
+# _is_candidate_evaluated
+# ---------------------------------------------------------------------------
+
+
+class TestIsCandidateEvaluated:
+ """Tests for thread-safe duplicate candidate check."""
+
+ def test_not_evaluated_when_empty(self):
+ strategy = _make_strategy()
+ strategy.state = SearchState()
+ candidate = _make_candidate("NewCandidate")
+ assert strategy._is_candidate_evaluated(candidate) is False
+
+ def test_evaluated_when_in_good_candidates(self):
+ strategy = _make_strategy()
+ existing = _make_candidate("ExistingCandidate")
+ strategy.state = SearchState(good_candidates=[(existing, 0.8)])
+ check = _make_candidate("ExistingCandidate")
+ assert strategy._is_candidate_evaluated(check) is True
+
+ def test_different_name_not_evaluated(self):
+ strategy = _make_strategy()
+ existing = _make_candidate("CandidateA")
+ strategy.state = SearchState(good_candidates=[(existing, 0.8)])
+ check = _make_candidate("CandidateB")
+ assert strategy._is_candidate_evaluated(check) is False
+
+ def test_thread_safe_check(self):
+ """Multiple threads can safely check without race conditions."""
+ strategy = _make_strategy()
+ existing = _make_candidate("SharedCandidate")
+ strategy.state = SearchState(good_candidates=[(existing, 0.8)])
+
+ results = []
+
+ def check():
+ candidate = _make_candidate("SharedCandidate")
+ results.append(strategy._is_candidate_evaluated(candidate))
+
+ threads = [threading.Thread(target=check) for _ in range(10)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert all(r is True for r in results)
+
+
+# ---------------------------------------------------------------------------
+# Initialization defaults
+# ---------------------------------------------------------------------------
+
+
+class TestInitializationDefaults:
+ """Tests for constructor parameter storage."""
+
+ def test_default_max_workers(self):
+ strategy = _make_strategy()
+ # Default from __init__ signature is 10
+ assert strategy.evaluation_executor._max_workers == 10
+
+ def test_custom_parameters_stored(self):
+ strategy = _make_strategy(
+ min_good_candidates=5,
+ target_candidates=8,
+ max_candidates=15,
+ min_score_threshold=0.7,
+ exceptional_score=0.98,
+ max_search_time=60.0,
+ max_evaluations=50,
+ )
+ assert strategy.min_good_candidates == 5
+ assert strategy.target_candidates == 8
+ assert strategy.max_candidates == 15
+ assert strategy.min_score_threshold == 0.7
+ assert strategy.exceptional_score == 0.98
+ assert strategy.max_search_time == 60.0
+ assert strategy.max_evaluations == 50
+
+ def test_state_initially_none(self):
+ strategy = _make_strategy()
+ assert strategy.state is None
diff --git a/tests/advanced_search_system/strategies/test_early_stop_high_value.py b/tests/advanced_search_system/strategies/test_early_stop_high_value.py
new file mode 100644
index 0000000000..fb01c7a32e
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_early_stop_high_value.py
@@ -0,0 +1,513 @@
+"""
+High-value tests for EarlyStopConstrainedStrategy.
+
+Covers pure logic paths:
+- _extract_confidence_from_response: regex parsing, keyword fallback, edge cases
+- _evaluate_evidence: averaging, empty evidence, missing confidence keys
+- Thread-safe tracking: evaluation_lock, found_answer Event, best_candidate updates
+- _evaluate_candidate_immediately: score accumulation, early critical failure, early stop trigger
+"""
+
+import threading
+from unittest.mock import MagicMock, Mock, patch
+
+
+from local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy import (
+ EarlyStopConstrainedStrategy,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_strategy(early_stop_threshold=0.99, concurrent_evaluation=True):
+ """Create an EarlyStopConstrainedStrategy with mocked dependencies."""
+ model = MagicMock()
+ search = MagicMock()
+ strategy = EarlyStopConstrainedStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ early_stop_threshold=early_stop_threshold,
+ concurrent_evaluation=concurrent_evaluation,
+ )
+ return strategy
+
+
+def _make_constraint(
+ value="test constraint", weight=1.0, type_value="property"
+):
+ """Create a mock Constraint object."""
+ constraint = Mock()
+ constraint.value = value
+ constraint.weight = weight
+ constraint.type = Mock()
+ constraint.type.value = type_value
+ return constraint
+
+
+def _make_candidate(name="TestCandidate"):
+ """Create a mock Candidate object."""
+ candidate = Mock()
+ candidate.name = name
+ return candidate
+
+
+# ---------------------------------------------------------------------------
+# _extract_confidence_from_response
+# ---------------------------------------------------------------------------
+
+
+class TestExtractConfidenceFromResponse:
+ """Tests for regex-based confidence extraction with keyword fallback."""
+
+ def test_extracts_decimal_number(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("Confidence: 0.85")
+ == 0.85
+ )
+
+ def test_extracts_last_number_when_multiple(self):
+ """Uses the last numeric match found."""
+ strategy = _make_strategy()
+ result = strategy._extract_confidence_from_response(
+ "Score is 0.3 but revised to 0.9"
+ )
+ assert result == 0.9
+
+ def test_extracts_1_0(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("Perfect match: 1.0")
+ == 1.0
+ )
+
+ def test_extracts_bare_1(self):
+ strategy = _make_strategy()
+ assert strategy._extract_confidence_from_response("Score: 1") == 1.0
+
+ def test_extracts_number_without_leading_zero(self):
+ """Regex requires word boundary so bare '.75' does not match; falls back to keyword/default."""
+ strategy = _make_strategy()
+ # The regex \b0?\.\d+ requires word boundary before the optional 0
+ # '.75' alone doesn't match, but '0.75' does
+ assert (
+ strategy._extract_confidence_from_response("Confidence 0.75")
+ == 0.75
+ )
+
+ def test_keyword_definitely_returns_0_9(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response(
+ "This is definitely the answer"
+ )
+ == 0.9
+ )
+
+ def test_keyword_certainly_returns_0_9(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("I certainly believe so")
+ == 0.9
+ )
+
+ def test_keyword_absolutely_returns_0_9(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("Absolutely correct")
+ == 0.9
+ )
+
+ def test_keyword_likely_returns_0_7(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("This is likely correct")
+ == 0.7
+ )
+
+ def test_keyword_probably_returns_0_7(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response(
+ "Probably the right answer"
+ )
+ == 0.7
+ )
+
+ def test_keyword_appears_returns_0_7(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response(
+ "It appears to be correct"
+ )
+ == 0.7
+ )
+
+ def test_keyword_possibly_returns_0_5(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("Possibly the answer")
+ == 0.5
+ )
+
+ def test_keyword_maybe_returns_0_5(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("Maybe it could be this")
+ == 0.5
+ )
+
+ def test_keyword_might_returns_0_5(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("It might be correct")
+ == 0.5
+ )
+
+ def test_keyword_unlikely_matches_likely_first(self):
+ """'unlikely' contains 'likely' substring, so 'likely' keyword matches first (0.7)."""
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("This is unlikely")
+ == 0.7
+ )
+
+ def test_keyword_doubtful_returns_0_3(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("It is doubtful") == 0.3
+ )
+
+ def test_keyword_not_returns_0_3(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("This is not the answer")
+ == 0.3
+ )
+
+ def test_no_number_no_keyword_returns_0_5(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response(
+ "Some generic response with no indicators"
+ )
+ == 0.5
+ )
+
+ def test_empty_string_returns_0_5(self):
+ strategy = _make_strategy()
+ assert strategy._extract_confidence_from_response("") == 0.5
+
+ def test_keyword_priority_high_confidence_first(self):
+ """'definitely' keyword is checked before 'likely'."""
+ strategy = _make_strategy()
+ # The function checks keywords in order; 'definitely' matches first
+ assert (
+ strategy._extract_confidence_from_response(
+ "This is definitely and likely correct"
+ )
+ == 0.9
+ )
+
+ def test_number_takes_priority_over_keywords(self):
+ """When a number is present, it wins over keyword matching."""
+ strategy = _make_strategy()
+ result = strategy._extract_confidence_from_response(
+ "Definitely the answer with confidence 0.42"
+ )
+ assert result == 0.42
+
+ def test_case_insensitive_keywords(self):
+ strategy = _make_strategy()
+ assert (
+ strategy._extract_confidence_from_response("DEFINITELY yes") == 0.9
+ )
+
+
+# ---------------------------------------------------------------------------
+# _evaluate_evidence
+# ---------------------------------------------------------------------------
+
+
+class TestEvaluateEvidence:
+ """Tests for evidence evaluation scoring."""
+
+ def test_empty_evidence_returns_zero(self):
+ strategy = _make_strategy()
+ constraint = _make_constraint()
+ assert strategy._evaluate_evidence([], constraint) == 0.0
+
+ def test_single_evidence_returns_its_confidence(self):
+ strategy = _make_strategy()
+ constraint = _make_constraint()
+ evidence = [{"confidence": 0.8, "text": "supports"}]
+ assert strategy._evaluate_evidence(evidence, constraint) == 0.8
+
+ def test_averages_multiple_evidence_confidences(self):
+ strategy = _make_strategy()
+ constraint = _make_constraint()
+ evidence = [
+ {"confidence": 0.6},
+ {"confidence": 0.8},
+ {"confidence": 1.0},
+ ]
+ result = strategy._evaluate_evidence(evidence, constraint)
+ assert abs(result - 0.8) < 0.001
+
+ def test_missing_confidence_defaults_to_0_5(self):
+ strategy = _make_strategy()
+ constraint = _make_constraint()
+ evidence = [
+ {"text": "no confidence key"},
+ {"confidence": 0.9},
+ ]
+ result = strategy._evaluate_evidence(evidence, constraint)
+ assert abs(result - 0.7) < 0.001 # (0.5 + 0.9) / 2
+
+ def test_all_missing_confidence_returns_0_5(self):
+ strategy = _make_strategy()
+ constraint = _make_constraint()
+ evidence = [{"text": "a"}, {"text": "b"}]
+ result = strategy._evaluate_evidence(evidence, constraint)
+ assert result == 0.5
+
+
+# ---------------------------------------------------------------------------
+# Thread-safe tracking
+# ---------------------------------------------------------------------------
+
+
+class TestThreadSafeTracking:
+ """Tests for thread-safe best_candidate and found_answer tracking."""
+
+ def test_initial_state(self):
+ strategy = _make_strategy()
+ assert strategy.best_candidate is None
+ assert strategy.best_score == 0.0
+ assert not strategy.found_answer.is_set()
+ assert strategy.evaluated_candidates == {}
+ assert strategy.evaluating_candidates == set()
+
+ def test_evaluation_lock_is_threading_lock(self):
+ strategy = _make_strategy()
+ assert isinstance(strategy.evaluation_lock, type(threading.Lock()))
+
+ def test_found_answer_is_threading_event(self):
+ strategy = _make_strategy()
+ assert isinstance(strategy.found_answer, threading.Event)
+
+ def test_early_stop_threshold_stored(self):
+ strategy = _make_strategy(early_stop_threshold=0.95)
+ assert strategy.early_stop_threshold == 0.95
+
+ def test_concurrent_evaluation_flag(self):
+ strategy = _make_strategy(concurrent_evaluation=False)
+ assert strategy.concurrent_evaluation is False
+
+
+# ---------------------------------------------------------------------------
+# _evaluate_candidate_immediately
+# ---------------------------------------------------------------------------
+
+
+class TestEvaluateCandidateImmediately:
+ """Tests for immediate candidate evaluation against constraints."""
+
+ def test_returns_zero_on_exception(self):
+ """If evaluation throws, returns 0.0."""
+ strategy = _make_strategy()
+ strategy.constraint_ranking = [_make_constraint()]
+ strategy._gather_evidence_for_constraint = Mock(
+ side_effect=Exception("fail")
+ )
+ candidate = _make_candidate("FailCandidate")
+
+ score = strategy._evaluate_candidate_immediately(candidate)
+ assert score == 0.0
+
+ def test_updates_best_candidate_on_higher_score(self):
+ """Candidate with higher score replaces best_candidate."""
+ strategy = _make_strategy()
+ strategy.constraint_ranking = [_make_constraint(weight=0.5)]
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.85}]
+ )
+ strategy._evaluate_evidence = Mock(return_value=0.85)
+
+ candidate = _make_candidate("GoodCandidate")
+ score = strategy._evaluate_candidate_immediately(candidate)
+
+ assert score == 0.85
+ assert strategy.best_candidate == "GoodCandidate"
+ assert strategy.best_score == 0.85
+ assert strategy.evaluated_candidates["GoodCandidate"] == 0.85
+
+ def test_does_not_replace_higher_score_candidate(self):
+ """Lower score candidate does not replace existing best."""
+ strategy = _make_strategy()
+ strategy.best_score = 0.9
+ strategy.best_candidate = "BetterCandidate"
+ strategy.constraint_ranking = [_make_constraint(weight=0.5)]
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.5}]
+ )
+ strategy._evaluate_evidence = Mock(return_value=0.5)
+
+ candidate = _make_candidate("WeakCandidate")
+ score = strategy._evaluate_candidate_immediately(candidate)
+
+ assert score == 0.5
+ assert strategy.best_candidate == "BetterCandidate"
+ assert strategy.best_score == 0.9
+
+ def test_triggers_early_stop_at_threshold(self):
+ """Score >= early_stop_threshold sets the found_answer Event."""
+ strategy = _make_strategy(early_stop_threshold=0.8)
+ strategy.constraint_ranking = [_make_constraint(weight=0.5)]
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.95}]
+ )
+ strategy._evaluate_evidence = Mock(return_value=0.95)
+
+ candidate = _make_candidate("PerfectCandidate")
+ strategy._evaluate_candidate_immediately(candidate)
+
+ assert strategy.found_answer.is_set()
+ assert strategy.best_candidate == "PerfectCandidate"
+
+ def test_does_not_trigger_early_stop_below_threshold(self):
+ strategy = _make_strategy(early_stop_threshold=0.99)
+ strategy.constraint_ranking = [_make_constraint(weight=0.5)]
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.8}]
+ )
+ strategy._evaluate_evidence = Mock(return_value=0.8)
+
+ candidate = _make_candidate("OkCandidate")
+ strategy._evaluate_candidate_immediately(candidate)
+
+ assert not strategy.found_answer.is_set()
+
+ def test_early_critical_failure_skips_remaining_constraints(self):
+ """Score < 0.3 on high-weight constraint skips remaining checks."""
+ strategy = _make_strategy()
+ c1 = _make_constraint(value="critical", weight=0.9)
+ c2 = _make_constraint(value="secondary", weight=0.5)
+ strategy.constraint_ranking = [c1, c2]
+
+ call_count = 0
+
+ def mock_gather(candidate, constraint):
+ nonlocal call_count
+ call_count += 1
+ return [{"confidence": 0.1}]
+
+ strategy._gather_evidence_for_constraint = mock_gather
+ strategy._evaluate_evidence = Mock(return_value=0.1)
+
+ candidate = _make_candidate("BadCandidate")
+ score = strategy._evaluate_candidate_immediately(candidate)
+
+ # Only the first constraint should have been checked (early break)
+ assert call_count == 1
+ # Score should be based on only the first constraint
+ assert score == 0.1
+
+ def test_averages_across_all_constraints_when_no_early_break(self):
+ """When no early failure, averages scores across all constraints."""
+ strategy = _make_strategy()
+ c1 = _make_constraint(value="first", weight=0.5)
+ c2 = _make_constraint(value="second", weight=0.5)
+ strategy.constraint_ranking = [c1, c2]
+
+ scores = iter([0.6, 0.8])
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.7}]
+ )
+ strategy._evaluate_evidence = Mock(
+ side_effect=lambda e, c: next(scores)
+ )
+
+ candidate = _make_candidate("MediumCandidate")
+ score = strategy._evaluate_candidate_immediately(candidate)
+
+ assert abs(score - 0.7) < 0.001 # (0.6 + 0.8) / 2
+
+ def test_no_constraints_returns_zero(self):
+ """With no constraints, score is 0.0."""
+ strategy = _make_strategy()
+ strategy.constraint_ranking = []
+
+ candidate = _make_candidate("NoConstraints")
+ score = strategy._evaluate_candidate_immediately(candidate)
+ assert score == 0.0
+
+ def test_progress_callback_called_per_constraint(self):
+ """Progress callback is called for each constraint evaluation."""
+ strategy = _make_strategy()
+ callback = Mock()
+ strategy.progress_callback = callback
+ strategy.constraint_ranking = [
+ _make_constraint(value="c1", weight=0.5),
+ _make_constraint(value="c2", weight=0.5),
+ ]
+ strategy._gather_evidence_for_constraint = Mock(
+ return_value=[{"confidence": 0.7}]
+ )
+ strategy._evaluate_evidence = Mock(return_value=0.7)
+
+ candidate = _make_candidate("CallbackTest")
+ strategy._evaluate_candidate_immediately(candidate)
+
+ assert callback.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# analyze_topic additions
+# ---------------------------------------------------------------------------
+
+
+class TestAnalyzeTopicEarlyStop:
+ """Tests that analyze_topic adds early stopping metadata."""
+
+ def test_analyze_topic_adds_early_stop_fields(self):
+ """Result dict includes early_stopped, evaluated_candidates, best_candidate, best_score."""
+ strategy = _make_strategy()
+ # Mock parent's analyze_topic to return a base result
+ with patch(
+ "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
+ return_value={"findings": [], "current_knowledge": "test"},
+ ):
+ result = strategy.analyze_topic("test query")
+
+ assert "early_stopped" in result
+ assert "evaluated_candidates" in result
+ assert "best_candidate" in result
+ assert "best_score" in result
+
+ def test_early_stopped_reflects_found_answer(self):
+ strategy = _make_strategy()
+ strategy.found_answer.set()
+
+ with patch(
+ "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
+ return_value={},
+ ):
+ result = strategy.analyze_topic("test")
+
+ assert result["early_stopped"] is True
+
+ def test_not_early_stopped_when_answer_not_found(self):
+ strategy = _make_strategy()
+
+ with patch(
+ "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
+ return_value={},
+ ):
+ result = strategy.analyze_topic("test")
+
+ assert result["early_stopped"] is False
diff --git a/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py b/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py
new file mode 100644
index 0000000000..5696785070
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py
@@ -0,0 +1,668 @@
+"""
+High-value tests for RecursiveDecompositionStrategy.
+
+Covers pure logic paths:
+- _decide_decomposition: DECOMPOSE/SEARCH_DIRECTLY response parsing, subtask extraction
+- _aggregate_subtask_results: link deduplication (dict vs string), questions format conversion
+- Max recursion depth guard
+- analyze_topic initialization and routing
+"""
+
+from unittest.mock import MagicMock, Mock, patch
+
+
+from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
+ RecursiveDecompositionStrategy,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+MODULE = "local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy"
+
+
+def _make_strategy(**kwargs):
+ """Create a RecursiveDecompositionStrategy with mocked dependencies."""
+ model = MagicMock()
+ search = MagicMock()
+ defaults = dict(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ max_recursion_depth=5,
+ )
+ defaults.update(kwargs)
+ return RecursiveDecompositionStrategy(**defaults)
+
+
+def _model_response(text):
+ resp = Mock()
+ resp.content = text
+ return resp
+
+
+# ---------------------------------------------------------------------------
+# _decide_decomposition
+# ---------------------------------------------------------------------------
+
+
+class TestDecideDecomposition:
+ """Tests for LLM response parsing to DECOMPOSE or SEARCH_DIRECTLY."""
+
+ def test_parses_decompose_decision(self):
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: DECOMPOSE\n"
+ "REASONING: Complex multi-part question\n"
+ "SUBTASKS:\n"
+ "1. Find the population of city X\n"
+ "2. Find the GDP of country Y\n"
+ "DEPENDENCIES: Subtask 2 depends on subtask 1"
+ )
+ result = strategy._decide_decomposition("complex query")
+
+ assert result["should_decompose"] is True
+ assert result["reasoning"] == "Complex multi-part question"
+ assert len(result["subtasks"]) == 2
+ assert "population of city X" in result["subtasks"][0]
+ assert "GDP of country Y" in result["subtasks"][1]
+ assert len(result["dependencies"]) == 1
+
+ def test_parses_search_directly_decision(self):
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: Simple factual question"
+ )
+ result = strategy._decide_decomposition("simple query")
+
+ assert result["should_decompose"] is False
+ assert result["reasoning"] == "Simple factual question"
+ assert result["subtasks"] == []
+
+ def test_unknown_decision_defaults_to_search_directly(self):
+ """Non-DECOMPOSE value defaults to search directly."""
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: MAYBE\nREASONING: unclear"
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["should_decompose"] is False
+
+ def test_no_decision_line_defaults_to_search_directly(self):
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "I think we should search for this directly."
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["should_decompose"] is False
+
+ def test_subtasks_with_dash_format(self):
+ """Supports dash-prefixed subtask lines."""
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: DECOMPOSE\n"
+ "REASONING: Has parts\n"
+ "SUBTASKS:\n"
+ "- First subtask\n"
+ "- Second subtask\n"
+ "DEPENDENCIES: None"
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["should_decompose"] is True
+ assert len(result["subtasks"]) == 2
+ assert result["subtasks"][0] == "First subtask"
+
+ def test_empty_subtasks_with_decompose(self):
+ """DECOMPOSE with no subtask lines still returns should_decompose=True."""
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: DECOMPOSE\n"
+ "REASONING: Should split\n"
+ "SUBTASKS:\n"
+ "DEPENDENCIES: None"
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["should_decompose"] is True
+ assert result["subtasks"] == []
+
+ def test_handles_think_tags(self):
+ """Think tags in LLM output are stripped."""
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "<think>Hmm let me think...</think>\n"
+ "DECISION: SEARCH_DIRECTLY\n"
+ "REASONING: Simple"
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["should_decompose"] is False
+
+ def test_includes_original_query_context(self):
+ """When original_query differs from current query, context is included in prompt."""
+ strategy = _make_strategy()
+ strategy.original_query = "Master research topic"
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: sub-query"
+ )
+ strategy._decide_decomposition("sub-question about aspect")
+ # Verify the prompt included the original query context
+ prompt_arg = strategy.model.invoke.call_args[0][0]
+ assert "Master research topic" in prompt_arg
+
+ def test_no_context_when_same_query(self):
+ """No context line when original_query matches current query."""
+ strategy = _make_strategy()
+ strategy.original_query = "same query"
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
+ )
+ strategy._decide_decomposition("same query")
+ prompt_arg = strategy.model.invoke.call_args[0][0]
+ assert "Original research topic" not in prompt_arg
+
+ def test_colon_in_reasoning_preserved(self):
+ strategy = _make_strategy()
+ strategy.original_query = None
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: DECOMPOSE\n"
+ "REASONING: Has parts: A, B, and C\n"
+ "SUBTASKS:\n"
+ "1. Part A\n"
+ "DEPENDENCIES: none"
+ )
+ result = strategy._decide_decomposition("query")
+ assert result["reasoning"] == "Has parts: A, B, and C"
+
+
+# ---------------------------------------------------------------------------
+# _aggregate_subtask_results
+# ---------------------------------------------------------------------------
+
+
+class TestAggregateSubtaskResults:
+ """Tests for result aggregation with link dedup and question format conversion."""
+
+ def _setup_strategy(self):
+ strategy = _make_strategy()
+ strategy.findings = []
+ strategy.questions_by_iteration = []
+ strategy.original_query = "original topic"
+ strategy.model.invoke.return_value = _model_response(
+ "Synthesized answer text"
+ )
+ return strategy
+
+ def test_synthesizes_subtask_results(self):
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "Knowledge from sub 1",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ }
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "original query", subtask_results, 0
+ )
+
+ assert result["current_knowledge"] == "Synthesized answer text"
+ assert result["strategy"] == "recursive_decomposition"
+
+ def test_deduplicates_string_links(self):
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K1",
+ "all_links_of_system": ["http://a.com", "http://b.com"],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ {
+ "subtask": "Sub 2",
+ "result": {
+ "current_knowledge": "K2",
+ "all_links_of_system": ["http://b.com", "http://c.com"],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 2,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "query", subtask_results, 0
+ )
+
+ links = result["all_links_of_system"]
+ link_strs = [str(link) for link in links]
+ assert len(link_strs) == 3 # a, b, c (b deduplicated)
+
+ def test_deduplicates_dict_links_by_url(self):
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K1",
+ "all_links_of_system": [
+ {"link": "http://example.com", "title": "Example"},
+ ],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ {
+ "subtask": "Sub 2",
+ "result": {
+ "current_knowledge": "K2",
+ "all_links_of_system": [
+ {"link": "http://example.com", "title": "Example Dup"},
+ ],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 2,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "query", subtask_results, 0
+ )
+
+ assert len(result["all_links_of_system"]) == 1
+
+ def test_dict_links_with_url_key(self):
+ """Dict links use 'url' key when 'link' is missing."""
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [
+ {"url": "http://a.com"},
+ {"url": "http://a.com"},
+ ],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "q", subtask_results, 0
+ )
+
+ assert len(result["all_links_of_system"]) == 1
+
+ def test_questions_list_format_conversion(self):
+ """List-type questions are converted to dict format."""
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [
+ ["Q1", "Q2"],
+ ["Q3"],
+ ],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "q", subtask_results, 0
+ )
+
+ qdict = result["questions_by_iteration"]
+ assert isinstance(qdict, dict)
+ assert 1 in qdict
+ assert qdict[1] == ["Q1", "Q2"]
+ assert 2 in qdict
+
+ def test_questions_dict_format_merged(self):
+ """Dict-type questions are merged directly."""
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [
+ {10: ["Q from dict"]},
+ ],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "q", subtask_results, 0
+ )
+
+ qdict = result["questions_by_iteration"]
+ assert 10 in qdict
+
+ def test_none_questions_skipped(self):
+ """None values in questions list are skipped."""
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "Sub 1",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [None, ["Q1"]],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "q", subtask_results, 0
+ )
+
+ # None should be converted as a single-item list via str()
+ # Actually looking at the code: None is not iterable for isinstance checks
+ # but the 'if questions is not None' guard skips it for the total count
+ assert isinstance(result["questions"], dict)
+
+ def test_result_has_expected_keys(self):
+ strategy = self._setup_strategy()
+ subtask_results = [
+ {
+ "subtask": "S",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ result = strategy._aggregate_subtask_results(
+ "q", subtask_results, 0
+ )
+
+ expected_keys = {
+ "current_knowledge",
+ "formatted_findings",
+ "findings",
+ "iterations",
+ "questions_by_iteration",
+ "all_links_of_system",
+ "sources",
+ "subtask_results",
+ "strategy",
+ "recursion_depth",
+ "questions",
+ }
+ assert expected_keys.issubset(result.keys())
+
+ def test_progress_callback_called_during_synthesis(self):
+ strategy = self._setup_strategy()
+ callback = Mock()
+ strategy.progress_callback = callback
+ subtask_results = [
+ {
+ "subtask": "S",
+ "result": {
+ "current_knowledge": "K",
+ "all_links_of_system": [],
+ "findings": [],
+ "questions_by_iteration": [],
+ },
+ "depth": 1,
+ "index": 1,
+ },
+ ]
+
+ with patch(f"{MODULE}.format_findings", return_value="formatted"):
+ strategy._aggregate_subtask_results("q", subtask_results, 0)
+
+ callback.assert_called()
+ # Check synthesis phase callback
+ synthesis_calls = [
+ c for c in callback.call_args_list if "Synthesizing" in str(c)
+ ]
+ assert len(synthesis_calls) >= 1
+
+
+# ---------------------------------------------------------------------------
+# Max recursion depth guard
+# ---------------------------------------------------------------------------
+
+
+class TestMaxRecursionDepth:
+ """Tests for recursion depth protection."""
+
+ def test_at_max_depth_falls_back_to_source_strategy(self):
+ """When recursion_depth >= max, uses source-based strategy."""
+ strategy = _make_strategy(max_recursion_depth=3)
+ strategy.all_links_of_system = []
+ strategy.questions_by_iteration = []
+ strategy.findings = []
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"current_knowledge": "direct", "findings": []},
+ ) as mock_source:
+ result = strategy.analyze_topic("query", recursion_depth=3)
+
+ mock_source.assert_called_once_with("query")
+ assert result["current_knowledge"] == "direct"
+
+ def test_below_max_depth_proceeds_normally(self):
+ """Below max depth, proceeds with decomposition decision."""
+ strategy = _make_strategy(max_recursion_depth=5)
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: simple"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"current_knowledge": "found", "findings": []},
+ ):
+ result = strategy.analyze_topic("query", recursion_depth=0)
+
+ assert result["current_knowledge"] == "found"
+
+ def test_exactly_at_max_triggers_guard(self):
+ strategy = _make_strategy(max_recursion_depth=2)
+ strategy.all_links_of_system = []
+ strategy.questions_by_iteration = []
+ strategy.findings = []
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"current_knowledge": "fallback", "findings": []},
+ ):
+ result = strategy.analyze_topic("query", recursion_depth=2)
+
+ assert result["current_knowledge"] == "fallback"
+
+ def test_above_max_also_triggers_guard(self):
+ strategy = _make_strategy(max_recursion_depth=2)
+ strategy.all_links_of_system = []
+ strategy.questions_by_iteration = []
+ strategy.findings = []
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"current_knowledge": "fallback", "findings": []},
+ ):
+ result = strategy.analyze_topic("query", recursion_depth=10)
+
+ assert result["current_knowledge"] == "fallback"
+
+
+# ---------------------------------------------------------------------------
+# analyze_topic initialization
+# ---------------------------------------------------------------------------
+
+
+class TestAnalyzeTopicInit:
+ """Tests for top-level initialization in analyze_topic."""
+
+ def test_clears_links_at_depth_zero(self):
+ strategy = _make_strategy()
+ strategy.all_links_of_system = ["old_link"]
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("query", recursion_depth=0)
+
+ # Links should have been cleared at depth 0
+ # (may have new ones added by source strategy, but old one gone)
+ assert "old_link" not in strategy.all_links_of_system
+
+ def test_stores_original_query_at_depth_zero(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("my research topic", recursion_depth=0)
+
+ assert strategy.original_query == "my research topic"
+
+ def test_initializes_findings_list_at_depth_zero(self):
+ strategy = _make_strategy()
+ strategy.findings = [{"old": True}]
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("query", recursion_depth=0)
+
+ # Old findings should be cleared, new ones may be added
+ assert {"old": True} not in strategy.findings
+
+ def test_progress_callback_at_depth_zero(self):
+ strategy = _make_strategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("query", recursion_depth=0)
+
+ # Should have been called with init phase
+ init_calls = [
+ c for c in callback.call_args_list if c[0][2].get("phase") == "init"
+ ]
+ assert len(init_calls) >= 1
+
+ def test_adds_search_decision_to_findings(self):
+ """When SEARCH_DIRECTLY, adds decision to findings."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: SEARCH_DIRECTLY\nREASONING: simple enough"
+ )
+
+ with patch.object(
+ strategy,
+ "_use_source_based_strategy",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("query", recursion_depth=0)
+
+ # Should have a finding about the search decision
+ phases = [f.get("phase", "") for f in strategy.findings]
+ assert any("Direct Search Decision" in p for p in phases)
+
+ def test_adds_decomposition_decision_to_findings(self):
+ """When DECOMPOSE, adds decomposition decision to findings."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "DECISION: DECOMPOSE\n"
+ "REASONING: multi-part\n"
+ "SUBTASKS:\n"
+ "1. Part A\n"
+ "2. Part B\n"
+ "DEPENDENCIES: none"
+ )
+
+ # Mock _handle_decomposition to avoid full recursion
+ with patch.object(
+ strategy,
+ "_handle_decomposition",
+ return_value={"findings": [], "current_knowledge": "k"},
+ ):
+ strategy.analyze_topic("complex query", recursion_depth=0)
+
+ phases = [f.get("phase", "") for f in strategy.findings]
+ assert any("Decomposition Decision" in p for p in phases)
diff --git a/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py b/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py
new file mode 100644
index 0000000000..8649aca03c
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py
@@ -0,0 +1,634 @@
+"""
+High-value tests for SmartDecompositionStrategy and QueryType.
+
+Covers pure logic paths:
+- QueryType enum completeness and values
+- _is_browsecomp_style indicator counting (threshold of 3)
+- _classify_query LLM response parsing (by name, by value, default fallback)
+- analyze_topic delegation to the correct sub-strategy
+- Progress callback invocation with query_type metadata
+"""
+
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy import (
+ QueryType,
+ SmartDecompositionStrategy,
+)
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+MODULE = "local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy"
+
+
+def _make_strategy(progress_callback=None):
+ """Create a SmartDecompositionStrategy with mocked model and search."""
+ model = MagicMock()
+ search = MagicMock()
+ strategy = SmartDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ settings_snapshot={},
+ )
+ if progress_callback is not None:
+ strategy.set_progress_callback(progress_callback)
+ return strategy
+
+
+def _model_response(text: str):
+ """Return a mock LLM response object whose .content is *text*."""
+ resp = Mock()
+ resp.content = text
+ return resp
+
+
+# ---------------------------------------------------------------------------
+# QueryType enum
+# ---------------------------------------------------------------------------
+
+
+class TestQueryType:
+ """Tests for the QueryType enum."""
+
+ def test_all_expected_members_exist(self):
+ assert QueryType.PUZZLE_LIKE.value == "puzzle_like"
+ assert QueryType.HIERARCHICAL.value == "hierarchical"
+ assert QueryType.EXPLORATORY.value == "exploratory"
+ assert QueryType.COMPARATIVE.value == "comparative"
+ assert QueryType.FACTUAL.value == "factual"
+ assert QueryType.CONSTRAINT_BASED.value == "constraint_based"
+
+ def test_member_count(self):
+ assert len(QueryType) == 6
+
+ def test_members_are_unique(self):
+ values = [qt.value for qt in QueryType]
+ assert len(values) == len(set(values))
+
+ def test_lookup_by_name(self):
+ assert QueryType["PUZZLE_LIKE"] is QueryType.PUZZLE_LIKE
+
+ def test_lookup_by_name_invalid_raises(self):
+ with pytest.raises(KeyError):
+ QueryType["NONEXISTENT"]
+
+
+# ---------------------------------------------------------------------------
+# _is_browsecomp_style
+# ---------------------------------------------------------------------------
+
+
+class TestIsBrowsecompStyle:
+ """Tests for the browsecomp indicator detection heuristic."""
+
+ def test_returns_true_with_three_indicators(self):
+ strategy = _make_strategy()
+ query = "At a specific scenic location, a body part fell from the viewpoint."
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_returns_true_with_many_indicators(self):
+ strategy = _make_strategy()
+ query = (
+ "At a specific scenic location a body part fell from a viewpoint "
+ "during search and rescue operations involving SAR incidents "
+ "requiring an exact answer from multiple clues."
+ )
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_returns_false_with_two_indicators(self):
+ strategy = _make_strategy()
+ query = "A body part fell from a height."
+ assert strategy._is_browsecomp_style(query) is False
+
+ def test_returns_false_with_zero_indicators(self):
+ strategy = _make_strategy()
+ query = "What is the capital of France?"
+ assert strategy._is_browsecomp_style(query) is False
+
+ def test_case_insensitive_matching(self):
+ strategy = _make_strategy()
+ query = (
+ "SPECIFIC SCENIC LOCATION with BODY PART and FELL FROM the cliff."
+ )
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_mixed_case_matching(self):
+ strategy = _make_strategy()
+ query = "Specific Scenic Location Body Part Fell From nowhere."
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_exact_threshold_boundary_two_indicators(self):
+ """Exactly 2 indicators should return False (below threshold)."""
+ strategy = _make_strategy()
+ query = "search and rescue at a viewpoint"
+ assert strategy._is_browsecomp_style(query) is False
+
+ def test_exact_threshold_boundary_three_indicators(self):
+ """Exactly 3 indicators should return True (at threshold)."""
+ strategy = _make_strategy()
+ query = "search and rescue at a viewpoint with a body part"
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_empty_query(self):
+ strategy = _make_strategy()
+ assert strategy._is_browsecomp_style("") is False
+
+ def test_between_and_times_more_and_what_is_the_name(self):
+ """Indicators 'between', 'times more', 'what is the name' count."""
+ strategy = _make_strategy()
+ query = "What is the name of the thing between A and B that is 5 times more?"
+ assert strategy._is_browsecomp_style(query) is True
+
+ def test_last_ice_age_indicator(self):
+ """'last ice age' is one of the recognised indicators."""
+ strategy = _make_strategy()
+ query = "Since the last ice age, search and rescue at a viewpoint"
+ assert strategy._is_browsecomp_style(query) is True
+
+
+# ---------------------------------------------------------------------------
+# _classify_query
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyQuery:
+ """Tests for LLM-based query classification and response parsing."""
+
+ def test_parses_query_type_by_enum_name(self):
+ """Exact enum member name on the QUERY_TYPE: line is parsed."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: PUZZLE_LIKE\nREASONING: has clues\nKEY_CHARACTERISTICS: clues"
+ )
+ result = strategy._classify_query("some puzzle query")
+ assert result is QueryType.PUZZLE_LIKE
+
+ def test_parses_hierarchical(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: HIERARCHICAL\nREASONING: multi-part"
+ )
+ assert (
+ strategy._classify_query("multi-part question")
+ is QueryType.HIERARCHICAL
+ )
+
+ def test_parses_comparative(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: COMPARATIVE\nREASONING: comparison"
+ )
+ assert (
+ strategy._classify_query("compare X and Y") is QueryType.COMPARATIVE
+ )
+
+ def test_parses_factual(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: FACTUAL\nREASONING: simple fact"
+ )
+ assert strategy._classify_query("what year was X?") is QueryType.FACTUAL
+
+ def test_parses_constraint_based(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: CONSTRAINT_BASED\nREASONING: constraints"
+ )
+ assert (
+ strategy._classify_query("find the thing with these constraints")
+ is QueryType.CONSTRAINT_BASED
+ )
+
+ def test_parses_exploratory(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: EXPLORATORY\nREASONING: open-ended"
+ )
+ assert (
+ strategy._classify_query("tell me about X") is QueryType.EXPLORATORY
+ )
+
+ def test_falls_back_to_value_match_when_key_fails(self):
+ """When the type string is not a valid enum name, try matching by value."""
+ strategy = _make_strategy()
+ # 'puzzle_like' is the *value*, not the enum *name* (PUZZLE_LIKE).
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: puzzle_like\nREASONING: has clues"
+ )
+ result = strategy._classify_query("puzzle query")
+ assert result is QueryType.PUZZLE_LIKE
+
+ def test_falls_back_to_value_match_constraint_based(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: constraint_based\nREASONING: constraints"
+ )
+ assert (
+ strategy._classify_query("constrained query")
+ is QueryType.CONSTRAINT_BASED
+ )
+
+ def test_defaults_to_exploratory_on_unparseable_response(self):
+ """When the response has no QUERY_TYPE: line, default to EXPLORATORY."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "I think this is a factual question."
+ )
+ result = strategy._classify_query("any query")
+ assert result is QueryType.EXPLORATORY
+
+ def test_defaults_to_exploratory_on_unknown_type(self):
+ """Unknown type string that matches no name or value defaults to EXPLORATORY."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: COMPLETELY_UNKNOWN\nREASONING: no idea"
+ )
+ result = strategy._classify_query("weird query")
+ assert result is QueryType.EXPLORATORY
+
+ def test_handles_think_tags_in_response(self):
+ """Think tags in the LLM output are stripped before parsing."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "<think>Let me think about this...</think>\n"
+ "QUERY_TYPE: FACTUAL\nREASONING: simple"
+ )
+ result = strategy._classify_query("simple fact")
+ assert result is QueryType.FACTUAL
+
+ def test_multiline_response_finds_query_type_line(self):
+ """QUERY_TYPE line buried among other lines is still found."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "Some preamble text.\n"
+ "More discussion.\n"
+ "QUERY_TYPE: COMPARATIVE\n"
+ "REASONING: needs comparison\n"
+ "KEY_CHARACTERISTICS: two entities"
+ )
+ assert (
+ strategy._classify_query("compare A vs B") is QueryType.COMPARATIVE
+ )
+
+ def test_empty_response_defaults_to_exploratory(self):
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response("")
+ assert strategy._classify_query("anything") is QueryType.EXPLORATORY
+
+ def test_value_match_is_case_insensitive(self):
+ """Value matching uses .lower() so mixed-case values still match."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: Puzzle_Like\nREASONING: clues"
+ )
+ result = strategy._classify_query("puzzle")
+ assert result is QueryType.PUZZLE_LIKE
+
+
+# ---------------------------------------------------------------------------
+# analyze_topic delegation
+# ---------------------------------------------------------------------------
+
+
+class TestAnalyzeTopicDelegation:
+ """Tests that analyze_topic routes to the correct sub-strategy."""
+
+ def _patch_classify(self, strategy, query_type):
+ """Patch _classify_query to return a fixed QueryType."""
+ strategy._classify_query = Mock(return_value=query_type)
+
+ def _patch_browsecomp_check(self, strategy, result):
+ """Patch _is_browsecomp_style to return a fixed boolean."""
+ strategy._is_browsecomp_style = Mock(return_value=result)
+
+ # -- PUZZLE_LIKE + browsecomp -> browsecomp strategy -------------------
+
+ @patch(f"{MODULE}.BrowseCompOptimizedStrategy")
+ def test_puzzle_like_browsecomp_uses_browsecomp_strategy(self, MockBrowse):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.PUZZLE_LIKE)
+ self._patch_browsecomp_check(strategy, True)
+
+ mock_sub = MockBrowse.return_value
+ mock_sub.analyze_topic.return_value = {"result": "browsecomp"}
+
+ result = strategy.analyze_topic("browsecomp puzzle query")
+
+ MockBrowse.assert_called_once_with(
+ model=strategy.model,
+ search=strategy.search,
+ all_links_of_system=strategy.all_links_of_system,
+ )
+ mock_sub.analyze_topic.assert_called_once_with(
+ "browsecomp puzzle query"
+ )
+ assert result == {"result": "browsecomp"}
+
+ # -- PUZZLE_LIKE + not browsecomp -> evidence strategy ------------------
+
+ @patch(f"{MODULE}.EvidenceBasedStrategy")
+ def test_puzzle_like_non_browsecomp_uses_evidence_strategy(
+ self, MockEvidence
+ ):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.PUZZLE_LIKE)
+ self._patch_browsecomp_check(strategy, False)
+
+ mock_sub = MockEvidence.return_value
+ mock_sub.analyze_topic.return_value = {"result": "evidence"}
+
+ result = strategy.analyze_topic("non-browsecomp puzzle")
+
+ MockEvidence.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with("non-browsecomp puzzle")
+ assert result == {"result": "evidence"}
+
+ # -- CONSTRAINT_BASED -> evidence strategy ------------------------------
+
+ @patch(f"{MODULE}.EvidenceBasedStrategy")
+ def test_constraint_based_uses_evidence_strategy(self, MockEvidence):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.CONSTRAINT_BASED)
+
+ mock_sub = MockEvidence.return_value
+ mock_sub.analyze_topic.return_value = {"result": "evidence_constraint"}
+
+ result = strategy.analyze_topic("constrained query")
+
+ MockEvidence.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with("constrained query")
+ assert result == {"result": "evidence_constraint"}
+
+ # -- HIERARCHICAL -> recursive strategy ---------------------------------
+
+ @patch(f"{MODULE}.RecursiveDecompositionStrategy")
+ def test_hierarchical_uses_recursive_strategy(self, MockRecursive):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.HIERARCHICAL)
+
+ mock_sub = MockRecursive.return_value
+ mock_sub.analyze_topic.return_value = {"result": "recursive"}
+
+ result = strategy.analyze_topic("multi-part hierarchical query")
+
+ MockRecursive.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with(
+ "multi-part hierarchical query"
+ )
+ assert result == {"result": "recursive"}
+
+ # -- COMPARATIVE -> recursive strategy ----------------------------------
+
+ @patch(f"{MODULE}.RecursiveDecompositionStrategy")
+ def test_comparative_uses_recursive_strategy(self, MockRecursive):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.COMPARATIVE)
+
+ mock_sub = MockRecursive.return_value
+ mock_sub.analyze_topic.return_value = {"result": "recursive_comp"}
+
+ result = strategy.analyze_topic("compare X and Y")
+
+ MockRecursive.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with("compare X and Y")
+ assert result == {"result": "recursive_comp"}
+
+ # -- EXPLORATORY -> recursive strategy ----------------------------------
+
+ @patch(f"{MODULE}.RecursiveDecompositionStrategy")
+ def test_exploratory_uses_recursive_strategy(self, MockRecursive):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.EXPLORATORY)
+
+ mock_sub = MockRecursive.return_value
+ mock_sub.analyze_topic.return_value = {"result": "recursive_exp"}
+
+ result = strategy.analyze_topic("open-ended research question")
+
+ MockRecursive.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with(
+ "open-ended research question"
+ )
+ assert result == {"result": "recursive_exp"}
+
+ # -- FACTUAL -> adaptive strategy ---------------------------------------
+
+ @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
+ def test_factual_uses_adaptive_strategy(self, MockAdaptive):
+ strategy = _make_strategy()
+ self._patch_classify(strategy, QueryType.FACTUAL)
+
+ mock_sub = MockAdaptive.return_value
+ mock_sub.analyze_topic.return_value = {"result": "adaptive"}
+
+ result = strategy.analyze_topic("what year was X founded?")
+
+ MockAdaptive.assert_called_once()
+ mock_sub.analyze_topic.assert_called_once_with(
+ "what year was X founded?"
+ )
+ assert result == {"result": "adaptive"}
+
+
+# ---------------------------------------------------------------------------
+# Progress callback
+# ---------------------------------------------------------------------------
+
+
+class TestProgressCallback:
+ """Tests that the progress callback is invoked correctly."""
+
+ @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
+ def test_progress_callback_called_with_query_type(self, MockAdaptive):
+ callback = Mock()
+ strategy = _make_strategy(progress_callback=callback)
+ strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
+
+ mock_sub = MockAdaptive.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ strategy.analyze_topic("test query")
+
+ callback.assert_called_once_with(
+ "Analyzing query type: factual",
+ 5,
+ {
+ "phase": "query_classification",
+ "query_type": "factual",
+ },
+ )
+
+ @patch(f"{MODULE}.RecursiveDecompositionStrategy")
+ def test_progress_callback_reports_correct_query_type_value(
+ self, MockRecursive
+ ):
+ callback = Mock()
+ strategy = _make_strategy(progress_callback=callback)
+ strategy._classify_query = Mock(return_value=QueryType.HIERARCHICAL)
+
+ mock_sub = MockRecursive.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ strategy.analyze_topic("hierarchical query")
+
+ callback.assert_called_once()
+ call_args = callback.call_args
+ assert call_args[0][0] == "Analyzing query type: hierarchical"
+ assert call_args[0][2]["query_type"] == "hierarchical"
+
+ @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
+ def test_no_progress_callback_does_not_raise(self, MockAdaptive):
+ """When no callback is set, analyze_topic completes without error."""
+ strategy = _make_strategy() # no callback
+ strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
+
+ mock_sub = MockAdaptive.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ # Should not raise
+ strategy.analyze_topic("test query")
+
+ @patch(f"{MODULE}.BrowseCompOptimizedStrategy")
+ def test_progress_callback_propagated_to_sub_strategy(self, MockBrowse):
+ """The callback is forwarded to the sub-strategy via set_progress_callback."""
+ callback = Mock()
+ strategy = _make_strategy(progress_callback=callback)
+ strategy._classify_query = Mock(return_value=QueryType.PUZZLE_LIKE)
+ strategy._is_browsecomp_style = Mock(return_value=True)
+
+ mock_sub = MockBrowse.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ strategy.analyze_topic("puzzle query")
+
+ mock_sub.set_progress_callback.assert_called_once_with(callback)
+
+
+# ---------------------------------------------------------------------------
+# Sub-strategy kwargs propagation
+# ---------------------------------------------------------------------------
+
+
+class TestKwargsPassthrough:
+ """Verify that extra kwargs are forwarded to sub-strategies."""
+
+ @patch(f"{MODULE}.RecursiveDecompositionStrategy")
+ def test_strategy_params_forwarded(self, MockRecursive):
+ model = MagicMock()
+ search = MagicMock()
+ strategy = SmartDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ settings_snapshot={},
+ max_iterations=5,
+ custom_param="hello",
+ )
+ strategy._classify_query = Mock(return_value=QueryType.HIERARCHICAL)
+
+ mock_sub = MockRecursive.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ strategy.analyze_topic("hierarchical query")
+
+ MockRecursive.assert_called_once_with(
+ model=model,
+ search=search,
+ all_links_of_system=[],
+ max_iterations=5,
+ custom_param="hello",
+ )
+
+ @patch(f"{MODULE}.EvidenceBasedStrategy")
+ def test_strategy_params_forwarded_to_evidence(self, MockEvidence):
+ model = MagicMock()
+ search = MagicMock()
+ strategy = SmartDecompositionStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=["link1"],
+ settings_snapshot={},
+ depth=3,
+ )
+ strategy._classify_query = Mock(return_value=QueryType.CONSTRAINT_BASED)
+
+ mock_sub = MockEvidence.return_value
+ mock_sub.analyze_topic.return_value = {}
+
+ strategy.analyze_topic("constraint query")
+
+ MockEvidence.assert_called_once_with(
+ model=model,
+ search=search,
+ all_links_of_system=["link1"],
+ depth=3,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestEdgeCases:
+ """Edge-case tests for robustness."""
+
+ def test_classify_query_with_extra_whitespace_in_type(self):
+ """Extra whitespace around the type string is stripped."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: FACTUAL \nREASONING: simple"
+ )
+ assert strategy._classify_query("fact query") is QueryType.FACTUAL
+
+ def test_classify_query_with_colon_in_reasoning(self):
+ """Colons in subsequent parts of the line don't break parsing."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: HIERARCHICAL\nREASONING: has parts: a, b, c"
+ )
+ assert strategy._classify_query("parts query") is QueryType.HIERARCHICAL
+
+ def test_classify_query_first_query_type_line_wins(self):
+ """If multiple QUERY_TYPE lines exist, the last one wins (loop iterates all)."""
+ strategy = _make_strategy()
+ strategy.model.invoke.return_value = _model_response(
+ "QUERY_TYPE: FACTUAL\nQUERY_TYPE: COMPARATIVE\nREASONING: mixed"
+ )
+ # The loop iterates all lines, so the last QUERY_TYPE line wins
+ assert (
+ strategy._classify_query("ambiguous query") is QueryType.COMPARATIVE
+ )
+
+ @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
+ def test_analyze_topic_returns_sub_strategy_result_unchanged(
+ self, MockAdaptive
+ ):
+ """The dict returned by the sub-strategy is returned as-is."""
+ strategy = _make_strategy()
+ strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
+
+ expected = {
+ "findings": [{"text": "found it"}],
+ "iterations": 2,
+ "questions": {"1": ["q1"]},
+ "formatted_findings": "formatted",
+ "current_knowledge": "knowledge",
+ }
+ MockAdaptive.return_value.analyze_topic.return_value = expected
+
+ result = strategy.analyze_topic("query")
+ assert result is expected
+
+ def test_browsecomp_partial_indicator_no_match(self):
+ """Substring match: 'body' alone does not match 'body part'."""
+ strategy = _make_strategy()
+ query = "body, fell, viewpoint fragment"
+ # 'body' != 'body part'; 'fell' != 'fell from'; 'viewpoint' does match
+ # Only 1 indicator matches ('viewpoint'), so should be False
+ assert strategy._is_browsecomp_style(query) is False
diff --git a/tests/benchmarks/test_calculation_high_value.py b/tests/benchmarks/test_calculation_high_value.py
new file mode 100644
index 0000000000..f0f0f01d7b
--- /dev/null
+++ b/tests/benchmarks/test_calculation_high_value.py
@@ -0,0 +1,290 @@
+"""
+High-value edge case tests for benchmarks/metrics/calculation.py.
+
+Complements test_metrics_calculation.py with additional edge cases:
+- JSONL with blank lines and whitespace
+- Mixed graded/ungraded results
+- Confidence with falsy values (0, empty string)
+- calculate_combined_score with partial metrics
+- calculate_resource_metrics with extreme values
+"""
+
+import json
+
+
+from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ calculate_metrics,
+ calculate_resource_metrics,
+)
+
+
+# ---------------------------------------------------------------------------
+# calculate_metrics edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateMetricsEdgeCases:
+ """Additional edge case tests for calculate_metrics."""
+
+ def test_blank_lines_in_jsonl_skipped(self, tmp_path):
+ """Blank lines between JSON entries are ignored."""
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text(
+ json.dumps({"is_correct": True}) + "\n"
+ "\n"
+ " \n" + json.dumps({"is_correct": False}) + "\n"
+ )
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["total_examples"] == 2
+ assert metrics["graded_examples"] == 2
+
+ def test_ungraded_results_not_counted_for_accuracy(self, tmp_path):
+ """Results without 'is_correct' are excluded from accuracy calculation."""
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": True},
+ {"question": "What is X?"}, # ungraded
+ {"is_correct": False},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["total_examples"] == 3
+ assert metrics["graded_examples"] == 2
+ assert metrics["accuracy"] == 0.5
+
+ def test_confidence_zero_string_is_included(self, tmp_path):
+ """String '0' is truthy so it passes the 'if r.get(confidence)' check.
+ int('0') = 0, so both values are included: (0 + 80) / 2 = 40."""
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"confidence": "0"},
+ {"confidence": "80"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ # "0" is truthy string, int("0")=0, so (0+80)/2 = 40
+ assert metrics["average_confidence"] == 40
+
+ def test_confidence_empty_string_skipped(self, tmp_path):
+ """Empty string confidence is falsy and skipped."""
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"confidence": ""},
+ {"confidence": "90"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["average_confidence"] == 90
+
+ def test_processing_time_only_from_entries_that_have_it(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"processing_time": 2.0},
+ {"question": "no time"},
+ {"processing_time": 4.0},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["average_processing_time"] == 3.0
+
+ def test_all_results_are_errors(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"error": "timeout"},
+ {"error": "connection failed"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["error_count"] == 2
+ assert metrics["error_rate"] == 1.0
+ assert metrics["graded_examples"] == 0
+ assert metrics["accuracy"] == 0
+
+ def test_category_with_zero_correct(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results = [
+ {"is_correct": False, "category": "hard"},
+ {"is_correct": False, "category": "hard"},
+ ]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["categories"]["hard"]["accuracy"] == 0.0
+
+ def test_single_result(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text(
+ json.dumps({"is_correct": True, "confidence": "95"}) + "\n"
+ )
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["total_examples"] == 1
+ assert metrics["accuracy"] == 1.0
+ assert metrics["average_confidence"] == 95
+
+ def test_is_correct_false_counted_in_graded(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results = [{"is_correct": False}]
+ with open(results_file, "w") as f:
+ for r in results:
+ f.write(json.dumps(r) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert metrics["graded_examples"] == 1
+ assert metrics["correct"] == 0
+ assert metrics["accuracy"] == 0.0
+
+ def test_timestamp_present_in_metrics(self, tmp_path):
+ results_file = tmp_path / "results.jsonl"
+ results_file.write_text(json.dumps({"is_correct": True}) + "\n")
+
+ metrics = calculate_metrics(str(results_file))
+ assert "timestamp" in metrics
+ assert "T" in metrics["timestamp"] # ISO format
+
+
+# ---------------------------------------------------------------------------
+# calculate_combined_score edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateCombinedScoreEdgeCases:
+ """Additional edge cases for combined score calculation."""
+
+ def test_empty_metrics_dict(self):
+ score = calculate_combined_score({})
+ assert score == 0.0
+
+ def test_only_quality_metric(self):
+ metrics = {"quality": {"quality_score": 0.9}}
+ score = calculate_combined_score(metrics)
+ # Only quality contributes: 0.9 * (0.6/1.0) = 0.54
+ expected = 0.9 * 0.6
+ assert abs(score - expected) < 0.001
+
+ def test_only_speed_metric(self):
+ metrics = {"speed": {"speed_score": 0.8}}
+ score = calculate_combined_score(metrics)
+ expected = 0.8 * 0.3
+ assert abs(score - expected) < 0.001
+
+ def test_only_resource_metric(self):
+ metrics = {"resource": {"resource_score": 0.5}}
+ score = calculate_combined_score(metrics)
+ expected = 0.5 * 0.1
+ assert abs(score - expected) < 0.001
+
+ def test_unrecognized_metric_keys_ignored(self):
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "custom_metric": {"score": 0.5},
+ }
+ score = calculate_combined_score(metrics)
+ # custom_metric has no weight, so ignored
+ expected = 1.0 * 0.6
+ assert abs(score - expected) < 0.001
+
+ def test_all_scores_zero(self):
+ metrics = {
+ "quality": {"quality_score": 0.0},
+ "speed": {"speed_score": 0.0},
+ "resource": {"resource_score": 0.0},
+ }
+ assert calculate_combined_score(metrics) == 0.0
+
+ def test_negative_weights_still_normalize(self):
+ """Negative weights are technically allowed by the function."""
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "speed": {"speed_score": 1.0},
+ }
+ weights = {"quality": 1.0, "speed": -0.5, "resource": 0.0}
+ score = calculate_combined_score(metrics, weights)
+ # total_weight = 0.5, norm: quality=2.0, speed=-1.0
+ # score = 1.0 * 2.0 + 1.0 * (-1.0) = 1.0
+ assert abs(score - 1.0) < 0.001
+
+ def test_missing_score_key_defaults_to_zero(self):
+ metrics = {
+ "quality": {}, # no quality_score key
+ }
+ score = calculate_combined_score(metrics)
+ assert score == 0.0
+
+
+# ---------------------------------------------------------------------------
+# calculate_resource_metrics edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateResourceMetricsEdgeCases:
+ """Additional edge cases for resource metrics."""
+
+ def test_very_high_complexity(self):
+ config = {
+ "iterations": 10,
+ "questions_per_iteration": 10,
+ "max_results": 200,
+ }
+ metrics = calculate_resource_metrics(config)
+ assert (
+ metrics["resource_score"] < 0.1
+ ) # Very high complexity -> low score
+
+ def test_minimal_complexity(self):
+ config = {
+ "iterations": 1,
+ "questions_per_iteration": 1,
+ "max_results": 10,
+ }
+ metrics = calculate_resource_metrics(config)
+ assert (
+ metrics["resource_score"] > 0.8
+ ) # Very low complexity -> high score
+
+ def test_zero_iterations(self):
+ config = {"iterations": 0}
+ metrics = calculate_resource_metrics(config)
+ assert metrics["estimated_complexity"] == 0
+ assert metrics["resource_score"] == 1.0 # 1/(1+0) = 1.0
+
+ def test_complexity_formula(self):
+ """Verify the exact formula: iterations * questions * (max_results/50)."""
+ config = {
+ "iterations": 3,
+ "questions_per_iteration": 4,
+ "max_results": 100,
+ }
+ metrics = calculate_resource_metrics(config)
+ expected_complexity = 3 * 4 * (100 / 50)
+ assert metrics["estimated_complexity"] == expected_complexity
+
+ def test_resource_score_formula(self):
+ """Verify: resource_score = 1/(1 + complexity/4)."""
+ config = {
+ "iterations": 2,
+ "questions_per_iteration": 2,
+ "max_results": 50,
+ }
+ metrics = calculate_resource_metrics(config)
+ # complexity = 2 * 2 * (50/50) = 4.0
+ expected_score = 1.0 / (1.0 + 4.0 / 4.0)
+ assert abs(metrics["resource_score"] - expected_score) < 0.001
diff --git a/tests/web/database/__init__.py b/tests/web/database/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/web/database/test_benchmark_schema_high_value.py b/tests/web/database/test_benchmark_schema_high_value.py
new file mode 100644
index 0000000000..b92d22dde4
--- /dev/null
+++ b/tests/web/database/test_benchmark_schema_high_value.py
@@ -0,0 +1,248 @@
+"""
+High-value tests for benchmark schema definitions.
+
+Covers:
+- BenchmarkStatus enum values and completeness
+- DatasetType enum values and completeness
+- Table definition structures (columns, indexes, constraints, foreign keys)
+- create_benchmark_tables_simple: actual table creation with in-memory SQLite
+"""
+
+import pytest
+from sqlalchemy import create_engine, inspect
+
+from local_deep_research.web.database.benchmark_schema import (
+ BenchmarkStatus,
+ DatasetType,
+ benchmark_configs_table,
+ benchmark_progress_table,
+ benchmark_results_table,
+ benchmark_runs_table,
+ create_benchmark_tables_simple,
+)
+
+
+# ---------------------------------------------------------------------------
+# Enum definitions
+# ---------------------------------------------------------------------------
+
+
+class TestBenchmarkStatus:
+ """Tests for BenchmarkStatus enum."""
+
+ def test_all_expected_values(self):
+ assert BenchmarkStatus.PENDING.value == "pending"
+ assert BenchmarkStatus.IN_PROGRESS.value == "in_progress"
+ assert BenchmarkStatus.COMPLETED.value == "completed"
+ assert BenchmarkStatus.FAILED.value == "failed"
+ assert BenchmarkStatus.CANCELLED.value == "cancelled"
+ assert BenchmarkStatus.PAUSED.value == "paused"
+
+ def test_member_count(self):
+ assert len(BenchmarkStatus) == 6
+
+ def test_values_are_unique(self):
+ values = [s.value for s in BenchmarkStatus]
+ assert len(values) == len(set(values))
+
+ def test_lookup_by_name(self):
+ assert BenchmarkStatus["PENDING"] is BenchmarkStatus.PENDING
+
+ def test_lookup_invalid_raises(self):
+ with pytest.raises(KeyError):
+ BenchmarkStatus["NONEXISTENT"]
+
+
+class TestDatasetType:
+ """Tests for DatasetType enum."""
+
+ def test_all_expected_values(self):
+ assert DatasetType.SIMPLEQA.value == "simpleqa"
+ assert DatasetType.BROWSECOMP.value == "browsecomp"
+ assert DatasetType.CUSTOM.value == "custom"
+
+ def test_member_count(self):
+ assert len(DatasetType) == 3
+
+ def test_values_are_unique(self):
+ values = [d.value for d in DatasetType]
+ assert len(values) == len(set(values))
+
+
+# ---------------------------------------------------------------------------
+# Table definition structures
+# ---------------------------------------------------------------------------
+
+
+class TestTableDefinitions:
+ """Tests for table definition dict structures."""
+
+ def test_benchmark_runs_table_name(self):
+ assert benchmark_runs_table["table_name"] == "benchmark_runs"
+
+ def test_benchmark_runs_has_columns(self):
+ assert len(benchmark_runs_table["columns"]) > 0
+
+ def test_benchmark_runs_has_indexes(self):
+ assert len(benchmark_runs_table["indexes"]) >= 2
+
+ def test_benchmark_results_table_name(self):
+ assert benchmark_results_table["table_name"] == "benchmark_results"
+
+ def test_benchmark_results_has_foreign_key(self):
+ """benchmark_results has a FK to benchmark_runs.id."""
+ columns = benchmark_results_table["columns"]
+ fk_columns = [
+ c
+ for c in columns
+ if c.foreign_keys or (hasattr(c, "name") and "run_id" in str(c))
+ ]
+ # At least one column should reference benchmark_runs
+ assert len(fk_columns) >= 1
+
+ def test_benchmark_results_has_unique_constraint(self):
+ constraints = benchmark_results_table.get("constraints", [])
+ assert len(constraints) >= 1
+
+ def test_benchmark_configs_table_name(self):
+ assert benchmark_configs_table["table_name"] == "benchmark_configs"
+
+ def test_benchmark_progress_table_name(self):
+ assert benchmark_progress_table["table_name"] == "benchmark_progress"
+
+ def test_all_tables_have_id_column(self):
+ for table_def in [
+ benchmark_runs_table,
+ benchmark_results_table,
+ benchmark_configs_table,
+ benchmark_progress_table,
+ ]:
+ column_names = [c.name for c in table_def["columns"]]
+ assert "id" in column_names, (
+ f"{table_def['table_name']} missing id column"
+ )
+
+
+# ---------------------------------------------------------------------------
+# create_benchmark_tables_simple with in-memory SQLite
+# ---------------------------------------------------------------------------
+
+
+class TestCreateBenchmarkTablesSimple:
+ """Tests for actual table creation using SQLite in-memory.
+
+ Uses a module-scoped engine because the Column objects in the schema module
+ are module-level singletons that get bound to a Table on first use and
+ cannot be re-bound to a different MetaData instance.
+ """
+
+ @pytest.fixture(scope="class")
+ def db_engine(self):
+ """Create an in-memory SQLite engine shared across tests in this class."""
+ engine = create_engine("sqlite:///:memory:")
+ create_benchmark_tables_simple(engine)
+ return engine
+
+ def test_creates_all_four_tables(self, db_engine):
+ inspector = inspect(db_engine)
+ tables = inspector.get_table_names()
+
+ assert "benchmark_runs" in tables
+ assert "benchmark_results" in tables
+ assert "benchmark_configs" in tables
+ assert "benchmark_progress" in tables
+
+ def test_benchmark_runs_columns(self, db_engine):
+ inspector = inspect(db_engine)
+ columns = {c["name"] for c in inspector.get_columns("benchmark_runs")}
+
+ expected = {
+ "id",
+ "run_name",
+ "config_hash",
+ "query_hash_list",
+ "search_config",
+ "evaluation_config",
+ "datasets_config",
+ "status",
+ "created_at",
+ "updated_at",
+ "start_time",
+ "end_time",
+ "total_examples",
+ "completed_examples",
+ "failed_examples",
+ "overall_accuracy",
+ "processing_rate",
+ "error_message",
+ }
+ assert expected.issubset(columns)
+
+ def test_benchmark_results_columns(self, db_engine):
+ inspector = inspect(db_engine)
+ columns = {
+ c["name"] for c in inspector.get_columns("benchmark_results")
+ }
+
+ expected = {
+ "id",
+ "benchmark_run_id",
+ "example_id",
+ "query_hash",
+ "dataset_type",
+ "question",
+ "correct_answer",
+ "response",
+ "is_correct",
+ "processing_time",
+ "confidence",
+ }
+ assert expected.issubset(columns)
+
+ def test_benchmark_configs_columns(self, db_engine):
+ inspector = inspect(db_engine)
+ columns = {
+ c["name"] for c in inspector.get_columns("benchmark_configs")
+ }
+
+ expected = {
+ "id",
+ "name",
+ "description",
+ "config_hash",
+ "search_config",
+ "evaluation_config",
+ "datasets_config",
+ "is_default",
+ "is_public",
+ "usage_count",
+ }
+ assert expected.issubset(columns)
+
+ def test_benchmark_progress_columns(self, db_engine):
+ inspector = inspect(db_engine)
+ columns = {
+ c["name"] for c in inspector.get_columns("benchmark_progress")
+ }
+
+ expected = {
+ "id",
+ "benchmark_run_id",
+ "timestamp",
+ "completed_examples",
+ "total_examples",
+ "overall_accuracy",
+ }
+ assert expected.issubset(columns)
+
+ def test_benchmark_results_foreign_key_exists(self, db_engine):
+ inspector = inspect(db_engine)
+ fks = inspector.get_foreign_keys("benchmark_results")
+ fk_tables = [fk["referred_table"] for fk in fks]
+ assert "benchmark_runs" in fk_tables
+
+ def test_benchmark_progress_foreign_key_exists(self, db_engine):
+ inspector = inspect(db_engine)
+ fks = inspector.get_foreign_keys("benchmark_progress")
+ fk_tables = [fk["referred_table"] for fk in fks]
+ assert "benchmark_runs" in fk_tables
diff --git a/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py b/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py
new file mode 100644
index 0000000000..6aef0439b4
--- /dev/null
+++ b/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py
@@ -0,0 +1,279 @@
+"""
+High-value tests for rate-limited LLM wrapper.
+
+Complements test_llm_wrapper_pure_logic.py by covering:
+- AdaptiveLLMWait.__call__: retry-after extraction, tracker wait time, max selection
+- RateLimitedLLMWrapper.invoke: direct passthrough without rate limiting
+- __getattr__ passthrough to base LLM
+- __str__ and __repr__ formatting
+- _do_invoke: exception wrapping for rate limit errors
+"""
+
+import types
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (
+ AdaptiveLLMWait,
+ create_rate_limited_llm_wrapper,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_llm(**attrs):
+ return types.SimpleNamespace(**attrs)
+
+
+def _wrapper(llm=None, provider=None):
+ if llm is None:
+ llm = _make_llm()
+ return create_rate_limited_llm_wrapper(llm, provider=provider)
+
+
+# ---------------------------------------------------------------------------
+# AdaptiveLLMWait.__call__
+# ---------------------------------------------------------------------------
+
+
+class TestAdaptiveLLMWait:
+ """Tests for the adaptive wait strategy."""
+
+ def test_uses_tracker_wait_time(self):
+ tracker = MagicMock()
+ tracker.get_wait_time.return_value = 5.0
+ wait = AdaptiveLLMWait(tracker, "test-engine")
+
+ retry_state = Mock()
+ retry_state.outcome = None
+
+ result = wait(retry_state)
+ assert result == 5.0
+ tracker.get_wait_time.assert_called_once_with("test-engine")
+
+ def test_uses_retry_after_when_larger(self):
+ tracker = MagicMock()
+ tracker.get_wait_time.return_value = 2.0
+ wait = AdaptiveLLMWait(tracker, "test-engine")
+
+ # Simulate a failed outcome with retry-after
+ error = Exception("rate limited")
+ outcome = Mock()
+ outcome.failed = True
+ outcome.exception.return_value = error
+
+ retry_state = Mock()
+ retry_state.outcome = outcome
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.extract_retry_after",
+ return_value=10.0,
+ ):
+ result = wait(retry_state)
+
+ assert result == 10.0 # max(2.0, 10.0)
+
+ def test_uses_tracker_when_retry_after_is_zero(self):
+ tracker = MagicMock()
+ tracker.get_wait_time.return_value = 3.0
+ wait = AdaptiveLLMWait(tracker, "test-engine")
+
+ error = Exception("rate limited")
+ outcome = Mock()
+ outcome.failed = True
+ outcome.exception.return_value = error
+
+ retry_state = Mock()
+ retry_state.outcome = outcome
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.extract_retry_after",
+ return_value=0,
+ ):
+ result = wait(retry_state)
+
+ assert result == 3.0
+
+ def test_stores_last_error(self):
+ tracker = MagicMock()
+ tracker.get_wait_time.return_value = 1.0
+ wait = AdaptiveLLMWait(tracker, "test-engine")
+
+ error = ValueError("specific error")
+ outcome = Mock()
+ outcome.failed = True
+ outcome.exception.return_value = error
+
+ retry_state = Mock()
+ retry_state.outcome = outcome
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.extract_retry_after",
+ return_value=0,
+ ):
+ wait(retry_state)
+
+ assert wait.last_error is error
+
+ def test_no_error_when_outcome_not_failed(self):
+ tracker = MagicMock()
+ tracker.get_wait_time.return_value = 1.0
+ wait = AdaptiveLLMWait(tracker, "test-engine")
+ wait.last_error = None
+
+ retry_state = Mock()
+ retry_state.outcome = Mock()
+ retry_state.outcome.failed = False
+
+ result = wait(retry_state)
+ assert result == 1.0
+ assert wait.last_error is None
+
+ def test_initial_state(self):
+ tracker = MagicMock()
+ wait = AdaptiveLLMWait(tracker, "my-engine")
+ assert wait.tracker is tracker
+ assert wait.engine_type == "my-engine"
+ assert wait.last_error is None
+
+
+# ---------------------------------------------------------------------------
+# RateLimitedLLMWrapper.invoke (without rate limiting)
+# ---------------------------------------------------------------------------
+
+
+class TestInvokeWithoutRateLimiting:
+ """Tests for invoke when rate limiting is disabled (default)."""
+
+ def test_invoke_passes_through_to_base_llm(self):
+ llm = MagicMock()
+ llm.invoke.return_value = "response"
+ wrapper = _wrapper(llm=llm)
+
+ result = wrapper.invoke("hello")
+ assert result == "response"
+ llm.invoke.assert_called_once_with("hello")
+
+ def test_invoke_passes_kwargs_through(self):
+ llm = MagicMock()
+ llm.invoke.return_value = "resp"
+ wrapper = _wrapper(llm=llm)
+
+ wrapper.invoke("prompt", temperature=0.5, max_tokens=100)
+ llm.invoke.assert_called_once_with(
+ "prompt", temperature=0.5, max_tokens=100
+ )
+
+ def test_invoke_propagates_non_rate_limit_error(self):
+ llm = MagicMock()
+ llm.invoke.side_effect = ValueError("bad input")
+ wrapper = _wrapper(llm=llm)
+
+ with pytest.raises(ValueError, match="bad input"):
+ wrapper.invoke("prompt")
+
+ def test_invoke_wraps_rate_limit_error(self):
+ """Rate limit errors are wrapped in RateLimitError."""
+ from local_deep_research.web_search_engines.rate_limiting.exceptions import (
+ RateLimitError,
+ )
+
+ llm = MagicMock()
+ error = Exception("429 Too Many Requests")
+ llm.invoke.side_effect = error
+ wrapper = _wrapper(llm=llm)
+
+ with patch(
+ "local_deep_research.web_search_engines.rate_limiting.llm.wrapper.is_llm_rate_limit_error",
+ return_value=True,
+ ):
+ with pytest.raises(RateLimitError):
+ wrapper.invoke("prompt")
+
+ def test_rate_limiter_is_none_by_default(self):
+ wrapper = _wrapper()
+ assert wrapper.rate_limiter is None
+
+
+# ---------------------------------------------------------------------------
+# __getattr__ passthrough
+# ---------------------------------------------------------------------------
+
+
+class TestGetAttrPassthrough:
+ """Tests for attribute delegation to base LLM."""
+
+ def test_passes_unknown_attr_to_base(self):
+ llm = _make_llm(model_name="gpt-4", temperature=0.7)
+ wrapper = _wrapper(llm=llm)
+ assert wrapper.model_name == "gpt-4"
+ assert wrapper.temperature == 0.7
+
+ def test_raises_attribute_error_for_missing(self):
+ llm = _make_llm()
+ wrapper = _wrapper(llm=llm)
+ with pytest.raises(AttributeError):
+ _ = wrapper.nonexistent_attribute
+
+ def test_base_llm_accessible(self):
+ llm = _make_llm(name="test-llm")
+ wrapper = _wrapper(llm=llm)
+ assert wrapper.base_llm is llm
+
+ def test_provider_accessible(self):
+ wrapper = _wrapper(provider="anthropic")
+ assert wrapper.provider == "anthropic"
+
+
+# ---------------------------------------------------------------------------
+# __str__ and __repr__
+# ---------------------------------------------------------------------------
+
+
+class TestStringRepresentation:
+ """Tests for __str__ and __repr__."""
+
+ def test_str_format(self):
+ llm = _make_llm()
+ wrapper = _wrapper(llm=llm)
+ result = str(wrapper)
+ assert result.startswith("RateLimited(")
+ assert result.endswith(")")
+
+ def test_repr_format(self):
+ llm = _make_llm()
+ wrapper = _wrapper(llm=llm)
+ result = repr(wrapper)
+ assert result.startswith("RateLimitedLLMWrapper(")
+ assert result.endswith(")")
+
+ def test_str_includes_base_llm_str(self):
+ llm = types.SimpleNamespace()
+ llm.__str__ = lambda self: "MyLLM"
+ # SimpleNamespace doesn't support __str__ override this way,
+ # so use a Mock
+ llm_mock = Mock()
+ llm_mock.__str__ = Mock(return_value="MockLLM")
+ wrapper = create_rate_limited_llm_wrapper(llm_mock)
+ assert "MockLLM" in str(wrapper)
+
+
+# ---------------------------------------------------------------------------
+# _should_rate_limit
+# ---------------------------------------------------------------------------
+
+
+class TestShouldRateLimit:
+ """Tests for the rate limiting check."""
+
+ def test_rate_limiting_disabled_by_default(self):
+ wrapper = _wrapper()
+ assert wrapper._should_rate_limit() is False
+
+ def test_rate_limiter_not_set_when_disabled(self):
+ wrapper = _wrapper()
+ assert wrapper.rate_limiter is None