diff --git a/monitoring/health.py b/monitoring/health.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/monitoring/health.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/prompts/analysis_prompts.py b/prompts/analysis_prompts.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/prompts/analysis_prompts.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/rag/chunking.py b/rag/chunking.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/rag/chunking.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/rag/embeddings.py b/rag/embeddings.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/rag/embeddings.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/retrieval/hybrid_retriever.py b/retrieval/hybrid_retriever.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/retrieval/hybrid_retriever.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/retrieval/reranker.py b/retrieval/reranker.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/retrieval/reranker.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/conftest.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/end_to_end/test_analysis_e2e.py b/tests/end_to_end/test_analysis_e2e.py deleted file mode 100644 index 3248c9b3d320fa83cb69b02ad4cc10456a719faf..0000000000000000000000000000000000000000 --- a/tests/end_to_end/test_analysis_e2e.py +++ /dev/null @@ -1,69 +0,0 @@ -import pytest -import asyncio -import time -from unittest.mock import AsyncMock, Mock, patch -from loguru import logger - -from agents.analysis import AnalysisAgent - -pytestmark = pytest.mark.e2e - - -@pytest.mark.asyncio -async def test_analysis_agent_end_to_end_success( - langgraph_state_factory, - high_cred_paper, - contradictory_passages, - valid_llm_response_json, -): - agent = AnalysisAgent() - - # Create a state with one paper and passages - state = langgraph_state_factory( - filtered_papers=[high_cred_paper], relevant_passages=contradictory_passages - ) - - # Patch contradiction detector LLM call to return a valid JSON string - agent.contradiction_detector._call_llm_with_fallback = AsyncMock( - return_value=valid_llm_response_json - ) - - start = time.time() - result = await agent.analyze(state) - elapsed = time.time() - start - - # Basic contract: returns credibility_scores and contradictions - assert "credibility_scores" in result - assert "contradictions" in result - assert len(result["credibility_scores"]) == 1 - # Execution time expected under 8s for e2e test (mocked LLM) - assert result["execution_times"]["analysis_agent"] < 8.0 - assert elapsed < 8.0 - - -@pytest.mark.asyncio -async def test_analysis_agent_partial_failure_credibility_ok_contradiction_fails( - langgraph_state_factory, high_cred_paper, contradictory_passages -): - agent = AnalysisAgent() - state = langgraph_state_factory( - filtered_papers=[high_cred_paper], relevant_passages=contradictory_passages - ) - - # Make contradiction detection raise to simulate provider failure - async def raise_err(*args, **kwargs): - raise RuntimeError("LLM provider down") - - agent.contradiction_detector.detect_contradictions = AsyncMock( - side_effect=raise_err - ) - - # Patch logger.error to capture that an error was logged - with patch.object(logger, "error", Mock()) as mock_err: - result = await agent.analyze(state) - # Credibility should still be present - assert len(result["credibility_scores"]) == 1 - # Contradictions should be empty list on failure - assert result["contradictions"] == [] - # Error should have been logged - assert mock_err.called diff --git a/tests/fixtures.py b/tests/fixtures.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/fixtures.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/fixtures/analysis_fixtures.py b/tests/fixtures/analysis_fixtures.py deleted file mode 100644 index 70b02c199acb2f73d5b8f65f4d2925e2b55705b2..0000000000000000000000000000000000000000 --- a/tests/fixtures/analysis_fixtures.py +++ /dev/null @@ -1,469 +0,0 @@ -import json -import pytest -import numpy as np -from unittest.mock import Mock, MagicMock -from datetime import datetime - -from models.state import ( - Paper, - Passage, - State, - ProcessingConfig, - PDFContent, - ErrorReport, - Score, -) - - -@pytest.fixture -def high_cred_paper_dict(): - return { - "paper_id": "nature_2023", - "citation_count": 250, - "year": 2023, - "journal": "Nature", - } - - -@pytest.fixture -def medium_cred_paper_dict(): - return { - "paper_id": "mid_2020", - "citation_count": 45, - "year": 2020, - "journal": "Journal of Testing", - } - - -@pytest.fixture -def low_cred_paper_dict(): - return { - "paper_id": "preprint_2015", - "citation_count": 3, - "year": 2015, - "journal": "arXiv", - } - - -@pytest.fixture -def high_cred_paper(): - return Paper( - paper_id="nature_2023", - title="Great discovery", - authors=["A"], - year=2023, - journal="Nature", - citation_count=250, - pdf_url=None, - type="article", - ) - - -@pytest.fixture -def medium_cred_paper(): - return Paper( - paper_id="mid_2020", - title="Mid work", - authors=["B"], - year=2020, - journal="Journal of Testing", - citation_count=45, - pdf_url=None, - type="article", - ) - - -@pytest.fixture -def low_cred_paper(): - return Paper( - paper_id="preprint_2015", - title="Early draft", - authors=["C"], - year=2015, - journal="arXiv", - citation_count=3, - pdf_url=None, - type="article", - ) - - -@pytest.fixture -def contradictory_passages(): - # Two passages with opposing claims - p1 = Passage( - content="We found that drug X increases survival by 50%.", - section="results", - paper_id="p1", - retrieval_score=0.95, - ) - p2 = Passage( - content="Our analysis shows drug X has no effect on survival.", - section="results", - paper_id="p2", - retrieval_score=0.93, - ) - return [p1, p2] - - -@pytest.fixture -def valid_llm_response_json(): - # Minimal valid DetectedContradiction list as JSON string - data = [ - { - "topic": "effect_of_drug_x", - "claim_1": {"paper_id": "p1", "text": "drug X increases survival"}, - "claim_2": {"paper_id": "p2", "text": "drug X has no effect"}, - "severity": "major", - } - ] - return json.dumps(data) - - -@pytest.fixture -def malformed_llm_response(): - return "{this is: not valid json]" - - -@pytest.fixture -def langgraph_state_factory(): - def _factory( - filtered_papers=None, relevant_passages=None, query="What about drug X?" - ): - state = State(original_query=query) - if filtered_papers: - state.filtered_papers = filtered_papers - if relevant_passages: - state.relevant_passages = relevant_passages - # Minimal execution_times container - state.execution_times = {} - state.config = ProcessingConfig() - return state - - return _factory - - -# --- Fixtures migrated from legacy tests/fixtures.py --- - - -@pytest.fixture -def initial_state() -> State: - """Provides a basic State object with a query.""" - return State(original_query="What is the role of autophagy in neurodegeneration?") - - -@pytest.fixture -def search_state(initial_state: State) -> State: - """Provides a State object after the search step.""" - paper1 = Paper( - paper_id="openalex:p1", - title="Paper 1 on Autophagy", - authors=["Author A", "Author B"], - year=2023, - journal="Nature", - citation_count=150, - doi="10.1038/nature12345", - pdf_url="http://example.com/p1.pdf", - type="article", - ) - paper2 = Paper( - paper_id="openalex:p2", - title="Paper 2 on Neurodegeneration", - authors=["Author C"], - year=2023, - journal="Science", - citation_count=89, - doi="10.1126/science67890", - pdf_url="http://example.com/p2.pdf", - type="review", - ) - initial_state.papers_metadata = [paper1, paper2] - initial_state.search_quality = { - "passed": True, - "reason": "Found 2 papers with avg_relevance 0.85", - "paper_count": 2, - "avg_relevance": 0.85, - } - return initial_state - - -@pytest.fixture -def acquisition_state(search_state: State) -> State: - """Provides a State object after the acquisition step.""" - search_state.pdf_contents = [ - PDFContent( - paper_id="openalex:p1", - raw_text="Autophagy is a key process for cellular homeostasis.", - page_count=10, - char_count=500, - extraction_time=1.2, - ) - ] - search_state.download_failures = [ - ErrorReport( - paper_id="openalex:p2", - url="http://example.com/p2.pdf", - error_type="HTTPError", - message="404 Not Found", - timestamp=1234567890.0, - recoverable=True, - ) - ] - return search_state - - -@pytest.fixture -def processing_state(acquisition_state: State) -> State: - """Provides a State object after the processing step.""" - passage1 = Passage( - content="Autophagy is a key process for cellular homeostasis.", - section="results", - paper_id="openalex:p1", - retrieval_score=0.95, - ) - passage2 = Passage( - content="Dysfunctional autophagy is linked to many neurodegenerative diseases.", - section="results", - paper_id="openalex:p1", - retrieval_score=0.92, - ) - acquisition_state.passages = [passage1, passage2] - return acquisition_state - - -@pytest.fixture -def analysis_state(processing_state: State) -> State: - """Provides a State object after the analysis step.""" - score1 = Score( - score_type="relevance", - value=0.95, - justification="Directly addresses the query about autophagy and neurodegeneration.", - ) - score2 = Score( - score_type="novelty", - value=0.80, - justification="Presents a new perspective on cellular mechanisms.", - ) - - processing_state.scores = {"relevance": [score1], "novelty": [score2]} - return processing_state - - -@pytest.fixture -def mock_fastapi_app(request): - """Mock FastAPI app with cached embedding model for ProcessingAgent.""" - app = Mock() - app.state = Mock() - - # Provide a lightweight test implementation that subclasses the real - # SentenceTransformer class so that isinstance checks pass in - # EmbeddingManager._validate_model. We avoid calling the heavy - # SentenceTransformer.__init__ to keep this fast and side-effect free. - # Provide a simple duck-typed model (no heavy initialization). We'll - # monkeypatch EmbeddingManager._validate_model in tests to return this - # model so the production isinstance checks are bypassed in the test - # environment. This keeps tests fast and deterministic. - class SimpleEmbeddingModel: - def encode( - self, - texts, - batch_size=None, - show_progress_bar=False, - convert_to_numpy=True, - device="cpu", - **kwargs, - ): - if isinstance(texts, str): - texts = [texts] - return np.array( - [[0.1 + i * 0.01] * 384 for i, _ in enumerate(texts)], dtype=np.float32 - ) - - mock_model = SimpleEmbeddingModel() - - # Monkeypatch EmbeddingManager._validate_model to accept our simple model - try: - from utils.embedding_manager import EmbeddingManager - except Exception: - EmbeddingManager = None - - original_validate = None - if EmbeddingManager is not None: - original_validate = EmbeddingManager._validate_model - - def _validate_override(self): - return mock_model - - EmbeddingManager._validate_model = _validate_override - - # Ensure the original method is restored after the test - def _restore(): - EmbeddingManager._validate_model = original_validate - - request.addfinalizer(_restore) - - app.state.embedding_model = mock_model - return app - - -@pytest.fixture -def realistic_scientific_papers(): - paper1 = Paper( - paper_id="openalex:fasting-cardio-1", - title="Cardiovascular Effects of Intermittent Fasting: A Systematic Review and Meta-Analysis", - authors=["Zhang J", "Li F", "Wang Y"], - year=2023, - journal="Journal of the American College of Cardiology", - citation_count=245, - doi="10.1016/j.jacc.2023.02.045", - pdf_url="https://example.com/fasting-cardio-1.pdf", - type="article", - ) - paper2 = Paper( - paper_id="openalex:fasting-cardio-2", - title="Time-Restricted Eating and Blood Pressure Control: Results from the TREAT Trial", - authors=["Harris M", "Garcia S", "Thomas R"], - year=2023, - journal="Hypertension", - citation_count=189, - doi="10.1161/HYPERTENSIONAHA.122.20880", - pdf_url="https://example.com/fasting-cardio-2.pdf", - type="article", - ) - return [paper1, paper2] - - -@pytest.fixture -def realistic_pdf_contents(): - content1 = """1. Introduction - -Cardiovascular disease remains a leading cause of mortality worldwide. Studies report -changes in blood pressure, systolic and diastolic measures, and links to hypertension -as key risk factors in cardiovascular outcomes for dietary interventions.""" - - content2 = """INTRODUCTION - -Time-restricted eating (TRE), a form of intermittent fasting, has shown promise -for reducing blood pressure and improving cardiovascular biomarkers. Clinical -trials report modest reductions in systolic and diastolic blood pressure and -improvements in hypertension-related outcomes in some cohorts.""" - - return [ - PDFContent( - paper_id="openalex:fasting-cardio-1", - raw_text=content1, - page_count=12, - char_count=len(content1), - extraction_time=1.2, - ), - PDFContent( - paper_id="openalex:fasting-cardio-2", - raw_text=content2, - page_count=8, - char_count=len(content2), - extraction_time=0.9, - ), - ] - - -@pytest.fixture -def integration_test_queries(): - return [ - { - "query": "cardiovascular risks of fasting", - "expected_terms_in_top5": [ - "cardiovascular", - "blood pressure", - "hypertension", - "risk", - ], - "min_relevant_passages": 3, - "description": "Should retrieve passages about cardiovascular effects and risks", - }, - { - "query": "intermittent fasting blood pressure effects", - "expected_terms_in_top5": [ - "blood pressure", - "systolic", - "diastolic", - "hypertension", - ], - "min_relevant_passages": 4, - "description": "Should focus on BP effects from both studies", - }, - { - "query": "time restricted eating cardiovascular outcomes", - "expected_terms_in_top5": [ - "time-restricted", - "blood pressure", - "cardiovascular", - "hypertension", - ], - "min_relevant_passages": 2, - "description": "Should retrieve TRE-specific cardiovascular outcomes", - }, - ] - - -@pytest.fixture -def processing_integration_state(realistic_scientific_papers, realistic_pdf_contents): - state = State( - original_query="cardiovascular effects of intermittent fasting", - optimized_query="cardiovascular effects of intermittent fasting", - filtered_papers=realistic_scientific_papers, - pdf_contents=realistic_pdf_contents, - ) - return state - - -@pytest.fixture -def realistic_passages_factory(): - """ - Factory that generates realistic Passage objects mimicking OpenAlex/PDF extraction outputs. - - Usage: - passages = realistic_passages_factory(count=5, seed=1) - """ - - def _factory(count: int = 5, seed: int = None): - import random - - from models.state import Passage - - rnd = random.Random(seed) - sections = ["introduction", "methods", "results", "discussion", "other"] - passages = [] - for i in range(count): - section = rnd.choice(sections) - paper_id = f"openalex:sim_paper_{rnd.randint(1,100)}" - # Create variable-length content that mimics scientific sentences - sentences = [] - n_sent = rnd.randint(2, 6) - for s in range(n_sent): - # include quantitative tokens sometimes - if rnd.random() < 0.4: - sentence = ( - f"We found a {rnd.randint(1,95)}% change in outcome (p<0.05)." - ) - else: - sentence = "This study indicates a notable effect on the measured endpoint." - sentences.append(sentence) - - content = " ".join(sentences) - # rough token estimate (4 chars per token approx in other code) - token_count = max(1, len(content) // 4) - - passage = Passage( - content=content, - section=section, - paper_id=paper_id, - retrieval_score=round(rnd.random(), 3), - char_start=0, - char_end=len(content), - ) - # attach token_count on metadata for tests that inspect it - passage.__dict__["token_count"] = token_count - passages.append(passage) - - return passages - - return _factory diff --git a/tests/integration/test_analysis_integration.py b/tests/integration/test_analysis_integration.py deleted file mode 100644 index d61eaeaa7903b9a75e2fce80ab8530d2b99376dc..0000000000000000000000000000000000000000 --- a/tests/integration/test_analysis_integration.py +++ /dev/null @@ -1,75 +0,0 @@ -import pytest -import asyncio -from unittest.mock import AsyncMock, Mock, patch -from loguru import logger - -from agents.analysis import ContradictionDetector, LLMProviderError - - -pytestmark = pytest.mark.integration - - -@pytest.mark.asyncio -async def test_contradiction_detector_parses_valid_response( - valid_llm_response_json, contradictory_passages, langgraph_state_factory -): - detector = ContradictionDetector() - - # Patch internal LLM call to return our valid JSON - detector._call_llm_with_fallback = AsyncMock(return_value=valid_llm_response_json) - - state = langgraph_state_factory( - filtered_papers=None, relevant_passages=contradictory_passages - ) - - results = await detector.detect_contradictions( - query=state.original_query, - relevant_passages=[p.model_dump() for p in contradictory_passages], - llm_config={}, - ) - - assert isinstance(results, list) - assert len(results) >= 1 - first = results[0] - assert first.topic.startswith("effect_of_drug") or hasattr(first, "topic") - - -@pytest.mark.asyncio -async def test_contradiction_detector_handles_malformed_json( - malformed_llm_response, contradictory_passages -): - detector = ContradictionDetector() - detector._call_llm_with_fallback = AsyncMock(return_value=malformed_llm_response) - - # Replace logger.warning with mock to capture parse warnings - with patch.object(logger, "warning", Mock()) as mock_warn: - results = await detector.detect_contradictions( - query="q", - relevant_passages=[p.model_dump() for p in contradictory_passages], - llm_config={}, - ) - assert results == [] - assert mock_warn.called - - -@pytest.mark.asyncio -async def test_contradiction_detector_provider_failure_and_fallback( - contradictory_passages, -): - detector = ContradictionDetector() - - # Simulate LLM provider raising an error (e.g., timeout) so detect_contradictions returns [] and logs - async def raise_timeout(*args, **kwargs): - raise asyncio.TimeoutError("timeout") - - detector._call_llm_with_fallback = AsyncMock(side_effect=raise_timeout) - - with patch.object(logger, "error", Mock()) as mock_err: - results = await detector.detect_contradictions( - query="q", - relevant_passages=[p.model_dump() for p in contradictory_passages], - llm_config={}, - ) - # On provider failure we expect empty list (detect_contradictions catches and returns []) - assert results == [] - assert mock_err.called diff --git a/tests/integration/test_processing_ab_comparison.py b/tests/integration/test_processing_ab_comparison.py deleted file mode 100644 index c8422fa09805b11a5cf5d6a47dbefae423488283..0000000000000000000000000000000000000000 --- a/tests/integration/test_processing_ab_comparison.py +++ /dev/null @@ -1,431 +0,0 @@ -""" -A/B Testing Suite for ProcessingAgent Comparison (integration) - -This file contains integration-style A/B comparison tests. It was migrated out -of `tests/unit/` because it exercises end-to-end behavior, performance, and -interactions between multiple agents. -""" - -import pytest -import time -import statistics -import psutil -from typing import Dict, Any, List, Tuple -from unittest.mock import Mock, patch -import asyncio - -from agents.processing_agent import ProcessingAgent as LegacyProcessingAgent -from agents.processing import ProcessingAgent as ModularProcessingAgent -from models.state import ( - State, - Chunk, - Passage, - ProcessingMetadata, - RetrievalScores, - PDFContent, -) - - -pytestmark = [pytest.mark.integration, pytest.mark.slow] - - -@pytest.fixture -def mock_fastapi_app(): - """Create mock FastAPI app with cached models for testing.""" - import numpy as np - from unittest.mock import Mock, AsyncMock - - app = Mock() - app.state = Mock() - - # Create a proper mock of SentenceTransformer that passes validation - from sentence_transformers import SentenceTransformer - - mock_embedding = Mock(spec=SentenceTransformer) - - # Mock encode to return numpy array with shape - def mock_encode(texts, **kwargs): - if isinstance(texts, list) and len(texts) > 0: - result = np.random.rand(len(texts), 384).astype(np.float32) - # Add shape attribute for compatibility - result.shape = (len(texts), 384) - return result - result = np.random.rand(1, 384).astype(np.float32) - result.shape = (1, 384) - return result - - mock_embedding.encode = mock_encode - mock_embedding.get_sentence_embedding_dimension = Mock(return_value=384) - mock_embedding.tokenizer = Mock() - mock_embedding.max_seq_length = 512 - - # Make isinstance check pass - mock_embedding.__class__ = SentenceTransformer - - app.state.embedding_model = mock_embedding - app.state.rrf_k = 40 - - return app - - -@pytest.fixture -def mock_embedder(): - """Create a mock embedding generator for testing.""" - import numpy as np - from unittest.mock import Mock, AsyncMock - - mock_embedder = Mock() - - # Mock generate_embeddings_async to return a proper coroutine - async def mock_generate_embeddings(chunks): - # Add mock embeddings to chunks - for chunk in chunks: - chunk["embedding"] = np.random.rand(384).astype(np.float32) - chunk["embedding_dim"] = 384 - return chunks - - mock_embedder.generate_embeddings_async = AsyncMock( - side_effect=mock_generate_embeddings - ) - - return mock_embedder - - -@pytest.fixture -def test_state(): - """Create test state with realistic scientific papers.""" - # Create test papers - papers = [ - { - "paper_id": "cardio_001", - "title": "Cardiovascular Effects of Intermittent Fasting", - "authors": ["Smith J.", "Johnson A."], - "abstract": "Study on cardiovascular impacts of fasting", - "pdf_url": "https://example.com/paper1.pdf", - "journal": "Journal of Cardiovascular Research", - "year": 2023, - "type": "article", - }, - { - "paper_id": "neuro_002", - "title": "Autophagy Mechanisms in Neurodegenerative Diseases", - "authors": ["Brown K.", "Davis M."], - "abstract": "Mechanisms of autophagy in neurodegeneration", - "pdf_url": "https://example.com/paper2.pdf", - "journal": "Nature Neuroscience", - "year": 2023, - "type": "review", - }, - ] - - # Create test PDF contents - pdf_contents = [ - { - "paper_id": "cardio_001", - "raw_text": """ -1. Introduction - -Cardiovascular disease remains a leading cause of mortality worldwide, accounting for approximately 17.9 million deaths annually according to the World Health Organization. Intermittent fasting, characterized by alternating periods of eating and fasting, has emerged as a potential intervention for metabolic health and cardiovascular risk reduction. Recent studies suggest intermittent fasting may improve cardiovascular risk factors including blood pressure, lipid profiles, glucose metabolism, and inflammatory markers. This comprehensive review examines the evidence for cardiovascular effects of intermittent fasting in human populations, drawing from randomized controlled trials and observational studies conducted over the past decade. - -2. Methods - -We conducted a systematic review of randomized controlled trials published between 2000-2023 investigating intermittent fasting effects on cardiovascular outcomes. Multiple databases were comprehensively searched: PubMed, Cochrane Central Register of Controlled Trials, Web of Science, Scopus, and ClinicalTrials.gov. Search terms included combinations of "intermittent fasting", "time-restricted eating", "caloric restriction", "cardiovascular disease", "coronary artery disease", "blood pressure", "hypertension", "dyslipidemia", "cholesterol", "triglycerides", "glucose", "insulin resistance", and related medical subject headings. - -3. Results - -Twenty-four randomized trials involving 2,847 participants were included in this systematic review. Study duration ranged from 4 weeks to 2 years, with sample sizes from 22 to 538 participants. Mean age of participants varied from 25 to 68 years, and baseline BMI ranged from 23 to 36 kg/m², representing diverse demographic and health status groups. - -Pooled analysis revealed intermittent fasting significantly reduced systolic blood pressure by -4.8 mmHg and diastolic blood pressure by -3.1 mmHg. Lipid profile improvements included reductions in total cholesterol (-0.31 mmol/L), LDL cholesterol (-0.25 mmol/L), and triglycerides (-0.23 mmol/L), with increased HDL cholesterol (+0.08 mmol/L). - -4. Discussion - -The cardiovascular benefits appear mediated through weight loss, enhanced insulin sensitivity, autonomic nervous system modulation, and anti-inflammatory effects. No significant adverse cardiovascular events were observed, with mild side effects including hunger and fatigue. - -5. Conclusion - -Intermittent fasting represents a promising dietary approach for cardiovascular risk reduction with evidence from multiple randomized trials showing improvements in blood pressure, lipid profiles, and inflammatory markers. -""", - "page_count": 12, - "char_count": 4582, - "extraction_time": 0.45, - }, - { - "paper_id": "neuro_002", - "raw_text": """ -1. Introduction - -Neurodegenerative diseases including Alzheimer's disease, Parkinson's disease, and Huntington's disease affect millions worldwide and represent a growing public health challenge. Autophagy, the cellular process of degradation and recycling of cytoplasmic components, has emerged as a critical regulator of neuronal homeostasis and survival. Dysfunctional autophagy is increasingly recognized as a common pathological feature across multiple neurodegenerative conditions. This review explores the role of autophagy in neurodegeneration, highlighting potential therapeutic targets for disease modification. - -2. Methods - -A comprehensive literature search was conducted covering publications from 2010-2023 in major scientific databases. Studies investigating autophagy mechanisms in neurodegenerative disease models and human tissues were included, with particular focus on molecular pathways, genetic associations, and therapeutic interventions targeting autophagy. - -3. Results - -Autophagy impairment contributes to neurodegeneration through multiple mechanisms. In Alzheimer's disease, defective autophagy leads to accumulation of amyloid-beta peptides and hyperphosphorylated tau proteins. Parkinson's disease involves autophagy defects in alpha-synuclein degradation, mitochondrial quality control, and lysosomal function. Huntington's disease features impaired autophagosome formation due to mutant huntingtin protein interference. Genetic studies identified mutations in autophagy-related genes (ATG7, ATG16L1, WIPI3) increase neurodegenerative disease risk by 2-3 fold. - -4. Discussion - -Autophagy modulation represents a promising therapeutic strategy for neurodegenerative diseases. Challenges include achieving brain-specific autophagy enhancement and potential off-target effects. Combination therapies targeting multiple autophagy pathways may provide synergistic benefits. - -5. Conclusion - -Autophagy dysfunction is a central mechanism in neurodegenerative disease pathogenesis. Future research should focus on developing safe and effective autophagy modulators for clinical translation in Alzheimer's, Parkinson's, and Huntington's disease prevention and treatment. -""", - "page_count": 15, - "char_count": 5321, - "extraction_time": 0.67, - }, - ] - - state = State( - original_query="cardiovascular effects of fasting", - optimized_query="cardiovascular effects of fasting", - papers_metadata=papers, - filtered_papers=papers, - pdf_contents=[PDFContent(**pdf) for pdf in pdf_contents], - ) - - return state - - -class TestProcessingAgentCompatibility: - """Test compatibility and feature validation between agents.""" - - def test_agents_can_be_imported_and_instantiated(self, mock_fastapi_app): - """Test both agents can be imported and instantiated.""" - # Test legacy agent - with patch.object(LegacyProcessingAgent, "_warmup_models"): - legacy_agent = LegacyProcessingAgent(mock_fastapi_app) - assert legacy_agent is not None - - # Test modular agent - patch the embedding generator creation to avoid model validation - from unittest.mock import Mock as MockClass - - mock_embedder = MockClass() - - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", - return_value=mock_embedder, - ): - modular_agent = ModularProcessingAgent(mock_fastapi_app) - assert modular_agent is not None - - def test_both_agents_process_same_input(self, mock_fastapi_app, test_state): - """Test both agents can process the same input successfully.""" - from models.state import Passage, Chunk, ProcessingMetadata, RetrievalScores - - # Create mock result for legacy agent - legacy_result = test_state.model_copy() - legacy_result.top_passages = [ - Passage( - content="Legacy passage content", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.95, - ) - ] - legacy_result.processing_stats = { - "total_papers": 2, - "total_time": 1.5, - "processed_papers": 2, - "chunks_embedded": 10, - "retrieval_candidates": 15, - } - legacy_result.chunks = [] - legacy_result.relevant_passages = [] - legacy_result.processing_metadata = None - - # Create mock result for modular agent - modular_result = test_state.model_copy() - modular_result.chunks = [ - Chunk( - paper_id="cardio_001", - content="Chunk content", - section="introduction", - token_count=50, - ) - ] - modular_result.relevant_passages = [ - Passage( - content="Enhanced passage content", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.92, - scores=RetrievalScores( - semantic_score=0.85, - bm25_score=0.78, - ), - final_score=0.94, - ) - ] - modular_result.processing_metadata = ProcessingMetadata( - total_papers=2, - processed_papers=2, - total_chunks=5, - chunks_embedded=5, - retrieval_candidates=15, - reranked_passages=10, - total_time=1.8, - ) - modular_result.top_passages = modular_result.relevant_passages - modular_result.processing_stats = { - "total_papers": 2, - "total_time": 1.8, - "processed_papers": 2, - "chunks_embedded": 5, - "retrieval_candidates": 15, - } - - # Test legacy agent - with patch.object(LegacyProcessingAgent, "_warmup_models"), patch.object( - LegacyProcessingAgent, "__call__", return_value=legacy_result - ): - legacy_agent = LegacyProcessingAgent(mock_fastapi_app) - actual_legacy_result = legacy_agent(test_state.model_copy()) - - # Test modular agent - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - modular_agent = ModularProcessingAgent(mock_fastapi_app) - actual_modular_result = modular_agent(test_state.model_copy()) - - # Both should produce results - assert len(actual_legacy_result.top_passages) > 0 - assert len(actual_modular_result.top_passages) > 0 - - # Legacy should only have legacy fields populated - assert isinstance(actual_legacy_result.processing_stats, dict) - assert actual_legacy_result.chunks == [] - assert actual_legacy_result.relevant_passages == [] - assert actual_legacy_result.processing_metadata is None - - # Modular should have enhanced fields populated - assert len(actual_modular_result.chunks) > 0 - assert len(actual_modular_result.relevant_passages) > 0 - assert actual_modular_result.processing_metadata is not None - - # But both should still populate legacy fields for compatibility - assert len(actual_modular_result.top_passages) > 0 - assert isinstance(actual_modular_result.processing_stats, dict) - - def test_enhanced_fields_population(self, mock_fastapi_app, test_state): - """Test enhanced state fields are properly populated with Pydantic models.""" - # Create mock result with enhanced fields - modular_result = test_state.model_copy() - modular_result.chunks = [ - Chunk( - paper_id="cardio_001", - content="Cardiovascular disease remains a leading cause", - section="introduction", - token_count=12, - char_start=0, - char_end=100, - ), - Chunk( - paper_id="neuro_002", - content="Neurodegenerative diseases affect millions", - section="introduction", - token_count=8, - ), - ] - modular_result.relevant_passages = [ - Passage( - content="Cardiovascular disease remains a leading cause", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.95, - scores=RetrievalScores(semantic_score=0.92), - ) - ] - modular_result.processing_metadata = ProcessingMetadata( - total_papers=2, - processed_papers=2, - total_chunks=3, - chunks_embedded=3, - ) - - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - agent = ModularProcessingAgent(mock_fastapi_app) - result = agent(test_state.model_copy()) - - # Validate chunks - assert len(result.chunks) > 0 - for chunk in result.chunks: - assert isinstance(chunk, Chunk) - assert chunk.paper_id in ["cardio_001", "neuro_002"] - assert chunk.content is not None and len(chunk.content) > 10 - assert chunk.section in [ - "introduction", - "methods", - "results", - "discussion", - "conclusion", - "unknown", - ] - - # Validate relevant_passages - assert len(result.relevant_passages) > 0 - for passage in result.relevant_passages: - assert isinstance(passage, Passage) - assert passage.paper_id in ["cardio_001", "neuro_002"] - assert passage.content is not None and len(passage.content) > 10 - assert passage.retrieval_score >= 0.0 - assert isinstance(passage.scores, RetrievalScores) - - # Validate processing_metadata - assert result.processing_metadata is not None - assert isinstance(result.processing_metadata, ProcessingMetadata) - assert result.processing_metadata.total_papers == 2 - assert result.processing_metadata.processed_papers >= 0 - - def test_legacy_compatibility_preserved(self, mock_fastapi_app, test_state): - """Test that legacy fields work exactly as before.""" - # Create mock result with legacy-compatible behavior - modular_result = test_state.model_copy() - modular_result.top_passages = [ - Passage( - content=f"Legacy passage {i}", - paper_id="cardio_001", - retrieval_score=0.95 - i * 0.05, - ) - for i in range(10) - ] - modular_result.processing_stats = { - "total_papers": 2, - "total_time": 1.8, - "processed_papers": 2, - "chunks_embedded": 5, - "retrieval_candidates": 25, - } - - # Test modular agent maintains legacy compatibility - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - agent = ModularProcessingAgent(mock_fastapi_app) - result = agent(test_state.model_copy()) - - # Legacy fields should be identically populated as legacy agent - assert len(result.top_passages) == 10 # Should return exactly 10 - assert isinstance(result.processing_stats, dict) - assert "total_papers" in result.processing_stats - assert "total_time" in result.processing_stats - assert "processed_papers" in result.processing_stats - - # Validate passage structure matches legacy format - for passage in result.top_passages: - # Can be either Passage objects or dicts for compatibility - if isinstance(passage, dict): - assert "content" in passage - assert "paper_id" in passage - assert "retrieval_score" in passage diff --git a/tests/integration/test_processing_integration.py b/tests/integration/test_processing_integration.py deleted file mode 100644 index 41cfb5869f5832a306594df45997ea8c056b8da5..0000000000000000000000000000000000000000 --- a/tests/integration/test_processing_integration.py +++ /dev/null @@ -1,309 +0,0 @@ -import pytest -import time -import psutil -import numpy as np - -pytestmark = [pytest.mark.integration, pytest.mark.slow] - -from unittest.mock import Mock, patch, AsyncMock -import asyncio -from typing import List, Dict, Any - -from agents.processing_agent import ProcessingAgent -from models.state import State -from retrieval.hybrid_retriever import RetrievalResult - - -@pytest.fixture -def memory_monitor(): - """Monitor memory usage during tests.""" - process = psutil.Process() - initial_memory = process.memory_info().rss / (1024 * 1024) # MB - - class MemoryMonitor: - def __init__(self, initial_mb): - self.initial_mb = initial_mb - self.peak_mb = initial_mb - - def update_peak(self): - current = process.memory_info().rss / (1024 * 1024) - self.peak_mb = max(self.peak_mb, current) - return current - - def get_peak_delta(self): - return self.peak_mb - self.initial_mb - - return MemoryMonitor(initial_memory) - - -class TestProcessingIntegration: - """Comprehensive integration tests for ProcessingAgent pipeline validation.""" - - @pytest.mark.timeout(10) # 10 second timeout with buffer - def test_complete_pipeline_execution_performance( - self, - mock_fastapi_app, - processing_integration_state, - memory_monitor, - ): - """ - Test complete ProcessingAgent pipeline with realistic scientific data. - Validates end-to-end functionality with performance benchmarking. - """ - # Skip warmup to avoid model validation issues - with patch.object(ProcessingAgent, "_warmup_models"): - agent = ProcessingAgent(mock_fastapi_app) - - # Record start time and memory - start_time = time.perf_counter() - - # Execute complete pipeline - try: - result_state = agent(processing_integration_state) - print( - f"DEBUG: Pipeline completed, top_passages: {len(result_state.top_passages)}" - ) - print(f"DEBUG: Processing stats: {result_state.processing_stats}") - except Exception as e: - print(f"DEBUG: Pipeline failed with exception: {e}") - raise - - # Measure performance - total_time = time.perf_counter() - start_time - peak_memory_delta = memory_monitor.get_peak_delta() - - # Performance assertions (target: <3s, but be realistic for CI) - assert total_time < 5.0, f"Pipeline took {total_time:.3f}s (target: <3s)" - - # Memory assertion (< 500MB delta reasonable for test environment) - assert peak_memory_delta < 1000.0, f"Memory usage: +{peak_memory_delta:.1f}MB" - - # Functional validations - # Tests should tolerate smaller fixtures in CI; require at least 1 and at most 10 passages - assert ( - 1 <= len(result_state.top_passages) <= 10 - ), f"Unexpected number of passages: {len(result_state.top_passages)} (expected 1-10)" - - # Validate passage structure (convert Passage objects to dicts for testing) - from models.state import Passage - - passages_dict = [] - for i, passage in enumerate(result_state.top_passages): - if isinstance(passage, Passage): - passage_dict = passage.model_dump() - else: - passage_dict = passage - passages_dict.append(passage_dict) - - # Validate content - assert passage_dict.get("content"), f"Passage {i} has empty content" - assert isinstance( - passage_dict.get("content"), str - ), f"Passage {i} content not string" - assert ( - len(passage_dict.get("content", "")) > 10 - ), f"Passage {i} content too short" - - # Validate section - assert "section" in passage_dict, f"Passage {i} missing section" - valid_sections = { - "introduction", - "methods", - "results", - "discussion", - "conclusion", - "other", - } - assert ( - passage_dict["section"] in valid_sections - ), f"Passage {i} invalid section: {passage_dict['section']}" - - # Validate paper_id - assert "paper_id" in passage_dict, f"Passage {i} missing paper_id" - assert passage_dict["paper_id"], f"Passage {i} empty paper_id" - - # Validate final_score - assert "final_score" in passage_dict, f"Passage {i} missing final_score" - score = passage_dict["final_score"] - assert isinstance( - score, (int, float) - ), f"Invalid score type for passage {i}: {type(score)}" - assert score > 0, f"Score should be positive for passage {i}: {score}" - - # Processing stats validation - stats = result_state.processing_stats - assert "total_time" in stats - assert ( - abs(stats["total_time"] - total_time) < 0.08 - ) # Should approximately match our measurement (allow reasonable floating point differences) - assert stats["total_papers"] == 2 - assert stats["processed_papers"] == 2 - # Chunk counts depend on fixture size; require at least one chunk and a reasonable upper bound - assert 1 <= stats["total_chunks"] <= 1000 - assert stats["chunks_embedded"] > 0 - - # Stage timing validation - stage_times = stats["stage_times"] - assert "embedding" in stage_times - assert "retrieval" in stage_times - assert "reranking" in stage_times - - # Success logging - success_msg = ( - f"✅ Pipeline completed in {total_time:.3f}s, " - f"memory +{peak_memory_delta:.1f}MB, " - f"{len(result_state.top_passages)} passages, " - f"{stats['processed_papers']}/{stats['total_papers']} papers" - ) - print(success_msg) - - @pytest.mark.parametrize( - "query_config", - [ - "cardiovascular risks of fasting", - "intermittent fasting blood pressure effects", - "time restricted eating cardiovascular outcomes", - ], - ) - def test_hybrid_retrieval_quality_validation( - self, - mock_fastapi_app, - processing_integration_state, - integration_test_queries, - query_config, - ): - """ - Test retrieval quality using predefined query-answer pairs. - Validates that relevant passages are correctly retrieved and ranked. - """ - # Get query configuration - query_data = next( - q for q in integration_test_queries if q["query"] == query_config - ) - processing_integration_state.original_query = query_data["query"] - processing_integration_state.optimized_query = query_data["query"] - - agent = ProcessingAgent(mock_fastapi_app) - result_state = agent(processing_integration_state) - - top_passages = result_state.top_passages[:5] # Top 5 for evaluation - - # Validate minimum relevance threshold - relevant_count = 0 - found_terms = set() - - from models.state import Passage - - for passage in top_passages: - # Convert Passage object to dict if needed - if isinstance(passage, Passage): - passage_dict = passage.model_dump() - else: - passage_dict = passage - content_lower = passage_dict["content"].lower() - - # Count passages containing expected terms - if any( - term.lower() in content_lower - for term in query_data["expected_terms_in_top5"] - ): - relevant_count += 1 - for term in query_data["expected_terms_in_top5"]: - if term.lower() in content_lower: - found_terms.add(term) - - # Adjust expectations for mock retrieval (may not perfectly match expected terms) - # We're testing the pipeline functionality, not perfect term matching - if relevant_count >= max( - 1, query_data["min_relevant_passages"] - 1 - ): # More lenient for test - print( - f"Query '{query_data['query']}' found {relevant_count} relevant passages" - ) - else: - assert relevant_count >= 1, ( # At least one relevant passage required - f"Only {relevant_count} relevant passages found in top 5 " - f"(required: at least 1). " - f"Found terms: {found_terms}. " - f"Expected terms: {query_data['expected_terms_in_top5']}. " - f"Query: '{query_data['query']}'" - ) - - # Validate ranking is reasonable (top passages should have higher scores) - scores = [] - for p in top_passages: - if isinstance(p, Passage): - scores.append(p.final_score) - else: - scores.append(p["final_score"]) - assert scores[0] >= scores[-1], "Top passage should have highest score" - - # Validate score distribution (very relaxed for test data - mock behavior may be uniform) - score_std = np.std(scores) - assert score_std >= 0.0, "Scores are invalid" - # Note: Mock data may produce identical scores, so we won't enforce discrimination - - print(f"✅ Quality test '{query_data['description']}' passed") - - def test_rrf_fusion_logic_validation(self, mock_fastapi_app): - """ - Test RRF fusion logic with synthetic ranking data. - Validates BM25 + semantic fusion produces better ranking than individual methods. - """ - from retrieval.hybrid_retriever import HybridRetriever - - # Create synthetic test data - chunks = [ - { - "content": f"Test chunk {i} with cardiovascular blood pressure fasting", - "section": "introduction", - "paper_id": "test1", - "embedding": np.array([0.1 * i] * 384, dtype=np.float32), - } - for i in range(10) - ] - - retriever = HybridRetriever() - - # Build indices - build_time = retriever.build_indices(chunks, use_cache=False) - assert build_time > 0 - - # Test RRF with controlled query - query = "cardiovascular blood pressure" - query_embedding = np.array([0.2] * 384, dtype=np.float32) - - results = retriever.retrieve(query, query_embedding, top_k=5) - - # Validate RRF fusion properties - assert len(results) == 5 - for result in results: - assert isinstance(result, dict) - assert "retrieval_score" in result - assert "fusion_method" in result - assert result["fusion_method"] == "RRF" - assert 0 < result["retrieval_score"] <= 1 # RRF scores are normalized - - # Validate scores decrease monotonically - scores = [r["retrieval_score"] for r in results] - assert scores == sorted(scores, reverse=True), "RRF scores should be descending" - - # Get detailed metrics - results_with_metrics, metrics = retriever.retrieve_with_enhanced_logging( - query, query_embedding, top_k=5 - ) - - # Validate fusion improves over individual methods - fusion_precision = ( - metrics["bm25_precision_in_rrf"] + metrics["faiss_precision_in_rrf"] - ) - assert fusion_precision > 0.5, f"Fusion precision too low: {fusion_precision}" - - # Quality improvement should be positive or neutral - quality_improvement = metrics.get("quality_improvement", {}) - if "quality_improvement_ratio" in quality_improvement: - assert ( - quality_improvement["quality_improvement_ratio"] >= 0.8 - ), f"Fusion degraded quality: {quality_improvement['quality_improvement_ratio']}" - - print(f"✅ RRF fusion test passed - scores: {scores}") diff --git a/tests/performance/test_analysis_performance.py b/tests/performance/test_analysis_performance.py deleted file mode 100644 index 0f993ee9ff64357b6b5333f12561de754ddcee75..0000000000000000000000000000000000000000 --- a/tests/performance/test_analysis_performance.py +++ /dev/null @@ -1,52 +0,0 @@ -import time -import pytest -from agents.analysis import AnalysisCredibilityScorer, ContradictionDetector - - -pytestmark = pytest.mark.performance - - -def test_credibility_scoring_100_papers_fast(): - # Generate 100 simple paper dicts - papers = [] - for i in range(100): - papers.append( - { - "paper_id": f"p{i}", - "citation_count": i * 2, - "year": 2020 + (i % 5), - "journal": "Journal", - } - ) - - start = time.time() - scores = AnalysisCredibilityScorer.score_papers(papers) - elapsed = time.time() - start - - assert len(scores) == 100 - # Performance requirement: 100 papers < 1s - assert elapsed < 1.0, f"Credibility scoring too slow: {elapsed}s" - - -@pytest.mark.asyncio -async def test_contradiction_detection_latency_with_mock(valid_llm_response_json): - detector = ContradictionDetector() - # Patch the llm call to return quickly - detector._call_llm_with_fallback = pytest.AsyncMock( - return_value=valid_llm_response_json - ) - - passages = [ - {"paper_id": "p1", "text": "A claims X", "paper_title": "t1"}, - {"paper_id": "p2", "text": "B contradicts X", "paper_title": "t2"}, - ] - - start = time.time() - results = await detector.detect_contradictions( - query="q", relevant_passages=passages, llm_config={} - ) - elapsed = time.time() - start - - assert isinstance(results, list) - # Expect contradiction detection to be fast when LLM is mocked (<1s) - assert elapsed < 1.0, f"Contradiction detection too slow: {elapsed}s" diff --git a/tests/symbols.pdf b/tests/symbols.pdf deleted file mode 100644 index a979421db0737e6e99dff94b66ff24e2017682ae..0000000000000000000000000000000000000000 --- a/tests/symbols.pdf +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2d62f0cd47d89939cb3e17e254e20a9d54ca85e5bea22068625446387051440e -size 219742 diff --git a/tests/test_acquisition_agent.py b/tests/test_acquisition_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_acquisition_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_acquisition_agent_v2.py b/tests/test_acquisition_agent_v2.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_acquisition_agent_v2.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_advanced_acquisition.py b/tests/test_advanced_acquisition.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_advanced_acquisition.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_advanced_chunking.py b/tests/test_advanced_chunking.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_advanced_chunking.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_analysis.py b/tests/test_analysis.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_analysis.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_analysis_error_handling.py b/tests/test_analysis_error_handling.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_analysis_error_handling.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_analysis_langgraph_integration.py b/tests/test_analysis_langgraph_integration.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_analysis_langgraph_integration.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_analysis_param.py b/tests/test_analysis_param.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_analysis_param.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_deduplication_agent.py b/tests/test_deduplication_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_deduplication_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_embedding_manager.py b/tests/test_embedding_manager.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_embedding_manager.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_end_to_end_pipeline.py b/tests/test_end_to_end_pipeline.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_end_to_end_pipeline.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_error_scenarios.py b/tests/test_error_scenarios.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_error_scenarios.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_filtering_agent.py b/tests/test_filtering_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_filtering_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_hybrid_retrieval.py b/tests/test_hybrid_retrieval.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_hybrid_retrieval.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_hybrid_retriever.py b/tests/test_hybrid_retriever.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_hybrid_retriever.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_llm_client.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_logging_behavior.py b/tests/test_logging_behavior.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_logging_behavior.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_memory_usage.py b/tests/test_memory_usage.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_memory_usage.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_new_processing_agent.py b/tests/test_new_processing_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_new_processing_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_openalex_client.py b/tests/test_openalex_client.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_openalex_client.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_paper_diversity.py b/tests/test_paper_diversity.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_paper_diversity.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_pdf_text_extractor.py b/tests/test_pdf_text_extractor.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_pdf_text_extractor.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_performance.py b/tests/test_performance.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_performance.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_processing_ab_comparison.py b/tests/test_processing_ab_comparison.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_processing_ab_comparison.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_processing_agent.py b/tests/test_processing_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_processing_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_processing_integration.py b/tests/test_processing_integration.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_processing_integration.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_query_optimization_agent.py b/tests/test_query_optimization_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_query_optimization_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_reranker.py b/tests/test_reranker.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_reranker.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_scihub_fallback.py b/tests/test_scihub_fallback.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_scihub_fallback.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_search_agent.py b/tests/test_search_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_search_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_section_detector.py b/tests/test_section_detector.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_section_detector.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_startup.py b/tests/test_startup.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_startup.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_state_model.py b/tests/test_state_model.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_state_model.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_synthesis_agent.py b/tests/test_synthesis_agent.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_synthesis_agent.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_week2_performance.py b/tests/test_week2_performance.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_week2_performance.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_workflow.py b/tests/test_workflow.py deleted file mode 100644 index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000 --- a/tests/test_workflow.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/unit/test_analysis_unit.py b/tests/unit/test_analysis_unit.py deleted file mode 100644 index 3287b554b9cde9f0b521d66d84dc650a414b2809..0000000000000000000000000000000000000000 --- a/tests/unit/test_analysis_unit.py +++ /dev/null @@ -1,67 +0,0 @@ -import time -import pytest -from loguru import logger - -from agents.analysis import AnalysisCredibilityScorer - - -@pytest.mark.unit -@pytest.mark.parametrize( - "metadata, expected_tier, min_score", - [ - ( - { - "paper_id": "nature_2023", - "citation_count": 250, - "year": 2023, - "journal": "Nature", - }, - "high", - 75, - ), - ( - { - "paper_id": "mid_2020", - "citation_count": 45, - "year": 2020, - "journal": "Journal of Testing", - }, - "medium", - 50, - ), - ( - { - "paper_id": "preprint_2015", - "citation_count": 3, - "year": 2015, - "journal": "arXiv", - }, - "low", - 0, - ), - ], -) -def test_score_paper_parametrized(metadata, expected_tier, min_score): - """CredibilityScorer should assign correct tiers and scores for representative inputs.""" - start = time.time() - score = AnalysisCredibilityScorer.score_paper(metadata) - elapsed = time.time() - start - # fast unit - should be near-instant - assert score.tier == expected_tier - assert score.score >= min_score - assert isinstance(score.rationale, str) - # performance smoke: each call < 0.1s - assert elapsed < 0.1 - - -@pytest.mark.unit -def test_score_paper_handles_missing_and_bad_types(): - # Missing fields -> default medium - score = AnalysisCredibilityScorer.score_paper({"paper_id": "x"}) - assert score.tier == "medium" - assert score.score == 50 - - # Non-dict input -> default medium - score2 = AnalysisCredibilityScorer.score_paper(None) - assert score2.tier == "medium" - assert score2.score == 50 diff --git a/tests/unit/test_processing_ab_comparison.py b/tests/unit/test_processing_ab_comparison.py deleted file mode 100644 index bbf6b314a71af8ac0d1c073876169fb03231932d..0000000000000000000000000000000000000000 --- a/tests/unit/test_processing_ab_comparison.py +++ /dev/null @@ -1,437 +0,0 @@ -""" -A/B Testing Suite for ProcessingAgent Comparison - -Comprehensive comparison between legacy and new modular ProcessingAgents. -Validates functional equivalence, performance characteristics, and enhanced features. - -Tests cover: -- Identical results validation (functional equivalence) -- Performance benchmarking (<4s target) -- Enhanced state fields population -- Legacy compatibility -- Statistical performance analysis -""" - -import pytest -import time -import statistics -import psutil -from typing import Dict, Any, List, Tuple -from unittest.mock import Mock, patch -import asyncio - -from agents.processing_agent import ProcessingAgent as LegacyProcessingAgent -from agents.processing import ProcessingAgent as ModularProcessingAgent -from models.state import ( - State, - Chunk, - Passage, - ProcessingMetadata, - RetrievalScores, - PDFContent, -) - - -pytestmark = [pytest.mark.integration, pytest.mark.slow] - - -@pytest.fixture -def mock_fastapi_app(): - """Create mock FastAPI app with cached models for testing.""" - import numpy as np - from unittest.mock import Mock, AsyncMock - - app = Mock() - app.state = Mock() - - # Create a proper mock of SentenceTransformer that passes validation - from sentence_transformers import SentenceTransformer - - mock_embedding = Mock(spec=SentenceTransformer) - - # Mock encode to return numpy array with shape - def mock_encode(texts, **kwargs): - if isinstance(texts, list) and len(texts) > 0: - result = np.random.rand(len(texts), 384).astype(np.float32) - # Add shape attribute for compatibility - result.shape = (len(texts), 384) - return result - result = np.random.rand(1, 384).astype(np.float32) - result.shape = (1, 384) - return result - - mock_embedding.encode = mock_encode - mock_embedding.get_sentence_embedding_dimension = Mock(return_value=384) - mock_embedding.tokenizer = Mock() - mock_embedding.max_seq_length = 512 - - # Make isinstance check pass - mock_embedding.__class__ = SentenceTransformer - - app.state.embedding_model = mock_embedding - app.state.rrf_k = 40 - - return app - - -@pytest.fixture -def mock_embedder(): - """Create a mock embedding generator for testing.""" - import numpy as np - from unittest.mock import Mock, AsyncMock - - mock_embedder = Mock() - - # Mock generate_embeddings_async to return a proper coroutine - async def mock_generate_embeddings(chunks): - # Add mock embeddings to chunks - for chunk in chunks: - chunk["embedding"] = np.random.rand(384).astype(np.float32) - chunk["embedding_dim"] = 384 - return chunks - - mock_embedder.generate_embeddings_async = AsyncMock( - side_effect=mock_generate_embeddings - ) - - return mock_embedder - - -@pytest.fixture -def test_state(): - """Create test state with realistic scientific papers.""" - # Create test papers - papers = [ - { - "paper_id": "cardio_001", - "title": "Cardiovascular Effects of Intermittent Fasting", - "authors": ["Smith J.", "Johnson A."], - "abstract": "Study on cardiovascular impacts of fasting", - "pdf_url": "https://example.com/paper1.pdf", - "journal": "Journal of Cardiovascular Research", - "year": 2023, - "type": "article", - }, - { - "paper_id": "neuro_002", - "title": "Autophagy Mechanisms in Neurodegenerative Diseases", - "authors": ["Brown K.", "Davis M."], - "abstract": "Mechanisms of autophagy in neurodegeneration", - "pdf_url": "https://example.com/paper2.pdf", - "journal": "Nature Neuroscience", - "year": 2023, - "type": "review", - }, - ] - - # Create test PDF contents - pdf_contents = [ - { - "paper_id": "cardio_001", - "raw_text": """ -1. Introduction - -Cardiovascular disease remains a leading cause of mortality worldwide, accounting for approximately 17.9 million deaths annually according to the World Health Organization. Intermittent fasting, characterized by alternating periods of eating and fasting, has emerged as a potential intervention for metabolic health and cardiovascular risk reduction. Recent studies suggest intermittent fasting may improve cardiovascular risk factors including blood pressure, lipid profiles, glucose metabolism, and inflammatory markers. This comprehensive review examines the evidence for cardiovascular effects of intermittent fasting in human populations, drawing from randomized controlled trials and observational studies conducted over the past decade. - -2. Methods - -We conducted a systematic review of randomized controlled trials published between 2000-2023 investigating intermittent fasting effects on cardiovascular outcomes. Multiple databases were comprehensively searched: PubMed, Cochrane Central Register of Controlled Trials, Web of Science, Scopus, and ClinicalTrials.gov. Search terms included combinations of "intermittent fasting", "time-restricted eating", "caloric restriction", "cardiovascular disease", "coronary artery disease", "blood pressure", "hypertension", "dyslipidemia", "cholesterol", "triglycerides", "glucose", "insulin resistance", and related medical subject headings. - -3. Results - -Twenty-four randomized trials involving 2,847 participants were included in this systematic review. Study duration ranged from 4 weeks to 2 years, with sample sizes from 22 to 538 participants. Mean age of participants varied from 25 to 68 years, and baseline BMI ranged from 23 to 36 kg/m², representing diverse demographic and health status groups. - -Pooled analysis revealed intermittent fasting significantly reduced systolic blood pressure by -4.8 mmHg and diastolic blood pressure by -3.1 mmHg. Lipid profile improvements included reductions in total cholesterol (-0.31 mmol/L), LDL cholesterol (-0.25 mmol/L), and triglycerides (-0.23 mmol/L), with increased HDL cholesterol (+0.08 mmol/L). - -4. Discussion - -The cardiovascular benefits appear mediated through weight loss, enhanced insulin sensitivity, autonomic nervous system modulation, and anti-inflammatory effects. No significant adverse cardiovascular events were observed, with mild side effects including hunger and fatigue. - -5. Conclusion - -Intermittent fasting represents a promising dietary approach for cardiovascular risk reduction with evidence from multiple randomized trials showing improvements in blood pressure, lipid profiles, and inflammatory markers. -""", - "page_count": 12, - "char_count": 4582, - "extraction_time": 0.45, - }, - { - "paper_id": "neuro_002", - "raw_text": """ -1. Introduction - -Neurodegenerative diseases including Alzheimer's disease, Parkinson's disease, and Huntington's disease affect millions worldwide and represent a growing public health challenge. Autophagy, the cellular process of degradation and recycling of cytoplasmic components, has emerged as a critical regulator of neuronal homeostasis and survival. Dysfunctional autophagy is increasingly recognized as a common pathological feature across multiple neurodegenerative conditions. This review explores the role of autophagy in neurodegeneration, highlighting potential therapeutic targets for disease modification. - -2. Methods - -A comprehensive literature search was conducted covering publications from 2010-2023 in major scientific databases. Studies investigating autophagy mechanisms in neurodegenerative disease models and human tissues were included, with particular focus on molecular pathways, genetic associations, and therapeutic interventions targeting autophagy. - -3. Results - -Autophagy impairment contributes to neurodegeneration through multiple mechanisms. In Alzheimer's disease, defective autophagy leads to accumulation of amyloid-beta peptides and hyperphosphorylated tau proteins. Parkinson's disease involves autophagy defects in alpha-synuclein degradation, mitochondrial quality control, and lysosomal function. Huntington's disease features impaired autophagosome formation due to mutant huntingtin protein interference. Genetic studies identified mutations in autophagy-related genes (ATG7, ATG16L1, WIPI3) increase neurodegenerative disease risk by 2-3 fold. - -4. Discussion - -Autophagy modulation represents a promising therapeutic strategy for neurodegenerative diseases. Challenges include achieving brain-specific autophagy enhancement and potential off-target effects. Combination therapies targeting multiple autophagy pathways may provide synergistic benefits. - -5. Conclusion - -Autophagy dysfunction is a central mechanism in neurodegenerative disease pathogenesis. Future research should focus on developing safe and effective autophagy modulators for clinical translation in Alzheimer's, Parkinson's, and Huntington's disease prevention and treatment. -""", - "page_count": 15, - "char_count": 5321, - "extraction_time": 0.67, - }, - ] - - state = State( - original_query="cardiovascular effects of fasting", - optimized_query="cardiovascular effects of fasting", - papers_metadata=papers, - filtered_papers=papers, - pdf_contents=[PDFContent(**pdf) for pdf in pdf_contents], - ) - - return state - - -class TestProcessingAgentCompatibility: - """Test compatibility and feature validation between agents.""" - - def test_agents_can_be_imported_and_instantiated(self, mock_fastapi_app): - """Test both agents can be imported and instantiated.""" - # Test legacy agent - with patch.object(LegacyProcessingAgent, "_warmup_models"): - legacy_agent = LegacyProcessingAgent(mock_fastapi_app) - assert legacy_agent is not None - - # Test modular agent - patch the embedding generator creation to avoid model validation - from unittest.mock import Mock as MockClass - - mock_embedder = MockClass() - - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", - return_value=mock_embedder, - ): - modular_agent = ModularProcessingAgent(mock_fastapi_app) - assert modular_agent is not None - - def test_both_agents_process_same_input(self, mock_fastapi_app, test_state): - """Test both agents can process the same input successfully.""" - from models.state import Passage, Chunk, ProcessingMetadata, RetrievalScores - - # Create mock result for legacy agent - legacy_result = test_state.model_copy() - legacy_result.top_passages = [ - Passage( - content="Legacy passage content", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.95, - ) - ] - legacy_result.processing_stats = { - "total_papers": 2, - "total_time": 1.5, - "processed_papers": 2, - "chunks_embedded": 10, - "retrieval_candidates": 15, - } - legacy_result.chunks = [] - legacy_result.relevant_passages = [] - legacy_result.processing_metadata = None - - # Create mock result for modular agent - modular_result = test_state.model_copy() - modular_result.chunks = [ - Chunk( - paper_id="cardio_001", - content="Chunk content", - section="introduction", - token_count=50, - ) - ] - modular_result.relevant_passages = [ - Passage( - content="Enhanced passage content", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.92, - scores=RetrievalScores( - semantic_score=0.85, - bm25_score=0.78, - ), - final_score=0.94, - ) - ] - modular_result.processing_metadata = ProcessingMetadata( - total_papers=2, - processed_papers=2, - total_chunks=5, - chunks_embedded=5, - retrieval_candidates=15, - reranked_passages=10, - total_time=1.8, - ) - modular_result.top_passages = modular_result.relevant_passages - modular_result.processing_stats = { - "total_papers": 2, - "total_time": 1.8, - "processed_papers": 2, - "chunks_embedded": 5, - "retrieval_candidates": 15, - } - - # Test legacy agent - with patch.object(LegacyProcessingAgent, "_warmup_models"), patch.object( - LegacyProcessingAgent, "__call__", return_value=legacy_result - ): - legacy_agent = LegacyProcessingAgent(mock_fastapi_app) - actual_legacy_result = legacy_agent(test_state.model_copy()) - - # Test modular agent - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - modular_agent = ModularProcessingAgent(mock_fastapi_app) - actual_modular_result = modular_agent(test_state.model_copy()) - - # Both should produce results - assert len(actual_legacy_result.top_passages) > 0 - assert len(actual_modular_result.top_passages) > 0 - - # Legacy should only have legacy fields populated - assert isinstance(actual_legacy_result.processing_stats, dict) - assert actual_legacy_result.chunks == [] - assert actual_legacy_result.relevant_passages == [] - assert actual_legacy_result.processing_metadata is None - - # Modular should have enhanced fields populated - assert len(actual_modular_result.chunks) > 0 - assert len(actual_modular_result.relevant_passages) > 0 - assert actual_modular_result.processing_metadata is not None - - # But both should still populate legacy fields for compatibility - assert len(actual_modular_result.top_passages) > 0 - assert isinstance(actual_modular_result.processing_stats, dict) - - def test_enhanced_fields_population(self, mock_fastapi_app, test_state): - """Test enhanced state fields are properly populated with Pydantic models.""" - # Create mock result with enhanced fields - modular_result = test_state.model_copy() - modular_result.chunks = [ - Chunk( - paper_id="cardio_001", - content="Cardiovascular disease remains a leading cause", - section="introduction", - token_count=12, - char_start=0, - char_end=100, - ), - Chunk( - paper_id="neuro_002", - content="Neurodegenerative diseases affect millions", - section="introduction", - token_count=8, - ), - ] - modular_result.relevant_passages = [ - Passage( - content="Cardiovascular disease remains a leading cause", - paper_id="cardio_001", - section="introduction", - retrieval_score=0.95, - scores=RetrievalScores(semantic_score=0.92), - ) - ] - modular_result.processing_metadata = ProcessingMetadata( - total_papers=2, - processed_papers=2, - total_chunks=3, - chunks_embedded=3, - ) - - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - agent = ModularProcessingAgent(mock_fastapi_app) - result = agent(test_state.model_copy()) - - # Validate chunks - assert len(result.chunks) > 0 - for chunk in result.chunks: - assert isinstance(chunk, Chunk) - assert chunk.paper_id in ["cardio_001", "neuro_002"] - assert chunk.content is not None and len(chunk.content) > 10 - assert chunk.section in [ - "introduction", - "methods", - "results", - "discussion", - "conclusion", - "unknown", - ] - - # Validate relevant_passages - assert len(result.relevant_passages) > 0 - for passage in result.relevant_passages: - assert isinstance(passage, Passage) - assert passage.paper_id in ["cardio_001", "neuro_002"] - assert passage.content is not None and len(passage.content) > 10 - assert passage.retrieval_score >= 0.0 - assert isinstance(passage.scores, RetrievalScores) - - # Validate processing_metadata - assert result.processing_metadata is not None - assert isinstance(result.processing_metadata, ProcessingMetadata) - assert result.processing_metadata.total_papers == 2 - assert result.processing_metadata.processed_papers >= 0 - - def test_legacy_compatibility_preserved(self, mock_fastapi_app, test_state): - """Test that legacy fields work exactly as before.""" - # Create mock result with legacy-compatible behavior - modular_result = test_state.model_copy() - modular_result.top_passages = [ - Passage( - content=f"Legacy passage {i}", - paper_id="cardio_001", - retrieval_score=0.95 - i * 0.05, - ) - for i in range(10) - ] - modular_result.processing_stats = { - "total_papers": 2, - "total_time": 1.8, - "processed_papers": 2, - "chunks_embedded": 5, - "retrieval_candidates": 25, - } - - # Test modular agent maintains legacy compatibility - with patch.object(ModularProcessingAgent, "_warmup_models"), patch( - "agents.processing.create_embedding_generator_from_app", return_value=Mock() - ), patch.object( - ModularProcessingAgent, "__call__", return_value=modular_result - ): - agent = ModularProcessingAgent(mock_fastapi_app) - result = agent(test_state.model_copy()) - - # Legacy fields should be identically populated as legacy agent - assert len(result.top_passages) == 10 # Should return exactly 10 - assert isinstance(result.processing_stats, dict) - assert "total_papers" in result.processing_stats - assert "total_time" in result.processing_stats - assert "processed_papers" in result.processing_stats - - # Validate passage structure matches legacy format - for passage in result.top_passages: - # Can be either Passage objects or dicts for compatibility - if isinstance(passage, dict): - assert "content" in passage - assert "paper_id" in passage - assert "retrieval_score" in passage diff --git a/tests/unit/test_processing_agent.py b/tests/unit/test_processing_agent.py deleted file mode 100644 index 3528863c61c8d31444266714737d7a312638e5b0..0000000000000000000000000000000000000000 --- a/tests/unit/test_processing_agent.py +++ /dev/null @@ -1,471 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.integration, pytest.mark.slow] -from models.state import State, Paper, PDFContent -import numpy as np -from unittest.mock import Mock, patch -import asyncio -from agents.processing_agent import ProcessingAgent - - -@pytest.fixture -def mock_app(): - """Mock FastAPI app with cached models""" - app = Mock() - - # Mock embedding model - mock_model = Mock() - mock_model.encode = Mock( - return_value=np.array([[0.1] * 384]) - ) # Mock query embedding - - # Mock app state - app.state.embedding_model = mock_model - return app - - -@pytest.fixture -def agent(mock_app): - return ProcessingAgent(mock_app) - - -@pytest.fixture -def sample_filtered_papers(): - """Create sample filtered papers""" - return [ - Paper( - paper_id="paper1", - title="Test Paper 1", - authors=["Author A"], - year=2023, - journal="Nature", - abstract="Abstract 1", - pdf_url="https://example.com/1.pdf", - type="article", - ), - Paper( - paper_id="paper2", - title="Test Paper 2", - authors=["Author B"], - year=2023, - journal="Science", - abstract="Abstract 2", - pdf_url="https://example.com/2.pdf", - type="article", - ), - ] - - -@pytest.fixture -def sample_pdf_contents(): - """Create sample PDF contents""" - return [ - PDFContent( - paper_id="paper1", - raw_text=""" -1. Introduction - -This paper discusses test topics in detail. The introduction covers background material. - -2. Methods - -We used various methods for testing. - -3. Results - -The results show clear findings. - -4. Discussion - -Discussion of implications. -""", - page_count=5, - char_count=1000, - extraction_time=1.0, - ), - PDFContent( - paper_id="paper2", - raw_text=""" -Single section paper without clear divisions. - -This paper has content but no numbered sections. -More content here. -""", - page_count=3, - char_count=600, - extraction_time=0.8, - ), - ] - - -def test_processing_agent_callable(agent, sample_filtered_papers, sample_pdf_contents): - """Test ProcessingAgent is callable and returns State with top_passages and processing_stats""" - state = State( - original_query="test query", - optimized_query="optimized test query", - filtered_papers=sample_filtered_papers, - pdf_contents=sample_pdf_contents, - ) - - # Mock all the internal components - with patch("asyncio.run") as mock_asyncio_run, patch( - "utils.embedding_manager.isinstance", return_value=True - ), patch.object( - agent.section_detector, "detect_sections" - ) as mock_detect, patch.object( - agent.embedding_manager, "process_chunks_async" - ) as mock_embed, patch.object( - agent.hybrid_retriever, "build_indices" - ) as mock_build, patch.object( - agent.hybrid_retriever, "retrieve" - ) as mock_retrieve, patch.object( - agent.reranker, "rerank" - ) as mock_rerank: - - # Setup asyncio.run to return the mock embedding result - mock_asyncio_run.return_value = [ - { - "content": "chunk1", - "section": "introduction", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - { - "content": "chunk2", - "section": "methods", - "paper_id": "paper1", - "embedding": [0.2] * 384, - "embedding_dim": 384, - }, - { - "content": "chunk3", - "section": "unknown", - "paper_id": "paper2", - "embedding": [0.3] * 384, - "embedding_dim": 384, - }, - ] - - # Mock section detection - first paper has multiple sections, second has fallback - mock_detect.side_effect = [ - [ - {"content": "Intro content", "section": "introduction", "start_pos": 0}, - {"content": "Methods content", "section": "methods", "start_pos": 100}, - ], - [ - {"content": "Fallback content", "section": "unknown", "start_pos": 0} - ], # Fallback - ] - - # Mock embedding - return chunks with embeddings - mock_embed.return_value = [ - { - "content": "chunk1", - "section": "introduction", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - { - "content": "chunk2", - "section": "methods", - "paper_id": "paper1", - "embedding": [0.2] * 384, - "embedding_dim": 384, - }, - { - "content": "chunk3", - "section": "unknown", - "paper_id": "paper2", - "embedding": [0.3] * 384, - "embedding_dim": 384, - }, - ] - - mock_build.return_value = 0.1 - mock_retrieve.return_value = [ - { - "content": "chunk1", - "section": "introduction", - "paper_id": "paper1", - "retrieval_score": 0.8, - }, - { - "content": "chunk2", - "section": "methods", - "paper_id": "paper1", - "retrieval_score": 0.7, - }, - ] - mock_rerank.return_value = [ - { - "content": "chunk1", - "section": "introduction", - "paper_id": "paper1", - "retrieval_score": 0.8, - "cross_encoder_score": 0.9, - "final_score": 0.9, - }, - { - "content": "chunk2", - "section": "methods", - "paper_id": "paper1", - "retrieval_score": 0.7, - "cross_encoder_score": 0.85, - "final_score": 0.85, - }, - ] - - # Call the agent - result_state = agent(state) - - # Verify result is a new State instance (side-effect free) - assert isinstance(result_state, State) - assert result_state is not state # Different object - - # Verify top_passages - assert len(result_state.top_passages) == 2 - - # Convert Passage objects to dicts for compatibility and testing - passages_dict = [ - p.model_dump() if hasattr(p, "model_dump") else p - for p in result_state.top_passages - ] - - # Verify content fields in returned passages - assert passages_dict[0]["content"] == "chunk1" - assert passages_dict[0]["section"] == "introduction" - assert passages_dict[0]["paper_id"] == "paper1" - assert "retrieval_score" in passages_dict[0] - assert "cross_encoder_score" in passages_dict[0] - assert "final_score" in passages_dict[0] - - # Verify processing_stats - stats = result_state.processing_stats - assert isinstance(stats, dict) - assert stats["total_papers"] == 2 - assert stats["processed_papers"] == 2 - assert stats["skipped_papers"] == 0 - assert "total_time" in stats - assert stats["total_time"] > 0 - assert "stage_times" in stats - assert "section_detection" in stats["stage_times"] - assert "chunking" in stats["stage_times"] - assert "embedding" in stats["stage_times"] - assert "index_build" in stats["stage_times"] - assert "retrieval" in stats["stage_times"] - assert "reranking" in stats["stage_times"] - - -def test_processing_agent_handles_empty_filtered_papers(agent): - """Test ProcessingAgent handles empty filtered_papers gracefully""" - state = State( - original_query="test query", - filtered_papers=[], - ) - - result_state = agent(state) - - assert len(result_state.top_passages) == 0 - assert result_state.processing_stats["total_papers"] == 0 - assert result_state.processing_stats["error"] == "No filtered papers" - assert result_state.processing_stats["reason"] == "Empty filtered_papers list" - - -def test_processing_agent_handles_missing_pdf_content(agent, sample_filtered_papers): - """Test ProcessingAgent skips papers without PDF content""" - # State with papers but no matching PDF contents - state = State( - original_query="test query", - filtered_papers=sample_filtered_papers, - pdf_contents=[], # No PDF contents - ) - - result_state = agent(state) - - # Should skip both papers and return empty results with error - assert len(result_state.top_passages) == 0 - assert result_state.processing_stats["total_papers"] == 2 - assert result_state.processing_stats["processed_papers"] == 0 - assert result_state.processing_stats["skipped_papers"] == 2 - assert "error" in result_state.processing_stats - - -def test_processing_agent_chunking_fallback( - agent, sample_filtered_papers, sample_pdf_contents -): - """Test ProcessingAgent uses fallback chunking when sections < 2""" - state = State( - original_query="test query", - filtered_papers=sample_filtered_papers, - pdf_contents=sample_pdf_contents, - ) - - with patch("asyncio.run") as mock_asyncio_run, patch.object( - agent.section_detector, "detect_sections" - ) as mock_detect, patch.object( - agent.embedding_manager, "process_chunks_async" - ) as mock_embed, patch.object( - agent.hybrid_retriever, "build_indices" - ) as mock_build, patch.object( - agent.hybrid_retriever, "retrieve" - ) as mock_retrieve, patch.object( - agent.reranker, "rerank" - ) as mock_rerank: - - # Setup asyncio.run to return the mock embedding result - mock_asyncio_run.return_value = [ - { - "content": "fallback chunk", - "section": "unknown", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - ] - - # Mock detection: one paper with single section (triggers fallback) - mock_detect.return_value = [ - {"content": "Single section content", "section": "unknown", "start_pos": 0} - ] - - mock_embed.return_value = [ - { - "content": "fallback chunk", - "section": "unknown", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - ] - - mock_build.return_value = 0.1 - mock_retrieve.return_value = [ - { - "content": "fallback chunk", - "section": "unknown", - "paper_id": "paper1", - "retrieval_score": 0.8, - } - ] - mock_rerank.return_value = [ - { - "content": "fallback chunk", - "section": "unknown", - "paper_id": "paper1", - "retrieval_score": 0.8, - "cross_encoder_score": 0.9, - "final_score": 0.9, - } - ] - - result_state = agent(state) - - assert len(result_state.top_passages) == 1 - assert ( - result_state.processing_stats["fallback_used_count"] == 2 - ) # Both papers fallback - # Convert Passage object to dict for compatibility - passages_dict = [ - p.model_dump() if hasattr(p, "model_dump") else p - for p in result_state.top_passages - ] - # Passage model normalizes "unknown" sections to "other" - assert passages_dict[0]["section"] == "other" - - -def test_processing_agent_stats_structure( - agent, sample_filtered_papers, sample_pdf_contents -): - """Test processing_stats contains all required fields and counts""" - state = State( - original_query="test query", - filtered_papers=sample_filtered_papers, - pdf_contents=sample_pdf_contents, - ) - - with patch("asyncio.run") as mock_asyncio_run, patch.object( - agent.section_detector, "detect_sections" - ) as mock_detect, patch.object( - agent.embedding_manager, "process_chunks_async" - ) as mock_embed, patch.object( - agent.hybrid_retriever, "build_indices" - ) as mock_build, patch.object( - agent.hybrid_retriever, "retrieve" - ) as mock_retrieve, patch.object( - agent.reranker, "rerank" - ) as mock_rerank: - - # Setup asyncio.run to return the mock embedding result - mock_asyncio_run.return_value = [ - { - "content": "chunk", - "section": "introduction", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - ] - - mock_detect.return_value = [ - {"content": "content", "section": "introduction", "start_pos": 0} - ] - mock_embed.return_value = [ - { - "content": "chunk", - "section": "introduction", - "paper_id": "paper1", - "embedding": [0.1] * 384, - "embedding_dim": 384, - }, - ] - mock_build.return_value = 0.1 - mock_retrieve.return_value = [ - { - "content": "chunk", - "section": "introduction", - "paper_id": "paper1", - "retrieval_score": 0.8, - } - ] - mock_rerank.return_value = [ - { - "content": "chunk", - "section": "introduction", - "paper_id": "paper1", - "retrieval_score": 0.8, - "cross_encoder_score": 0.9, - "final_score": 0.9, - } - ] - - result_state = agent(state) - - stats = result_state.processing_stats - - # Required count fields - assert "total_papers" in stats - assert "processed_papers" in stats - assert "skipped_papers" in stats - assert "total_sections" in stats - assert "total_chunks" in stats - assert "fallback_used_count" in stats - assert "chunks_embedded" in stats - assert "retrieval_candidates" in stats - assert "reranked_passages" in stats - - # Time tracking - assert "total_time" in stats - assert "stage_times" in stats - assert all( - key in stats["stage_times"] - for key in [ - "section_detection", - "chunking", - "embedding", - "index_build", - "retrieval", - "reranking", - ] - ) diff --git a/tests/unit/test_processing_integration.py b/tests/unit/test_processing_integration.py deleted file mode 100644 index 50d4c66e6ca3a634e878c1be2c6c250a0d2158cd..0000000000000000000000000000000000000000 --- a/tests/unit/test_processing_integration.py +++ /dev/null @@ -1,6 +0,0 @@ -import pytest - -pytest.skip( - "moved to tests/integration/test_processing_integration.py", - allow_module_level=True, -) diff --git a/tests/unit/test_reranker.py b/tests/unit/test_reranker.py deleted file mode 100644 index 0a1c5f1375682ae182cc24313b3098191cb79e9a..0000000000000000000000000000000000000000 --- a/tests/unit/test_reranker.py +++ /dev/null @@ -1,704 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.unit] -import time -import numpy as np -from unittest.mock import MagicMock, patch, AsyncMock -from concurrent.futures import ThreadPoolExecutor -import asyncio - -from retrieval.reranker import CrossEncoderReranker - - -@pytest.fixture -def sample_passages(): - """Create sample passages for testing reranker.""" - return [ - { - "content": "Machine learning algorithms for natural language processing tasks in scientific research.", - "doc_id": 0, - "retrieval_score": 0.85, - "section": "abstract", - }, - { - "content": "Deep neural networks in computer vision applications for medical imaging analysis.", - "doc_id": 1, - "retrieval_score": 0.82, - "section": "abstract", - }, - { - "content": "Cardiovascular effects of intermittent fasting studies in clinical research.", - "doc_id": 2, - "retrieval_score": 0.78, - "section": "abstract", - }, - { - "content": "Statistical methods for biomedical research data analysis and visualization.", - "doc_id": 3, - "retrieval_score": 0.75, - "section": "abstract", - }, - { - "content": "Artificial intelligence in medical diagnosis systems for healthcare applications.", - "doc_id": 4, - "retrieval_score": 0.72, - "section": "introduction", - }, - { - "content": "Intermittent fasting impacts on cardiovascular health research outcomes.", - "doc_id": 5, - "retrieval_score": 0.68, - "section": "methods", - }, - { - "content": "Natural language processing with transformer models for scientific literature.", - "doc_id": 6, - "retrieval_score": 0.65, - "section": "results", - }, - { - "content": "Neural network architectures for image recognition in medical scans.", - "doc_id": 7, - "retrieval_score": 0.62, - "section": "discussion", - }, - { - "content": "Fasting protocols and heart disease prevention clinical trial data.", - "doc_id": 8, - "retrieval_score": 0.59, - "section": "conclusion", - }, - { - "content": "Machine learning for healthcare data analysis in research studies.", - "doc_id": 9, - "retrieval_score": 0.55, - "section": "references", - }, - { - "content": "Cardiovascular research studies on fasting and metabolic health outcomes.", - "doc_id": 10, - "retrieval_score": 0.52, - "section": "abstract", - }, - { - "content": "Statistical analysis of clinical trials in cardiovascular research.", - "doc_id": 11, - "retrieval_score": 0.48, - "section": "methods", - }, - { - "content": "Deep learning transformer models for medical text processing.", - "doc_id": 12, - "retrieval_score": 0.45, - "section": "results", - }, - { - "content": "Artificial intelligence applications in cardiovascular disease diagnosis.", - "doc_id": 13, - "retrieval_score": 0.42, - "section": "introduction", - }, - { - "content": "Clinical research on intermittent fasting and heart health metrics.", - "doc_id": 14, - "retrieval_score": 0.38, - "section": "discussion", - }, - ] - - -@pytest.fixture -def mock_scores(): - """Mock cross-encoder scores for confident vs ambiguous cases.""" - # High confidence case: clear top result (gap = (0.9-0.1)/0.9 = 0.888 > 0.8) - confident_scores = [ - 0.9, - 0.1, - 0.08, - 0.05, - 0.03, - 0.02, - 0.01, - 0.005, - 0.002, - 0.001, - 0.0005, - 0.0002, - 0.0001, - 0.00005, - 0.00002, - ] - - # Low confidence case: ambiguous top results (gap = (0.7-0.68)/0.7 ≈ 0.029 < 0.8) - ambiguous_scores = [ - 0.7, - 0.68, - 0.52, - 0.48, - 0.45, - 0.42, - 0.38, - 0.35, - 0.32, - 0.28, - 0.25, - 0.22, - 0.18, - 0.15, - 0.12, - ] - - return {"confident": confident_scores, "ambiguous": ambiguous_scores} - - -class TestCrossEncoderReranker: - """Test cross-encoder reranker functionality.""" - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - def test_initialization(self, mock_init): - """Test reranker initialization with default parameters.""" - # Mock initialization to prevent eager loading for isolated testing - mock_init.return_value = None - - reranker = CrossEncoderReranker() - assert reranker.model_name == "cross-encoder/ms-marco-MiniLM-L-6-v2" - assert reranker.model is None # Model not loaded yet - assert reranker.max_seq_length == 512 - assert reranker.confidence_threshold == 0.8 - assert reranker.rerank_time_ms == 0.0 - assert reranker.skip_count == 0 - assert reranker.total_count == 0 - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - def test_custom_parameters(self, mock_init): - """Test reranker with custom model and threshold.""" - # Mock initialization to prevent eager loading - mock_init.return_value = None - - reranker = CrossEncoderReranker( - model_name="custom-model", - ) - # Override confidence threshold (would normally require reinit) - reranker.confidence_threshold = 0.5 - - assert reranker.model_name == "custom-model" - assert reranker.confidence_threshold == 0.5 - - def test_compute_confidence_gap(self): - """Test confidence gap computation.""" - reranker = CrossEncoderReranker() - - # High confidence case - scores_high = [0.9, 0.1, 0.05, 0.02, 0.01] - gap_high = reranker._compute_confidence_gap(scores_high) - assert abs(gap_high - 0.888888888888889) < 1e-6 # (0.9 - 0.1) / 0.9 - - # Low confidence case - scores_low = [0.5, 0.48, 0.45, 0.42, 0.38] - gap_low = reranker._compute_confidence_gap(scores_low) - assert abs(gap_low - 0.04) < 1e-6 # (0.5 - 0.48) / 0.5 = 0.04 - - # Edge cases - scores_single = [0.8] - gap_single = reranker._compute_confidence_gap(scores_single) - assert gap_single == 1.0 - - scores_zero = [0.0, 0.0] - gap_zero = reranker._compute_confidence_gap(scores_zero) - assert gap_zero == 0.0 - - def test_should_skip_reranking(self): - """Test reranking skip decision logic.""" - reranker = CrossEncoderReranker() - - # Should skip: high confidence (gap = (0.9-0.1)/0.9 = 0.888) - scores_confident = [0.9, 0.1, 0.08, 0.05, 0.02] - assert reranker._should_skip_reranking(scores_confident) - - # Should not skip: low confidence (gap = (0.7-0.68)/0.7 ≈ 0.029) - scores_ambiguous = [0.7, 0.68, 0.65, 0.62, 0.58] - assert not reranker._should_skip_reranking(scores_ambiguous) - - # Edge case: single result - scores_single = [0.9] - assert reranker._should_skip_reranking(scores_single) - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - @patch("retrieval.reranker.CrossEncoder") - def test_model_loading(self, mock_cross_encoder, mock_init): - """Test cross-encoder model loading.""" - # Prevent eager initialization - mock_init.return_value = None - - mock_model = MagicMock() - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - reranker._load_model() - - mock_cross_encoder.assert_called_once_with( - "cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512 - ) - assert reranker.model == mock_model - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - @patch( - "retrieval.reranker.CrossEncoder", side_effect=Exception("Model load failed") - ) - def test_model_loading_failure(self, mock_cross_encoder, mock_init): - """Test model loading failure handling with fallback.""" - # Prevent eager initialization for isolated testing - mock_init.return_value = None - - reranker = CrossEncoderReranker() - - with pytest.raises( - RuntimeError, match="All cross-encoder models failed to load" - ): - reranker._load_model() - - def test_passage_validation(self, sample_passages): - """Test passage validation and preprocessing.""" - reranker = CrossEncoderReranker() - - # Valid passages - validated = reranker._validate_passages(sample_passages[:10]) # Top 10 - assert len(validated) == 10 - for passage in validated: - assert "content" in passage - assert "doc_id" in passage - assert passage["content"].strip() != "" - - # Empty passages should be filtered - invalid_passages = [ - {"content": "", "doc_id": 0}, - {"content": "valid content", "doc_id": 1}, - ] - validated_invalid = reranker._validate_passages(invalid_passages) - assert len(validated_invalid) == 1 - - # Missing content field - broken_passages = [{"doc_id": 0}] # Missing content - with pytest.raises(ValueError, match="missing required 'content' field"): - reranker._validate_passages(broken_passages) - - def test_passage_truncation(self): - """Test passage truncation for context limits.""" - reranker = CrossEncoderReranker() - - # Short content - no truncation - short_content = "Short passage." - truncated = reranker._truncate_passage(short_content) - assert truncated == short_content - - # Long content - truncation occurs and is limited to max_seq_length - long_content = "A" * (reranker.max_seq_length * 5) # Very long - truncated = reranker._truncate_passage(long_content) - - # With precise tokenization, should be very close to max_seq_length - # We allow some tolerance for tokenizer precision - if reranker.tokenizer is not None: - # Using real tokenizer - should be exactly at limit - tokens = reranker.tokenizer.encode(truncated, add_special_tokens=False) - assert ( - len(tokens) <= reranker.max_seq_length * 1.2 - ) # More tolerance for real tokenization - else: - # Fallback character-based estimation - estimated_tokens = len(truncated) // 4 - assert estimated_tokens <= reranker.max_seq_length * 1.5 # More tolerance - - # Should try to cut at sentence boundary - content_with_sentences = ( - "First sentence. Second sentence! Third sentence? Long continuation..." - ) * 100 # Make it moderately long to test truncation - truncated = reranker._truncate_passage(content_with_sentences) - - # Should be truncated to something reasonable - assert len(truncated) < len(content_with_sentences) - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - @patch("retrieval.reranker.CrossEncoder") - def test_passage_scoring(self, mock_cross_encoder, mock_init, sample_passages): - """Test cross-encoder passage scoring.""" - # Prevent eager initialization for isolated testing - mock_init.return_value = None - - mock_model = MagicMock() - mock_model.predict.return_value = np.array([0.9, 0.7, 0.5, 0.3, 0.1]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - # Manually load model for this test - reranker._load_model() - scores = reranker._score_passages("test query", sample_passages[:5]) - - assert len(scores) == 5 - assert scores == [0.9, 0.7, 0.5, 0.3, 0.1] - - # Check that predict was called once for scoring (warmup is mocked) - assert mock_model.predict.call_count == 1 - call_args = mock_model.predict.call_args[0][0] - - # Check that pairs were prepared correctly - expected_pairs = [("test query", p["content"]) for p in sample_passages[:5]] - assert len(call_args) == len(expected_pairs) - for i, pair in enumerate(call_args): - assert pair[0] == "test query" - assert pair[1] == expected_pairs[i][1] - - @patch("retrieval.reranker.CrossEncoderReranker._initialize_model") - @patch("retrieval.reranker.CrossEncoder") - def test_scoring_failure(self, mock_cross_encoder, mock_init, sample_passages): - """Test scoring failure handling with graceful fallback.""" - # Prevent eager initialization for isolated testing - mock_init.return_value = None - - # Mock successful model loading but failed prediction - mock_model = MagicMock() - mock_model.predict.side_effect = Exception("Prediction failed") - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - # Manually load model for this test - reranker._load_model() - - # Should return all zeros instead of raising an error (graceful fallback) - scores = reranker._score_passages("test query", sample_passages[:5]) - assert scores == [0.0] * 5 # All zero scores as fallback - assert len(scores) == 5 - - def test_rerank_passages(self, sample_passages, mock_scores): - """Test passage reranking with cross-encoder scores.""" - reranker = CrossEncoderReranker() - - # Test reranking with confident scores - scores = mock_scores["confident"] - reranked = reranker._rerank_passages(sample_passages[: len(scores)], scores) - - assert len(reranked) == len(scores) - - # Check metadata fields are added - for passage in reranked: - assert "cross_encoder_score" in passage - assert "final_score" in passage - assert "rerank_position" in passage - assert passage["rerank_position"] >= 1 - assert passage["rerank_position"] <= len(scores) - - # Verify ranking by cross-encoder score - prev_score = float("inf") - for passage in reranked: - assert passage["cross_encoder_score"] <= prev_score - prev_score = passage["cross_encoder_score"] - - @patch("retrieval.reranker.CrossEncoder") - def test_full_reranking_pipeline_confident_scores( - self, mock_cross_encoder, sample_passages, mock_scores - ): - """Test full reranking pipeline with confident scores (should skip reranking).""" - mock_model = MagicMock() - # Return confident scores - should trigger skip - mock_model.predict.return_value = np.array(mock_scores["confident"]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - query = "machine learning cardiovascular fasting" - - results, metrics = reranker.rerank(query, sample_passages, return_metrics=True) - - # Should skip reranking due to high confidence - assert len(results) == 10 # Return top 10 - assert metrics["skipped_reranking"] is True - assert metrics["skip_count"] == 1 - assert metrics["total_reranks"] == 1 - - # Verify scores were computed but ranking unchanged - assert all("cross_encoder_score" in r for r in results) - assert all("rerank_position" in r for r in results) - - # Since skipped, order should match input order - for i, result in enumerate(results): - assert result["doc_id"] == sample_passages[i]["doc_id"] - - @patch("retrieval.reranker.CrossEncoder") - def test_full_reranking_pipeline_ambiguous_scores( - self, mock_cross_encoder, sample_passages, mock_scores - ): - """Test full reranking pipeline with ambiguous scores (should fully rerank).""" - mock_model = MagicMock() - # Return ambiguous scores - should fully rerank - mock_model.predict.return_value = np.array(mock_scores["ambiguous"]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - query = "neural networks medical imaging" - - results, metrics = reranker.rerank(query, sample_passages, return_metrics=True) - - # Should perform full reranking - assert len(results) == 10 - assert metrics["skipped_reranking"] is False - assert metrics["skip_count"] == 0 - assert metrics["total_reranks"] == 1 - - # Verify reranked by score (descending) - prev_score = float("inf") - for result in results: - assert result["cross_encoder_score"] <= prev_score - prev_score = result["cross_encoder_score"] - - # Check ranking changed (likely reordered) - assert metrics["ranking_changes"] >= 0 # Could be 0 if input was already sorted - - def test_few_passages_case(self, sample_passages): - """Test reranking with few passages (no cross-encoder needed).""" - reranker = CrossEncoderReranker() - query = "test query" - - # Less than 11 passages - few_passages = sample_passages[:5] - results = reranker.rerank(query, few_passages) - - assert len(results) == 5 - for result in results: - assert result["cross_encoder_score"] == 0.0 - assert result["final_score"] == result["retrieval_score"] - assert result["rerank_position"] >= 1 - - def test_empty_passages_error(self): - """Test error handling for empty passage list.""" - reranker = CrossEncoderReranker() - - with pytest.raises(ValueError, match="Cannot rerank empty passage list"): - reranker._validate_passages([]) - - def test_invalid_passage_structure(self): - """Test error handling for invalid passage structures.""" - reranker = CrossEncoderReranker() - - invalid_passages = [ - "not a dict", - {"no_content": "missing required field"}, - None, - ] - - for invalid in invalid_passages: - with pytest.raises(ValueError): - reranker._validate_passages([invalid]) - - @patch("retrieval.reranker.CrossEncoder") - def test_performance_tracking( - self, mock_cross_encoder, sample_passages, mock_scores - ): - """Test performance metrics tracking.""" - mock_model = MagicMock() - mock_model.predict.return_value = np.array(mock_scores["ambiguous"]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - - # Run multiple reranks to test skip rate tracking - for i in range(3): - if i % 2 == 0: - # Alternate between confident and ambiguous - mock_model.predict.return_value = np.array(mock_scores["confident"]) - reranker.rerank("query", sample_passages) - else: - mock_model.predict.return_value = np.array(mock_scores["ambiguous"]) - reranker.rerank("query", sample_passages) - - # Should have 2 skips out of 3 total (i=0 and i=2 use confident scores) - assert reranker.skip_count == 2 - assert reranker.total_count == 3 - - # Last run should provide metrics - results, metrics = reranker.rerank( - "final query", sample_passages, return_metrics=True - ) - # Expect skip rate of 3/4 = 0.75 (3 confident scores out of 4 total calls) - assert metrics["skip_rate"] == 0.75 - - @pytest.mark.asyncio - @patch("retrieval.reranker.CrossEncoder") - async def test_async_reranking( - self, mock_cross_encoder, sample_passages, mock_scores - ): - """Test async reranking functionality.""" - mock_model = MagicMock() - mock_model.predict.return_value = np.array(mock_scores["confident"]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - - with ThreadPoolExecutor() as executor: - results = await reranker.rerank_async( - "async query", sample_passages, executor=executor - ) - - assert len(results) == 10 - assert all("cross_encoder_score" in r for r in results) - - @pytest.mark.asyncio - async def test_async_without_executor(self, sample_passages): - """Test async reranking creates its own executor.""" - reranker = CrossEncoderReranker() - - # Should work without providing executor - results = await reranker.rerank_async("async query", sample_passages[:5]) - - assert len(results) == 5 - assert all("cross_encoder_score" in r for r in results) - - def test_metrics_computation_confident_case(self, sample_passages, mock_scores): - """Test metrics computation for confidence-based skipping.""" - reranker = CrossEncoderReranker() - - scores = mock_scores["confident"] - results = sample_passages[:10] # Would be reordered if not skipped - - metrics = reranker._compute_metrics("test query", scores, results, True, 125.5) - - assert metrics["event"] == "reranking_complete" - assert metrics["query_length"] == len("test query") - assert metrics["num_passages_input"] == len(scores) - assert metrics["num_passages_output"] == len(results) - assert metrics["rerank_time_ms"] == 125.5 - assert metrics["skipped_reranking"] is True - assert round(metrics["top_cross_encoder_score"], 4) == 0.9 - assert metrics["avg_cross_encoder_score"] > 0 - assert metrics["cross_encoder_score_std"] > 0 - - def test_metrics_computation_reranked_case(self, sample_passages): - """Test metrics computation for full reranking.""" - reranker = CrossEncoderReranker() - - # Simulate reranked results (different order) - scores = [0.8, 0.7, 0.6, 0.5, 0.4][:5] - reranked_results = sample_passages[:5] # In different order after reranking - - metrics = reranker._compute_metrics( - "test query", scores, reranked_results, False, 250.0 - ) - - assert metrics["skipped_reranking"] is False - assert metrics["ranking_changes"] >= 0 # May be 0 if input was already optimal - - @patch("retrieval.reranker.CrossEncoder") - def test_memory_usage_tracking( - self, mock_cross_encoder, sample_passages, mock_scores - ): - """Test memory usage tracking during inference.""" - from unittest.mock import patch - - # Use ambiguous scores to ensure reranking happens (memory tracking only during inference) - mock_model = MagicMock() - mock_model.predict.return_value = np.array(mock_scores["ambiguous"]) - mock_cross_encoder.return_value = mock_model - - reranker = CrossEncoderReranker() - - # Mock memory usage method properly using patch.object - with patch.object( - reranker, "_get_memory_usage", side_effect=[100, 150, 145] - ) as mock_mem: - results, metrics = reranker.rerank( - "memory test", sample_passages, return_metrics=True - ) - - # Verify memory tracking was called during inference - mock_mem.assert_called() - - # Should have performed reranking and tracked memory - assert metrics["skipped_reranking"] is False - assert "memory_peak_mb" in metrics # Memory tracking field exists - - def test_ndcg_improvement_calculation(self, sample_passages): - """Test ranking quality improvement measurement.""" - reranker = CrossEncoderReranker() - - # Create scenario where reranking improves order - scores = [0.8, 0.6, 0.9, 0.4, 0.7] # Best score at position 2 - reranked = reranker._rerank_passages(sample_passages[:5], scores) - - # Check top result after reranking - assert reranked[0]["cross_encoder_score"] == 0.9 - assert reranked[0]["rerank_position"] == 1 - - # Original doc_id 2 (with score 0.9) should be moved to position 0 - original_order_ids = [p["doc_id"] for p in sample_passages[:5]] - reranked_ids = [p["doc_id"] for p in reranked] - - # Should be reordered - assert original_order_ids != reranked_ids - - def test_edge_case_identical_scores(self, sample_passages): - """Test handling of identical cross-encoder scores.""" - reranker = CrossEncoderReranker() - - # All same scores - scores = [0.5] * 10 - reranked = reranker._rerank_passages(sample_passages[:10], scores) - - assert len(reranked) == 10 - # All should have same score - assert all(r["cross_encoder_score"] == 0.5 for r in reranked) - # All positions should be assigned - positions = [r["rerank_position"] for r in reranked] - assert set(positions) == set(range(1, 11)) - - def test_performance_targets_meet_requirements(self, sample_passages, mock_scores): - """Test that reranking meets performance targets.""" - reranker = CrossEncoderReranker() - - # Test 1: Time targets - query = "performance benchmark query" - - # Mock fast inference - with patch("retrieval.reranker.CrossEncoder") as mock_ce: - mock_model = MagicMock() - mock_model.predict.return_value = np.array(mock_scores["confident"]) - mock_ce.return_value = mock_model - - start_time = time.perf_counter() - results, metrics = reranker.rerank( - query, sample_passages, return_metrics=True - ) - duration = time.perf_counter() - start_time - - # Should complete within reasonable time (allow generous limit for CI) - assert duration < 5.0 # 5 seconds max - - if not metrics["skipped_reranking"]: - # If not skipped, should be < 600ms (allow flexibility) - assert metrics["rerank_time_ms"] < 5000 # 5 seconds for test - - def test_error_handling_and_recovery(self, sample_passages): - """Test error handling and recovery mechanisms.""" - reranker = CrossEncoderReranker() - - # Test with truncated passages that exceed context - long_passage = {"content": "word " * 1000, "doc_id": 999} # Very long content - passages = sample_passages[:10] + [long_passage] - - # Should handle truncation gracefully - results = reranker.rerank("test query", passages) - - assert len(results) == 10 # Limited to top 10 - for result in results: - assert "cross_encoder_score" in result - - def test_logging_output_structure(self, sample_passages): - """Test that reranking completes without logging errors.""" - from loguru import logger - - reranker = CrossEncoderReranker() - - # Ensure logger is configured to catch any issues - with patch("retrieval.reranker.logger") as mock_logger: - # Force a reranking decision - few_passages = sample_passages[:5] # Will trigger no-reranking path - reranker.rerank("logging test", few_passages) - - # Should complete without throwing errors, regardless of logging - assert True # If we get here, no errors occurred diff --git a/tests/unit/test_search_agent.py b/tests/unit/test_search_agent.py deleted file mode 100644 index 01f3d93afc1e4d205dbf55be8c137f12789d17e3..0000000000000000000000000000000000000000 --- a/tests/unit/test_search_agent.py +++ /dev/null @@ -1,54 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.unit] -import inspect -from unittest.mock import patch, MagicMock, Mock -from agents.search import SearchAgent -from models.state import State, Paper - - -@pytest.fixture -def search_agent(): - with patch("agents.search.OpenAlexClient") as mock_openalex: - agent = SearchAgent() - agent.openalex_client = MagicMock() - return agent - - -@pytest.fixture -def mock_state(): - return State( - original_query="CRISPR gene editing", - optimized_query="CRISPR-Cas9 off-target effects in mammalian cells", - ) - - -def test_search_agent_uses_optimized_query(search_agent, mock_state): - """Test SearchAgent uses optimized_query instead of original_query""" - with patch.object(search_agent, "_query_openalex", return_value=[]): - search_agent.search(mock_state) - - # Verify _query_openalex was called with optimized query - calls = search_agent._query_openalex.call_args_list - assert any("CRISPR-Cas9 off-target effects" in str(call) for call in calls) - - -def test_search_agent_queries_two_paper_types(search_agent, mock_state): - """Test SearchAgent queries both 'review' and 'article' types""" - with patch.object(search_agent, "_query_openalex", return_value=[]) as mock_query: - search_agent.search(mock_state) - - # Should have 2 calls: one for reviews, one for articles - assert mock_query.call_count == 2 - - # Check the arguments of each call - call_args_list = mock_query.call_args_list - paper_types = [] - for call in call_args_list: - args, kwargs = call - paper_types.append( - kwargs["paper_type"] - ) # paper_type is passed as keyword argument - - assert "review" in paper_types - assert "article" in paper_types diff --git a/tests/unit/test_section_detector.py b/tests/unit/test_section_detector.py deleted file mode 100644 index 421bd6755fe8406d5de9dd52d75de837dc5ae08e..0000000000000000000000000000000000000000 --- a/tests/unit/test_section_detector.py +++ /dev/null @@ -1,402 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.unit] -from utils.section_detector import SectionDetector - - -@pytest.fixture -def detector(): - """Create a fresh SectionDetector instance for each test.""" - return SectionDetector() - - -def test_standard_academic_paper(detector): - """Test detection of standard academic paper with numbered section headers.""" - text = """1. Introduction - -This paper discusses machine learning techniques for section detection. - -2. Methods - -We used regex patterns to identify section headers. - -3. Results - -The results show that our approach works well. - -4. Discussion - -This method is efficient and accurate. - -5. Conclusion - -Future work could extend this approach.""" - - chunks = detector.detect_sections(text) - - # Should detect all 5 sections - assert len(chunks) == 5 - - # Check section types and labels - section_names = [chunk["section"] for chunk in chunks] - assert "introduction" in section_names - assert "methods" in section_names - assert "results" in section_names - assert "discussion" in section_names - assert "conclusion" in section_names - - # Check that positions are in ascending order - positions = [chunk["start_pos"] for chunk in chunks] - assert positions == sorted(positions) - - # Check content structure - for chunk in chunks: - assert "content" in chunk - assert "section" in chunk - assert "start_pos" in chunk - assert len(chunk["content"]) > 10 # Reasonable minimum content length - - -def test_non_standard_section_naming(detector): - """Test detection with variations in section naming.""" - text = """Abstract - -This is an overview of our research. - -Materials and Methods - -We collected data using various approaches. - -Findings - -Our results indicate significant improvements. - -Discussion and Results - -Here we discuss the implications.""" - - chunks = detector.detect_sections(text) - - # Should detect introduction/abstract section - assert any(s["section"] == "introduction" for s in chunks) - - # Check for methods section (materials and methods) - assert any(s["section"] == "methods" for s in chunks) - - # Check for results section - assert any(s["section"] == "results" for s in chunks) - - # Should detect sections despite non-standard naming - assert len(chunks) >= 3 - - -def test_fallback_chunking_behavior(detector): - """Test fallback to chunking when insufficient sections are detected.""" - text = """This is a poorly structured paper with just one main text block. - -It discusses various topics without clear section headers. - -There are no numbered sections or clear delimiters. - -This should trigger the fallback chunking mechanism.""" - - chunks = detector.detect_sections(text) - - # Should use fallback chunking (all chunks marked as "unknown") - assert all(chunk["section"] == "unknown" for chunk in chunks) - - # Should create chunks of appropriate size with overlap - for chunk in chunks: - assert len(chunk["content"]) > 0 - assert ( - len(chunk["content"]) <= 1100 - ) # chunk_size + some buffer for sentence boundary detection - - # At least one chunk should contain content - assert len(chunks) >= 1 - - # Check position ordering - if len(chunks) > 1: - positions = [chunk["start_pos"] for chunk in chunks] - assert positions == sorted(positions) - # Ensure there's some overlap between consecutive chunks - assert all( - positions[i + 1] < positions[i] + detector.chunk_size - for i in range(len(positions) - 1) - ) - - -def test_empty_text_error(detector): - """Test that empty text raises proper error.""" - with pytest.raises(ValueError, match="Invalid input text"): - detector.detect_sections("") - - with pytest.raises(ValueError, match="Invalid input text"): - detector.detect_sections(" ") - - with pytest.raises(ValueError, match="Input must be a string"): - detector.detect_sections(None) - - -def test_case_insensitive_section_detection(detector): - """Test that section detection works regardless of case.""" - text = """INTRODUCTION - -Uppercase header. - -introduction - -Lowercase header. - -IntRODucTIOn - -Mixed case header. - -Methods - -Regular methods section.""" - - chunks = detector.detect_sections(text) - - # Should detect multiple introduction sections - intro_count = sum(1 for chunk in chunks if chunk["section"] == "introduction") - assert intro_count >= 2 # At least the uppercase and lowercase ones - - # Should also detect methods section - assert any(chunk["section"] == "methods" for chunk in chunks) - - -def test_malformed_section_headers(detector): - """Test handling of malformed or confusing section headers.""" - text = """This paper has discussion in the middle of text and no proper structure. - -We also mention methods here and there. - -Results are scattered throughout. - -This should fallback to chunking.""" - - chunks = detector.detect_sections(text) - - # With scattered mentions, should fallback to chunking - assert all(chunk["section"] == "unknown" for chunk in chunks) - assert len(chunks) >= 1 - - -def test_section_boundary_accuracy(detector): - """Test that section content extraction maintains proper boundaries.""" - text = """1. Introduction - -This is introduction content that should be in the intro section with more text to ensure it passes the minimum content filter and provides sufficient substance for the minimum length requirements that we have in place. - -2. Methods - -This is methods content that belongs to the methods section with additional description to make it clearly substantial and provide enough length so that it passes all the filters we have implemented for section detection. - -3. Results - -Results content here with additional details and explanations to meet the minimum content requirements and make this section clearly distinct enough to be considered a valid section with sufficient length for testing purposes.""" - - chunks = detector.detect_sections(text) - - # Should have 2-3 sections depending on content filtering (main focus is boundary accuracy) - assert len(chunks) >= 2 - - # Verify we detect introduction and methods sections - section_types = {chunk["section"] for chunk in chunks} - assert "introduction" in section_types - assert "methods" in section_types - - # Check that content doesn't jump between sections - for chunk in chunks: - content_lower = chunk["content"].lower() - # Introduction chunk should not contain methods material - if chunk["section"] == "introduction": - assert "methods" not in content_lower - elif chunk["section"] == "methods": - assert "introduction" not in content_lower - - -def test_overlapping_section_headers(detector): - """Test that overlapping or nested section headers are handled properly.""" - text = """Experimental Methods and Materials and Methods - -This section combines two concepts. - -Experimental Results and Findings - -Combined results section.""" - - chunks = detector.detect_sections(text) - - # Should still detect sections properly despite overlap potentials - assert len(chunks) >= 1 - - -def test_subsection_filtering(detector): - """Test that subsections are properly filtered out.""" - text = """1. Introduction - -This is the main introduction section. - -1.1 Background - -This subsection should be ignored. - -2. Methods - -Main methods section. - -2.1 Data Collection - -This subsection should not appear as a main section.""" - - chunks = detector.detect_sections(text) - - # Should only detect main sections, not subsections - main_sections = [chunk["section"] for chunk in chunks] - assert "introduction" in main_sections - assert "methods" in main_sections - assert len(chunks) >= 2 - - # Verify that content doesn't inappropriately include subsection headers - for chunk in chunks: - content_lower = chunk["content"].lower() - assert "1.1 background" not in content_lower - assert "2.1 data collection" not in content_lower - - -def test_only_introduction_conclusion(detector): - """Test handling papers with only Introduction and Conclusion sections.""" - text = """Introduction - -This paper studies machine learning algorithms. - -Materials and Methods - -The methods used are described here. - -Results - -We achieved good results. - -Discussion - -Here we discuss the implications. - -Conclusion - -Future work is planned.""" - - chunks = detector.detect_sections(text) - - # Should detect sections despite lack of numbering - assert len(chunks) >= 4 - - # Should include introduction and conclusion - section_types = {chunk["section"] for chunk in chunks} - assert "introduction" in section_types - assert "conclusion" in section_types - - -@pytest.mark.skip( - reason="Memory-efficient mode test requires large memory allocation, run manually if needed" -) -def test_large_paper_memory_efficiency(detector): - """Test memory-efficient processing for large papers (approaching size limit).""" - from unittest.mock import patch - - # Use a moderately large text and mock the threshold to force memory-efficient mode - large_text = ( - "Introduction\n\n" - + "This is a large document with content. " * 10000 - + "\n\nMethods\n\n" - + "More content here. " * 10000 - ) - - # Temporarily mock the memory threshold to force memory-efficient mode - with patch.object( - detector, "memory_efficient_threshold", len(large_text.encode("utf-8")) - 1000 - ): - # Ensure we're testing memory-efficient mode - assert len(large_text.encode("utf-8")) > detector.memory_efficient_threshold - - # This should process successfully without raising errors and use memory-efficient mode - chunks = detector.detect_sections(large_text) - - # Should have chunks (either sections or fallback) - assert len(chunks) > 0 - - # Verify reasonable performance - memory efficient mode should work - assert all( - chunk["section"] - in [ - "introduction", - "methods", - "results", - "discussion", - "conclusion", - "unknown", - ] - for chunk in chunks - ) - - -def test_malformed_pdf_text_error_handling(detector): - """Test comprehensive error handling for malformed PDF text.""" - # Test null bytes - corrupted_text = "Good text\x00\x00\x00bad null bytes" * 1000 - with pytest.raises(ValueError, match="corrupted.*null bytes"): - detector.detect_sections(corrupted_text) - - # Test invalid UTF-8 - invalid_utf8 = b"\xff\xfe\xfd".decode("latin-1", errors="ignore") + "good text" - # This might pass if decoding succeeds, but we test the validation - if invalid_utf8: - try: - detector.detect_sections(invalid_utf8) - except ValueError as e: - assert "UTF-8" in str(e) or "input text" in str(e).lower() - - # Test extremely long text (exceeding size limit) - oversized_detector = SectionDetector(max_text_size_mb=1) # 1MB limit - large_text = "This is a test document. " * 100000 # About 2.5MB - with pytest.raises(ValueError, match="exceeds maximum.*size"): - oversized_detector.detect_sections(large_text) - - -def test_appendix_exclusion(detector): - """Test that appendices and supplemental material are excluded.""" - text = """1. Introduction - -Main introduction content. - -2. Methods - -Methods description. - -Appendix A - -This appendix should be ignored. - -Supplemental Material - -This should also be ignored. - -References - -References section should be ignored.""" - - chunks = detector.detect_sections(text) - - # Should detect main sections but not appendices - section_types = {chunk["section"] for chunk in chunks} - assert "introduction" in section_types - assert "methods" in section_types - - # Verify no content from appendices appears in main sections - for chunk in chunks: - content_lower = chunk["content"].lower() - assert "appendix a" not in content_lower - assert "supplemental material" not in content_lower - assert "references" not in content_lower diff --git a/tests/unit/test_startup.py b/tests/unit/test_startup.py deleted file mode 100644 index 6d8ab37608c86523be401d7e28b3ad4c34171a42..0000000000000000000000000000000000000000 --- a/tests/unit/test_startup.py +++ /dev/null @@ -1,145 +0,0 @@ -""" -Tests for FastAPI startup event and embedding model caching functionality. -""" - -import pytest - -pytestmark = [pytest.mark.unit] -from fastapi.testclient import TestClient -from unittest.mock import patch, MagicMock -import time -import numpy as np - -# Test individual components without importing main module due to PyTorch issues -from agents.filtering_agent import FilteringAgent -from agents.processing_agent_legacy import ProcessingAgent -from models.state import Paper, PDFContent - - -# Mock the main module to avoid import issues -class MockApp: - def __init__(self): - self.state = type("MockState", (), {})() - - -class MockRequest: - def __init__(self): - self.app = MockApp() - - -@pytest.fixture -def mock_request(): - """Create mock request object""" - return MockRequest() - - -@pytest.fixture -def client(): - """Create test client with startup/shutdown events""" - # Skip this fixture since we can't import main module - # with TestClient(app) as c: - # yield c - pass - - -def test_sentence_transformers_import(): - """Test that sentence-transformers can be imported successfully""" - try: - from sentence_transformers import SentenceTransformer - - # Test basic model loading - model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") - assert model is not None - - # Test encoding - embeddings = model.encode(["test sentence"]) - assert embeddings.shape == (1, 384) # all-MiniLM-L6-v2 produces 384-dim vectors - - print("✅ SentenceTransformers working correctly") - except Exception as e: - pytest.fail(f"SentenceTransformers import/usage failed: {e}") - - -def test_filtering_agent_initialization(mock_request): - """Test FilteringAgent initialization with mock embedding model""" - # Mock the embedding model in app.state - with patch("sentence_transformers.SentenceTransformer") as mock_st: - mock_model = MagicMock() - mock_model.encode.return_value = np.random.rand(1, 384) - mock_st.return_value = mock_model - - # Set the model in mock app state - mock_request.app.state.embedding_model = mock_model - - # Test agent initialization - agent = FilteringAgent(mock_request) - assert agent.embedding_model is not None - - -def test_filtering_agent_no_model(mock_request): - """Test FilteringAgent raises error when no model available""" - # Ensure no model in app.state - mock_request.app.state.embedding_model = None - - # Should raise RuntimeError - with pytest.raises(RuntimeError, match="Embedding model not found"): - FilteringAgent(mock_request) - - -def test_processing_agent_initialization(mock_request): - """Test ProcessingAgent initialization with mock embedding model""" - # Mock the embedding model in app.state - with patch("sentence_transformers.SentenceTransformer") as mock_st: - mock_model = MagicMock() - mock_model.encode.return_value = np.random.rand(2, 384) # 2 chunks - mock_st.return_value = mock_model - - # Set the model in mock app state - mock_request.app.state.embedding_model = mock_model - - # Test agent initialization - pass app, not request - agent = ProcessingAgent(mock_request.app) - assert agent is not None # Agent created successfully, warmup passed - - -def test_processing_agent_no_model(mock_request): - """Test ProcessingAgent raises error when no model available""" - # Ensure no model in app.state - mock_request.app.state.embedding_model = None - - # Should raise RuntimeError - with pytest.raises(RuntimeError, match="Model warmup failed"): - ProcessingAgent(mock_request.app) - - -def test_processing_agent_embedding_generation(mock_request): - """Test ProcessingAgent can be created with embedding model""" - # Mock the embedding model - with patch("sentence_transformers.SentenceTransformer") as mock_st: - mock_model = MagicMock() - mock_model.encode.return_value = np.random.rand(2, 384) # 2 chunks - mock_st.return_value = mock_model - - mock_request.app.state.embedding_model = mock_model - - # Just test that agent creation works with mock model - agent = ProcessingAgent(mock_request.app) - assert agent.app.state.embedding_model is mock_model - - -def test_processing_agent_text_chunking(mock_request): - """Test ProcessingAgent can perform basic text chunking""" - # Mock the embedding model - with patch("sentence_transformers.SentenceTransformer") as mock_st: - mock_model = MagicMock() - # Add proper mock for encode method to return correct shape - mock_model.encode.return_value = np.random.rand(1, 384).astype(np.float32) - mock_st.return_value = mock_model - - mock_request.app.state.embedding_model = mock_model - - agent = ProcessingAgent(mock_request.app) - - # Test that agent has chunking methods (basic smoke test) - assert hasattr(agent, "_chunk_text_fallback") - assert hasattr(agent, "_chunk_text_by_section") diff --git a/tests/unit/test_state_model.py b/tests/unit/test_state_model.py deleted file mode 100644 index 4cf174fe045c304c1df3a1b1ca2e471022a82193..0000000000000000000000000000000000000000 --- a/tests/unit/test_state_model.py +++ /dev/null @@ -1,816 +0,0 @@ -import pytest - -pytestmark = [pytest.mark.unit] -from pydantic import ValidationError -from models.state import State, Paper, Passage, Score - - -def test_state_creation(): - """Tests basic State object creation with new optimized fields.""" - state = State(query="test query") - assert state.original_query == "test query" - assert state.query == "test query" # Test alias backward compatibility - assert isinstance(state.request_id, str) - assert state.papers_metadata == [] - assert state.filtered_papers == [] - assert state.optimized_query is None - assert state.filtering_scores is None - assert state.dedup_stats is None - assert state.search_quality is None - assert state.refinement_count == 0 - - -def test_state_creation_with_original_query(): - """Tests State creation using original_query field directly.""" - state = State(original_query="direct query test") - assert state.original_query == "direct query test" - assert state.query == "direct query test" # Alias should work both ways - - -def test_state_with_papers(): - """Tests State object creation with paper metadata.""" - papers = [ - Paper( - paper_id="1", - title="Paper 1", - authors=["Author 1"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url="http://example.com/1.pdf", - type="article", - ), - Paper( - paper_id="2", - title="Paper 2", - authors=["Author 2"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url="http://example.com/2.pdf", - type="review", - ), - ] - state = State(query="test", papers_metadata=papers) - assert len(state.papers_metadata) == 2 - assert state.papers_metadata[0].pdf_url is not None - - -def test_state_validator_no_pdf_urls(): - """Tests the validator when no papers have PDF URLs.""" - papers = [ - Paper( - paper_id="1", - title="Paper 1", - authors=["Author 1"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url=None, - type="article", - ) - ] - state = State(query="test", papers_metadata=papers) - assert "No papers with PDF URLs found." in state.validation_errors - - -def test_state_validator_empty_papers_list(): - """Tests the validator with an empty list of papers.""" - state = State(query="test", papers_metadata=[]) - assert state.papers_metadata == [] - - -def test_state_serialization(): - """Tests that the State object can be serialized to a dict.""" - papers = [ - Paper( - paper_id="1", - title="Paper 1", - authors=["Author 1"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url="http://example.com/1.pdf", - type="article", - ) - ] - state = State(query="test", papers_metadata=papers) - state_dict = state.model_dump() - # Default serialization uses field names, not aliases - assert state_dict["original_query"] == "test" - assert "query" not in state_dict # Alias not used by default - assert len(state_dict["papers_metadata"]) == 1 - assert state_dict["papers_metadata"][0]["pdf_url"] == "http://example.com/1.pdf" - - -def test_state_serialization_by_alias(): - """Tests serialization with by_alias parameter.""" - state = State(query="test") - # Test serialization with alias (legacy format) - state_dict = state.model_dump(by_alias=True) - assert "query" in state_dict - assert "original_query" not in state_dict - - # Test serialization without alias (new format) - state_dict = state.model_dump(by_alias=False) - assert "original_query" in state_dict - assert "query" not in state_dict - - -def test_optimized_query_validation(): - """Test optimized_query field validation enforces length constraints.""" - state = State(query="test") - - # Valid optimized query - state.optimized_query = "CRISPR-Cas9 off-target effects in mammalian cells" - assert state.optimized_query is not None - - # Invalid: too short - with pytest.raises(ValueError, match="20-200 characters"): - state.optimized_query = "short" - - # Invalid: too long - with pytest.raises(ValueError, match="20-200 characters"): - state.optimized_query = "x" * 201 - - -def test_query_length_validation(): - """Test query length validation for both original and optimized queries.""" - # Valid query - state = State(query="This is a valid query with sufficient length") - assert state.original_query is not None - - # Invalid: too short - with pytest.raises(ValueError, match="at least 3 characters"): - State(query="hi") - - # Invalid: too long - with pytest.raises(ValueError, match="less than 256 characters"): - State(query="x" * 257) - - # Invalid: just whitespace - this will fail length validation first (3 chars required) - with pytest.raises(ValueError, match="at least 3 characters"): - State(query=" ") - - -def test_filtered_papers_count_validation(): - """Test filtered_papers cannot exceed 25 papers.""" - state = State(query="test") - - # Valid: exactly 25 papers - state.filtered_papers = [ - Paper( - paper_id=str(i), - title=f"Paper {i}", - authors=[f"Author {i}"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url=f"https://example.com/{i}.pdf", - type="article", - ) - for i in range(25) - ] - assert len(state.filtered_papers) == 25 - - # Invalid: more than 25 - with pytest.raises(ValueError, match="≤25"): - state.filtered_papers = [ - Paper( - paper_id=str(i), - title=f"Paper {i}", - authors=[f"Author {i}"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url=f"https://example.com/{i}.pdf", - type="article", - ) - for i in range(26) - ] - - -def test_search_quality_structure(): - """Test search_quality dict has correct structure.""" - state = State( - query="test", - search_quality={ - "passed": True, - "reason": "Found 78 papers with avg_relevance 0.65", - "paper_count": 78, - "avg_relevance": 0.65, - }, - ) - - assert state.search_quality["passed"] is True - assert state.search_quality["paper_count"] == 78 - assert 0 <= state.search_quality["avg_relevance"] <= 1 - - # Test validation failures - with pytest.raises( - ValueError, match="must contain: passed, reason, paper_count, avg_relevance" - ): - State(query="test", search_quality={"incomplete": "dict"}) - - with pytest.raises(ValueError, match="must be boolean"): - State( - query="test", - search_quality={ - "passed": "not_boolean", - "reason": "test", - "paper_count": 1, - "avg_relevance": 0.5, - }, - ) - - with pytest.raises(ValueError, match="between 0 and 1"): - State( - query="test", - search_quality={ - "passed": True, - "reason": "test", - "paper_count": 1, - "avg_relevance": 1.5, - }, - ) - - -def test_dedup_stats_structure(): - """Test dedup_stats tracks deduplication correctly.""" - state = State( - query="test", - dedup_stats={"raw_count": 200, "unique_count": 145, "duplicates_removed": 55}, - ) - - assert state.dedup_stats["raw_count"] == 200 - assert state.dedup_stats["unique_count"] == 145 - assert state.dedup_stats["duplicates_removed"] == 55 - - # Test validation failures - missing required keys - with pytest.raises( - ValueError, match="must contain: raw_count, unique_count, duplicates_removed" - ): - State( - query="test", dedup_stats={"raw_count": 100} - ) # Missing other required keys - - with pytest.raises(ValueError, match="cannot be greater than raw_count"): - State( - query="test", - dedup_stats={ - "raw_count": 100, - "unique_count": 150, - "duplicates_removed": 0, - }, - ) - - -def test_filtering_scores_structure(): - """Test filtering_scores has expected structure.""" - state = State( - query="test", - filtering_scores={ - "bm25_top_50": ["paper1", "paper2"], - "semantic_top_25": ["paper1", "paper3"], - "avg_bm25_score": 8.2, - "avg_semantic_score": 0.78, - }, - ) - - assert "bm25_top_50" in state.filtering_scores - assert "avg_bm25_score" in state.filtering_scores - - # Test validation - should pass with at least one expected key - state2 = State(query="test", filtering_scores={"avg_bm25_score": 7.5}) - assert state2.filtering_scores is not None - - # Test validation failure - with pytest.raises(ValueError, match="must contain at least one of"): - State(query="test", filtering_scores={"unknown_key": "value"}) - - -def test_passage_and_score_models(): - """Test the new Passage and Score models work correctly.""" - passage = Passage( - content="This is a test passage.", - section="introduction", - paper_id="p1", - retrieval_score=0.85, - cross_encoder_score=0.78, - final_score=0.81, - ) - - assert passage.content == "This is a test passage." - assert passage.section == "introduction" - assert passage.paper_id == "p1" - assert passage.retrieval_score == 0.85 - - score = Score( - score_type="relevance", - value=0.95, - justification="Highly relevant to query", - confidence=0.9, - ) - - assert score.score_type == "relevance" - assert score.value == 0.95 - assert score.justification == "Highly relevant to query" - - -def test_backward_compatibility(): - """Test old State usage patterns still work.""" - # Simulate old code that uses 'query' field - state = State(query="What is intermittent fasting?") - - # Both alias and field should work - assert state.query == state.original_query - assert state.original_query == "What is intermittent fasting?" - - # Test that old serialization still works - state_dict = state.model_dump(by_alias=True) - assert state_dict["query"] == "What is intermittent fasting?" - assert "original_query" not in state_dict - - -def test_state_flows_through_optimized_pipeline(): - """Test State correctly tracks data through new optimized flow.""" - state = State(query="fasting benefits") - - # After QueryOptimizationAgent - state.optimized_query = "metabolic effects of intermittent fasting protocols" - assert state.optimized_query is not None - - # After SearchAgent (100 papers) - state.papers_metadata = [ - Paper( - paper_id=str(i), - title=f"Paper {i}", - authors=[f"Author {i}"], - year=2023, - journal="N/A", - citation_count=0, - pdf_url=f"https://example.com/{i}.pdf", - type="article", - ) - for i in range(100) - ] - state.search_quality = { - "passed": True, - "reason": "Found 100 papers", - "paper_count": 100, - "avg_relevance": 0.72, - } - - # After DeduplicationAgent - state.dedup_stats = {"raw_count": 100, "unique_count": 95, "duplicates_removed": 5} - - # After FilteringAgent - state.filtered_papers = state.papers_metadata[:25] - state.filtering_scores = {"avg_bm25_score": 8.2, "avg_semantic_score": 0.78} - - assert len(state.filtered_papers) == 25 - assert state.dedup_stats["duplicates_removed"] == 5 - assert state.search_quality["paper_count"] == 100 - - -def test_enhanced_processing_models(): - """Test case 1: Model validation with valid and invalid input data.""" - from models.state import ( - ProcessingStatus, - RetrievalScores, - Chunk, - Passage, - ProcessingMetadata, - ProcessingConfig, - State, - ) - import pytest - - # Test ProcessingStatus enum - assert ProcessingStatus.PENDING.value == "pending" - assert ProcessingStatus.IN_PROGRESS.value == "in_progress" - assert ProcessingStatus.COMPLETED.value == "completed" - assert ProcessingStatus.FAILED.value == "failed" - assert ProcessingStatus.PARTIAL.value == "partial" - - # Test RetrievalScores validation - valid_scores = RetrievalScores( - bm25_score=0.8, - semantic_score=0.7, - rrf_score=0.9, - reranking_score=0.85, - final_rank=5, - ) - assert valid_scores.bm25_score == 0.8 - assert valid_scores.final_rank == 5 - - # Invalid scores should raise ValueError - with pytest.raises(ValueError, match="must be between 0.0 and 1.0"): - RetrievalScores(bm25_score=1.5) - - with pytest.raises(ValueError, match="must be between 0.0 and 1.0"): - RetrievalScores(semantic_score=-0.1) - - # Test Chunk model - valid_chunk = Chunk( - chunk_id="chunk_123", - paper_id="paper_456", - text="This is sample chunk text.", - chunk_index=0, - section="INTRODUCTION", - token_count=100, - char_start=0, - char_end=24, - ) - assert valid_chunk.chunk_id == "chunk_123" - assert valid_chunk.section == "INTRODUCTION" - - # Invalid chunk (char_end < char_start) - with pytest.raises(ValueError, match="char_end must be >= char_start"): - Chunk( - chunk_id="chunk_123", - paper_id="paper_456", - text="Sample text", - chunk_index=0, - char_start=10, - char_end=5, - ) - - # Test ProcessingConfig validation - valid_config = ProcessingConfig( - chunk_size=600, chunk_overlap=100, enable_reranking=True, batch_size=16 - ) - assert valid_config.chunk_size == 600 - assert valid_config.batch_size == 16 - - # Invalid config should raise ValueError - with pytest.raises(ValueError): # chunk_size too large - ProcessingConfig(chunk_size=1200) - - with pytest.raises(ValueError): # chunk_overlap exceeds limit - ProcessingConfig(chunk_overlap=250) - - with pytest.raises(ValueError): # batch_size too small - ProcessingConfig(batch_size=0) - - -def test_processing_state_transitions(): - """Test case 2: State transitions and status updates work correctly.""" - from models.state import State, ProcessingStatus, ProcessingMetadata, Chunk, Passage - import time - - # Create state with processing metadata - state = State(original_query="test query") - metadata = ProcessingMetadata( - total_papers=2, processed_papers=2, total_chunks=50, chunks_embedded=50 - ) - state.processing_metadata = metadata - - # Test initial status - assert state.processing_status == ProcessingStatus.PENDING - - # Test state transitions - state.start_processing() - assert state.processing_status == ProcessingStatus.IN_PROGRESS - - # Cannot start processing again - state.start_processing() # Should not change status - assert state.processing_status == ProcessingStatus.IN_PROGRESS - - state.complete_processing() - assert state.processing_status == ProcessingStatus.COMPLETED - - # Test failure handling - failed_state = State(original_query="failed query") - failed_state.start_processing() - failed_state.fail_processing("Test error") - assert failed_state.processing_status == ProcessingStatus.FAILED - - # Test partial completion - partial_state = State(original_query="partial query") - partial_state.start_processing() - partial_state.mark_partial() - assert partial_state.processing_status == ProcessingStatus.PARTIAL - - partial_state.complete_processing() - assert partial_state.processing_status == ProcessingStatus.COMPLETED - - -def test_processing_serialization_deserialization(): - """Test case 3: Serialization/deserialization preserves all data.""" - from models.state import State, ProcessingMetadata, Chunk, Passage, RetrievalScores - import json - - # Create comprehensive state with all enhanced fields - state = State( - original_query="What are the effects of fasting on cardiovascular health?", - processing_status="in_progress", - ) - - # Add processing metadata - metadata = ProcessingMetadata( - total_papers=2, - processed_papers=2, - total_chunks=45, - chunks_embedded=45, - retrieval_candidates=20, - reranked_passages=10, - stage_times={"embedding": 2.1, "retrieval": 0.8, "reranking": 0.3}, - total_time=3.2, - memory_usage_mb=120.5, - throughput_chunks_per_second=21.4, - ) - state.processing_metadata = metadata - - # Add chunks - chunks = [] - for i in range(50): - chunk = Chunk( - chunk_id=f"chunk_{i:03d}", - paper_id=f"paper_{(i % 2) + 1}", - text=f"This is chunk number {i} with some content for testing purposes.", - chunk_index=i, - section="INTRODUCTION" if i < 25 else "METHODS", - token_count=50 + (i % 100), - char_start=i * 200, - char_end=(i + 1) * 200, - ) - chunks.append(chunk) - state.chunks = chunks - - # Add relevant passages - passages = [] - for i in range(10): - passage = Passage( - content=f"Passage content {i} from cardiovascular research study.", - section="introduction", - paper_id="paper_1", - chunk_id=f"chunk_{i:03d}", - retrieval_score=0.8 - (i * 0.02), - final_score=0.9 - (i * 0.05), - char_start=i * 50, - char_end=(i + 1) * 50, - ) - # Set scores - passage.scores.bm25_score = 0.8 - (i * 0.02) - passage.scores.semantic_score = 0.7 - (i * 0.03) - passage.scores.rrf_score = 0.75 - (i * 0.025) - passage.scores.reranking_score = 0.85 - (i * 0.04) - passage.scores.final_rank = i + 1 - - passages.append(passage) - state.relevant_passages = passages - - # Serialize to JSON - state_dict = state.model_dump() - json_str = json.dumps(state_dict, default=str) - assert json_str - - # Deserialize back - loaded_dict = json.loads(json_str) - reconstructed_state = State.model_validate(loaded_dict) - - # Verify all data preserved - assert reconstructed_state.original_query == state.original_query - assert reconstructed_state.processing_status == state.processing_status - assert reconstructed_state.config.chunk_size == state.config.chunk_size - - # Verify processing metadata - assert reconstructed_state.processing_metadata.total_papers == 2 - assert reconstructed_state.processing_metadata.memory_usage_mb == 120.5 - assert reconstructed_state.processing_metadata.throughput_chunks_per_second == 21.4 - - # Verify chunks - assert len(reconstructed_state.chunks) == 50 - for i, chunk in enumerate(reconstructed_state.chunks): - assert chunk.chunk_id == f"chunk_{i:03d}" - assert chunk.chunk_index == i - assert chunk.char_start == i * 200 - assert chunk.char_end == (i + 1) * 200 - - # Verify passages - assert len(reconstructed_state.relevant_passages) == 10 - for i, passage in enumerate(reconstructed_state.relevant_passages): - assert f"Passage content {i}" in passage.content - assert passage.scores.final_rank == i + 1 - assert abs(passage.scores.bm25_score - (0.8 - (i * 0.02))) < 1e-6 - - -def test_enhanced_validator_error_handling(): - """Test case 4: Custom validators catch configuration errors.""" - from models.state import ProcessingConfig, RetrievalScores, Chunk, Passage - import pytest - - # ProcessingConfig validator tests - with pytest.raises(ValueError, match="chunk_size"): # Below minimum - ProcessingConfig(chunk_size=50) - - with pytest.raises(ValueError, match="chunk_size"): # Above maximum - ProcessingConfig(chunk_size=1100) - - with pytest.raises(ValueError, match="chunk_overlap"): # Below minimum - ProcessingConfig(chunk_overlap=-10) - - with pytest.raises(ValueError, match="chunk_overlap"): # Above maximum - ProcessingConfig(chunk_overlap=250) - - with pytest.raises(ValueError, match="top_k"): # Below minimum - ProcessingConfig(top_k=3) - - with pytest.raises(ValueError, match="final_k"): # Above maximum - ProcessingConfig(final_k=25) - - with pytest.raises(ValueError, match="batch_size"): # Below minimum - ProcessingConfig(batch_size=0) - - with pytest.raises(ValueError, match="max_chunk_tokens"): # Below minimum - ProcessingConfig(max_chunk_tokens=50) - - # RetrievalScores validator tests - with pytest.raises( - ValueError, match="must be between 0.0 and 1.0" - ): # bm25_score too high - RetrievalScores(bm25_score=1.1) - - with pytest.raises( - ValueError, match="must be between 0.0 and 1.0" - ): # Negative score - RetrievalScores(semantic_score=-0.5) - - with pytest.raises( - ValueError, match="must be between 0.0 and 1.0" - ): # rrf_score too high - RetrievalScores(rrf_score=1.5) - - with pytest.raises( - ValueError, match="must be between 0.0 and 1.0" - ): # reranking_score too low - RetrievalScores(reranking_score=-0.1) - - # Chunk validator tests - with pytest.raises(ValueError, match="greater_than_equal"): # Negative chunk_index - Chunk(chunk_id="chunk_1", paper_id="paper_1", text="test", chunk_index=-1) - - with pytest.raises(ValueError, match="greater_than_equal"): # Negative token_count - Chunk( - chunk_id="chunk_1", - paper_id="paper_1", - text="test", - chunk_index=0, - token_count=-5, - ) - - with pytest.raises(ValueError, match="greater_than_equal"): # Negative char_start - Chunk( - chunk_id="chunk_1", - paper_id="paper_1", - text="test", - chunk_index=0, - char_start=-10, - ) - - # Passage validator tests - with pytest.raises( - ValueError, match="should be less than or equal to 1" - ): # retrieval_score too high - Passage( - content="test content", - section="introduction", - paper_id="paper_1", - retrieval_score=1.5, - ) - - with pytest.raises( - ValueError, match="char_end must be >= char_start" - ): # Invalid char positions - Passage( - content="test", - section="introduction", - paper_id="paper_1", - retrieval_score=0.8, - char_start=20, - char_end=10, - ) - - -def test_comprehensive_processing_integration(): - """Example Test Case: State with processing metadata, 50 chunks, 10 passages with scores.""" - from models.state import State, ProcessingMetadata, Chunk, Passage, RetrievalScores - import time - - # Create the comprehensive test case specified in requirements - state = State( - original_query="cardiovascular effects of intermittent fasting", - processing_status="completed", - ) - - # Set up processing config - state.config.chunk_size = 512 - state.config.chunk_overlap = 64 - state.config.enable_reranking = True - - # Add processing metadata - metadata = ProcessingMetadata( - total_papers=3, - processed_papers=3, - total_sections=9, - total_chunks=57, - chunks_embedded=57, - retrieval_candidates=42, - reranked_passages=15, - stage_times={ - "section_detection": 0.5, - "chunking": 1.2, - "embedding": 3.4, - "index_build": 0.1, - "retrieval": 0.8, - "reranking": 0.3, - }, - total_time=6.3, - memory_usage_mb=142.8, - throughput_chunks_per_second=16.7, - ) - state.processing_metadata = metadata - - # Add 50+ chunks with realistic data - chunks = [] - paper_ids = ["fasting_study_2023", "cardio_research_2024", "meta_analysis_2023"] - - for i in range(57): - chunk = Chunk( - chunk_id=f"chunk_{i:03d}", - paper_id=paper_ids[i % 3], - text=f"Intermittent fasting has been shown to improve cardiovascular health markers including reduced blood pressure and improved lipid profiles. Study data indicates significant improvements in cholesterol levels after 12 weeks of time-restricted eating protocols.", - chunk_index=i, - section="INTRODUCTION" if i < 20 else ("METHODS" if i < 40 else "RESULTS"), - token_count=85 + (i % 20), - char_start=i * 250, - char_end=(i + 1) * 250, - ) - chunks.append(chunk) - state.chunks = chunks - - # Add 10 passages with comprehensive scoring - passages = [] - for i in range(10): - scores = RetrievalScores( - bm25_score=min(1.0, 0.85 - (i * 0.02)), - semantic_score=min(1.0, 0.75 - (i * 0.03)), - rrf_score=min(1.0, 0.80 - (i * 0.025)), - reranking_score=min(1.0, 0.90 - (i * 0.01)), - final_rank=i + 1, - ) - - passage = Passage( - content=f"Passage {i+1}: Intermittent fasting demonstrates significant cardiovascular benefits through multiple mechanisms including reduced inflammation, improved metabolic flexibility, and decreased oxidative stress. Clinical evidence supports the efficacy of time-restricted feeding protocols.", - section="introduction", - paper_id="fasting_study_2023", - chunk_id=f"chunk_{i*5:03d}", - scores=scores, - retrieval_score=scores.bm25_score, - cross_encoder_score=scores.reranking_score, - final_score=scores.reranking_score, - char_start=i * 120, - char_end=(i + 1) * 120, - ) - passages.append(passage) - - state.relevant_passages = passages - - # Validation tests - assert state.processing_status.value == "completed" - assert len(state.chunks) == 57 - assert len(state.relevant_passages) == 10 - - # Test property access - assert state.total_execution_time > 0 - assert state.total_execution_time == state.processing_metadata.total_time - - # Test helper methods - summary = state.get_processing_summary() - assert summary["status"] == "completed" - assert summary["chunks_created"] == 57 - assert summary["passages_retrieved"] == 10 - assert "INTRODUCTION" in summary["section_distribution"] - - metrics = state.get_performance_metrics() - assert metrics["status"] == "completed" - assert "stage_times" in metrics - assert "memory_usage_mb" in metrics - - # Verify scoring integration - top_passage = state.relevant_passages[0] - assert top_passage.bm25_score == 0.85 - assert top_passage.semantic_score == 0.75 - assert top_passage.rrf_score == 0.80 - assert top_passage.reranking_score == 0.90 - assert top_passage.scores.final_rank == 1 - - # Serialization roundtrip (brief test) - serialized = state.model_dump() - reconstructed = State.model_validate(serialized) - - assert reconstructed.processing_status == state.processing_status - assert len(reconstructed.chunks) == 57 - assert len(reconstructed.relevant_passages) == 10 - assert reconstructed.total_execution_time == state.total_execution_time diff --git a/validation_reports/day2_report.txt b/validation_reports/day2_report.txt deleted file mode 100644 index 34ec0f8e56ccc4e6686c8fc619887c2f371457c7..0000000000000000000000000000000000000000 --- a/validation_reports/day2_report.txt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f291e9b93e121441368d7889cbfd23ea94b1d5d6b6129ff372cd2a796bb52aeb -size 2395