~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Test/comprehensive citation formatter tests (#589)
LearningCircuitfeeb2c597d41
diff --git a/tests/citation_bugs/README.md b/tests/citation_bugs/README.mdnew file mode 100644index 0000000000..eddeb9e127--- /dev/null+++ b/tests/citation_bugs/README.md@@ -0,0 +1,39 @@+# Citation Formatting Bugs++This folder contains tests for known bugs in the citation formatting system.++## Bug: Multiple Citations to Same Source++### Description+When using non-IEEE citation formats (domain-based formats), if a source is cited multiple times, the system might incorrectly revert to IEEE-style numbering [1] instead of maintaining the selected format.++### Expected Behavior+- **Domain format**: All citations to `arxiv.org/abs/1234` should appear as `[arxiv.org]`+- **Domain ID format**: Should use `[arxiv.org-1]` consistently when there are multiple arxiv sources+- **Domain ID Always format**: Should always use `[arxiv.org-1]` even for single sources++### Current Behavior+The citation formatter might mix formats or revert to IEEE-style `[1]` numbering when the same source is cited multiple times.++### Test Coverage+- `test_multiple_citations_bug.py` - Contains comprehensive tests for this issue++## Running the Tests++```bash+# Run all citation bug tests+pdm run pytest tests/citation_bugs/ -v++# Run specific test+pdm run pytest tests/citation_bugs/test_multiple_citations_bug.py -v+```++## Notes+The current implementation doesn't actually have IEEE/APA/MLA citation styles. The available modes are:+- `NUMBER_HYPERLINKS`: [1] with hyperlinks+- `DOMAIN_HYPERLINKS`: [arxiv.org] with hyperlinks+- `DOMAIN_ID_HYPERLINKS`: Smart numbering - [arxiv.org] or [arxiv.org-1]+- `DOMAIN_ID_ALWAYS_HYPERLINKS`: Always numbered - [arxiv.org-1]+- `NO_HYPERLINKS`: [1] without hyperlinks++These control how citations appear in the text, not the bibliographic format of the references.\ No newline at end of filediff --git a/tests/citation_bugs/__init__.py b/tests/citation_bugs/__init__.pynew file mode 100644index 0000000000..cbc7bb3df3--- /dev/null+++ b/tests/citation_bugs/__init__.py@@ -0,0 +1 @@+"""Tests for citation formatting bugs."""\ No newline at end of filediff --git a/tests/citation_bugs/test_citation_edge_cases.py b/tests/citation_bugs/test_citation_edge_cases.pynew file mode 100644index 0000000000..92e127be4b--- /dev/null+++ b/tests/citation_bugs/test_citation_edge_cases.py@@ -0,0 +1,408 @@+"""+Comprehensive edge case tests for citation formatter to ensure robust handling+of various citation scenarios and malformed inputs.+"""++from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+)+++class TestCitationEdgeCases:+ """Test edge cases and potential bugs in citation formatting."""++ def test_multiple_citations_same_sentence(self):+ """Test multiple citations in the same sentence."""+ content = """# Research Report++Recent advances in AI [1] [2] have shown that transformers [3] [4] [5] are effective.++## Sources++[1] Attention Is All You Need+URL: https://arxiv.org/abs/1706.03762++[2] BERT Paper+URL: https://arxiv.org/abs/1810.04805++[3] GPT-3 Paper+URL: https://openai.com/research/gpt-3++[4] T5 Paper+URL: https://arxiv.org/abs/1910.10683++[5] RoBERTa Paper+URL: https://arxiv.org/abs/1907.11692"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should have correct number of citations+ assert result.count("[arxiv.org]") == 4 # sources 1, 2, 4, 5+ assert result.count("[openai.com]") == 1 # source 3++ # Original numbers should not appear in body+ body_text = result.split("## Sources")[0]+ for i in range(1, 6):+ assert f"[{i}]" not in body_text++ def test_citations_with_punctuation(self):+ """Test citations followed by various punctuation marks."""+ content = """# Research Report++This is proven [1]. Also shown [2], and demonstrated [3]; furthermore [4]: see [5]!++## Sources++[1] First Paper+URL: https://example.com/1++[2] Second Paper+URL: https://example.com/2++[3] Third Paper+URL: https://example.com/3++[4] Fourth Paper+URL: https://example.com/4++[5] Fifth Paper+URL: https://example.com/5"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)+ result = formatter.format_document(content)++ # All citations should be properly formatted+ assert "[[example.com-1]](https://example.com/1)." in result+ assert "[[example.com-2]](https://example.com/2)," in result+ assert "[[example.com-3]](https://example.com/3);" in result+ assert "[[example.com-4]](https://example.com/4):" in result+ assert "[[example.com-5]](https://example.com/5)!" in result++ def test_missing_url_in_source(self):+ """Test handling of sources without URLs."""+ content = """# Research Report++This cites a book [1] and a paper [2].++## Sources++[1] Deep Learning Book by Goodfellow et al.++[2] Neural Networks Paper+URL: https://nature.com/article"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Source with URL should be formatted+ assert "[nature.com]" in result+ # Source without URL should remain as-is+ assert "[1]" in result+ assert "Deep Learning Book" in result++ def test_malformed_source_section(self):+ """Test handling of malformed source sections."""+ content = """# Research Report++Citation here [1] and here [2].++## Sources++[1] Paper One+Some description+URL: https://arxiv.org/abs/1234.5678++[2] Paper Two URL: https://nature.com/123+Additional text++[3] Not cited in text+URL: https://unused.com/paper"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # The formatter's regex only captures URLs that are on the immediate next line+ # after the title line, starting with "URL:"++ # Source [1] has extra description line, so URL is not captured+ assert "[1]" in result # Citation remains unchanged+ assert "[arxiv.org]" not in result++ # Source [2] has inline URL which won't be parsed as a URL+ assert "[2]" in result # Remains unchanged+ assert "[nature.com]" not in result++ # Source [3] is properly formatted and would work if cited+ body = result.split("## Sources")[0]+ assert "[3]" not in body # Not cited in text++ def test_duplicate_urls_different_sources(self):+ """Test handling of multiple sources with the same URL."""+ content = """# Research Report++First reference [1] and second reference [2] to same paper.++## Sources++[1] Original Paper Title+URL: https://arxiv.org/abs/1706.03762++[2] Same Paper Different Title+URL: https://arxiv.org/abs/1706.03762"""++ formatter = CitationFormatter(+ mode=CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS+ )+ result = formatter.format_document(content)++ # Both should be formatted with IDs+ assert "[arxiv.org-1]" in result+ assert "[arxiv.org-2]" in result++ def test_citations_in_headers_and_lists(self):+ """Test citations in markdown headers and lists."""+ content = """# Research Report [1]++## Introduction with Citation [2]++- First point [3]+- Second point with reference [4]+ - Nested item [5]++### Subsection [6]++## Sources++[1] Header Paper+URL: https://example.com/1++[2] Intro Paper+URL: https://example.com/2++[3] List Item One+URL: https://example.com/3++[4] List Item Two+URL: https://example.com/4++[5] Nested Paper+URL: https://example.com/5++[6] Subsection Paper+URL: https://example.com/6"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)+ result = formatter.format_document(content)++ # All citations should be formatted, even in headers and lists+ for i in range(1, 7):+ assert f"[example.com-{i}]" in result+ assert f"[{i}]" not in result.split("## Sources")[0]++ def test_citations_in_code_blocks(self):+ """Test that citations inside code blocks are not formatted."""+ content = """# Research Report++This is a citation [1].++```python+# This [1] should not be formatted+def cite(ref):+ return f"[{ref}]" # [2] in string+```++Another citation [2].++## Sources++[1] First Paper+URL: https://arxiv.org/abs/1111.1111++[2] Second Paper+URL: https://nature.com/2222"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Citations outside code blocks should be formatted+ assert "[[arxiv.org]](https://arxiv.org/abs/1111.1111)" in result+ assert "[[nature.com]](https://nature.com/2222)" in result++ # Citations inside code blocks should remain unchanged+ assert "# This [1] should not be formatted" in result+ assert 'return f"[{ref}]" # [2] in string' in result++ def test_non_sequential_citations(self):+ """Test non-sequential citation numbers."""+ content = """# Research Report++Citations [5] and [1] and [10].++## Sources++[1] First Paper+URL: https://first.com/paper++[5] Fifth Paper+URL: https://fifth.com/paper++[10] Tenth Paper+URL: https://tenth.com/paper"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # All citations should be formatted correctly+ assert "[first.com]" in result+ assert "[fifth.com]" in result+ assert "[tenth.com]" in result++ # Original numbers should not remain+ body = result.split("## Sources")[0]+ assert "[1]" not in body+ assert "[5]" not in body+ assert "[10]" not in body++ def test_citations_with_special_urls(self):+ """Test citations with special characters in URLs."""+ content = """# Research Report++Various sources [1] [2] [3] [4].++## Sources++[1] DOI Paper+URL: https://doi.org/10.1234/journal.2023.12345++[2] Paper with Query+URL: https://example.com/search?q=machine+learning&filter=2023++[3] Paper with Fragment+URL: https://example.com/paper#section-3.2++[4] Paper with Port+URL: https://repository.edu:8080/papers/123"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # All domains should be extracted correctly+ assert "[doi.org]" in result+ assert "[example.com]" in result+ assert "[repository.edu]" in result++ def test_empty_and_whitespace_handling(self):+ """Test handling of empty content and various whitespace."""+ # Empty content+ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ assert formatter.format_document("") == ""++ # Only whitespace+ assert formatter.format_document(" \n\n \t") == " \n\n \t"++ # No sources section+ content = "This has a citation [1] but no sources."+ assert formatter.format_document(content) == content++ def test_case_sensitivity_in_sources_header(self):+ """Test various cases for Sources section header."""+ test_cases = [+ "## Sources",+ "## SOURCES",+ "## sources",+ "## Sources:",+ "##Sources",+ "## References", # Should not match+ ]++ for header in test_cases[:4]:+ content = f"""Citation [1].++{header}++[1] Paper+URL: https://example.com/1"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ if "References" not in header:+ assert "[example.com]" in result+ else:+ assert "[1]" in result # Should remain unchanged++ def test_unicode_and_international_domains(self):+ """Test handling of unicode and international domains."""+ content = """# Research Report++Chinese research [1], Russian study [2], and emoji domain [3].++## Sources++[1] 中文论文+URL: https://研究.中国/paper++[2] Русская статья+URL: https://наука.рф/article++[3] Modern Paper+URL: https://👍.ws/research"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should handle international domains+ assert "[研究.中国]" in result or "[xn--" in result # Punycode+ assert "[наука.рф]" in result or "[xn--" in result+ assert "[👍.ws]" in result or "[xn--" in result++ def test_very_long_urls(self):+ """Test handling of very long URLs."""+ long_path = "a" * 500+ content = f"""# Research Report++Long URL citation [1].++## Sources++[1] Paper with Long URL+URL: https://example.com/{long_path}"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should handle long URLs without issues+ assert "[example.com]" in result+ assert long_path in result # URL should be preserved in sources++ def test_multiple_source_sections(self):+ """Test document with multiple sections that look like sources."""+ content = """# Research Report++Main citation [1].++## Sources++[1] Real Source+URL: https://real.com/paper++## Other Sources (not formatted)++[2] This should not be formatted+URL: https://notformatted.com++Back to text [2].++## Sources Again++This section also has [3] which shouldn't format."""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Only first Sources section should be used+ assert "[real.com]" in result+ assert "[2]" in result # Should remain as-is+ assert "[notformatted.com]" not in resultdiff --git a/tests/citation_bugs/test_citation_error_handling.py b/tests/citation_bugs/test_citation_error_handling.pynew file mode 100644index 0000000000..b21b290d44--- /dev/null+++ b/tests/citation_bugs/test_citation_error_handling.py@@ -0,0 +1,381 @@+"""+Tests for citation formatter error handling and malformed input scenarios.+"""++from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+)+++class TestCitationErrorHandling:+ """Test error handling and resilience of citation formatter."""++ def test_malformed_citation_brackets(self):+ """Test handling of malformed citation brackets."""+ content = """# Research Report++Good citation [1], broken citation [2, missing citation ]3[,+reversed [4[ and double [[5]].++## Sources++[1] Good Paper+URL: https://example.com/1++[2] Second Paper+URL: https://example.com/2++[3] Third Paper+URL: https://example.com/3++[4] Fourth Paper+URL: https://example.com/4++[5] Fifth Paper+URL: https://example.com/5"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Good citations should be formatted+ assert "[example.com]" in result++ # Malformed citations should be left as-is+ assert "[2," in result # Broken bracket+ assert "]3[" in result # Reversed brackets+ assert "[4[" in result # Double opening++ def test_invalid_citation_numbers(self):+ """Test handling of invalid citation numbers."""+ content = """# Research Report++Valid [1], invalid [0], [999], [-1], [abc], [1.5], [ 2 ].++## Sources++[1] Only Valid Source+URL: https://example.com/valid++[2] Second Source+URL: https://example.com/2"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Valid citation should be formatted+ assert "[[example.com]](https://example.com/valid)" in result++ # Invalid citations should remain+ assert "[0]" in result+ assert "[999]" in result+ assert "[-1]" in result+ assert "[abc]" in result+ assert "[1.5]" in result++ # Citation with spaces might be processed+ # body = result.split("## Sources")[0]+ # [ 2 ] with spaces is an edge case - formatter might or might not handle it++ def test_circular_and_self_referencing(self):+ """Test handling of circular references in sources."""+ content = """# Research Report++Citation [1] refers to [2].++## Sources++[1] First Paper [2]+URL: https://first.com++[2] Second Paper [1]+URL: https://second.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should format main text citations+ assert "[first.com]" in result+ assert "[second.com]" in result++ # Should not format citations within source descriptions+ sources_section = result.split("## Sources")[1]+ assert "[1] First Paper [2]" in sources_section+ assert "[2] Second Paper [1]" in sources_section++ def test_missing_source_numbers(self):+ """Test handling when source numbers are missing."""+ content = """# Research Report++Citations [1], [2], [3].++## Sources++[1] First Paper+URL: https://first.com++[3] Third Paper (note: [2] is missing)+URL: https://third.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Existing sources should be formatted+ assert "[first.com]" in result+ assert "[third.com]" in result++ # Missing source [2] should remain as-is+ assert "[2]" in result++ def test_duplicate_source_numbers(self):+ """Test handling of duplicate source numbers."""+ content = """# Research Report++Citations [1] and another [1].++## Sources++[1] First Paper+URL: https://first.com++[1] Duplicate Paper+URL: https://duplicate.com++[2] Normal Paper+URL: https://second.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should handle duplicates (typically takes first occurrence)+ # The specific behavior depends on implementation+ assert "[first.com]" in result or "[duplicate.com]" in result++ def test_sources_without_numbers(self):+ """Test handling of sources without proper numbering."""+ content = """# Research Report++Citation [1].++## Sources++[1] Proper Source+URL: https://proper.com++Missing Number Source+URL: https://missing.com++[] Empty Brackets+URL: https://empty.com++[a] Letter Instead+URL: https://letter.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Properly numbered source should work+ assert "[proper.com]" in result++ # Improperly formatted sources should be ignored+ assert "[missing.com]" not in result+ assert "[empty.com]" not in result+ assert "[letter.com]" not in result++ def test_nested_brackets_and_escaping(self):+ """Test handling of nested brackets and escaped characters."""+ content = r"""# Research Report++Normal [1], escaped \[2\], nested [[3]], and markdown [link](url) [4].++## Sources++[1] First+URL: https://first.com++[2] Second+URL: https://second.com++[3] Third+URL: https://third.com++[4] Fourth+URL: https://fourth.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Normal citation should work+ assert "[first.com]" in result++ # Escaped brackets should be preserved+ assert r"\[2\]" in result++ # Markdown links should not interfere+ assert "[link](url)" in result++ def test_malformed_urls(self):+ """Test handling of malformed URLs in sources."""+ content = """# Research Report++Citations [1] [2] [3] [4] [5].++## Sources++[1] No Protocol+URL: example.com/paper++[2] Invalid Protocol+URL: htp://example.com/paper++[3] Just Domain+URL: https://example.com++[4] Spaces in URL+URL: https://example.com/my paper.pdf++[5] Missing URL Label+https://example.com/nolabel"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Well-formed URLs should work+ assert result.count("[example.com]") >= 1++ # Malformed URLs might not be processed correctly+ # The specific behavior depends on URL parsing implementation++ def test_special_markdown_interference(self):+ """Test that special markdown doesn't interfere with citations."""+ content = """# Research Report++**Bold [1]**, *italic [2]*, `code [3]`, ~~strike [4]~~.++> Quote [5]+> Multiple lines++| Table | Cell [6] |+|-------|----------|+| Data | [7] |++## Sources++[1] Bold Source+URL: https://bold.com++[2] Italic Source+URL: https://italic.com++[3] Code Source+URL: https://code.com++[4] Strike Source+URL: https://strike.com++[5] Quote Source+URL: https://quote.com++[6] Table Source+URL: https://table.com++[7] Cell Source+URL: https://cell.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # All citations should be formatted despite markdown+ domains = [+ "bold.com",+ "italic.com",+ "code.com",+ "strike.com",+ "quote.com",+ "table.com",+ "cell.com",+ ]++ for domain in domains:+ assert f"[{domain}]" in result++ def test_extremely_long_content(self):+ """Test handling of very long documents."""+ # Create a document with many citations+ citations = []+ sources = []++ for i in range(1, 101):+ citations.append(f"Citation [{i}]")+ sources.append(f"""[{i}] Source {i}+URL: https://example{i}.com/paper""")++ content = f"""# Large Document++{" ".join(citations)}++## Sources++{chr(10).join(sources)}"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)+ result = formatter.format_document(content)++ # Should handle all citations+ for i in range(1, 101):+ assert f"[example{i}.com" in result++ def test_source_url_edge_cases(self):+ """Test edge cases in URL detection within sources."""+ content = """# Research Report++Citations [1] [2] [3].++## Sources++[1] Multiple URLs+URL: https://first.com+Also available at: https://mirror.com++[2] URL in Middle+Paper Title URL: https://second.com more text++[3] Commented URL+# URL: https://commented.com+URL: https://actual.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should pick up the first URL after "URL:"+ assert "[first.com]" in result+ assert "[second.com]" in result+ assert "[actual.com]" in result+ assert "[commented.com]" not in result++ def test_mixed_citation_styles(self):+ """Test documents with mixed citation styles."""+ content = """# Research Report++IEEE style [1], parenthetical (Smith, 2023), footnote[^1], and [2].++## Sources++[1] First Paper+URL: https://first.com++[2] Second Paper+URL: https://second.com++[^1]: This is a footnote, not a citation source."""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should only format numbered citations+ assert "[first.com]" in result+ assert "[second.com]" in result++ # Other citation styles should remain+ assert "(Smith, 2023)" in result+ assert "[^1]" in resultdiff --git a/tests/citation_bugs/test_citation_export_formats.py b/tests/citation_bugs/test_citation_export_formats.pynew file mode 100644index 0000000000..38d9600368--- /dev/null+++ b/tests/citation_bugs/test_citation_export_formats.py@@ -0,0 +1,332 @@+"""+Tests for citation export formats (RIS, LaTeX, Quarto) to ensure+they handle edge cases correctly.+"""++import pytest+from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+ RISExporter,+ LaTeXExporter,+ QuartoExporter,+)+++class TestCitationExportFormats:+ """Test various export formats for citations."""++ def test_ris_export_with_multiple_citations(self):+ """Test RIS export handles multiple citations to same source."""+ content = """# Research Report++Multiple citations [1] to same [1] source [1]. And another [2].++## Sources++[1] Machine Learning Paper+URL: https://arxiv.org/abs/2023.12345++[2] Nature Article+URL: https://nature.com/articles/s41586-023-06789-9"""++ exporter = RISExporter()+ ris_output = exporter.export_to_ris(content)++ # Should have exactly 2 RIS entries (not 3)+ assert ris_output.count("TY - ELEC") == 2+ assert ris_output.count("ER -") == 2++ # Should include both URLs+ assert "https://arxiv.org/abs/2023.12345" in ris_output+ assert "https://nature.com/articles/s41586-023-06789-9" in ris_output++ def test_ris_export_with_special_characters(self):+ """Test RIS export handles special characters properly."""+ content = """# Research Report++Citation [1] with special chars.++## Sources++[1] Paper with Special Chars: Ñoño, Müller & 中文+URL: https://example.com/special-chars?param=value&other=test"""++ exporter = RISExporter()+ ris_output = exporter.export_to_ris(content)++ # Should handle special characters+ assert "Ñoño" in ris_output+ assert "Müller" in ris_output+ assert "中文" in ris_output+ assert "param=value&other=test" in ris_output++ def test_latex_export_with_equations(self):+ """Test LaTeX export with equations in content."""+ content = r"""# Research Report++The equation $E = mc^2$ from [1] shows mass-energy equivalence.++Consider the integral $$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$ from [2].++## Sources++[1] Einstein's Original Paper+URL: https://physics.org/einstein-1905++[2] Mathematical Methods+URL: https://math.edu/integrals"""++ exporter = LaTeXExporter()+ latex_output = exporter.export_to_latex(content)++ # Should preserve math mode+ assert r"$E = mc^2$" in latex_output+ assert r"$$\int_0^\infty" in latex_output++ # Should have proper bibliography+ assert r"\bibitem{1}" in latex_output+ assert r"\bibitem{2}" in latex_output++ def test_latex_export_special_characters_escaping(self):+ """Test LaTeX export properly escapes special characters."""+ content = """# Research Report++Citation [1] with special LaTeX chars: $, %, &, #, _, {, }.++## Sources++[1] Paper & Title with % Special # Chars+URL: https://example.com/paper_with_underscore"""++ exporter = LaTeXExporter()+ latex_output = exporter.export_to_latex(content)++ # Should escape special LaTeX characters in text+ assert r"\%" in latex_output+ assert r"\&" in latex_output+ assert r"\#" in latex_output+ assert (+ r"\_" in latex_output or "_" in latex_output+ ) # URLs might not be escaped++ def test_quarto_export_with_metadata(self):+ """Test Quarto export includes proper metadata."""+ content = """# Deep Learning Research Report++This reviews [1] and extends [2].++## Sources++[1] Attention Is All You Need+URL: https://arxiv.org/abs/1706.03762++[2] BERT: Pre-training of Deep Bidirectional Transformers+URL: https://arxiv.org/abs/1810.04805"""++ exporter = QuartoExporter()+ quarto_output = exporter.export_to_quarto(content)++ # Should have YAML frontmatter+ assert "---" in quarto_output+ assert "title:" in quarto_output+ assert "bibliography:" in quarto_output++ # Should extract title+ assert "Deep Learning Research Report" in quarto_output++ # Should have citations in Quarto format+ assert "[@cite1]" in quarto_output or "@cite1" in quarto_output+ assert "[@cite2]" in quarto_output or "@cite2" in quarto_output++ def test_export_with_missing_sources_section(self):+ """Test export formats handle missing sources section gracefully."""+ content = """# Research Report++This has citations [1] and [2] but no sources section."""++ # Test RIS+ ris_exporter = RISExporter()+ ris_output = ris_exporter.export_to_ris(content)+ assert ris_output == "" # Should return empty for no sources++ # Test LaTeX+ latex_exporter = LaTeXExporter()+ latex_output = latex_exporter.export_to_latex(content)+ assert "bibliography" not in latex_output.lower()++ # Test Quarto+ quarto_exporter = QuartoExporter()+ quarto_output = quarto_exporter.export_to_quarto(content)+ # Should still have content but no bibliography+ assert "This has citations" in quarto_output++ def test_export_with_duplicate_urls(self):+ """Test export formats handle duplicate URLs correctly."""+ content = """# Report++Cite [1] and [2].++## Sources++[1] First Title+URL: https://same.url/paper++[2] Different Title Same URL+URL: https://same.url/paper"""++ # RIS should have separate entries+ ris_exporter = RISExporter()+ ris_output = ris_exporter.export_to_ris(content)+ assert ris_output.count("TY - ELEC") == 2+ assert ris_output.count("https://same.url/paper") == 2++ # LaTeX should have separate bibitems+ latex_exporter = LaTeXExporter()+ latex_output = latex_exporter.export_to_latex(content)+ assert r"\bibitem{1}" in latex_output+ assert r"\bibitem{2}" in latex_output++ def test_export_preserves_markdown_structure(self):+ """Test that exports preserve document structure."""+ content = """# Main Title++## Introduction++This is **bold** and *italic* text [1].++### Subsection++- List item [2]+- Another item+ - Nested [3]++## Sources++[1] Source One+URL: https://one.com++[2] Source Two+URL: https://two.com++[3] Source Three+URL: https://three.com"""++ # Test LaTeX preserves structure+ latex_exporter = LaTeXExporter()+ latex_output = latex_exporter.export_to_latex(content)+ assert r"\section" in latex_output+ assert r"\subsection" in latex_output+ assert r"\textbf{bold}" in latex_output+ assert r"\textit{italic}" in latex_output+ assert r"\begin{itemize}" in latex_output++ def test_quarto_bibliography_generation(self):+ """Test Quarto generates proper bibliography entries."""+ content = """# Research++Citation [1].++## Sources++[1] 2023 AI Paper by Smith, J. and Doe, J.+URL: https://ai-journal.com/2023/paper"""++ exporter = QuartoExporter()+ quarto_output = exporter.export_to_quarto(content)++ # Should generate a references section+ assert "references:" in quarto_output.lower() or "@" in quarto_output++ def test_export_with_malformed_content(self):+ """Test exports handle malformed content gracefully."""+ content = """# Report++[1] [2 [3]] [[4]++## Sources++[1 Source One+URL: https://one.com++[2] Source Two+No URL++[3]+URL: https://three.com"""++ # All exporters should handle this without crashing+ exporters = [RISExporter(), LaTeXExporter(), QuartoExporter()]++ for exporter in exporters:+ try:+ if isinstance(exporter, RISExporter):+ output = exporter.export_to_ris(content)+ elif isinstance(exporter, LaTeXExporter):+ output = exporter.export_to_latex(content)+ elif isinstance(exporter, QuartoExporter):+ output = exporter.export_to_quarto(content)+ assert output is not None+ except Exception as e:+ pytest.fail(+ f"{exporter.__class__.__name__} failed on malformed content: {e}"+ )++ def test_ris_export_field_extraction(self):+ """Test RIS export extracts various metadata fields."""+ content = """# Report++Citation [1].++## Sources++[1] Deep Learning in Nature 2023 by LeCun, Y., Bengio, Y., & Hinton, G.+Published in Nature Machine Intelligence, Volume 5, Pages 123-145+DOI: 10.1038/s42256-023-00001-2+URL: https://nature.com/articles/s42256-023-00001-2"""++ exporter = RISExporter()+ ris_output = exporter.export_to_ris(content)++ # Should extract various fields+ assert "TI - Deep Learning in Nature 2023" in ris_output+ assert "AU - LeCun, Y." in ris_output or "LeCun" in ris_output+ assert "PY - 2023" in ris_output+ assert "DO - 10.1038/s42256-023-00001-2" in ris_output++ def test_concurrent_export_formats(self):+ """Test that different export formats can be used concurrently."""+ content = """# Research++Multiple [1] citations [1] here [2].++## Sources++[1] First Paper+URL: https://first.com++[2] Second Paper+URL: https://second.com"""++ # Format for different uses+ formatter_domain = CitationFormatter(+ mode=CitationMode.DOMAIN_HYPERLINKS+ )+ formatted_domain = formatter_domain.format_document(content)++ formatter_number = CitationFormatter(+ mode=CitationMode.NUMBER_HYPERLINKS+ )+ formatted_number = formatter_number.format_document(content)++ # Export to different formats+ ris_output = RISExporter().export_to_ris(content)+ latex_output = LaTeXExporter().export_to_latex(content)+ quarto_output = QuartoExporter().export_to_quarto(content)++ # All should work independently+ assert "[first.com]" in formatted_domain+ assert "[[1]](https://first.com)" in formatted_number+ assert "TY - ELEC" in ris_output+ assert r"\bibitem" in latex_output+ assert "bibliography" in quarto_output or "@" in quarto_outputdiff --git a/tests/citation_bugs/test_citation_performance.py b/tests/citation_bugs/test_citation_performance.pynew file mode 100644index 0000000000..d09613f5a9--- /dev/null+++ b/tests/citation_bugs/test_citation_performance.py@@ -0,0 +1,343 @@+"""+Performance tests for citation formatter to ensure it handles large documents efficiently.+"""++import time+import pytest+from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+)+++class TestCitationPerformance:+ """Test performance of citation formatter with large documents."""++ def test_many_citations_performance(self):+ """Test performance with many citations."""+ # Generate content with 1000 citations+ citations = []+ sources = []++ for i in range(1, 1001):+ # Mix up citation patterns+ if i % 3 == 0:+ citations.append(f"Multiple [{i}] citations [{i}] here [{i}]")+ else:+ citations.append(f"Single citation [{i}]")++ sources.append(f"""[{i}] Source {i} Title+URL: https://example{i % 100}.com/paper/{i}""")++ content = f"""# Large Document Performance Test++{" ".join(citations)}++## Sources++{chr(10).join(sources)}"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)++ start_time = time.time()+ result = formatter.format_document(content)+ end_time = time.time()++ processing_time = end_time - start_time++ # Should complete in reasonable time (less than 5 seconds for 1000 citations)+ assert processing_time < 5.0, (+ f"Processing took {processing_time:.2f}s, which is too slow"+ )++ # Should have formatted all citations+ for i in range(100):+ assert f"[example{i}.com]" in result++ def test_long_document_performance(self):+ """Test performance with very long documents."""+ # Create a 100KB document+ paragraphs = []++ for i in range(200):+ paragraph = f"""+This is paragraph {i} with some citations [{i % 50 + 1}] and more text to make+it longer. The citation [{i % 50 + 1}] appears multiple times in this paragraph.+Sometimes we reference [{(i + 1) % 50 + 1}] as well. This helps test performance+with realistic document sizes and citation patterns.+"""+ paragraphs.append(paragraph)++ # Add sources+ sources = []+ for i in range(1, 51):+ sources.append(f"""[{i}] Academic Paper {i}+URL: https://journal{i % 10}.com/article/{i}""")++ content = f"""# Very Long Document++{"".join(paragraphs)}++## Sources++{chr(10).join(sources)}"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)++ start_time = time.time()+ result = formatter.format_document(content)+ end_time = time.time()++ processing_time = end_time - start_time++ # Should handle large documents efficiently+ assert processing_time < 10.0, (+ f"Processing took {processing_time:.2f}s for large document"+ )++ # Verify formatting worked+ assert "[journal0.com" in result+ assert "[journal9.com" in result++ def test_deeply_nested_markdown_performance(self):+ """Test performance with deeply nested markdown structures."""+ # Create nested lists with citations+ nested_content = """# Document with Nested Structure++"""++ for i in range(10):+ nested_content += f"{' ' * i}- Level {i} item [{i + 1}]\n"+ nested_content += (+ f"{' ' * i} - Sub-item with citation [{i + 11}]\n"+ )+ nested_content += f"{' ' * i} - Deep sub-item [{i + 21}]\n"++ # Add complex markdown+ nested_content += """+| Header 1 [31] | Header 2 [32] | Header 3 [33] |+|---------------|---------------|---------------|+| Cell [34] | Cell [35] | Cell [36] |+| Cell [37] | Cell [38] | Cell [39] |++> Blockquote level 1 [40]+>> Blockquote level 2 [41]+>>> Blockquote level 3 [42]++"""++ # Add sources+ sources = []+ for i in range(1, 43):+ sources.append(+ f"[{i}] Source {i}\nURL: https://site{i % 5}.com/{i}"+ )++ content = nested_content + "\n## Sources\n\n" + "\n\n".join(sources)++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)++ start_time = time.time()+ result = formatter.format_document(content)+ end_time = time.time()++ processing_time = end_time - start_time++ # Should handle complex structure efficiently+ assert processing_time < 2.0, (+ f"Processing complex structure took {processing_time:.2f}s"+ )++ # Verify citations in various contexts were formatted+ assert "[site0.com]" in result+ assert "[site4.com]" in result++ def test_repeated_formatting_performance(self):+ """Test performance when formatting the same document multiple times."""+ content = """# Document++Citations [1] and [2] and [3].++## Sources++[1] First+URL: https://first.com++[2] Second+URL: https://second.com++[3] Third+URL: https://third.com"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)++ # Format 100 times+ start_time = time.time()+ for _ in range(100):+ formatter.format_document(content)+ end_time = time.time()++ total_time = end_time - start_time+ avg_time = total_time / 100++ # Average time should be very fast+ assert avg_time < 0.01, (+ f"Average formatting time {avg_time:.4f}s is too slow"+ )++ def test_citation_modes_performance_comparison(self):+ """Compare performance across different citation modes."""+ # Create test document+ citations = [f"Citation [{i}]" for i in range(1, 101)]+ sources = [+ f"[{i}] Source {i}\nURL: https://domain{i % 20}.com/{i}"+ for i in range(1, 101)+ ]++ content = f"""# Performance Test++{" ".join(citations)}++## Sources++{chr(10).join(sources)}"""++ modes = [+ CitationMode.NUMBER_HYPERLINKS,+ CitationMode.DOMAIN_HYPERLINKS,+ CitationMode.DOMAIN_ID_HYPERLINKS,+ CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS,+ CitationMode.NO_HYPERLINKS,+ ]++ times = {}++ for mode in modes:+ formatter = CitationFormatter(mode=mode)++ start_time = time.time()+ formatter.format_document(content)+ end_time = time.time()++ times[mode.value] = end_time - start_time++ # All modes should complete quickly+ for mode_name, duration in times.items():+ assert duration < 1.0, f"Mode {mode_name} took {duration:.3f}s"++ # Performance shouldn't vary drastically between modes+ max_time = max(times.values())+ min_time = min(times.values())+ # Allow more variance as some modes do more work+ if min_time > 0:+ assert max_time / min_time < 10.0, (+ f"Performance varies too much between modes: {times}"+ )++ def test_memory_efficiency_large_content(self):+ """Test that formatter doesn't use excessive memory."""+ # Create a large document (10MB+)+ large_text = "This is a test paragraph. " * 10000++ content = f"""# Large Document++{large_text}++Citation at the end [1].++## Sources++[1] Only Source+URL: https://example.com/source"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)++ # Should handle large content without issues+ try:+ start_time = time.time()+ result = formatter.format_document(content)+ end_time = time.time()++ # Should complete even with large content+ assert "[example.com]" in result+ assert end_time - start_time < 5.0++ except MemoryError:+ pytest.fail("Formatter used too much memory")++ @pytest.mark.parametrize("num_sources", [10, 50, 100, 500])+ def test_scaling_with_source_count(self, num_sources):+ """Test how performance scales with number of sources."""+ # Create content with varying number of sources+ citations = []+ sources = []++ # Each source cited 3 times+ for i in range(1, num_sources + 1):+ citations.extend([f"[{i}]", f"[{i}]", f"[{i}]"])+ sources.append(f"[{i}] Source {i}\nURL: https://example.com/{i}")++ content = f"""# Scaling Test++Citations: {" ".join(citations)}++## Sources++{chr(10).join(sources)}"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)++ start_time = time.time()+ formatter.format_document(content)+ end_time = time.time()++ processing_time = end_time - start_time++ # Time should scale roughly linearly with source count+ expected_max_time = num_sources * 0.01 # 10ms per source max+ assert processing_time < expected_max_time, (+ f"Processing {num_sources} sources took {processing_time:.3f}s, "+ f"expected < {expected_max_time:.3f}s"+ )++ def test_regex_performance_edge_cases(self):+ """Test performance with content that might cause regex issues."""+ # Create content with patterns that could cause backtracking+ tricky_patterns = [+ "[" * 100 + "1" + "]" * 100, # Many brackets+ "[[[[1]]]]", # Nested brackets+ "[1][2][3][4][5]" * 50, # Many consecutive citations+ "[1] " + "." * 1000 + " [2]", # Long spans between citations+ ]++ sources = """+[1] Source 1+URL: https://one.com++[2] Source 2+URL: https://two.com++[3] Source 3+URL: https://three.com++[4] Source 4+URL: https://four.com++[5] Source 5+URL: https://five.com"""++ for pattern in tricky_patterns:+ content = f"# Test\n\n{pattern}\n\n## Sources\n{sources}"++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)++ start_time = time.time()+ try:+ formatter.format_document(content)+ end_time = time.time()++ # Should complete quickly even with tricky patterns+ assert end_time - start_time < 1.0++ except Exception as e:+ pytest.fail(f"Failed on pattern: {pattern[:50]}... Error: {e}")diff --git a/tests/citation_bugs/test_multiple_citations_bug.py b/tests/citation_bugs/test_multiple_citations_bug.pynew file mode 100644index 0000000000..8fefd77839--- /dev/null+++ b/tests/citation_bugs/test_multiple_citations_bug.py@@ -0,0 +1,223 @@+"""+Test for citation formatting bug with multiple citations to the same source.++This test reproduces a bug where when a source is cited multiple times+and the citation format is not IEEE-style (e.g., using domain-based formats),+the formatting might incorrectly default to IEEE-style numbering.+"""++import pytest+from tests.test_utils import add_src_to_path++# Add src to path+add_src_to_path()++from local_deep_research.text_optimization.citation_formatter import ( # noqa: E402+ CitationFormatter,+ CitationMode,+)+++class TestMultipleCitationsBug:+ """Test cases for the multiple citations formatting bug."""++ def test_domain_format_with_multiple_citations_same_source(self):+ """+ Test that domain-based citation format correctly handles multiple citations+ to the same source without reverting to IEEE-style numbering.+ """+ # Create test content with multiple citations to the same source+ content = """# Research Report++This is the first citation to arXiv [1]. Here is another citation+to the same arXiv paper [1]. And a third citation [1].++This is a citation to a different source [2].++## Sources++[1] Attention Is All You Need+URL: https://arxiv.org/abs/1706.03762++[2] BERT: Pre-training in Nature+URL: https://nature.com/articles/s41586-023-06785-z"""++ # Test with domain_hyperlinks mode+ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # All three citations to source 1 should be [arxiv.org]+ assert result.count("[arxiv.org]") == 3, (+ "Expected 3 instances of [arxiv.org] for multiple citations to same source, "+ f"but found {result.count('[arxiv.org]')}"+ )++ # One citation to source 2 should be [nature.com]+ assert result.count("[nature.com]") == 1, (+ "Expected 1 instance of [nature.com], "+ f"but found {result.count('[nature.com]')}"+ )++ # Should not contain any IEEE-style numbering [1] in body text+ body_text = result.split("## Sources")[0]+ assert "[1]" not in body_text, (+ "Found IEEE-style [1] citation in body when using domain format"+ )+ assert "[2]" not in body_text, (+ "Found IEEE-style [2] citation in body when using domain format"+ )++ def test_domain_id_format_with_multiple_citations_same_source(self):+ """+ Test domain_id format handles multiple citations to same source correctly.+ When there's only one source from a domain, it should use [domain.com],+ not [domain.com-1].+ """+ content = """# Research Report++First citation [1], second citation [1], third citation [1].+Citation to different paper from same domain [2].+Citation to different domain [3].++## Sources++[1] Paper One+URL: https://arxiv.org/abs/1706.03762++[2] Paper Two+URL: https://arxiv.org/abs/1810.04805++[3] Other Paper+URL: https://openai.com/blog/chatgpt"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_ID_HYPERLINKS)+ result = formatter.format_document(content)++ # With smart numbering, since there are 2 arxiv papers, should use numbered format+ assert "[arxiv.org-1]" in result, (+ "Expected [arxiv.org-1] for first arxiv paper"+ )+ assert "[arxiv.org-2]" in result, (+ "Expected [arxiv.org-2] for second arxiv paper"+ )++ # Single source from openai.com should just be [openai.com]+ assert "[openai.com]" in result, (+ "Expected [openai.com] for single openai source"+ )+ assert "[openai.com-1]" not in result, (+ "Should not add -1 for single source from domain"+ )++ # Should not have any plain number citations in body+ body_text = result.split("## Sources")[0]+ assert "[1]" not in body_text, "Found IEEE-style [1] citation in body"+ assert "[2]" not in body_text, "Found IEEE-style [2] citation in body"+ assert "[3]" not in body_text, "Found IEEE-style [3] citation in body"++ def test_consecutive_citations_different_sources(self):+ """Test that consecutive citations to different sources are handled correctly."""+ content = """# Research Report++Here are three consecutive citations [1][2][3].++## Sources++[1] Paper One+URL: https://arxiv.org/abs/1111.1111++[2] Paper Two+URL: https://nature.com/articles/2222++[3] Paper Three+URL: https://science.org/doi/3333"""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Should have three different domain citations+ assert "[arxiv.org]" in result+ assert "[nature.com]" in result+ assert "[science.org]" in result++ # Should not have any number citations in body+ body_text = result.split("## Sources")[0]+ assert "[1][2][3]" not in body_text+ assert "[1]" not in body_text+ assert "[2]" not in body_text+ assert "[3]" not in body_text++ def test_mixed_citation_formats_in_text(self):+ """Test handling of mixed citation formats like [1, 2, 3] vs [1][2][3]."""+ content = """# Research Report++Comma-separated citations [1, 2, 3].+Consecutive citations [1][2][3].+Single citations [1] and [2] and [3].++## Sources++[1] Paper One+URL: https://arxiv.org/abs/1111.1111++[2] Paper Two+URL: https://arxiv.org/abs/2222.2222++[3] Paper Three+URL: https://arxiv.org/abs/3333.3333"""++ formatter = CitationFormatter(+ mode=CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS+ )+ result = formatter.format_document(content)++ # All arxiv citations should be numbered consistently+ assert result.count("[arxiv.org-1]") == 3, (+ "Each citation to paper 1 should be [arxiv.org-1]"+ )+ assert result.count("[arxiv.org-2]") == 3, (+ "Each citation to paper 2 should be [arxiv.org-2]"+ )+ assert result.count("[arxiv.org-3]") == 3, (+ "Each citation to paper 3 should be [arxiv.org-3]"+ )++ # No plain numbers should remain in the body (before Sources section)+ body_text = result.split("## Sources")[0]+ for i in range(1, 4):+ assert f"[{i}]" not in body_text, (+ f"Found IEEE-style [{i}] citation in body"+ )++ def test_citation_format_preservation_in_sources_section(self):+ """Test that the Sources section format is preserved correctly."""+ content = """# Research Report++Citation one [1] and citation two [2].++## Sources++[1] Important Paper+URL: https://example.com/paper1++[2] Another Paper+URL: https://example.org/paper2++### References++Some additional references here."""++ formatter = CitationFormatter(mode=CitationMode.DOMAIN_HYPERLINKS)+ result = formatter.format_document(content)++ # Sources section should still have numbered format+ assert "[1] Important Paper" in result+ assert "[2] Another Paper" in result++ # But inline citations should be domain-based+ assert "[example.com]" in result+ assert "[example.org]" in result+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])