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 186 high-value tests across 10 files (#2403)

LearningCircuit2ae15b201e27
diff --git a/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py b/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py
new file mode 100644
index 0000000000..7973c05d9a
--- /dev/null
+++ b/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py
@@ -0,0 +1,401 @@
+"""
+Tests for ConstraintChecker.check_candidate orchestration logic.
+
+Existing tests only cover a mock ConcreteConstraintChecker, not the real
+ConstraintChecker with its no-evidence fallback, rejection override, and
+weighted average calculation.
+
+Source: src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.advanced_search_system.constraint_checking.constraint_checker import (
+ ConstraintChecker,
+ ConstraintCheckResult,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_constraint(value="test_constraint", weight=1.0, type_val="hard"):
+ """Create a mock Constraint."""
+ c = Mock()
+ c.value = value
+ c.weight = weight
+ c.type = Mock()
+ c.type.value = type_val
+ return c
+
+
+def _make_candidate(name="test_candidate"):
+ """Create a mock Candidate."""
+ c = Mock()
+ c.name = name
+ return c
+
+
+def _make_dual_evidence(positive=0.8, negative=0.1, uncertainty=0.1):
+ """Create a mock DualConfidenceEvidence result."""
+ e = Mock()
+ e.positive_confidence = positive
+ e.negative_confidence = negative
+ e.uncertainty = uncertainty
+ return e
+
+
+# ---------------------------------------------------------------------------
+# No-evidence fallback
+# ---------------------------------------------------------------------------
+
+
+class TestNoEvidenceFallback:
+ """When no evidence is found, score = 0.5 - uncertainty_penalty."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_default_uncertainty_penalty(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """Default penalty 0.2: score = 0.5 - 0.2 = 0.3."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
+
+ candidate = _make_candidate()
+ constraint = _make_constraint(weight=1.0)
+
+ result = checker.check_candidate(candidate, [constraint])
+
+ assert result.constraint_scores["test_constraint"][
+ "total"
+ ] == pytest.approx(0.3)
+ assert result.constraint_scores["test_constraint"]["positive"] == 0.0
+ assert result.constraint_scores["test_constraint"]["negative"] == 0.0
+ assert result.constraint_scores["test_constraint"]["uncertainty"] == 1.0
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_custom_uncertainty_penalty(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """Custom penalty 0.4: score = 0.5 - 0.4 = 0.1."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(
+ model,
+ evidence_gatherer=lambda c, con: [],
+ uncertainty_penalty=0.4,
+ )
+
+ candidate = _make_candidate()
+ constraint = _make_constraint(weight=1.0)
+
+ result = checker.check_candidate(candidate, [constraint])
+
+ assert result.constraint_scores["test_constraint"][
+ "total"
+ ] == pytest.approx(0.1)
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_multiple_no_evidence_weighted_average(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """Multiple no-evidence constraints: weighted average of fallback scores."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(
+ model,
+ evidence_gatherer=lambda c, con: [],
+ uncertainty_penalty=0.2,
+ )
+
+ candidate = _make_candidate()
+ c1 = _make_constraint("c1", weight=1.0)
+ c2 = _make_constraint("c2", weight=2.0)
+
+ result = checker.check_candidate(candidate, [c1, c2])
+
+ # Both have score 0.3, weights 1.0 and 2.0
+ # Weighted avg = (0.3*1 + 0.3*2) / 3 = 0.3
+ assert result.total_score == pytest.approx(0.3)
+
+
+# ---------------------------------------------------------------------------
+# Evidence gatherer
+# ---------------------------------------------------------------------------
+
+
+class TestEvidenceGatherer:
+ """Evidence gatherer is called correctly."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_called_once_per_constraint(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """Evidence gatherer is called once per constraint."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ mock_analyzer = Mock()
+ mock_analyzer.analyze_evidence_dual_confidence.return_value = (
+ _make_dual_evidence()
+ )
+ mock_analyzer.evaluate_evidence_list.return_value = 0.8
+ mock_analyzer_cls.return_value = mock_analyzer
+
+ gatherer = Mock(return_value=[{"text": "evidence"}])
+ model = Mock()
+ checker = ConstraintChecker(model, evidence_gatherer=gatherer)
+
+ candidate = _make_candidate()
+ c1 = _make_constraint("c1")
+ c2 = _make_constraint("c2")
+
+ checker.check_candidate(candidate, [c1, c2])
+
+ assert gatherer.call_count == 2
+ gatherer.assert_any_call(candidate, c1)
+ gatherer.assert_any_call(candidate, c2)
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_no_gatherer_returns_empty(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """No evidence gatherer provided returns empty evidence."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(model) # No gatherer
+
+ candidate = _make_candidate()
+ constraint = _make_constraint()
+
+ result = checker.check_candidate(candidate, [constraint])
+
+ # No evidence -> fallback score
+ assert result.constraint_scores["test_constraint"]["uncertainty"] == 1.0
+
+
+# ---------------------------------------------------------------------------
+# Rejection override
+# ---------------------------------------------------------------------------
+
+
+class TestRejectionOverride:
+ """Rejection sets total_score to 0.0."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_rejection_sets_score_zero(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """When rejection_result.should_reject=True, total_score=0.0."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=True
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ mock_analyzer = Mock()
+ mock_analyzer.analyze_evidence_dual_confidence.return_value = (
+ _make_dual_evidence(0.9, 0.0, 0.1)
+ )
+ mock_analyzer.evaluate_evidence_list.return_value = 0.9
+ mock_analyzer_cls.return_value = mock_analyzer
+
+ model = Mock()
+ checker = ConstraintChecker(
+ model,
+ evidence_gatherer=lambda c, con: [{"text": "strong evidence"}],
+ )
+
+ candidate = _make_candidate()
+ constraint = _make_constraint(weight=1.0)
+
+ result = checker.check_candidate(candidate, [constraint])
+
+ assert result.total_score == 0.0
+ assert result.rejection_result.should_reject is True
+
+
+# ---------------------------------------------------------------------------
+# Weighted average calculation
+# ---------------------------------------------------------------------------
+
+
+class TestWeightedAverage:
+ """Non-rejection weighted average score calculation."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_weighted_average_calculation(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """(0.8*1.0 + 0.4*2.0) / (1.0+2.0) = 0.533."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ mock_analyzer = Mock()
+ call_count = [0]
+
+ def side_effect_eval(evidence_list, constraint, penalty, neg_weight):
+ call_count[0] += 1
+ return 0.8 if call_count[0] == 1 else 0.4
+
+ mock_analyzer.analyze_evidence_dual_confidence.return_value = (
+ _make_dual_evidence()
+ )
+ mock_analyzer.evaluate_evidence_list.side_effect = side_effect_eval
+ mock_analyzer_cls.return_value = mock_analyzer
+
+ model = Mock()
+ checker = ConstraintChecker(
+ model,
+ evidence_gatherer=lambda c, con: [{"text": "evidence"}],
+ )
+
+ candidate = _make_candidate()
+ c1 = _make_constraint("c1", weight=1.0)
+ c2 = _make_constraint("c2", weight=2.0)
+
+ result = checker.check_candidate(candidate, [c1, c2])
+
+ expected = (0.8 * 1.0 + 0.4 * 2.0) / (1.0 + 2.0)
+ assert result.total_score == pytest.approx(expected, abs=0.01)
+
+
+# ---------------------------------------------------------------------------
+# Empty constraints
+# ---------------------------------------------------------------------------
+
+
+class TestEmptyConstraints:
+ """Empty constraints list produces total_score = 0.0."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_empty_constraints_score_zero(
+ self, mock_rejection_cls, mock_analyzer_cls
+ ):
+ """No constraints -> total_score = 0.0."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
+
+ candidate = _make_candidate()
+
+ result = checker.check_candidate(candidate, [])
+
+ assert result.total_score == 0.0
+ assert result.constraint_scores == {}
+ assert result.detailed_results == []
+
+
+# ---------------------------------------------------------------------------
+# Result structure
+# ---------------------------------------------------------------------------
+
+
+class TestResultStructure:
+ """ConstraintCheckResult has correct fields."""
+
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
+ )
+ @patch(
+ "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
+ )
+ def test_result_fields(self, mock_rejection_cls, mock_analyzer_cls):
+ """Result has candidate, total_score, constraint_scores, detailed_results."""
+ mock_rejection = Mock()
+ mock_rejection.check_all_constraints.return_value = Mock(
+ should_reject=False
+ )
+ mock_rejection_cls.return_value = mock_rejection
+
+ model = Mock()
+ checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
+
+ candidate = _make_candidate("my_candidate")
+ constraint = _make_constraint("my_constraint", weight=1.0)
+
+ result = checker.check_candidate(candidate, [constraint])
+
+ assert isinstance(result, ConstraintCheckResult)
+ assert result.candidate is candidate
+ assert isinstance(result.total_score, float)
+ assert "my_constraint" in result.constraint_scores
+ assert len(result.detailed_results) == 1
+ assert result.detailed_results[0]["constraint"] == "my_constraint"
+ assert result.detailed_results[0]["weight"] == 1.0
diff --git a/tests/advanced_search_system/questions/test_standard_question_parsing.py b/tests/advanced_search_system/questions/test_standard_question_parsing.py
new file mode 100644
index 0000000000..f876cc2a3e
--- /dev/null
+++ b/tests/advanced_search_system/questions/test_standard_question_parsing.py
@@ -0,0 +1,204 @@
+"""
+Tests for Q:-prefix parsing in generate_questions and numbered/dash format
+parsing in generate_sub_questions.
+
+Source: src/local_deep_research/advanced_search_system/questions/standard_question.py
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.advanced_search_system.questions.standard_question import (
+ StandardQuestionGenerator,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def generator():
+ """Create StandardQuestionGenerator with a mock LLM."""
+ mock_llm = Mock()
+ gen = StandardQuestionGenerator.__new__(StandardQuestionGenerator)
+ gen.model = mock_llm
+ return gen
+
+
+# ---------------------------------------------------------------------------
+# generate_questions — Q: prefix parsing
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateQuestionsQPrefix:
+ """Test Q:-prefix parsing edge cases."""
+
+ def test_standard_q_prefix(self, generator):
+ """Standard 'Q: question' format parsed correctly."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: What is AI?\nQ: How does ML work?"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ assert result == ["What is AI?", "How does ML work?"]
+
+ def test_q_prefix_no_space_after_colon(self, generator):
+ """'Q:question' with no space after colon still works."""
+ generator.model.invoke.return_value = Mock(
+ content="Q:What is AI?\nQ:How does ML work?"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ assert result == ["What is AI?", "How does ML work?"]
+
+ def test_leading_whitespace_before_q(self, generator):
+ """' Q: question' with leading whitespace still matches."""
+ generator.model.invoke.return_value = Mock(
+ content=" Q: What is AI?\n Q: How does ML work?"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ # strip() on line then startswith("Q:") should work
+ assert len(result) == 2
+ assert result[0] == "What is AI?"
+
+ def test_q_midline_ignored(self, generator):
+ """'The Q: is not a question' — Q: mid-line should not match."""
+ generator.model.invoke.return_value = Mock(
+ content="This has Q: mid-line\nQ: Real question"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ # "This has Q: mid-line" does NOT start with "Q:" so should be skipped
+ assert len(result) == 1
+ assert result[0] == "Real question"
+
+ def test_empty_q_line_produces_empty_string(self, generator):
+ """'Q: ' (just Q: with space) produces empty string — potential bug."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: \nQ: Real question"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ assert len(result) == 2
+ # First question is empty string after replace("Q:", "").strip()
+ assert result[0] == ""
+ assert result[1] == "Real question"
+
+ def test_respects_questions_per_iteration_limit(self, generator):
+ """Only returns up to questions_per_iteration questions."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: Q1\nQ: Q2\nQ: Q3\nQ: Q4"
+ )
+ result = generator.generate_questions("knowledge", "query", 2)
+ assert len(result) == 2
+
+ def test_string_response_no_content_attr(self, generator):
+ """Response without .content attribute uses str()."""
+ generator.model.invoke.return_value = "Q: Plain string question"
+ result = generator.generate_questions("knowledge", "query", 1)
+ assert len(result) == 1
+ assert result[0] == "Plain string question"
+
+ def test_with_questions_by_iteration(self, generator):
+ """Passing questions_by_iteration changes prompt but parsing is same."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: Follow-up question"
+ )
+ result = generator.generate_questions(
+ "knowledge",
+ "query",
+ 1,
+ questions_by_iteration={1: ["Previous question"]},
+ )
+ assert result == ["Follow-up question"]
+
+
+# ---------------------------------------------------------------------------
+# generate_sub_questions — numbered/dash format parsing
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateSubQuestions:
+ """Test sub-question parsing from numbered and bulleted formats."""
+
+ def test_standard_numbered_format(self, generator):
+ """'1. question' parsed correctly using split('.', 1)."""
+ generator.model.invoke.return_value = Mock(
+ content="1. What is X?\n2. How does Y work?\n3. Why is Z important?"
+ )
+ result = generator.generate_sub_questions("complex query")
+ assert len(result) == 3
+ assert result[0] == "What is X?"
+ assert result[1] == "How does Y work?"
+
+ def test_parenthesis_format(self, generator):
+ """'1) question' format — digit is detected, split by '.' or ' '."""
+ generator.model.invoke.return_value = Mock(
+ content="1) What is X?\n2) How does Y work?"
+ )
+ result = generator.generate_sub_questions("query")
+ # '1) What is X?' — line[0].isdigit()=True, no '.' so split(' ', 1)
+ # parts = ['1)', 'What is X?'] -> parts[1] = 'What is X?'
+ assert len(result) == 2
+ assert result[0] == "What is X?"
+
+ def test_numbered_with_no_content(self, generator):
+ """'1.' with no text after dot."""
+ generator.model.invoke.return_value = Mock(
+ content="1.\n2. Real question"
+ )
+ result = generator.generate_sub_questions("query")
+ # '1.' -> split('.', 1) -> ['1', ''] -> parts[1].strip() = ''
+ # Empty string is still appended
+ assert any(q == "" for q in result) or len(result) == 1
+
+ def test_dash_format(self, generator):
+ """'- question' format parsed correctly."""
+ generator.model.invoke.return_value = Mock(
+ content="- What is X?\n- How does Y work?"
+ )
+ result = generator.generate_sub_questions("query")
+ assert len(result) == 2
+
+ def test_lines_without_digit_or_dash_skipped(self, generator):
+ """Lines not starting with digit or dash are skipped."""
+ generator.model.invoke.return_value = Mock(
+ content="Here are the sub-questions:\n1. What is X?\nNote: these are important\n2. How?"
+ )
+ result = generator.generate_sub_questions("query")
+ # Only lines starting with digit or dash are parsed
+ assert len(result) == 2
+
+ def test_max_5_sub_questions(self, generator):
+ """At most 5 sub-questions returned."""
+ generator.model.invoke.return_value = Mock(
+ content="\n".join(f"{i}. Question {i}" for i in range(1, 10))
+ )
+ result = generator.generate_sub_questions("query")
+ assert len(result) <= 5
+
+ def test_exception_returns_empty_list(self, generator):
+ """Exception during generation returns empty list."""
+ generator.model.invoke.side_effect = RuntimeError("LLM error")
+ result = generator.generate_sub_questions("query")
+ assert result == []
+
+ def test_string_response_handling(self, generator):
+ """Response without .content attribute uses str()."""
+ generator.model.invoke.return_value = (
+ "1. Sub question one\n2. Sub question two"
+ )
+ result = generator.generate_sub_questions("query")
+ assert len(result) == 2
+
+ def test_with_context(self, generator):
+ """Context parameter is passed to prompt."""
+ generator.model.invoke.return_value = Mock(
+ content="1. Question with context"
+ )
+ result = generator.generate_sub_questions(
+ "query", context="Some context"
+ )
+ assert len(result) == 1
+ # Verify context was included in the prompt
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Some context" in call_args
diff --git a/tests/citation_bugs/test_citation_regression.py b/tests/citation_bugs/test_citation_regression.py
new file mode 100644
index 0000000000..16709e2bf6
--- /dev/null
+++ b/tests/citation_bugs/test_citation_regression.py
@@ -0,0 +1,284 @@
+"""
+Citation regression tests covering:
+- Parametrized test across all 5 CitationModes
+- Multi-source DOMAIN_ID_HYPERLINKS with repeated domains
+- Export round-trip (Quarto BibTeX consistency)
+- LaTeX math-mode edge cases
+- RIS author extraction false positives
+- Quarto hardcoded year=2024
+
+Source: src/local_deep_research/text_optimization/citation_formatter.py
+"""
+
+import re
+
+import pytest
+
+from local_deep_research.text_optimization.citation_formatter import (
+ CitationFormatter,
+ CitationMode,
+ QuartoExporter,
+ RISExporter,
+ LaTeXExporter,
+)
+
+
+# ---------------------------------------------------------------------------
+# Shared test content
+# ---------------------------------------------------------------------------
+
+SAMPLE_CONTENT = """# Research Report
+
+This is about AI [1] and ML [2].
+
+## Sources
+
+[1] Introduction to Artificial Intelligence
+URL: https://arxiv.org/abs/2024.12345
+
+[2] Machine Learning Fundamentals
+URL: https://github.com/ml-project/fundamentals
+"""
+
+MULTI_DOMAIN_CONTENT = """# Report
+
+Topic A [1] and topic B [2] with extra [3].
+
+## Sources
+
+[1] First arxiv paper
+URL: https://arxiv.org/abs/2024.001
+
+[2] Second arxiv paper
+URL: https://arxiv.org/abs/2024.002
+
+[3] GitHub project
+URL: https://github.com/project/repo
+"""
+
+
+# ---------------------------------------------------------------------------
+# Parametrized test across all 5 modes
+# ---------------------------------------------------------------------------
+
+
+class TestAllCitationModes:
+ """Same document formatted across all 5 CitationModes."""
+
+ @pytest.mark.parametrize(
+ "mode,expected_fragment",
+ [
+ (CitationMode.NUMBER_HYPERLINKS, "[[1]](https://arxiv.org"),
+ (CitationMode.DOMAIN_HYPERLINKS, "[[arxiv.org]](https://arxiv.org"),
+ (CitationMode.DOMAIN_ID_HYPERLINKS, "arxiv.org"),
+ (CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS, "arxiv.org-1"),
+ (CitationMode.NO_HYPERLINKS, "[1]"),
+ ],
+ )
+ def test_mode_produces_expected_fragment(self, mode, expected_fragment):
+ """Each mode produces its characteristic citation fragment."""
+ formatter = CitationFormatter(mode)
+ result = formatter.format_document(SAMPLE_CONTENT)
+ assert expected_fragment in result
+
+ def test_no_hyperlinks_returns_content_unchanged(self):
+ """NO_HYPERLINKS mode returns content unchanged."""
+ formatter = CitationFormatter(CitationMode.NO_HYPERLINKS)
+ result = formatter.format_document(SAMPLE_CONTENT)
+ assert result == SAMPLE_CONTENT
+
+
+# ---------------------------------------------------------------------------
+# Multi-source DOMAIN_ID_HYPERLINKS
+# ---------------------------------------------------------------------------
+
+
+class TestDomainIdMultiSource:
+ """DOMAIN_ID_HYPERLINKS adds IDs only for repeated domains."""
+
+ def test_repeated_domain_gets_ids(self):
+ """Two arxiv sources get arxiv.org-1 and arxiv.org-2."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(MULTI_DOMAIN_CONTENT)
+ assert "arxiv.org-1" in result or "arxiv.org-2" in result
+
+ def test_unique_domain_no_id(self):
+ """Single github source gets just github.com (no -1)."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(MULTI_DOMAIN_CONTENT)
+ # github.com should appear without -1 suffix
+ assert "[[github.com]]" in result
+
+
+# ---------------------------------------------------------------------------
+# Quarto export
+# ---------------------------------------------------------------------------
+
+
+class TestQuartoExport:
+ """Quarto export round-trip and consistency."""
+
+ def test_all_refs_have_bibtex_entries(self):
+ """Every @refN in Quarto body has matching BibTeX @misc{refN,...}."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(SAMPLE_CONTENT, "Test Report")
+
+ # Find all @refN references in body
+ ref_pattern = re.compile(r"@ref(\d+)")
+ refs_in_body = set(ref_pattern.findall(result))
+
+ # Find all BibTeX entries
+ bib_pattern = re.compile(r"@misc\{ref(\d+),")
+ bib_entries = set(bib_pattern.findall(result))
+
+ assert refs_in_body, "Should have at least one @ref in body"
+ assert refs_in_body.issubset(bib_entries), (
+ f"Missing BibTeX entries for: {refs_in_body - bib_entries}"
+ )
+
+ def test_bibtex_keys_unique(self):
+ """All BibTeX keys are unique."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(SAMPLE_CONTENT)
+
+ bib_pattern = re.compile(r"@misc\{(ref\d+),")
+ keys = bib_pattern.findall(result)
+ assert len(keys) == len(set(keys)), f"Duplicate BibTeX keys: {keys}"
+
+ def test_hardcoded_year_2024(self):
+ """Documents the hardcoded year = {2024} at line 543."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(SAMPLE_CONTENT)
+
+ # Every BibTeX entry should have year = {2024}
+ assert "year = {2024}" in result
+
+ def test_yaml_header_included(self):
+ """Quarto output includes YAML front matter."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(SAMPLE_CONTENT, "My Report")
+ assert result.startswith("---")
+ assert 'title: "My Report"' in result
+
+ def test_comma_citations_converted(self):
+ """Comma-separated citations [1, 2] converted to [@ref1, @ref2]."""
+ content = "Text [1, 2] here.\n\n## Sources\n\n[1] A\nURL: https://a.com\n\n[2] B\nURL: https://b.com\n"
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(content)
+ assert "@ref1" in result
+ assert "@ref2" in result
+
+
+# ---------------------------------------------------------------------------
+# RIS export
+# ---------------------------------------------------------------------------
+
+
+class TestRISExport:
+ """RIS format export tests."""
+
+ def test_basic_ris_structure(self):
+ """RIS output has TY, TI, UR, ER tags."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(SAMPLE_CONTENT)
+ assert "TY - ELEC" in result
+ assert "TI -" in result
+ assert "ER - " in result
+
+ def test_url_included_in_ris(self):
+ """URL from source is included in RIS entry."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(SAMPLE_CONTENT)
+ assert "UR - https://arxiv.org" in result
+
+ def test_author_extraction_by_keyword(self):
+ """'by Author Name' extracts author correctly."""
+ content = """# Report
+Text [1].
+## Sources
+[1] Research Paper by John Smith and Jane Doe
+URL: https://example.com
+"""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(content)
+ assert "AU -" in result
+
+ def test_author_false_positive_stand_by_me(self):
+ """'Stand by Me' should NOT extract 'Me' as an author.
+
+ The regex \\bby\\s+([^.\\n]+?) matches 'by Me' in 'Stand by Me'.
+ This documents the false positive behavior of the current regex.
+ """
+ content = """# Report
+Text [1].
+## Sources
+[1] Stand by Me - A Classic Film Analysis
+URL: https://example.com
+"""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(content)
+ # The regex WILL match "by Me" — this documents the current behavior
+ # The "AU - Me" line documents this false positive
+ if "AU -" in result:
+ # If authors are extracted, "Me" would be one of them
+ # This is a known false positive from the simple regex
+ pass # Document behavior without asserting it's correct
+
+ def test_no_sources_section_returns_empty(self):
+ """Content without sources section returns empty string."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris("Just some text without sources")
+ assert result == ""
+
+ def test_arxiv_publisher(self):
+ """arxiv.org URL produces PB - arXiv."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(SAMPLE_CONTENT)
+ assert "PB - arXiv" in result
+
+ def test_github_publisher(self):
+ """github.com URL produces PB - GitHub."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(SAMPLE_CONTENT)
+ assert "PB - GitHub" in result
+
+
+# ---------------------------------------------------------------------------
+# LaTeX export
+# ---------------------------------------------------------------------------
+
+
+class TestLaTeXExport:
+ """LaTeX export edge cases."""
+
+ def test_basic_latex_structure(self):
+ """LaTeX output includes documentclass and begin{document}."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex(SAMPLE_CONTENT)
+ assert "\\documentclass" in result
+ assert "\\begin{document}" in result
+ assert "\\end{document}" in result
+
+ def test_headings_converted(self):
+ """Markdown headings converted to LaTeX sections."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex("# Title\n\n## Subtitle\n\nText")
+ assert "\\section{" in result
+ assert "\\subsection{" in result
+
+ def test_unbalanced_dollar_sign(self):
+ """Unbalanced $ (e.g., 'costs $100') in content.
+
+ LaTeX exporter should handle or at least not crash on unbalanced $.
+ """
+ content = "# Report\n\nThis costs $100 per unit.\n\n## Sources\n\n[1] Test\nURL: https://a.com\n"
+ exporter = LaTeXExporter()
+ # Should not raise
+ result = exporter.export_to_latex(content)
+ assert isinstance(result, str)
+
+ def test_citations_converted_to_cite(self):
+ """[1] converted to \\cite{ref1} or similar."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex(SAMPLE_CONTENT)
+ assert "\\cite{" in result or "ref1" in result
diff --git a/tests/report/__init__.py b/tests/report/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/report/test_report_structure_parsing.py b/tests/report/test_report_structure_parsing.py
index cd55f938c9..a156a07cbc 100644
--- a/tests/report/test_report_structure_parsing.py
+++ b/tests/report/test_report_structure_parsing.py
@@ -556,6 +556,84 @@ class TestReportGenerationIntegration:
assert "Standalone" in sections
+class TestSplitDotBug:
+ """Document the split('.')[1] bug at line 139 that mangles section names
+ containing periods.
+
+ The parser does: section_name = line.split(".")[1].strip()
+ This means "1. U.S. Policy" -> ["1", " U", "S", " Policy"] -> [1] = " U"
+ """
+
+ @pytest.fixture
+ def report_generator(self):
+ with patch("local_deep_research.report_generator.AdvancedSearchSystem"):
+ with patch(
+ "local_deep_research.report_generator.get_llm"
+ ) as mock_get_llm:
+ mock_llm = MagicMock()
+ mock_get_llm.return_value = mock_llm
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ generator = IntegratedReportGenerator(llm=mock_llm)
+ yield generator
+
+ def test_period_in_section_name_bug(self, report_generator):
+ """'1. U.S. Policy' is mangled to 'U' by split('.')[1]."""
+ response = "STRUCTURE\n1. U.S. Policy\nEND_STRUCTURE"
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert len(structure) == 1
+ # Documents the current buggy behavior:
+ assert structure[0]["name"] == "U"
+
+ def test_abbreviation_in_section_name_bug(self, report_generator):
+ """'1. IPv4 vs. IPv6' is mangled to 'IPv4 vs' by split('.')[1]."""
+ response = "STRUCTURE\n1. IPv4 vs. IPv6\nEND_STRUCTURE"
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert structure[0]["name"] == "IPv4 vs"
+
+ def test_double_digit_section_number(self, report_generator):
+ """'10. Conclusion' parses correctly since split('.')[1] = ' Conclusion'."""
+ response = "STRUCTURE\n10. Conclusion\nEND_STRUCTURE"
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert structure[0]["name"] == "Conclusion"
+
+ def test_orphan_subsection_before_section(self, report_generator):
+ """Subsection before any section header is skipped."""
+ response = (
+ "STRUCTURE\n - Orphan | purpose\n1. Real Section\nEND_STRUCTURE"
+ )
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Real Section"
+ assert structure[0]["subsections"] == []
+
+ def test_only_source_section_returns_empty(self, report_generator):
+ """If only section is source-related, result is empty."""
+ response = "STRUCTURE\n1. References\nEND_STRUCTURE"
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert len(structure) == 0
+
+ def test_empty_lines_between_sections(self, report_generator):
+ """Empty lines between sections are ignored."""
+ response = "STRUCTURE\n1. Intro\n\n\n2. Methods\nEND_STRUCTURE"
+ report_generator.model.invoke.return_value = MagicMock(content=response)
+ findings = {"current_knowledge": "Test " * 100}
+ structure = report_generator._determine_report_structure(findings, "q")
+ assert len(structure) == 2
+
+
class TestFormatFinalReport:
"""Tests for final report formatting."""
diff --git a/tests/research_library/deletion/routes/test_delete_routes_http.py b/tests/research_library/deletion/routes/test_delete_routes_http.py
new file mode 100644
index 0000000000..e033b12343
--- /dev/null
+++ b/tests/research_library/deletion/routes/test_delete_routes_http.py
@@ -0,0 +1,399 @@
+"""
+HTTP integration tests for delete API endpoints.
+
+42 existing tests mock services directly — zero client.delete() calls.
+This file tests all 11 endpoints via Flask test client.
+
+Source: src/local_deep_research/research_library/deletion/routes/delete_routes.py
+"""
+
+from contextlib import contextmanager
+from unittest.mock import Mock, patch
+
+from flask import Flask, jsonify
+
+from local_deep_research.web.auth.routes import auth_bp
+from local_deep_research.research_library.deletion.routes.delete_routes import (
+ delete_bp,
+)
+
+
+# ---------------------------------------------------------------------------
+# Test Infrastructure
+# ---------------------------------------------------------------------------
+
+
+def _create_test_app():
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.register_blueprint(auth_bp)
+ app.register_blueprint(delete_bp)
+
+ @app.errorhandler(500)
+ def _handle_500(error):
+ return jsonify({"error": "Internal server error"}), 500
+
+ return app
+
+
+@contextmanager
+def _authenticated_client(
+ app, mock_doc_service=None, mock_coll_service=None, mock_bulk_service=None
+):
+ """Context manager providing authenticated test client with mocked services."""
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ _routes_mod = (
+ "local_deep_research.research_library.deletion.routes.delete_routes"
+ )
+
+ mock_doc_cls = Mock(return_value=mock_doc_service or Mock())
+ mock_coll_cls = Mock(return_value=mock_coll_service or Mock())
+ mock_bulk_cls = Mock(return_value=mock_bulk_service or Mock())
+
+ patches = [
+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
+ patch(f"{_routes_mod}.DocumentDeletionService", mock_doc_cls),
+ patch(f"{_routes_mod}.CollectionDeletionService", mock_coll_cls),
+ patch(f"{_routes_mod}.BulkDeletionService", mock_bulk_cls),
+ ]
+
+ started = []
+ try:
+ for p in patches:
+ started.append(p.start())
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ yield client
+ finally:
+ for p in patches:
+ p.stop()
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/document/<id>
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteDocument:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_document.return_value = {
+ "deleted": True,
+ "chunks_deleted": 5,
+ }
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-1")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["success"] is True
+
+ def test_not_found_returns_404(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_document.return_value = {
+ "deleted": False,
+ "error": "Not found",
+ }
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-missing")
+ assert resp.status_code == 404
+ data = resp.get_json()
+ assert data["success"] is False
+
+ def test_exception_returns_500(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_document.side_effect = RuntimeError("DB error")
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-1")
+ assert resp.status_code == 500
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/document/<id>/blob
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteDocumentBlob:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_blob_only.return_value = {
+ "deleted": True,
+ "bytes_freed": 1024,
+ }
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-1/blob")
+ assert resp.status_code == 200
+
+ def test_not_found_returns_404(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_blob_only.return_value = {
+ "deleted": False,
+ "error": "Document not found",
+ }
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-1/blob")
+ assert resp.status_code == 404
+
+ def test_no_blob_returns_400(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_blob_only.return_value = {
+ "deleted": False,
+ "error": "No blob attached",
+ }
+ with _authenticated_client(app, mock_doc_service=svc) as client:
+ resp = client.delete("/library/api/document/doc-1/blob")
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/documents/bulk
+# ---------------------------------------------------------------------------
+
+
+class TestBulkDeleteDocuments:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_documents.return_value = {"deleted_count": 3}
+ with _authenticated_client(app, mock_bulk_service=svc) as client:
+ resp = client.delete(
+ "/library/api/documents/bulk",
+ json={"document_ids": ["d1", "d2", "d3"]},
+ )
+ assert resp.status_code == 200
+ assert resp.get_json()["success"] is True
+
+ def test_missing_document_ids_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/documents/bulk",
+ json={"wrong_key": []},
+ )
+ assert resp.status_code == 400
+ assert "document_ids required" in resp.get_json()["error"]
+
+ def test_empty_list_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/documents/bulk",
+ json={"document_ids": []},
+ )
+ assert resp.status_code == 400
+ assert "non-empty list" in resp.get_json()["error"]
+
+ def test_non_list_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/documents/bulk",
+ json={"document_ids": "not-a-list"},
+ )
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/documents/blobs
+# ---------------------------------------------------------------------------
+
+
+class TestBulkDeleteBlobs:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_blobs.return_value = {"deleted_count": 2}
+ with _authenticated_client(app, mock_bulk_service=svc) as client:
+ resp = client.delete(
+ "/library/api/documents/blobs",
+ json={"document_ids": ["d1", "d2"]},
+ )
+ assert resp.status_code == 200
+
+ def test_missing_document_ids_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/documents/blobs",
+ json={},
+ )
+ assert resp.status_code == 400
+
+ def test_empty_list_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/documents/blobs",
+ json={"document_ids": []},
+ )
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/collection/<cid>/documents/bulk
+# ---------------------------------------------------------------------------
+
+
+class TestBulkRemoveFromCollection:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.remove_documents_from_collection.return_value = {"removed_count": 2}
+ with _authenticated_client(app, mock_bulk_service=svc) as client:
+ resp = client.delete(
+ "/library/api/collection/coll-1/documents/bulk",
+ json={"document_ids": ["d1", "d2"]},
+ )
+ assert resp.status_code == 200
+
+ def test_missing_ids_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.delete(
+ "/library/api/collection/coll-1/documents/bulk",
+ json={},
+ )
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# POST /library/api/documents/preview
+# ---------------------------------------------------------------------------
+
+
+class TestBulkDeletionPreview:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.get_bulk_preview.return_value = {"total_size": 5000}
+ with _authenticated_client(app, mock_bulk_service=svc) as client:
+ resp = client.post(
+ "/library/api/documents/preview",
+ json={"document_ids": ["d1"]},
+ )
+ assert resp.status_code == 200
+ assert resp.get_json()["success"] is True
+
+ def test_missing_ids_returns_400(self):
+ app = _create_test_app()
+ with _authenticated_client(app) as client:
+ resp = client.post(
+ "/library/api/documents/preview",
+ json={},
+ )
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/collections/<id>
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteCollection:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_collection.return_value = {"deleted": True}
+ with _authenticated_client(app, mock_coll_service=svc) as client:
+ resp = client.delete("/library/api/collections/coll-1")
+ assert resp.status_code == 200
+
+ def test_not_found_returns_404(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_collection.return_value = {
+ "deleted": False,
+ "error": "Not found",
+ }
+ with _authenticated_client(app, mock_coll_service=svc) as client:
+ resp = client.delete("/library/api/collections/coll-missing")
+ assert resp.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# DELETE /library/api/collections/<id>/index
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteCollectionIndex:
+ def test_success_returns_200(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_collection_index_only.return_value = {"deleted": True}
+ with _authenticated_client(app, mock_coll_service=svc) as client:
+ resp = client.delete("/library/api/collections/coll-1/index")
+ assert resp.status_code == 200
+
+ def test_not_found_returns_404(self):
+ app = _create_test_app()
+ svc = Mock()
+ svc.delete_collection_index_only.return_value = {
+ "deleted": False,
+ "error": "Not found",
+ }
+ with _authenticated_client(app, mock_coll_service=svc) as client:
+ resp = client.delete("/library/api/collections/coll-missing/index")
+ assert resp.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Unauthenticated requests
+# ---------------------------------------------------------------------------
+
+
+class TestUnauthenticatedRequests:
+ """All endpoints redirect (302) for unauthenticated requests.
+
+ Note: /library/api/* paths do NOT start with /api/ so the login_required
+ decorator redirects (302) instead of returning 401.
+ """
+
+ def test_delete_document_unauthenticated(self):
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {}
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ):
+ with app.test_client() as client:
+ resp = client.delete("/library/api/document/doc-1")
+ assert resp.status_code == 302
+
+ def test_delete_collection_unauthenticated(self):
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {}
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ):
+ with app.test_client() as client:
+ resp = client.delete("/library/api/collections/coll-1")
+ assert resp.status_code == 302
+
+ def test_bulk_delete_unauthenticated(self):
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {}
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ):
+ with app.test_client() as client:
+ resp = client.delete(
+ "/library/api/documents/bulk",
+ json={"document_ids": ["d1"]},
+ )
+ assert resp.status_code == 302
diff --git a/tests/research_library/services/test_download_service_logic.py b/tests/research_library/services/test_download_service_logic.py
new file mode 100644
index 0000000000..544fe4d43f
--- /dev/null
+++ b/tests/research_library/services/test_download_service_logic.py
@@ -0,0 +1,418 @@
+"""
+Tests for DownloadService that actually invoke methods and assert behavior.
+
+Replaces 8 of 9 shallow tests (lines 1200-1420 in existing test file) that only
+assert hasattr(), service.username == "test_user", or service is not None.
+
+Source: src/local_deep_research/research_library/services/download_service.py
+"""
+
+from contextlib import contextmanager
+from unittest.mock import Mock, patch
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _create_service(tmp_path, username="testuser", password="testpw"):
+ """Create a DownloadService with mocked dependencies."""
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: {
+ "research_library.storage_path": str(tmp_path),
+ "search.engine.web.semantic_scholar.api_key": "",
+ "research_library.pdf_storage_mode": "none",
+ "research_library.max_pdf_size_mb": 100,
+ }.get(key, default)
+
+ with (
+ patch(
+ "local_deep_research.research_library.services.download_service.get_settings_manager",
+ return_value=mock_settings,
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.RetryManager",
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.get_library_directory",
+ return_value=tmp_path,
+ ),
+ ):
+ from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+ )
+
+ service = DownloadService(username, password)
+ return service
+
+
+# ---------------------------------------------------------------------------
+# Context manager / close()
+# ---------------------------------------------------------------------------
+
+
+class TestContextManagerAndClose:
+ """Test context manager and close() behavior."""
+
+ def test_close_closes_all_downloaders(self, tmp_path):
+ """close() calls close() on all downloaders that have it."""
+ service = _create_service(tmp_path)
+
+ # Replace downloaders with mocks that have close()
+ mock_dl1 = Mock()
+ mock_dl2 = Mock()
+ mock_dl2.close = Mock()
+ service.downloaders = [mock_dl1, mock_dl2]
+
+ service.close()
+
+ # Both should have close() called (mock_dl1 has it via Mock)
+ assert service._closed is True
+ assert service.downloaders == []
+
+ def test_close_is_idempotent(self, tmp_path):
+ """Calling close() twice does not raise."""
+ service = _create_service(tmp_path)
+ service.close()
+ service.close() # Should not raise
+
+ def test_context_manager_calls_close(self, tmp_path):
+ """__exit__ calls close()."""
+ service = _create_service(tmp_path)
+ service.__enter__()
+ service.__exit__(None, None, None)
+ assert service._closed is True
+
+ def test_context_manager_returns_self(self, tmp_path):
+ """__enter__ returns self."""
+ service = _create_service(tmp_path)
+ result = service.__enter__()
+ assert result is service
+ service.close()
+
+
+# ---------------------------------------------------------------------------
+# get_text_content
+# ---------------------------------------------------------------------------
+
+
+class TestGetTextContent:
+ """Test get_text_content method."""
+
+ def test_resource_not_found_returns_none(self, tmp_path):
+ """get_text_content returns None when resource not found."""
+ service = _create_service(tmp_path)
+
+ mock_session = Mock()
+ mock_session.query.return_value.get.return_value = None
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.research_library.services.download_service.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ result = service.get_text_content(999)
+
+ assert result is None
+ service.close()
+
+ def test_success_returns_text(self, tmp_path):
+ """get_text_content returns text when downloader succeeds."""
+ service = _create_service(tmp_path)
+
+ resource = Mock()
+ resource.url = "https://example.com/paper"
+ resource.title = "Test Paper"
+
+ mock_session = Mock()
+ mock_session.query.return_value.get.return_value = resource
+
+ # Mock downloader that can handle the URL
+ mock_downloader = Mock()
+ mock_downloader.can_handle.return_value = True
+ mock_downloader.download_text.return_value = "Extracted text content"
+ service.downloaders = [mock_downloader]
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.research_library.services.download_service.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ result = service.get_text_content(1)
+
+ assert result == "Extracted text content"
+ service.close()
+
+ def test_no_matching_downloader_returns_none(self, tmp_path):
+ """get_text_content returns None when no downloader can handle URL."""
+ service = _create_service(tmp_path)
+
+ resource = Mock()
+ resource.url = "ftp://weird-protocol.com/file"
+ resource.title = "Test"
+
+ mock_session = Mock()
+ mock_session.query.return_value.get.return_value = resource
+
+ # No downloaders can handle it
+ for dl in service.downloaders:
+ dl.can_handle = Mock(return_value=False)
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.research_library.services.download_service.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ result = service.get_text_content(1)
+
+ assert result is None
+ service.close()
+
+ def test_downloader_raises_returns_none(self, tmp_path):
+ """get_text_content returns None when downloader raises."""
+ service = _create_service(tmp_path)
+
+ resource = Mock()
+ resource.url = "https://example.com/paper"
+ resource.title = "Test"
+
+ mock_session = Mock()
+ mock_session.query.return_value.get.return_value = resource
+
+ mock_downloader = Mock()
+ mock_downloader.can_handle.return_value = True
+ mock_downloader.download_text.side_effect = RuntimeError(
+ "Network error"
+ )
+ service.downloaders = [mock_downloader]
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ with patch(
+ "local_deep_research.research_library.services.download_service.get_user_db_session",
+ side_effect=fake_session,
+ ):
+ result = service.get_text_content(1)
+
+ assert result is None
+ service.close()
+
+
+# ---------------------------------------------------------------------------
+# _try_existing_pdf_extraction
+# ---------------------------------------------------------------------------
+
+
+class TestTryExistingPdfExtraction:
+ """Test _try_existing_pdf_extraction method."""
+
+ def test_no_document_returns_none(self, tmp_path):
+ """No Document record -> returns None."""
+ service = _create_service(tmp_path)
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.first.return_value = None
+ mock_session.query.return_value = mock_query
+
+ result = service._try_existing_pdf_extraction(mock_session, Mock(), 1)
+ assert result is None
+ service.close()
+
+ def test_not_completed_returns_none(self, tmp_path):
+ """Document with status != 'completed' -> returns None."""
+ service = _create_service(tmp_path)
+
+ doc = Mock()
+ doc.status = "pending"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.first.return_value = doc
+ mock_session.query.return_value = mock_query
+
+ result = service._try_existing_pdf_extraction(mock_session, Mock(), 1)
+ assert result is None
+ service.close()
+
+ def test_file_missing_returns_none(self, tmp_path):
+ """Document is completed but file doesn't exist -> returns None."""
+ service = _create_service(tmp_path)
+
+ doc = Mock()
+ doc.status = "completed"
+ doc.file_path = "pdfs/nonexistent.pdf"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.first.return_value = doc
+ mock_session.query.return_value = mock_query
+
+ result = service._try_existing_pdf_extraction(mock_session, Mock(), 1)
+ assert result is None
+ service.close()
+
+
+# ---------------------------------------------------------------------------
+# _fallback_pdf_extraction
+# ---------------------------------------------------------------------------
+
+
+class TestFallbackPdfExtraction:
+ """Test _fallback_pdf_extraction method."""
+
+ def test_no_compatible_downloader(self, tmp_path):
+ """No compatible downloader returns (False, error_msg)."""
+ service = _create_service(tmp_path)
+
+ # Make all downloaders not handle URL
+ for dl in service.downloaders:
+ dl.can_handle = Mock(return_value=False)
+
+ resource = Mock()
+ resource.url = "ftp://weird.com/file"
+ resource.title = "Test Title"
+ resource.id = 1
+
+ mock_session = Mock()
+
+ success, reason = service._fallback_pdf_extraction(
+ mock_session, resource
+ )
+ assert success is False
+ assert "No compatible downloader" in reason
+ service.close()
+
+ def test_download_fails(self, tmp_path):
+ """Download fails returns (False, error_msg)."""
+ service = _create_service(tmp_path)
+
+ mock_downloader = Mock()
+ mock_downloader.can_handle.return_value = True
+ result_obj = Mock()
+ result_obj.is_success = False
+ result_obj.content = None
+ result_obj.skip_reason = "Server returned 403"
+ mock_downloader.download_with_result.return_value = result_obj
+ service.downloaders = [mock_downloader]
+
+ resource = Mock()
+ resource.url = "https://example.com/paper.pdf"
+ resource.title = "Test"
+ resource.id = 1
+
+ mock_session = Mock()
+
+ success, reason = service._fallback_pdf_extraction(
+ mock_session, resource
+ )
+ assert success is False
+ assert "403" in reason
+ service.close()
+
+
+# ---------------------------------------------------------------------------
+# Initialization
+# ---------------------------------------------------------------------------
+
+
+class TestInitialization:
+ """Test DownloadService initialization."""
+
+ def test_username_stored(self, tmp_path):
+ """Username is stored on the service."""
+ service = _create_service(tmp_path, username="alice")
+ assert service.username == "alice"
+ service.close()
+
+ def test_password_stored(self, tmp_path):
+ """Password is stored on the service."""
+ service = _create_service(tmp_path, password="secret123")
+ assert service.password == "secret123"
+ service.close()
+
+ def test_library_root_set(self, tmp_path):
+ """Library root is set from settings."""
+ service = _create_service(tmp_path)
+ assert service.library_root == str(tmp_path)
+ service.close()
+
+ def test_downloaders_initialized(self, tmp_path):
+ """Multiple downloaders are initialized."""
+ service = _create_service(tmp_path)
+ assert len(service.downloaders) > 0
+ service.close()
+
+ def test_closed_starts_false(self, tmp_path):
+ """_closed flag starts as False."""
+ service = _create_service(tmp_path)
+ assert service._closed is False
+ service.close()
+
+ def test_none_storage_path_raises(self, tmp_path):
+ """None storage path raises ValueError."""
+ mock_settings = Mock()
+ mock_settings.get_setting.return_value = None
+
+ with (
+ patch(
+ "local_deep_research.research_library.services.download_service.get_settings_manager",
+ return_value=mock_settings,
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.RetryManager",
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.get_library_directory",
+ return_value=tmp_path,
+ ),
+ ):
+ from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+ )
+
+ with pytest.raises(ValueError, match="Storage path"):
+ DownloadService("user", "pw")
+
+
+# ---------------------------------------------------------------------------
+# _normalize_url
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeUrl:
+ """Test URL normalization."""
+
+ def test_basic_url_normalized(self, tmp_path):
+ """Basic URL normalization works."""
+ service = _create_service(tmp_path)
+ # _normalize_url should at least return a string
+ result = service._normalize_url("https://example.com/path")
+ assert isinstance(result, str)
+ service.close()
+
+ def test_url_with_trailing_slash(self, tmp_path):
+ """Trailing slashes handled consistently."""
+ service = _create_service(tmp_path)
+ r1 = service._normalize_url("https://example.com/path/")
+ r2 = service._normalize_url("https://example.com/path")
+ # Both should normalize to the same thing
+ assert r1 == r2
+ service.close()
diff --git a/tests/utilities/test_json_utils_production_gaps.py b/tests/utilities/test_json_utils_production_gaps.py
new file mode 100644
index 0000000000..a8569fa256
--- /dev/null
+++ b/tests/utilities/test_json_utils_production_gaps.py
@@ -0,0 +1,240 @@
+"""
+Tests for realistic LLM output patterns in JSON parsing that are not covered
+by the existing 75 tests across 3 files.
+
+Source: src/local_deep_research/utilities/json_utils.py
+"""
+
+from local_deep_research.utilities.json_utils import (
+ extract_json,
+ get_llm_response_text,
+ _extract_by_brackets,
+ _strip_code_fences,
+)
+
+
+# ---------------------------------------------------------------------------
+# Think tags wrapping code fences (real DeepSeek pattern)
+# ---------------------------------------------------------------------------
+
+
+class TestThinkTagsWithCodeFences:
+ """Real LLM patterns where think tags wrap JSON code fences."""
+
+ def test_think_tags_wrapping_json_code_fence(self):
+ """<think>...</think> followed by ```json ... ``` — real DeepSeek pattern."""
+ text = '<think>Let me analyze this...</think>\n```json\n{"key": "value"}\n```'
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+ def test_think_tags_wrapping_list_code_fence(self):
+ """Think tags before a JSON list in code fence."""
+ text = (
+ '<think>Planning response...</think>\n```json\n["a", "b", "c"]\n```'
+ )
+ result = extract_json(text)
+ assert result == ["a", "b", "c"]
+
+ def test_nested_think_content_with_json(self):
+ """Think tags with JSON-like content inside, real JSON outside."""
+ text = '<think>Maybe {"wrong": true}?</think>\n{"correct": true}'
+ result = extract_json(text)
+ assert result == {"correct": True}
+
+ def test_unclosed_think_tag_before_json(self):
+ """<think> without closing </think> before JSON."""
+ text = '<think>some reasoning\n{"key": "value"}'
+ result = extract_json(text)
+ assert result == {"key": "value"}
+
+
+# ---------------------------------------------------------------------------
+# Code fences with non-json language tags
+# ---------------------------------------------------------------------------
+
+
+class TestNonJsonCodeFences:
+ """JSON inside code fences tagged with non-json language."""
+
+ def test_typescript_tagged_code_fence(self):
+ """```typescript wrapping JSON."""
+ text = '```typescript\n{"type": "config"}\n```'
+ # _strip_code_fences looks for ```json or plain ``` (3+ backticks)
+ # For non-json tags, it falls to the plain ``` path
+ result = extract_json(text)
+ # The stripping gets "typescript\n{...}" which isn't valid JSON
+ # but bracket extraction should still find the JSON
+ assert result == {"type": "config"}
+
+ def test_plain_code_fence(self):
+ """Plain ``` without language tag."""
+ text = '```\n{"plain": true}\n```'
+ result = extract_json(text)
+ assert result == {"plain": True}
+
+
+# ---------------------------------------------------------------------------
+# JSON with preamble/trailing text (common LLM pattern)
+# ---------------------------------------------------------------------------
+
+
+class TestPreambleAndTrailing:
+ """JSON surrounded by conversational text."""
+
+ def test_apologize_preamble(self):
+ """'I apologize...' preamble before JSON."""
+ text = 'I apologize for the confusion. Here is the corrected JSON:\n{"fixed": true}'
+ result = extract_json(text)
+ assert result == {"fixed": True}
+
+ def test_trailing_explanation(self):
+ """JSON followed by explanation text."""
+ text = '{"result": 42}\n\nThis represents the answer to the question.'
+ result = extract_json(text)
+ assert result == {"result": 42}
+
+ def test_preamble_and_trailing(self):
+ """Both preamble and trailing text around JSON."""
+ text = 'Sure! Here it is:\n{"data": [1, 2, 3]}\nHope this helps!'
+ result = extract_json(text)
+ assert result == {"data": [1, 2, 3]}
+
+
+# ---------------------------------------------------------------------------
+# get_llm_response_text edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestGetLlmResponseText:
+ """Edge cases for extracting text from LLM response objects."""
+
+ def test_none_returns_empty(self):
+ """None input returns empty string."""
+ assert get_llm_response_text(None) == ""
+
+ def test_content_attribute_used(self):
+ """Object with .content attribute uses it."""
+ obj = type("Resp", (), {"content": "hello"})()
+ assert get_llm_response_text(obj) == "hello"
+
+ def test_text_attribute_used(self):
+ """Object with .text but no .content uses .text."""
+ obj = type("Resp", (), {"text": "world", "content": None})()
+ assert get_llm_response_text(obj) == "world"
+
+ def test_both_none_falls_to_str(self):
+ """.content and .text both None -> falls to str()."""
+ obj = type("Resp", (), {"content": None, "text": None})()
+ result = get_llm_response_text(obj)
+ # str() of the object
+ assert isinstance(result, str)
+
+ def test_empty_string_content_used(self):
+ """Empty string .content is used as-is (not None)."""
+ obj = type("Resp", (), {"content": ""})()
+ assert get_llm_response_text(obj) == ""
+
+ def test_think_tags_removed(self):
+ """Think tags in content are removed."""
+ obj = type("Resp", (), {"content": "<think>reasoning</think>answer"})()
+ assert get_llm_response_text(obj) == "answer"
+
+ def test_non_string_content_converted(self):
+ """Non-string .content is converted to string."""
+ obj = type("Resp", (), {"content": 42})()
+ result = get_llm_response_text(obj)
+ assert result == "42"
+
+
+# ---------------------------------------------------------------------------
+# _extract_by_brackets edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestExtractByBrackets:
+ """Edge cases for bracket extraction."""
+
+ def test_adjacent_braces(self):
+ """Adjacent {} objects — extracts outermost."""
+ result = _extract_by_brackets('{"a": 1}{"b": 2}', "{", "}")
+ # find("{")=0, rfind("}")=17 -> extracts whole string
+ assert '"a"' in result
+ assert '"b"' in result
+
+ def test_only_open_bracket(self):
+ """Only open bracket, no close -> returns None."""
+ result = _extract_by_brackets("{no close", "{", "}")
+ assert result is None
+
+ def test_empty_string(self):
+ """Empty string -> returns None."""
+ result = _extract_by_brackets("", "{", "}")
+ assert result is None
+
+ def test_close_before_open(self):
+ """Close bracket before open -> returns None."""
+ result = _extract_by_brackets("} then {", "{", "}")
+ # find("{")=7, rfind("}")=0, 0 < 7 -> None
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# _strip_code_fences edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestStripCodeFences:
+ """Edge cases for code fence stripping."""
+
+ def test_no_code_fences(self):
+ """Text without code fences returned as-is."""
+ text = '{"key": "value"}'
+ assert _strip_code_fences(text) == text
+
+ def test_json_code_fence(self):
+ """```json ... ``` stripped correctly."""
+ text = '```json\n{"key": "value"}\n```'
+ result = _strip_code_fences(text)
+ assert result == '{"key": "value"}'
+
+ def test_multiple_code_fences_first_extracted(self):
+ """Multiple code fences — first one extracted."""
+ text = '```json\n{"first": 1}\n```\n\n```json\n{"second": 2}\n```'
+ result = _strip_code_fences(text)
+ assert '{"first": 1}' in result
+
+
+# ---------------------------------------------------------------------------
+# extract_json with expected_type
+# ---------------------------------------------------------------------------
+
+
+class TestExtractJsonExpectedType:
+ """Test expected_type parameter behavior."""
+
+ def test_expect_list_gets_list(self):
+ """expected_type=list prefers list extraction."""
+ text = '{"dict": true}\n[1, 2, 3]'
+ result = extract_json(text, expected_type=list)
+ assert result == [1, 2, 3]
+
+ def test_expect_dict_gets_dict(self):
+ """expected_type=dict prefers dict extraction."""
+ text = '[1, 2]\n{"dict": true}'
+ result = extract_json(text, expected_type=dict)
+ assert result == {"dict": True}
+
+ def test_none_type_accepts_either(self):
+ """expected_type=None accepts first valid JSON."""
+ text = '{"key": "value"}'
+ result = extract_json(text, expected_type=None)
+ assert result == {"key": "value"}
+
+ def test_empty_input_returns_none(self):
+ """Empty string returns None."""
+ assert extract_json("") is None
+ assert extract_json(" ") is None
+
+ def test_no_valid_json_returns_none(self):
+ """Text without valid JSON returns None."""
+ assert extract_json("just some text without json") is None
diff --git a/tests/utilities/test_type_utils_behavior.py b/tests/utilities/test_type_utils_behavior.py
index a4f67ea6f0..243fa0df77 100644
--- a/tests/utilities/test_type_utils_behavior.py
+++ b/tests/utilities/test_type_utils_behavior.py
@@ -289,15 +289,11 @@ class TestToBoolEdgeCases:
"""Tests for edge cases."""
def test_whitespace_true_variant(self):
- """' true ' (with whitespace) is not converted."""
+ """' true ' (with whitespace) is stripped and converted."""
from local_deep_research.utilities.type_utils import to_bool
- # Note: the function doesn't strip, so this returns False
- # (unless implementation strips whitespace)
result = to_bool(" true ")
- # The implementation uses .lower() but doesn't strip
- # so " true ".lower() is " true " which is not in truthy set
- assert result is False
+ assert result is True
def test_tRuE_mixed_case(self):
"""'tRuE' (odd case) returns True."""
diff --git a/tests/web/queue/test_processor_v2_concurrency.py b/tests/web/queue/test_processor_v2_concurrency.py
new file mode 100644
index 0000000000..9ff21e04e2
--- /dev/null
+++ b/tests/web/queue/test_processor_v2_concurrency.py
@@ -0,0 +1,386 @@
+"""
+Tests for QueueProcessorV2 error recovery, cleanup, concurrency, and
+process_user_request — replacing fake tests that never import the real class.
+
+Source: src/local_deep_research/web/queue/processor_v2.py
+"""
+
+import threading
+from contextlib import contextmanager
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web.queue.processor_v2 import QueueProcessorV2
+from local_deep_research.constants import ResearchStatus
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def processor():
+ """Create a fresh QueueProcessorV2 instance (not started)."""
+ return QueueProcessorV2(check_interval=1)
+
+
+@contextmanager
+def _mock_db_session():
+ """Yield a chainable mock db session."""
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.first.return_value = None
+ mock_query.all.return_value = []
+ mock_query.count.return_value = 0
+ mock_session.query.return_value = mock_query
+ yield mock_session
+
+
+# ---------------------------------------------------------------------------
+# _start_queued_researches error recovery
+# ---------------------------------------------------------------------------
+
+
+class TestStartQueuedResearchesErrorRecovery:
+ """When _start_research throws, verify is_processing reset and task FAILED."""
+
+ def test_error_resets_is_processing(self, processor):
+ """On exception, is_processing must be set back to False (line 568)."""
+ queued = Mock()
+ queued.is_processing = False
+ queued.research_id = "res-1"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = [queued]
+ mock_session.query.return_value = mock_query
+
+ mock_queue_service = Mock()
+
+ # _start_research throws
+ processor._start_research = Mock(side_effect=RuntimeError("boom"))
+
+ processor._start_queued_researches(
+ mock_session, mock_queue_service, "alice", "pw", 1
+ )
+
+ assert queued.is_processing is False
+
+ def test_error_sets_task_status_failed(self, processor):
+ """On exception, task status must be set to FAILED (line 574)."""
+ queued = Mock()
+ queued.is_processing = False
+ queued.research_id = "res-2"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = [queued]
+ mock_session.query.return_value = mock_query
+
+ mock_queue_service = Mock()
+ processor._start_research = Mock(side_effect=RuntimeError("boom"))
+
+ processor._start_queued_researches(
+ mock_session, mock_queue_service, "alice", "pw", 1
+ )
+
+ mock_queue_service.update_task_status.assert_any_call(
+ "res-2",
+ ResearchStatus.FAILED,
+ error_message="Failed to start research",
+ )
+
+ def test_success_deletes_queued_record(self, processor):
+ """On success, the queued_research is deleted from DB."""
+ queued = Mock()
+ queued.is_processing = False
+ queued.research_id = "res-3"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = [queued]
+ mock_session.query.return_value = mock_query
+
+ mock_queue_service = Mock()
+ processor._start_research = Mock() # success
+
+ processor._start_queued_researches(
+ mock_session, mock_queue_service, "alice", "pw", 1
+ )
+
+ mock_session.delete.assert_called_once_with(queued)
+
+ def test_respects_available_slots_limit(self, processor):
+ """The .limit() call should use available_slots."""
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = []
+ mock_session.query.return_value = mock_query
+
+ mock_queue_service = Mock()
+
+ processor._start_queued_researches(
+ mock_session, mock_queue_service, "alice", "pw", 5
+ )
+
+ mock_query.limit.assert_called_with(5)
+
+
+# ---------------------------------------------------------------------------
+# _start_research_directly cleanup
+# ---------------------------------------------------------------------------
+
+
+class TestStartResearchDirectlyCleanup:
+ """When start_research_process throws, verify UserActiveResearch deleted."""
+
+ @patch("local_deep_research.web.queue.processor_v2.UserQueueService")
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ @patch("local_deep_research.web.queue.processor_v2.start_research_process")
+ def test_cleanup_on_start_failure(
+ self, mock_start, mock_get_session, mock_qs, processor
+ ):
+ """When start_research_process raises, active record is deleted (line 305)."""
+ # Session 1: create record (success)
+ # Session 2: cleanup after start_research_process failure — query, find, delete
+ active_record = Mock()
+
+ session1 = Mock() # Create record session
+ session2 = Mock() # Cleanup session
+ q2 = Mock()
+ q2.filter_by.return_value = q2
+ q2.first.return_value = active_record
+ session2.query.return_value = q2
+
+ sessions = [session1, session2]
+ call_count = [0]
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ idx = min(call_count[0], len(sessions) - 1)
+ call_count[0] += 1
+ yield sessions[idx]
+
+ mock_get_session.side_effect = fake_session
+ mock_start.side_effect = RuntimeError("process failed")
+
+ processor._start_research_directly(
+ "alice",
+ "res-1",
+ "password",
+ query="test",
+ mode="quick",
+ )
+
+ # The cleanup session should delete the active record
+ session2.delete.assert_called_once_with(active_record)
+
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ @patch("local_deep_research.web.queue.processor_v2.start_research_process")
+ def test_success_updates_thread_id(
+ self, mock_start, mock_get_session, processor
+ ):
+ """On success, thread ID is updated in active record."""
+ mock_thread = Mock()
+ mock_thread.ident = 12345
+ mock_start.return_value = mock_thread
+
+ active_record = Mock()
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.first.return_value = active_record
+ mock_session.query.return_value = mock_query
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ mock_get_session.side_effect = fake_session
+
+ processor._start_research_directly(
+ "alice",
+ "res-1",
+ "password",
+ query="test",
+ mode="quick",
+ )
+
+ assert active_record.thread_id == "12345"
+
+
+# ---------------------------------------------------------------------------
+# process_user_request
+# ---------------------------------------------------------------------------
+
+
+class TestProcessUserRequest:
+ """Tests for process_user_request return values."""
+
+ @patch("local_deep_research.web.queue.processor_v2.db_manager")
+ @patch("local_deep_research.web.queue.processor_v2.session_password_store")
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ def test_no_password_returns_zero(
+ self, mock_session, mock_pw_store, mock_db, processor
+ ):
+ """When no password available, returns 0 (line 686)."""
+ mock_pw_store.get_session_password.return_value = None
+
+ result = processor.process_user_request("alice", "sess-1")
+ assert result == 0
+
+ @patch("local_deep_research.web.queue.processor_v2.db_manager")
+ @patch("local_deep_research.web.queue.processor_v2.session_password_store")
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ def test_exception_returns_zero(
+ self, mock_session, mock_pw_store, mock_db, processor
+ ):
+ """When exception occurs, returns 0 (line 690)."""
+ mock_pw_store.get_session_password.return_value = "pw"
+ mock_db.open_user_database.side_effect = RuntimeError("db error")
+
+ result = processor.process_user_request("alice", "sess-1")
+ assert result == 0
+
+ @patch("local_deep_research.web.queue.processor_v2.db_manager")
+ @patch("local_deep_research.web.queue.processor_v2.session_password_store")
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ def test_returns_queued_count(
+ self, mock_get_session, mock_pw_store, mock_db, processor
+ ):
+ """When queue has items, returns queued count (line 684)."""
+ mock_pw_store.get_session_password.return_value = "pw"
+ mock_db.open_user_database.return_value = Mock()
+
+ mock_queue_service = Mock()
+ mock_queue_service.get_queue_status.return_value = {"queued_tasks": 3}
+
+ mock_session = Mock()
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ mock_get_session.side_effect = fake_session
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.UserQueueService",
+ return_value=mock_queue_service,
+ ):
+ result = processor.process_user_request("alice", "sess-1")
+
+ assert result == 3
+
+ @patch("local_deep_research.web.queue.processor_v2.db_manager")
+ @patch("local_deep_research.web.queue.processor_v2.session_password_store")
+ @patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
+ def test_empty_queue_returns_zero(
+ self, mock_get_session, mock_pw_store, mock_db, processor
+ ):
+ """When queue is empty, returns 0."""
+ mock_pw_store.get_session_password.return_value = "pw"
+ mock_db.open_user_database.return_value = Mock()
+
+ mock_queue_service = Mock()
+ mock_queue_service.get_queue_status.return_value = {"queued_tasks": 0}
+
+ mock_session = Mock()
+
+ @contextmanager
+ def fake_session(*args, **kwargs):
+ yield mock_session
+
+ mock_get_session.side_effect = fake_session
+
+ with patch(
+ "local_deep_research.web.queue.processor_v2.UserQueueService",
+ return_value=mock_queue_service,
+ ):
+ result = processor.process_user_request("alice", "sess-1")
+
+ assert result == 0
+
+
+# ---------------------------------------------------------------------------
+# notify_user_activity concurrency
+# ---------------------------------------------------------------------------
+
+
+class TestNotifyUserActivityConcurrency:
+ """Concurrent notify_user_activity calls from 20 threads."""
+
+ def test_concurrent_notify_all_users_registered(self, processor):
+ """All users registered via concurrent notify_user_activity calls."""
+ barrier = threading.Barrier(20)
+ errors = []
+
+ def worker(i):
+ try:
+ barrier.wait(timeout=5)
+ processor.notify_user_activity(f"user-{i}", f"sess-{i}")
+ except Exception as e:
+ errors.append(e)
+
+ threads = [
+ threading.Thread(target=worker, args=(i,)) for i in range(20)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert not errors
+ assert len(processor._users_to_check) == 20
+ for i in range(20):
+ assert f"user-{i}:sess-{i}" in processor._users_to_check
+
+ def test_duplicate_user_session_deduplicated(self, processor):
+ """Same user:session added multiple times is stored once (set behavior)."""
+ for _ in range(5):
+ processor.notify_user_activity("alice", "sess-1")
+
+ assert len(processor._users_to_check) == 1
+ assert "alice:sess-1" in processor._users_to_check
+
+
+# ---------------------------------------------------------------------------
+# Start/stop lifecycle
+# ---------------------------------------------------------------------------
+
+
+class TestProcessorLifecycle:
+ """Basic start/stop behavior."""
+
+ def test_start_sets_running(self, processor):
+ processor.start()
+ assert processor.running is True
+ processor.stop()
+ assert processor.running is False
+
+ def test_double_start_is_noop(self, processor):
+ processor.start()
+ processor.start() # should not raise
+ processor.stop()
+
+ def test_stop_without_start(self, processor):
+ """Stopping without starting should not raise."""
+ processor.stop()
+ assert processor.running is False
diff --git a/tests/web/routes/test_context_overflow_api_http.py b/tests/web/routes/test_context_overflow_api_http.py
new file mode 100644
index 0000000000..6ab7ebd47a
--- /dev/null
+++ b/tests/web/routes/test_context_overflow_api_http.py
@@ -0,0 +1,507 @@
+"""
+HTTP integration tests for context overflow API endpoints.
+
+The existing 673 unit tests only test math helpers. Two "route tests" at
+lines 495-524 are bogus (test wrong URLs, accept any status code). This file
+provides real Flask test client tests.
+
+Source: src/local_deep_research/web/routes/context_overflow_api.py
+"""
+
+from contextlib import contextmanager
+from datetime import datetime, timezone
+from unittest.mock import Mock, patch
+
+from flask import Flask, jsonify
+
+from local_deep_research.web.auth.routes import auth_bp
+from local_deep_research.web.routes.context_overflow_api import (
+ context_overflow_bp,
+)
+
+
+# ---------------------------------------------------------------------------
+# Test Infrastructure
+# ---------------------------------------------------------------------------
+
+
+def _create_test_app():
+ """Create Flask app with auth + context_overflow blueprints."""
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.register_blueprint(auth_bp)
+ app.register_blueprint(context_overflow_bp)
+
+ @app.errorhandler(500)
+ def _handle_500(error):
+ return jsonify({"error": "Internal server error"}), 500
+
+ return app
+
+
+@contextmanager
+def _authenticated_client(app):
+ """Provide test client with mocked auth and DB session."""
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ # Build a chainable mock query
+ _mock_query = Mock()
+ _mock_query.all.return_value = []
+ _mock_query.first.return_value = None
+ _mock_query.count.return_value = 0
+ _mock_query.scalar.return_value = 0
+ _mock_query.filter_by.return_value = _mock_query
+ _mock_query.filter.return_value = _mock_query
+ _mock_query.order_by.return_value = _mock_query
+ _mock_query.limit.return_value = _mock_query
+ _mock_query.offset.return_value = _mock_query
+ _mock_query.group_by.return_value = _mock_query
+ _mock_query.with_entities.return_value = _mock_query
+
+ _mock_db_session = Mock()
+ _mock_db_session.query.return_value = _mock_query
+
+ @contextmanager
+ def _fake_session(*args, **kwargs):
+ yield _mock_db_session
+
+ _routes_mod = "local_deep_research.web.routes.context_overflow_api"
+
+ patches = [
+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
+ patch(
+ f"{_routes_mod}.get_user_db_session",
+ side_effect=_fake_session,
+ ),
+ ]
+
+ started = []
+ try:
+ for p in patches:
+ started.append(p.start())
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ yield client, _mock_db_session, _mock_query
+ finally:
+ for p in patches:
+ p.stop()
+
+
+# ---------------------------------------------------------------------------
+# GET /api/context-overflow
+# ---------------------------------------------------------------------------
+
+
+class TestGetContextOverflowMetrics:
+ """Tests for GET /api/context-overflow."""
+
+ def test_unauthenticated_returns_401(self):
+ """Unauthenticated request returns 401."""
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {}
+ mock_db.has_encryption = False
+
+ with patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ):
+ with app.test_client() as client:
+ resp = client.get("/api/context-overflow")
+ assert resp.status_code == 401
+
+ def test_default_period_success(self):
+ """Default period (30d) returns success with overview."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ # Mock overview_counts result
+ overview_row = Mock()
+ overview_row.total_requests = 5
+ overview_row.requests_with_context = 3
+ overview_row.truncated_requests = 1
+
+ # Mock token_summary_row
+ token_row = Mock()
+ token_row.total_requests = 5
+ token_row.total_tokens = 1000
+ token_row.total_prompt_tokens = 700
+ token_row.total_completion_tokens = 300
+ token_row.avg_prompt_tokens = 140.0
+ token_row.avg_completion_tokens = 60.0
+ token_row.max_prompt_tokens = 200
+
+ # with_entities().first() should return our mocked rows
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ if call_count[0] == 1:
+ return overview_row
+ return token_row
+
+ mock_query.first.side_effect = multi_first
+
+ resp = client.get("/api/context-overflow")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ assert "overview" in data
+
+ def test_period_7d_accepted(self):
+ """period=7d is a valid period."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ if call_count[0] == 1:
+ return overview_row
+ return token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?period=7d")
+ assert resp.status_code == 200
+
+ def test_period_all_accepted(self):
+ """period=all returns success (no date filter)."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ return overview_row if call_count[0] == 1 else token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?period=all")
+ assert resp.status_code == 200
+
+ def test_invalid_period_defaults_to_30d(self):
+ """Invalid period value defaults to 30d."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ return overview_row if call_count[0] == 1 else token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?period=invalid")
+ assert resp.status_code == 200
+
+ def test_pagination_params(self):
+ """page and per_page params are accepted."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ return overview_row if call_count[0] == 1 else token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?page=2&per_page=10")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["pagination"]["page"] == 2
+ assert data["pagination"]["per_page"] == 10
+
+ def test_per_page_clamped_to_500(self):
+ """per_page > 500 is clamped to 500."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ return overview_row if call_count[0] == 1 else token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?per_page=999")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["pagination"]["per_page"] == 500
+
+ def test_per_page_min_is_1(self):
+ """per_page < 1 is clamped to 1."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ overview_row = Mock(
+ total_requests=0, requests_with_context=0, truncated_requests=0
+ )
+ token_row = Mock(
+ total_requests=0,
+ total_tokens=0,
+ total_prompt_tokens=0,
+ total_completion_tokens=0,
+ avg_prompt_tokens=0,
+ avg_completion_tokens=0,
+ max_prompt_tokens=0,
+ )
+ call_count = [0]
+
+ def multi_first():
+ call_count[0] += 1
+ return overview_row if call_count[0] == 1 else token_row
+
+ mock_query.first.side_effect = multi_first
+ mock_query.scalar.return_value = 0
+
+ resp = client.get("/api/context-overflow?per_page=-5")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["pagination"]["per_page"] == 1
+
+ def test_db_exception_returns_500(self):
+ """DB exception returns 500 with error message."""
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ @contextmanager
+ def _exploding_session(*args, **kwargs):
+ raise RuntimeError("DB connection failed")
+ yield # pragma: no cover
+
+ _routes_mod = "local_deep_research.web.routes.context_overflow_api"
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ),
+ patch(
+ f"{_routes_mod}.get_user_db_session",
+ side_effect=_exploding_session,
+ ),
+ ):
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ resp = client.get("/api/context-overflow")
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# GET /api/research/<id>/context-overflow
+# ---------------------------------------------------------------------------
+
+
+class TestGetResearchContextOverflow:
+ """Tests for GET /api/research/<id>/context-overflow."""
+
+ def test_no_token_usage_returns_empty(self):
+ """No token usage for research returns empty data."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ mock_query.all.return_value = []
+
+ resp = client.get("/api/research/res-1/context-overflow")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ assert data["data"]["overview"]["total_requests"] == 0
+
+ def test_with_data_returns_overview_and_requests(self):
+ """With token usage data, returns overview + phase_stats + requests."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ usage1 = Mock()
+ usage1.total_tokens = 100
+ usage1.prompt_tokens = 80
+ usage1.completion_tokens = 20
+ usage1.context_limit = 4096
+ usage1.context_truncated = False
+ usage1.tokens_truncated = 0
+ usage1.research_phase = "search"
+ usage1.timestamp = datetime(2024, 1, 1, tzinfo=timezone.utc)
+ usage1.ollama_prompt_eval_count = None
+ usage1.calling_function = "search"
+ usage1.response_time_ms = 500
+ usage1.model_name = "gpt-4"
+ usage1.model_provider = "openai"
+ usage1.research_id = "res-1"
+
+ usage2 = Mock()
+ usage2.total_tokens = 200
+ usage2.prompt_tokens = 150
+ usage2.completion_tokens = 50
+ usage2.context_limit = 4096
+ usage2.context_truncated = True
+ usage2.tokens_truncated = 30
+ usage2.research_phase = "analysis"
+ usage2.timestamp = datetime(2024, 1, 2, tzinfo=timezone.utc)
+ usage2.ollama_prompt_eval_count = None
+ usage2.calling_function = "analyze"
+ usage2.response_time_ms = 800
+ usage2.model_name = "gpt-4"
+ usage2.model_provider = "openai"
+ usage2.research_id = "res-1"
+
+ mock_query.all.return_value = [usage1, usage2]
+
+ resp = client.get("/api/research/res-1/context-overflow")
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ assert data["data"]["overview"]["total_requests"] == 2
+ assert data["data"]["overview"]["total_tokens"] == 300
+ assert data["data"]["overview"]["truncation_occurred"] is True
+ assert "search" in data["data"]["phase_stats"]
+ assert "analysis" in data["data"]["phase_stats"]
+ assert len(data["data"]["requests"]) == 2
+
+ def test_phase_stats_grouped_correctly(self):
+ """Phase stats are grouped by research_phase."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session, mock_query):
+ # Two entries in same phase
+ usage1 = Mock(
+ total_tokens=100,
+ prompt_tokens=80,
+ completion_tokens=20,
+ context_limit=4096,
+ context_truncated=False,
+ tokens_truncated=0,
+ research_phase="search",
+ model_name="gpt-4",
+ model_provider="openai",
+ timestamp=datetime(2024, 1, 1, tzinfo=timezone.utc),
+ ollama_prompt_eval_count=None,
+ calling_function="s",
+ response_time_ms=100,
+ research_id="res-1",
+ )
+ usage2 = Mock(
+ total_tokens=100,
+ prompt_tokens=80,
+ completion_tokens=20,
+ context_limit=4096,
+ context_truncated=True,
+ tokens_truncated=10,
+ research_phase="search",
+ model_name="gpt-4",
+ model_provider="openai",
+ timestamp=datetime(2024, 1, 2, tzinfo=timezone.utc),
+ ollama_prompt_eval_count=None,
+ calling_function="s",
+ response_time_ms=100,
+ research_id="res-1",
+ )
+ mock_query.all.return_value = [usage1, usage2]
+
+ resp = client.get("/api/research/res-1/context-overflow")
+ data = resp.get_json()
+
+ search_stats = data["data"]["phase_stats"]["search"]
+ assert search_stats["count"] == 2
+ assert search_stats["truncated_count"] == 1
+ assert search_stats["total_tokens"] == 200
+
+ def test_db_exception_returns_500(self):
+ """DB exception returns 500."""
+ app = _create_test_app()
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ @contextmanager
+ def _exploding_session(*args, **kwargs):
+ raise RuntimeError("DB error")
+ yield # pragma: no cover
+
+ _routes_mod = "local_deep_research.web.routes.context_overflow_api"
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager", mock_db
+ ),
+ patch(
+ f"{_routes_mod}.get_user_db_session",
+ side_effect=_exploding_session,
+ ),
+ ):
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ resp = client.get("/api/research/res-1/context-overflow")
+ assert resp.status_code == 500
diff --git a/tests/web/routes/test_settings_routes_security.py b/tests/web/routes/test_settings_routes_security.py
new file mode 100644
index 0000000000..467802342d
--- /dev/null
+++ b/tests/web/routes/test_settings_routes_security.py
@@ -0,0 +1,175 @@
+"""
+HTTP security tests for settings routes.
+
+Existing unit tests cover is_blocked_setting() and corrupted value detection
+at the function level, but not via HTTP endpoints. This file tests the
+save_all_settings endpoint end-to-end.
+
+Source: src/local_deep_research/web/routes/settings_routes.py
+"""
+
+from contextlib import contextmanager
+from unittest.mock import Mock, patch
+
+from flask import Flask, jsonify
+
+from local_deep_research.web.auth.routes import auth_bp
+from local_deep_research.web.routes.settings_routes import settings_bp
+
+
+# ---------------------------------------------------------------------------
+# Test Infrastructure
+# ---------------------------------------------------------------------------
+
+
+def _create_test_app():
+ app = Flask(__name__)
+ app.config["SECRET_KEY"] = "test-secret"
+ app.config["WTF_CSRF_ENABLED"] = False
+ app.register_blueprint(auth_bp)
+ app.register_blueprint(settings_bp)
+
+ @app.errorhandler(500)
+ def _handle_500(error):
+ return jsonify({"error": "Internal server error"}), 500
+
+ return app
+
+
+@contextmanager
+def _authenticated_client(app, mock_settings=None):
+ """Provide test client with mocked auth and DB session for settings routes."""
+ mock_db = Mock()
+ mock_db.connections = {"testuser": True}
+ mock_db.has_encryption = False
+
+ # Build mock db session with Setting query
+ mock_setting_obj = Mock()
+ mock_setting_obj.key = "llm.temperature"
+ mock_setting_obj.value = "0.7"
+ mock_setting_obj.editable = True
+ mock_setting_obj.ui_element = "number"
+
+ _mock_query = Mock()
+ _mock_query.all.return_value = mock_settings or [mock_setting_obj]
+ _mock_query.first.return_value = None
+ _mock_query.filter_by.return_value = _mock_query
+ _mock_query.filter.return_value = _mock_query
+
+ _mock_db_session = Mock()
+ _mock_db_session.query.return_value = _mock_query
+
+ @contextmanager
+ def _fake_session(*args, **kwargs):
+ yield _mock_db_session
+
+ _routes_mod = "local_deep_research.web.routes.settings_routes"
+
+ patches = [
+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
+ patch(f"{_routes_mod}.get_user_db_session", side_effect=_fake_session),
+ patch(
+ f"{_routes_mod}.settings_limit", lambda f: f
+ ), # disable rate limit
+ ]
+
+ started = []
+ try:
+ for p in patches:
+ started.append(p.start())
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ sess["session_id"] = "test-session-id"
+ yield client, _mock_db_session
+ finally:
+ for p in patches:
+ p.stop()
+
+
+# ---------------------------------------------------------------------------
+# Blocked settings via HTTP
+# ---------------------------------------------------------------------------
+
+
+class TestBlockedSettingsHTTP:
+ """POST save_all_settings with blocked settings returns 403."""
+
+ def test_blocked_module_path_returns_403(self):
+ """Setting containing 'module_path' is blocked."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, _):
+ resp = client.post(
+ "/settings/save_all_settings",
+ json={"search.custom_engine.module_path": "/evil/path"},
+ content_type="application/json",
+ )
+ assert resp.status_code == 403
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert "Security violation" in data["message"]
+
+ def test_blocked_class_name_returns_403(self):
+ """Setting containing 'class_name' is blocked."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, _):
+ resp = client.post(
+ "/settings/save_all_settings",
+ json={"search.handler_class_name": "EvilClass"},
+ content_type="application/json",
+ )
+ assert resp.status_code == 403
+
+ def test_mixed_blocked_and_valid_returns_403(self):
+ """Mixed blocked + valid settings returns 403 (nothing saved)."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, mock_session):
+ resp = client.post(
+ "/settings/save_all_settings",
+ json={
+ "llm.temperature": 0.5,
+ "search.module_path": "/evil",
+ },
+ content_type="application/json",
+ )
+ assert resp.status_code == 403
+ # Verify nothing was saved (set_setting should NOT be called)
+
+ def test_blocked_error_lists_keys(self):
+ """Error response lists which keys were blocked."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, _):
+ resp = client.post(
+ "/settings/save_all_settings",
+ json={"search.module_path": "/evil", "llm.class_name": "Bad"},
+ content_type="application/json",
+ )
+ data = resp.get_json()
+ assert resp.status_code == 403
+ blocked_keys = [e["key"] for e in data["errors"]]
+ assert "search.module_path" in blocked_keys
+ assert "llm.class_name" in blocked_keys
+
+
+# ---------------------------------------------------------------------------
+# Corrupted value auto-correction via HTTP
+# ---------------------------------------------------------------------------
+
+
+class TestSaveAllSettingsValidation:
+ """Additional HTTP tests for save_all_settings endpoint."""
+
+ def test_empty_json_body_returns_400(self):
+ """POST with empty JSON object triggers 'No settings data provided'."""
+ app = _create_test_app()
+ with _authenticated_client(app) as (client, _):
+ resp = client.post(
+ "/settings/save_all_settings",
+ json={},
+ content_type="application/json",
+ )
+ # Empty dict is falsy, so save_all_settings returns 400
+ assert resp.status_code == 400
+ data = resp.get_json()
+ assert data["status"] == "error"
+ assert "No settings data" in data["message"]