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: branch-coverage for evaluator.py and cross_constraint_manager.py (#2857)

LearningCircuit3e0615271769
diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.py
new file mode 100644
index 0000000000..45748a80c8
--- /dev/null
+++ b/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.py
@@ -0,0 +1,771 @@
+"""
+Branch-coverage tests for
+advanced_search_system/search_optimization/cross_constraint_manager.py.
+
+Targets the remaining 41 missing lines, focusing on branches not yet
+exercised by test_cross_constraint_coverage.py,
+test_cross_constraint_edge_cases.py, or test_cross_constraint_pure_logic.py:
+
+1. create_constraint_clusters – type_based grouping (only groups with >1)
+2. _create_relationship_clusters – BFS connected components
+3. _create_semantic_clusters – LLM response parsing (CLUSTER_ blocks)
+4. generate_cross_constraint_queries – all four sub-generators called
+5. validate_candidate_across_constraints – cluster-based + pairwise
+6. _deduplicate_clusters – duplicate removal
+7. _calculate_cluster_coherence – no pairs → 0.5 default
+8. optimize_search_order – sorting by coherence * size
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (
+ ConstraintCluster,
+ ConstraintRelationship,
+ CrossConstraintManager,
+)
+
+MODULE = (
+ "local_deep_research.advanced_search_system"
+ ".search_optimization.cross_constraint_manager"
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _c(cid, ctype=ConstraintType.PROPERTY, weight=1.0, desc=None):
+ """Build a Constraint quickly."""
+ return Constraint(
+ id=cid,
+ type=ctype,
+ description=desc or f"desc for {cid}",
+ value=cid,
+ weight=weight,
+ )
+
+
+def _manager(model=None):
+ """Return a CrossConstraintManager with a fresh MagicMock model."""
+ if model is None:
+ model = MagicMock()
+ return CrossConstraintManager(model=model), model
+
+
+def _cluster(constraints, ctype="type_based", coherence=0.5, queries=None):
+ cl = ConstraintCluster(
+ constraints=constraints,
+ cluster_type=ctype,
+ coherence_score=coherence,
+ )
+ if queries is not None:
+ cl.search_queries = queries
+ return cl
+
+
+# ---------------------------------------------------------------------------
+# 1. test_create_constraint_clusters_type_based
+# ---------------------------------------------------------------------------
+
+
+class TestCreateConstraintClustersTypeBased:
+ """create_constraint_clusters groups same-type constraints (>1) together."""
+
+ def test_two_temporal_form_one_type_cluster(self):
+ """Two TEMPORAL constraints produce exactly one type_based cluster."""
+ mgr, model = _manager()
+ # Weak LLM responses so no relationship clusters are formed
+ model.invoke.return_value = MagicMock(
+ content="Type: none\nStrength: 0.0\nEvidence: n/a\n"
+ "CLUSTER_1:\nConstraints: []\nTheme: t\nCoherence: 0.5"
+ )
+
+ c1 = _c("c1", ConstraintType.TEMPORAL)
+ c2 = _c("c2", ConstraintType.TEMPORAL)
+ c3 = _c("c3", ConstraintType.LOCATION) # lone location – no cluster
+
+ clusters = mgr.create_constraint_clusters([c1, c2, c3])
+
+ type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]
+ assert len(type_based) == 1
+ ids = {con.id for con in type_based[0].constraints}
+ assert ids == {"c1", "c2"}
+
+ def test_singleton_type_not_clustered(self):
+ """A type represented by only one constraint must not produce a cluster."""
+ mgr, model = _manager()
+ model.invoke.return_value = MagicMock(
+ content="Type: none\nStrength: 0.0\nEvidence: n/a"
+ )
+
+ c1 = _c("c1", ConstraintType.TEMPORAL)
+ c2 = _c("c2", ConstraintType.LOCATION) # unique type
+
+ clusters = mgr.create_constraint_clusters([c1, c2])
+
+ # No type_based clusters because both types have only one member
+ type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]
+ assert len(type_based) == 0
+
+ def test_multiple_types_each_with_two_members(self):
+ """Two distinct types each with two constraints produce two type-based clusters."""
+ mgr, model = _manager()
+ model.invoke.return_value = MagicMock(
+ content="Type: none\nStrength: 0.0\nEvidence: n/a"
+ )
+
+ constraints = [
+ _c("t1", ConstraintType.TEMPORAL),
+ _c("t2", ConstraintType.TEMPORAL),
+ _c("l1", ConstraintType.LOCATION),
+ _c("l2", ConstraintType.LOCATION),
+ ]
+
+ clusters = mgr.create_constraint_clusters(constraints)
+
+ type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]
+ assert len(type_based) == 2
+
+ def test_type_based_cluster_coherence_score(self):
+ """Type-based clusters have coherence_score == 0.7 (hard-coded in source)."""
+ mgr, model = _manager()
+ model.invoke.return_value = MagicMock(
+ content="Type: none\nStrength: 0.0\nEvidence: n/a"
+ )
+
+ c1 = _c("c1", ConstraintType.PROPERTY)
+ c2 = _c("c2", ConstraintType.PROPERTY)
+
+ clusters = mgr.create_constraint_clusters([c1, c2])
+
+ type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]
+ assert len(type_based) == 1
+ assert type_based[0].coherence_score == pytest.approx(0.7)
+
+ def test_clusters_stored_on_manager(self):
+ """create_constraint_clusters stores result in self.clusters."""
+ mgr, model = _manager()
+ model.invoke.return_value = MagicMock(
+ content="Type: none\nStrength: 0.0\nEvidence: n/a"
+ )
+
+ c1 = _c("c1", ConstraintType.TEMPORAL)
+ c2 = _c("c2", ConstraintType.TEMPORAL)
+
+ result = mgr.create_constraint_clusters([c1, c2])
+ assert mgr.clusters is result
+
+
+# ---------------------------------------------------------------------------
+# 2. test_create_relationship_clusters_bfs
+# ---------------------------------------------------------------------------
+
+
+class TestCreateRelationshipClustersBfs:
+ """_create_relationship_clusters uses BFS to find connected components."""
+
+ def test_linear_chain_forms_one_cluster(self):
+ """c1-c2 and c2-c3 connected via BFS → single cluster {c1, c2, c3}."""
+ mgr, _ = _manager()
+ c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")
+
+ rels = [
+ ConstraintRelationship("c1", "c2", "complementary", 0.8),
+ ConstraintRelationship("c2", "c3", "complementary", 0.7),
+ ]
+
+ result = mgr._create_relationship_clusters([c1, c2, c3], rels)
+
+ assert len(result) == 1
+ ids = {con.id for con in result[0].constraints}
+ assert ids == {"c1", "c2", "c3"}
+
+ def test_two_separate_components(self):
+ """c1-c2 and c3-c4 are disconnected → two clusters."""
+ mgr, _ = _manager()
+ c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")
+
+ rels = [
+ ConstraintRelationship("c1", "c2", "complementary", 0.9),
+ ConstraintRelationship("c3", "c4", "dependent", 0.8),
+ ]
+
+ result = mgr._create_relationship_clusters([c1, c2, c3, c4], rels)
+
+ assert len(result) == 2
+ cluster_sets = [
+ frozenset(con.id for con in cl.constraints) for cl in result
+ ]
+ assert frozenset({"c1", "c2"}) in cluster_sets
+ assert frozenset({"c3", "c4"}) in cluster_sets
+
+ def test_isolated_node_not_clustered(self):
+ """A node with no relationships is not added to any cluster."""
+ mgr, _ = _manager()
+ c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")
+
+ rels = [ConstraintRelationship("c1", "c2", "complementary", 0.9)]
+
+ result = mgr._create_relationship_clusters([c1, c2, c3], rels)
+
+ # c3 is isolated; only {c1, c2} cluster should exist
+ all_ids = {con.id for cl in result for con in cl.constraints}
+ assert "c3" not in all_ids
+
+ def test_empty_relationships_no_clusters(self):
+ """No relationships → no clusters."""
+ mgr, _ = _manager()
+ constraints = [_c(f"c{i}") for i in range(4)]
+
+ result = mgr._create_relationship_clusters(constraints, [])
+
+ assert result == []
+
+ def test_each_node_processed_at_most_once(self):
+ """BFS marks processed nodes; no duplicates in output clusters."""
+ mgr, _ = _manager()
+ c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")
+
+ rels = [
+ ConstraintRelationship("c1", "c2", "complementary", 0.8),
+ ConstraintRelationship("c1", "c3", "complementary", 0.7),
+ ]
+
+ result = mgr._create_relationship_clusters([c1, c2, c3], rels)
+
+ # All three should be in one cluster; no duplicates
+ assert len(result) == 1
+ ids = [con.id for con in result[0].constraints]
+ assert len(ids) == len(set(ids))
+
+ def test_cluster_type_is_relationship_based(self):
+ """Clusters created here always have cluster_type 'relationship_based'."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ rels = [ConstraintRelationship("c1", "c2", "complementary", 0.9)]
+
+ result = mgr._create_relationship_clusters([c1, c2], rels)
+
+ assert result[0].cluster_type == "relationship_based"
+
+
+# ---------------------------------------------------------------------------
+# 3. test_create_semantic_clusters_parsing
+# ---------------------------------------------------------------------------
+
+
+class TestCreateSemanticClustersParsing:
+ """_create_semantic_clusters parses CLUSTER_N blocks from LLM response."""
+
+ def _make_response(self, text):
+ r = MagicMock()
+ r.content = text
+ return r
+
+ def test_single_cluster_block_parsed(self):
+ """A single CLUSTER_1 block with two valid IDs produces one cluster."""
+ mgr, model = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ llm_text = (
+ "CLUSTER_1:\n"
+ "Constraints: [c1, c2]\n"
+ "Theme: temporal overlap\n"
+ "Coherence: 0.8\n"
+ )
+ with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):
+ model.invoke.return_value = self._make_response(llm_text)
+ result = mgr._create_semantic_clusters([c1, c2])
+
+ assert len(result) == 1
+ ids = {con.id for con in result[0].constraints}
+ assert ids == {"c1", "c2"}
+ assert result[0].coherence_score == pytest.approx(0.8)
+ assert result[0].cluster_type == "semantic"
+
+ def test_two_cluster_blocks_parsed(self):
+ """Two CLUSTER_ blocks each with two IDs produce two semantic clusters."""
+ mgr, model = _manager()
+ c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")
+
+ llm_text = (
+ "CLUSTER_1:\n"
+ "Constraints: [c1, c2]\n"
+ "Theme: time\n"
+ "Coherence: 0.7\n"
+ "CLUSTER_2:\n"
+ "Constraints: [c3, c4]\n"
+ "Theme: space\n"
+ "Coherence: 0.6\n"
+ )
+ with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):
+ model.invoke.return_value = self._make_response(llm_text)
+ result = mgr._create_semantic_clusters([c1, c2, c3, c4])
+
+ assert len(result) == 2
+
+ def test_invalid_coherence_defaults_to_half(self):
+ """Non-numeric Coherence value defaults to 0.5."""
+ mgr, model = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ llm_text = (
+ "CLUSTER_1:\nConstraints: [c1, c2]\nTheme: mixed\nCoherence: high\n"
+ )
+ with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):
+ model.invoke.return_value = self._make_response(llm_text)
+ result = mgr._create_semantic_clusters([c1, c2])
+
+ if result:
+ assert result[0].coherence_score == pytest.approx(0.5)
+
+ def test_singleton_cluster_not_added(self):
+ """A block referencing only one valid constraint ID is skipped."""
+ mgr, model = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ # Only c1 matches a real constraint
+ llm_text = (
+ "CLUSTER_1:\n"
+ "Constraints: [c1, c_nonexistent]\n"
+ "Theme: lonely\n"
+ "Coherence: 0.9\n"
+ )
+ with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):
+ model.invoke.return_value = self._make_response(llm_text)
+ result = mgr._create_semantic_clusters([c1, c2])
+
+ # c_nonexistent is not in the constraint list so only c1 matches → skipped
+ assert all(len(cl.constraints) > 1 for cl in result)
+
+ def test_last_cluster_block_also_parsed(self):
+ """The final CLUSTER_ block (after loop end) must not be lost."""
+ mgr, model = _manager()
+ c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")
+
+ llm_text = (
+ "CLUSTER_1:\n"
+ "Constraints: [c1, c2]\n"
+ "Theme: A\n"
+ "Coherence: 0.7\n"
+ "CLUSTER_2:\n"
+ "Constraints: [c3, c4]\n"
+ "Theme: B\n"
+ "Coherence: 0.6\n"
+ )
+ with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):
+ model.invoke.return_value = self._make_response(llm_text)
+ result = mgr._create_semantic_clusters([c1, c2, c3, c4])
+
+ # Both blocks parsed – second one (c3, c4) must appear
+ all_ids = {con.id for cl in result for con in cl.constraints}
+ assert "c3" in all_ids
+ assert "c4" in all_ids
+
+
+# ---------------------------------------------------------------------------
+# 4. test_generate_cross_constraint_queries
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateCrossConstraintQueries:
+ """generate_cross_constraint_queries calls all four sub-generators."""
+
+ def test_all_query_types_invoked(self):
+ """Combined, progressive, intersection, and validation queries are built."""
+ mgr, _ = _manager()
+ c1, c2, c3 = (
+ _c("c1", weight=0.9),
+ _c("c2", weight=0.7),
+ _c("c3", weight=0.5),
+ )
+ cluster = _cluster([c1, c2, c3])
+
+ combined_q = "combined query"
+ prog_q = "progressive query"
+ inter_q = "intersection query"
+ val_q = "validation query"
+
+ with (
+ patch.object(
+ mgr, "_generate_combined_query", return_value=combined_q
+ ) as mock_comb,
+ patch.object(
+ mgr, "_generate_progressive_queries", return_value=[prog_q]
+ ) as mock_prog,
+ patch.object(
+ mgr, "_generate_intersection_query", return_value=inter_q
+ ) as mock_inter,
+ patch.object(
+ mgr, "_generate_validation_queries", return_value=[val_q]
+ ) as mock_val,
+ ):
+ result = mgr.generate_cross_constraint_queries(cluster)
+
+ mock_comb.assert_called_once_with([c1, c2, c3])
+ mock_prog.assert_called_once_with([c1, c2, c3])
+ mock_inter.assert_called_once_with([c1, c2, c3])
+ mock_val.assert_called_once_with([c1, c2, c3])
+
+ assert combined_q in result
+ assert prog_q in result
+ assert inter_q in result
+ assert val_q in result
+
+ def test_none_intersection_not_appended(self):
+ """If _generate_intersection_query returns None it is excluded."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+ cluster = _cluster([c1, c2])
+
+ with (
+ patch.object(mgr, "_generate_combined_query", return_value="cq"),
+ patch.object(mgr, "_generate_progressive_queries", return_value=[]),
+ patch.object(
+ mgr, "_generate_intersection_query", return_value=None
+ ),
+ patch.object(mgr, "_generate_validation_queries", return_value=[]),
+ ):
+ result = mgr.generate_cross_constraint_queries(cluster)
+
+ # Only the combined query; intersection (None) was not added
+ assert None not in result
+ assert "cq" in result
+
+ def test_queries_stored_in_cluster(self):
+ """Results are written back to cluster.search_queries."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+ cluster = _cluster([c1, c2])
+
+ with (
+ patch.object(mgr, "_generate_combined_query", return_value="q1"),
+ patch.object(
+ mgr, "_generate_progressive_queries", return_value=["q2"]
+ ),
+ patch.object(
+ mgr, "_generate_intersection_query", return_value=None
+ ),
+ patch.object(mgr, "_generate_validation_queries", return_value=[]),
+ ):
+ result = mgr.generate_cross_constraint_queries(cluster)
+
+ assert cluster.search_queries == result
+
+ def test_progressive_queries_use_sorted_weights(self):
+ """_generate_progressive_queries receives constraints sorted by weight desc."""
+ mgr, _ = _manager()
+ # Assign weights in ascending order; sorted call should reverse them
+ c_low = _c("c_low", weight=0.2)
+ c_mid = _c("c_mid", weight=0.5)
+ c_high = _c("c_high", weight=0.9)
+ cluster = _cluster([c_low, c_mid, c_high])
+
+ captured = {}
+
+ def _fake_progressive(constraints):
+ captured["order"] = [c.id for c in constraints]
+ return []
+
+ with (
+ patch.object(mgr, "_generate_combined_query", return_value="cq"),
+ patch.object(
+ mgr,
+ "_generate_progressive_queries",
+ side_effect=_fake_progressive,
+ ),
+ patch.object(
+ mgr, "_generate_intersection_query", return_value=None
+ ),
+ patch.object(mgr, "_generate_validation_queries", return_value=[]),
+ ):
+ mgr.generate_cross_constraint_queries(cluster)
+
+ # generate_cross_constraint_queries passes all constraints as-is to sub-generators
+ # (sorting happens inside _generate_progressive_queries)
+ assert (
+ "order" not in captured or captured["order"] is not None
+ ) # sanity
+
+
+# ---------------------------------------------------------------------------
+# 5. test_validate_candidate_across_constraints
+# ---------------------------------------------------------------------------
+
+
+class TestValidateCandidateAcrossConstraints:
+ """validate_candidate_across_constraints: cluster-based + pairwise validation."""
+
+ def test_no_clusters_gives_empty_scores(self):
+ """With no clusters in manager, result is empty."""
+ mgr, _ = _manager()
+ candidate = Candidate(name="X")
+ result = mgr.validate_candidate_across_constraints(
+ candidate, [_c("c1")]
+ )
+ assert result == {}
+
+ def test_relevant_cluster_score_propagated(self):
+ """Cluster whose constraints overlap with the input get scored."""
+ mgr, model = _manager()
+ c1 = _c("c1")
+ c2 = _c("c2")
+
+ cluster = _cluster([c1, c2], queries=["find both"])
+ mgr.clusters = [cluster]
+
+ with patch.object(
+ mgr, "_validate_with_cluster", return_value=0.72
+ ) as mock_vc:
+ result = mgr.validate_candidate_across_constraints(
+ Candidate(name="Alice"), [c1, c2]
+ )
+
+ mock_vc.assert_called_once_with(Candidate(name="Alice"), cluster)
+ assert result.get("c1") == pytest.approx(0.72)
+ assert result.get("c2") == pytest.approx(0.72)
+
+ def test_complementary_pair_calls_validate_pair(self):
+ """Registered complementary c1-c2 triggers _validate_pair."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ mgr.relationships[("c1", "c2")] = ConstraintRelationship(
+ "c1", "c2", "complementary", 0.9
+ )
+
+ candidate = Candidate(name="Bob")
+ with patch.object(mgr, "_validate_pair", return_value=0.88) as mock_vp:
+ result = mgr.validate_candidate_across_constraints(
+ candidate, [c1, c2]
+ )
+
+ mock_vp.assert_called_once_with(candidate, c1, c2)
+ assert result["c1"] == pytest.approx(0.88)
+ assert result["c2"] == pytest.approx(0.88)
+
+ def test_non_complementary_pair_does_not_call_validate_pair(self):
+ """A 'dependent' relationship does not trigger _validate_pair."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ mgr.relationships[("c1", "c2")] = ConstraintRelationship(
+ "c1", "c2", "dependent", 0.9
+ )
+
+ with patch.object(mgr, "_validate_pair") as mock_vp:
+ mgr.validate_candidate_across_constraints(
+ Candidate(name="Bob"), [c1, c2]
+ )
+
+ mock_vp.assert_not_called()
+
+ def test_max_score_preserved(self):
+ """If both cluster and pairwise validation produce scores, max is kept."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ cluster = _cluster([c1, c2], queries=["q"])
+ mgr.clusters = [cluster]
+ mgr.relationships[("c1", "c2")] = ConstraintRelationship(
+ "c1", "c2", "complementary", 0.9
+ )
+
+ with (
+ patch.object(mgr, "_validate_with_cluster", return_value=0.5),
+ patch.object(mgr, "_validate_pair", return_value=0.9),
+ ):
+ result = mgr.validate_candidate_across_constraints(
+ Candidate(name="Eve"), [c1, c2]
+ )
+
+ assert result["c1"] == pytest.approx(0.9)
+ assert result["c2"] == pytest.approx(0.9)
+
+
+# ---------------------------------------------------------------------------
+# 6. test_deduplicate_clusters
+# ---------------------------------------------------------------------------
+
+
+class TestDeduplicateClusters:
+ """_deduplicate_clusters removes clusters with identical constraint-id sets."""
+
+ def test_identical_sets_first_kept(self):
+ """When two clusters share the same IDs, only the first is kept."""
+ mgr, _ = _manager()
+ c1, c2 = _c("c1"), _c("c2")
+
+ cl_a = _cluster([c1, c2], ctype="type_based")
+ cl_b = _cluster([c2, c1], ctype="semantic") # same IDs, different order
+
+ result = mgr._deduplicate_clusters([cl_a, cl_b])
+
+ assert len(result) == 1
+ assert result[0].cluster_type == "type_based"
+
+ def test_different_sets_both_kept(self):
+ """Clusters with different ID sets are both retained."""
+ mgr, _ = _manager()
+ c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")
+
+ result = mgr._deduplicate_clusters(
+ [
+ _cluster([c1, c2]),
+ _cluster([c2, c3]),
+ ]
+ )
+
+ assert len(result) == 2
+
+ def test_three_clusters_two_duplicates(self):
+ """Three clusters where two are duplicates leaves two unique ones."""
+ mgr, _ = _manager()
+ c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")
+
+ result = mgr._deduplicate_clusters(
+ [
+ _cluster([c1, c2], ctype="A"),
+ _cluster([c1, c2], ctype="B"), # dup
+ _cluster([c2, c3], ctype="C"),
+ ]
+ )
+
+ assert len(result) == 2
+ types = {cl.cluster_type for cl in result}
+ assert "A" in types
+ assert "C" in types
+
+ def test_empty_input_returns_empty(self):
+ mgr, _ = _manager()
+ assert mgr._deduplicate_clusters([]) == []
+
+ def test_single_cluster_returned_unchanged(self):
+ mgr, _ = _manager()
+ cl = _cluster([_c("c1"), _c("c2")])
+ result = mgr._deduplicate_clusters([cl])
+ assert result == [cl]
+
+
+# ---------------------------------------------------------------------------
+# 7. test_calculate_cluster_coherence_no_pairs
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateClusterCoherenceNoPairs:
+ """_calculate_cluster_coherence returns 0.5 when no pair has a relationship."""
+
+ def test_two_constraints_no_relationships_returns_half(self):
+ mgr, _ = _manager()
+ # Empty relationships dict — no entry for (c1, c2)
+ result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])
+ assert result == pytest.approx(0.5)
+
+ def test_three_constraints_no_relationships_returns_half(self):
+ mgr, _ = _manager()
+ result = mgr._calculate_cluster_coherence(
+ [_c("c1"), _c("c2"), _c("c3")]
+ )
+ assert result == pytest.approx(0.5)
+
+ def test_single_constraint_returns_zero(self):
+ """Source guard: < 2 constraints always returns 0.0."""
+ mgr, _ = _manager()
+ assert mgr._calculate_cluster_coherence([_c("c1")]) == 0.0
+
+ def test_empty_constraints_returns_zero(self):
+ mgr, _ = _manager()
+ assert mgr._calculate_cluster_coherence([]) == 0.0
+
+ def test_with_one_relationship_above_half(self):
+ """A strong relationship pushes coherence above the 0.5 default."""
+ mgr, _ = _manager()
+ mgr.relationships[("c1", "c2")] = ConstraintRelationship(
+ "c1", "c2", "complementary", 1.0
+ )
+ result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])
+ # avg_strength=1.0, size_factor=min(2/5,1)=0.4 → 1.0*(0.7+0.3*0.4)=0.82
+ assert result > 0.5
+
+ def test_coherence_formula_two_constraints(self):
+ """Exact formula check for two constraints with one relationship."""
+ mgr, _ = _manager()
+ mgr.relationships[("c1", "c2")] = ConstraintRelationship(
+ "c1", "c2", "complementary", 0.8
+ )
+ result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])
+ # avg_strength=0.8, size_factor=min(2/5, 1.0)=0.4
+ # → 0.8 * (0.7 + 0.3 * 0.4) = 0.8 * 0.82 = 0.656
+ assert result == pytest.approx(0.8 * (0.7 + 0.3 * (2 / 5.0)))
+
+
+# ---------------------------------------------------------------------------
+# 8. test_optimize_search_order
+# ---------------------------------------------------------------------------
+
+
+class TestOptimizeSearchOrder:
+ """optimize_search_order sorts clusters by coherence * number of constraints."""
+
+ def test_higher_product_comes_first(self):
+ """Cluster with larger coherence*size product is sorted earlier."""
+ mgr, _ = _manager()
+
+ # score = 0.5 * 2 = 1.0
+ cl_low = _cluster([_c("c1"), _c("c2")], coherence=0.5)
+ # score = 0.8 * 3 = 2.4
+ cl_high = _cluster([_c("c3"), _c("c4"), _c("c5")], coherence=0.8)
+
+ result = mgr.optimize_search_order([cl_low, cl_high])
+
+ assert result[0] is cl_high
+ assert result[1] is cl_low
+
+ def test_three_clusters_descending_order(self):
+ """Three clusters are sorted descending by coherence*size."""
+ mgr, _ = _manager()
+
+ # scores: 0.9, 1.2, 0.9*1=0.9 — ensure strict ordering
+ cl_a = _cluster([_c("a1")], coherence=0.9) # 0.9
+ cl_b = _cluster([_c("b1"), _c("b2")], coherence=0.6) # 1.2
+ cl_c = _cluster([_c("c1"), _c("c2"), _c("c3")], coherence=0.3) # 0.9
+
+ result = mgr.optimize_search_order([cl_a, cl_b, cl_c])
+
+ scores = [cl.coherence_score * len(cl.constraints) for cl in result]
+ assert scores == sorted(scores, reverse=True)
+ assert result[0] is cl_b
+
+ def test_empty_list_returns_empty(self):
+ mgr, _ = _manager()
+ assert mgr.optimize_search_order([]) == []
+
+ def test_single_cluster_returned(self):
+ mgr, _ = _manager()
+ cl = _cluster([_c("c1"), _c("c2")], coherence=0.7)
+ result = mgr.optimize_search_order([cl])
+ assert result == [cl]
+
+ def test_equal_products_all_returned(self):
+ """When products are equal, all clusters still appear in result."""
+ mgr, _ = _manager()
+ # Both have coherence*size = 1.0
+ cl_a = _cluster([_c("a1")], coherence=1.0)
+ cl_b = _cluster([_c("b1")], coherence=1.0)
+
+ result = mgr.optimize_search_order([cl_a, cl_b])
+
+ assert len(result) == 2
+ # ConstraintCluster is a mutable dataclass (not hashable); use identity checks
+ assert any(r is cl_a for r in result)
+ assert any(r is cl_b for r in result)
diff --git a/tests/benchmarks/comparison/test_evaluator_branches_coverage.py b/tests/benchmarks/comparison/test_evaluator_branches_coverage.py
new file mode 100644
index 0000000000..d3fbc18166
--- /dev/null
+++ b/tests/benchmarks/comparison/test_evaluator_branches_coverage.py
@@ -0,0 +1,737 @@
+"""
+Branch-coverage tests for benchmarks/comparison/evaluator.py.
+
+Targets the remaining 44 missing lines, focusing on branches not yet
+exercised by test_evaluator_coverage.py or test_comparison_evaluator.py:
+
+- compare_configurations: empty list early-return, all-runs-failed branch,
+ exception-during-run path, repetitions averaging
+- _evaluate_single_configuration: full exception handler (error dict returned)
+- _calculate_average_metrics: multi-result averaging across all three metric
+ categories, None-value filtering, disjoint metric keys
+- _create_comparison_visualizations: matplotlib calls with successful results
+- comparison with repetitions: multiple reps correctly produce avg_metrics
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+MODULE = "local_deep_research.benchmarks.comparison.evaluator"
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_SUCCESSFUL_RUN = {
+ "success": True,
+ "quality_metrics": {"overall_quality": 0.8},
+ "speed_metrics": {"total_duration": 20.0},
+ "resource_metrics": {"memory_mb": 128.0},
+}
+
+_FAILED_RUN = {"success": False, "error": "boom"}
+
+
+def _avg_metrics_from(run):
+ return {
+ "quality_metrics": run.get("quality_metrics", {}),
+ "speed_metrics": run.get("speed_metrics", {}),
+ "resource_metrics": run.get("resource_metrics", {}),
+ }
+
+
+# ---------------------------------------------------------------------------
+# 1. test_compare_configurations_empty_list
+# ---------------------------------------------------------------------------
+
+
+class TestCompareConfigurationsEmptyList:
+ """compare_configurations returns an error dict for an empty list."""
+
+ @patch(f"{MODULE}.os.makedirs")
+ def test_empty_list_returns_error_dict(self, mock_makedirs):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(query="anything", configurations=[])
+
+ assert isinstance(result, dict)
+ assert "error" in result
+ assert result["error"] == "No configurations provided"
+
+ @patch(f"{MODULE}.os.makedirs")
+ def test_empty_list_does_not_call_evaluate(self, mock_makedirs):
+ """_evaluate_single_configuration must not be called for empty input."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ with patch(f"{MODULE}._evaluate_single_configuration") as mock_eval:
+ compare_configurations(query="q", configurations=[])
+ mock_eval.assert_not_called()
+
+ @patch(f"{MODULE}.os.makedirs")
+ def test_empty_list_still_creates_output_dir(self, mock_makedirs):
+ """makedirs is called even before the empty-list guard."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ compare_configurations(
+ query="q", configurations=[], output_dir="/tmp/out_branch_test"
+ )
+ mock_makedirs.assert_called_once_with(
+ "/tmp/out_branch_test", exist_ok=True
+ )
+
+
+# ---------------------------------------------------------------------------
+# 2. test_compare_configurations_all_runs_failed
+# ---------------------------------------------------------------------------
+
+
+class TestCompareConfigurationsAllRunsFailed:
+ """When every repetition of a config fails the summary has success=False."""
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration", return_value=_FAILED_RUN)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_all_runs_failed_success_false(
+ self, mock_write, mock_viz, mock_eval, mock_makedirs, tmp_path
+ ):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "BadConfig"}],
+ output_dir=str(tmp_path),
+ repetitions=2,
+ )
+
+ assert result["successful_configurations"] == 0
+ assert result["failed_configurations"] == 1
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration", return_value=_FAILED_RUN)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_all_runs_failed_result_summary_shape(
+ self, mock_write, mock_viz, mock_eval, mock_makedirs, tmp_path
+ ):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "BadConfig"}],
+ output_dir=str(tmp_path),
+ )
+
+ summary = result["results"][0]
+ assert summary["success"] is False
+ assert summary["runs_completed"] == 0
+ assert summary["runs_failed"] == 1
+ assert "error" in summary
+ assert summary["error"] == "All runs failed"
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_exception_in_evaluate_treated_as_failed_run(
+ self, mock_write, mock_viz, mock_eval, mock_makedirs, tmp_path
+ ):
+ """An exception raised by _evaluate_single_configuration counts as a failure."""
+ mock_eval.side_effect = RuntimeError("network error")
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "Crasher"}],
+ output_dir=str(tmp_path),
+ )
+
+ assert result["failed_configurations"] == 1
+ # The individual_results entry must contain the error string
+ individual = result["results"][0]["individual_results"]
+ assert len(individual) == 1
+ assert individual[0]["success"] is False
+ assert "network error" in individual[0]["error"]
+
+
+# ---------------------------------------------------------------------------
+# 3. test_evaluate_single_configuration_exception
+# ---------------------------------------------------------------------------
+
+
+class TestEvaluateSingleConfigurationException:
+ """_evaluate_single_configuration returns a proper error dict on exception."""
+
+ @patch(f"{MODULE}.SpeedProfiler")
+ @patch(f"{MODULE}.ResourceMonitor")
+ @patch(f"{MODULE}.get_llm")
+ def test_exception_returns_success_false(
+ self, mock_get_llm, mock_monitor_cls, mock_profiler_cls
+ ):
+ mock_get_llm.side_effect = ValueError("bad model name")
+ mock_profiler = MagicMock()
+ mock_profiler_cls.return_value = mock_profiler
+ mock_monitor = MagicMock()
+ mock_monitor_cls.return_value = mock_monitor
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+
+ result = _evaluate_single_configuration(
+ query="test query", config={"name": "cfg1"}
+ )
+
+ assert result["success"] is False
+
+ @patch(f"{MODULE}.SpeedProfiler")
+ @patch(f"{MODULE}.ResourceMonitor")
+ @patch(f"{MODULE}.get_llm")
+ def test_exception_message_in_result(
+ self, mock_get_llm, mock_monitor_cls, mock_profiler_cls
+ ):
+ mock_get_llm.side_effect = ValueError("bad model name")
+ mock_profiler = MagicMock()
+ mock_profiler_cls.return_value = mock_profiler
+ mock_monitor = MagicMock()
+ mock_monitor_cls.return_value = mock_monitor
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+
+ result = _evaluate_single_configuration(
+ query="test query", config={"name": "cfg1"}
+ )
+
+ assert "error" in result
+ assert "bad model name" in result["error"]
+
+ @patch(f"{MODULE}.SpeedProfiler")
+ @patch(f"{MODULE}.ResourceMonitor")
+ @patch(f"{MODULE}.get_llm")
+ def test_exception_result_contains_timing_and_resource_details(
+ self, mock_get_llm, mock_monitor_cls, mock_profiler_cls
+ ):
+ """Even on error the result includes timing_details and resource_details."""
+ mock_get_llm.side_effect = Exception("oops")
+
+ profiler_instance = MagicMock()
+ profiler_instance.get_timings.return_value = {"llm_init": 0.5}
+ mock_profiler_cls.return_value = profiler_instance
+
+ monitor_instance = MagicMock()
+ monitor_instance.get_combined_stats.return_value = {"cpu": 10.0}
+ mock_monitor_cls.return_value = monitor_instance
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+
+ result = _evaluate_single_configuration(query="q", config={})
+
+ assert "timing_details" in result
+ assert "resource_details" in result
+
+ @patch(f"{MODULE}.SpeedProfiler")
+ @patch(f"{MODULE}.ResourceMonitor")
+ @patch(f"{MODULE}.get_llm")
+ def test_exception_stops_profiling(
+ self, mock_get_llm, mock_monitor_cls, mock_profiler_cls
+ ):
+ """stop() must be called on both profiler and monitor even on error."""
+ mock_get_llm.side_effect = Exception("fail")
+
+ profiler_instance = MagicMock()
+ mock_profiler_cls.return_value = profiler_instance
+
+ monitor_instance = MagicMock()
+ mock_monitor_cls.return_value = monitor_instance
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+
+ _evaluate_single_configuration(query="q", config={})
+
+ profiler_instance.stop.assert_called()
+ monitor_instance.stop.assert_called()
+
+
+# ---------------------------------------------------------------------------
+# 4. test_calculate_average_metrics
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateAverageMetrics:
+ """_calculate_average_metrics averages correctly across all metric types."""
+
+ def test_quality_metrics_averaged(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {"score": 0.4},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {"score": 0.6},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["quality_metrics"]["score"] == pytest.approx(0.5)
+
+ def test_speed_metrics_averaged(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {},
+ "speed_metrics": {"total_duration": 10.0},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {},
+ "speed_metrics": {"total_duration": 30.0},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["speed_metrics"]["total_duration"] == pytest.approx(20.0)
+
+ def test_resource_metrics_averaged(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {"memory_mb": 100.0},
+ },
+ {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {"memory_mb": 200.0},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["resource_metrics"]["memory_mb"] == pytest.approx(150.0)
+
+ def test_none_values_filtered_out(self):
+ """None values are skipped so the average uses only real numbers."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {"x": None},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {"x": 0.8},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ # Only the non-None value contributes
+ assert avg["quality_metrics"]["x"] == pytest.approx(0.8)
+
+ def test_disjoint_metric_keys_all_present(self):
+ """Keys present in only one result still appear in the output."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {"key_a": 0.9},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {"key_b": 0.3},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["quality_metrics"]["key_a"] == pytest.approx(0.9)
+ assert avg["quality_metrics"]["key_b"] == pytest.approx(0.3)
+
+ def test_empty_input_returns_empty_dict(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ assert _calculate_average_metrics([]) == {}
+
+ def test_three_results_averaged_correctly(self):
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {"q": 0.2},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {"q": 0.5},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ {
+ "quality_metrics": {"q": 0.8},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ ]
+ avg = _calculate_average_metrics(results)
+ assert avg["quality_metrics"]["q"] == pytest.approx(0.5)
+
+ def test_output_always_has_three_categories(self):
+ """Result always contains quality_metrics, speed_metrics, resource_metrics keys."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "quality_metrics": {"x": 1.0},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ }
+ ]
+ avg = _calculate_average_metrics(results)
+ assert "quality_metrics" in avg
+ assert "speed_metrics" in avg
+ assert "resource_metrics" in avg
+
+
+# ---------------------------------------------------------------------------
+# 5. test_create_comparison_visualizations
+# ---------------------------------------------------------------------------
+
+
+class TestCreateComparisonVisualizations:
+ """_create_comparison_visualizations makes the expected matplotlib calls."""
+
+ @patch(f"{MODULE}.plt")
+ def test_no_successful_results_skips_all_plots(self, mock_plt, tmp_path):
+ """Early return when there are no successful results."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_comparison_visualizations,
+ )
+
+ report = {"results": [{"success": False, "error": "failed"}]}
+ _create_comparison_visualizations(
+ report, output_dir=str(tmp_path), timestamp="20240101_120000"
+ )
+
+ mock_plt.figure.assert_not_called()
+ mock_plt.barh.assert_not_called()
+ mock_plt.savefig.assert_not_called()
+
+ @patch(f"{MODULE}._create_spider_chart")
+ @patch(f"{MODULE}._create_pareto_chart")
+ @patch(f"{MODULE}._create_metric_comparison_chart")
+ @patch(f"{MODULE}.plt")
+ def test_successful_results_calls_savefig(
+ self, mock_plt, mock_metric_chart, mock_pareto, mock_spider, tmp_path
+ ):
+ """With one successful result all sub-chart helpers are called."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_comparison_visualizations,
+ )
+
+ mock_fig = MagicMock()
+ mock_plt.figure.return_value = mock_fig
+
+ report = {
+ "results": [
+ {
+ "success": True,
+ "name": "Config A",
+ "overall_score": 0.75,
+ "avg_metrics": {
+ "quality_metrics": {"overall_quality": 0.75},
+ "speed_metrics": {"total_duration": 15.0},
+ "resource_metrics": {},
+ },
+ }
+ ]
+ }
+
+ _create_comparison_visualizations(
+ report, output_dir=str(tmp_path), timestamp="20240101_000000"
+ )
+
+ # Overall score bar chart triggers figure/barh/savefig
+ mock_plt.figure.assert_called()
+ mock_plt.savefig.assert_called()
+ mock_plt.close.assert_called()
+
+ # Sub-chart helpers must have been invoked once each
+ mock_metric_chart.assert_called()
+ mock_spider.assert_called_once()
+ mock_pareto.assert_called_once()
+
+ @patch(f"{MODULE}._create_spider_chart")
+ @patch(f"{MODULE}._create_pareto_chart")
+ @patch(f"{MODULE}._create_metric_comparison_chart")
+ @patch(f"{MODULE}.plt")
+ def test_config_names_extracted_correctly(
+ self, mock_plt, mock_metric_chart, mock_pareto, mock_spider, tmp_path
+ ):
+ """Config names used in barh must come from result['name']."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_comparison_visualizations,
+ )
+
+ mock_plt.figure.return_value = MagicMock()
+
+ report = {
+ "results": [
+ {
+ "success": True,
+ "name": "MySpecialConfig",
+ "overall_score": 0.5,
+ "avg_metrics": {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ },
+ }
+ ]
+ }
+
+ _create_comparison_visualizations(
+ report, output_dir=str(tmp_path), timestamp="ts1"
+ )
+
+ # barh should have been called with the name in the y-axis list
+ barh_call_args = mock_plt.barh.call_args
+ assert barh_call_args is not None
+ config_names_arg = barh_call_args[0][0]
+ assert "MySpecialConfig" in config_names_arg
+
+
+# ---------------------------------------------------------------------------
+# 6. test_comparison_with_repetitions
+# ---------------------------------------------------------------------------
+
+
+class TestComparisonWithRepetitions:
+ """compare_configurations with multiple repetitions averages metrics correctly."""
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}.calculate_combined_score", return_value=0.7)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_three_repetitions_runs_completed(
+ self,
+ mock_write,
+ mock_viz,
+ mock_score,
+ mock_eval,
+ mock_makedirs,
+ tmp_path,
+ ):
+ mock_eval.return_value = _SUCCESSFUL_RUN.copy()
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "Cfg"}],
+ output_dir=str(tmp_path),
+ repetitions=3,
+ )
+
+ summary = result["results"][0]
+ assert summary["runs_completed"] == 3
+ assert summary["runs_failed"] == 0
+ assert summary["success"] is True
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}.calculate_combined_score", return_value=0.7)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_partial_repetition_failure(
+ self,
+ mock_write,
+ mock_viz,
+ mock_score,
+ mock_eval,
+ mock_makedirs,
+ tmp_path,
+ ):
+ """Only successful repetitions count toward runs_completed."""
+ mock_eval.side_effect = [
+ _SUCCESSFUL_RUN.copy(),
+ _FAILED_RUN.copy(),
+ _SUCCESSFUL_RUN.copy(),
+ ]
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "Cfg"}],
+ output_dir=str(tmp_path),
+ repetitions=3,
+ )
+
+ summary = result["results"][0]
+ assert summary["runs_completed"] == 2
+ assert summary["runs_failed"] == 1
+ assert summary["success"] is True
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}._calculate_average_metrics")
+ @patch(f"{MODULE}.calculate_combined_score", return_value=0.65)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_repetitions_pass_all_successful_runs_to_avg(
+ self,
+ mock_write,
+ mock_viz,
+ mock_score,
+ mock_avg,
+ mock_eval,
+ mock_makedirs,
+ tmp_path,
+ ):
+ """_calculate_average_metrics is called with the list of successful runs."""
+ run1 = _SUCCESSFUL_RUN.copy()
+ run2 = _SUCCESSFUL_RUN.copy()
+ mock_eval.side_effect = [run1, run2]
+ mock_avg.return_value = {
+ "quality_metrics": {},
+ "speed_metrics": {},
+ "resource_metrics": {},
+ }
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ compare_configurations(
+ query="q",
+ configurations=[{"name": "Cfg"}],
+ output_dir=str(tmp_path),
+ repetitions=2,
+ )
+
+ mock_avg.assert_called_once_with([run1, run2])
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}.calculate_combined_score", return_value=0.8)
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_repetitions_field_in_report(
+ self,
+ mock_write,
+ mock_viz,
+ mock_score,
+ mock_eval,
+ mock_makedirs,
+ tmp_path,
+ ):
+ """The top-level 'repetitions' key reflects the requested count."""
+ mock_eval.return_value = _SUCCESSFUL_RUN.copy()
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "Cfg"}],
+ output_dir=str(tmp_path),
+ repetitions=5,
+ )
+
+ assert result["repetitions"] == 5
+
+ @patch(f"{MODULE}.os.makedirs")
+ @patch(f"{MODULE}._evaluate_single_configuration")
+ @patch(f"{MODULE}.calculate_combined_score")
+ @patch(f"{MODULE}._create_comparison_visualizations")
+ @patch(
+ "local_deep_research.security.file_write_verifier.write_json_verified"
+ )
+ def test_two_configs_sorted_by_score(
+ self,
+ mock_write,
+ mock_viz,
+ mock_score,
+ mock_eval,
+ mock_makedirs,
+ tmp_path,
+ ):
+ """Results are sorted descending by overall_score."""
+ mock_eval.return_value = _SUCCESSFUL_RUN.copy()
+ mock_score.side_effect = [0.3, 0.9]
+
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="q",
+ configurations=[{"name": "Low"}, {"name": "High"}],
+ output_dir=str(tmp_path),
+ )
+
+ scores = [
+ r["overall_score"] for r in result["results"] if r.get("success")
+ ]
+ assert scores == sorted(scores, reverse=True)