Commit ·
56bcac1
1
Parent(s): aaa41f4
clean up main
Browse files- .nicegui/storage-user-304a5539-485e-42a5-8c19-b6aaec62a41b.json +1 -0
- config/config.py +2 -0
- main.py +5 -104
- requirements.txt +2 -2
- services/query_service.py +1 -13
- tests/integration/test_api_endpoint.py +0 -504
- tests/integration/test_query_endpoint.py +0 -379
- tests/integration/test_query_service_integration.py +288 -0
- ui/pages.py +22 -25
.nicegui/storage-user-304a5539-485e-42a5-8c19-b6aaec62a41b.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"search_history":[1770352285.076799,1770352645.3336556,1770353598.5381844]}
|
config/config.py
CHANGED
|
@@ -20,6 +20,8 @@ class Settings(BaseSettings):
|
|
| 20 |
SYNTHESIS_MODEL: str = "mistral/mistral-large-2512"
|
| 21 |
SYNTHESIS_FALLBACK: str = "cerebras/llama-3.3-70b"
|
| 22 |
|
|
|
|
|
|
|
| 23 |
# Tuning
|
| 24 |
RAG_RETRIEVAL_TOP_K: int = 50
|
| 25 |
RAG_RERANK_TOP_K: int = 12
|
|
|
|
| 20 |
SYNTHESIS_MODEL: str = "mistral/mistral-large-2512"
|
| 21 |
SYNTHESIS_FALLBACK: str = "cerebras/llama-3.3-70b"
|
| 22 |
|
| 23 |
+
NICEGUI_STORAGE_SECRET: str
|
| 24 |
+
|
| 25 |
# Tuning
|
| 26 |
RAG_RETRIEVAL_TOP_K: int = 50
|
| 27 |
RAG_RERANK_TOP_K: int = 12
|
main.py
CHANGED
|
@@ -8,24 +8,18 @@ import os
|
|
| 8 |
import sys
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
|
| 11 |
-
from config import
|
| 12 |
|
| 13 |
# Disable tokenizers parallelism to avoid warnings
|
| 14 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 15 |
|
| 16 |
from datetime import datetime
|
| 17 |
|
| 18 |
-
from fastapi import FastAPI
|
| 19 |
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
from fastapi.staticfiles import StaticFiles
|
| 21 |
from loguru import logger
|
| 22 |
from nicegui import ui
|
| 23 |
-
from pydantic import BaseModel, Field
|
| 24 |
-
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 25 |
-
from slowapi.errors import RateLimitExceeded
|
| 26 |
-
from slowapi.util import get_remote_address
|
| 27 |
-
|
| 28 |
-
from config.config import get_settings
|
| 29 |
|
| 30 |
# Global concurrency control
|
| 31 |
MAX_CONCURRENT_SEARCHES = 2
|
|
@@ -170,14 +164,9 @@ app = FastAPI(
|
|
| 170 |
title="Necthrall API",
|
| 171 |
description="AI-powered scientific research assistant",
|
| 172 |
version="3.0.0",
|
| 173 |
-
lifespan=lifespan,
|
| 174 |
)
|
| 175 |
|
| 176 |
-
# Initialize Rate Limiter
|
| 177 |
-
limiter = Limiter(key_func=get_remote_address)
|
| 178 |
-
app.state.limiter = limiter
|
| 179 |
-
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 180 |
-
|
| 181 |
# Mount static files
|
| 182 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 183 |
|
|
@@ -201,95 +190,6 @@ async def health_check():
|
|
| 201 |
}
|
| 202 |
|
| 203 |
|
| 204 |
-
class QueryRequest(BaseModel):
|
| 205 |
-
query: str = Field(..., min_length=1, max_length=500)
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
@app.post("/query")
|
| 209 |
-
@limiter.limit(f"{get_settings().RATE_LIMIT_QUERIES_PER_HOUR}/hour")
|
| 210 |
-
async def query_endpoint(query_request: QueryRequest, request: Request):
|
| 211 |
-
"""Process a research query."""
|
| 212 |
-
if not hasattr(app.state, "query_service"):
|
| 213 |
-
raise HTTPException(status_code=503, detail="Query service not initialized")
|
| 214 |
-
|
| 215 |
-
if search_semaphore.locked():
|
| 216 |
-
raise HTTPException(
|
| 217 |
-
status_code=503, detail="Server is busy. Please try again later."
|
| 218 |
-
)
|
| 219 |
-
|
| 220 |
-
async with search_semaphore:
|
| 221 |
-
try:
|
| 222 |
-
result = await app.state.query_service.process_query(query_request.query)
|
| 223 |
-
|
| 224 |
-
if not result.success:
|
| 225 |
-
# Handle specific error cases
|
| 226 |
-
if (
|
| 227 |
-
result.error_message
|
| 228 |
-
and "Semantic Scholar API is currently unavailable"
|
| 229 |
-
in result.error_message
|
| 230 |
-
):
|
| 231 |
-
raise HTTPException(
|
| 232 |
-
status_code=503,
|
| 233 |
-
detail=result.error_message,
|
| 234 |
-
)
|
| 235 |
-
|
| 236 |
-
# Include stage in error detail for debugging
|
| 237 |
-
error_detail = (
|
| 238 |
-
result.error_message or "Pipeline failed without error message"
|
| 239 |
-
)
|
| 240 |
-
if result.error_stage:
|
| 241 |
-
error_detail = f"{error_detail} (Stage: {result.error_stage})"
|
| 242 |
-
|
| 243 |
-
raise HTTPException(
|
| 244 |
-
status_code=500,
|
| 245 |
-
detail=error_detail,
|
| 246 |
-
)
|
| 247 |
-
|
| 248 |
-
# Format citations with IDs
|
| 249 |
-
citations = []
|
| 250 |
-
if result.passages:
|
| 251 |
-
for idx, p in enumerate(result.passages, 1):
|
| 252 |
-
# Handle both dict and object access
|
| 253 |
-
text = (
|
| 254 |
-
p.get("text") if isinstance(p, dict) else getattr(p, "text", "")
|
| 255 |
-
)
|
| 256 |
-
metadata = (
|
| 257 |
-
p.get("metadata")
|
| 258 |
-
if isinstance(p, dict)
|
| 259 |
-
else getattr(p, "metadata", {})
|
| 260 |
-
).copy()
|
| 261 |
-
|
| 262 |
-
# Ensure score is in metadata if available
|
| 263 |
-
score = (
|
| 264 |
-
p.get("score")
|
| 265 |
-
if isinstance(p, dict)
|
| 266 |
-
else getattr(p, "score", None)
|
| 267 |
-
)
|
| 268 |
-
if score is not None:
|
| 269 |
-
metadata["score"] = score
|
| 270 |
-
|
| 271 |
-
citations.append({"id": idx, "text": text, "metadata": metadata})
|
| 272 |
-
|
| 273 |
-
return {
|
| 274 |
-
"query": query_request.query,
|
| 275 |
-
"answer": result.answer
|
| 276 |
-
or "No answer could be generated from the available sources.",
|
| 277 |
-
"citations": citations,
|
| 278 |
-
"finalists": result.finalists,
|
| 279 |
-
"execution_time": result.execution_time,
|
| 280 |
-
"timing_breakdown": result.timing_breakdown,
|
| 281 |
-
"optimized_queries": result.optimized_queries,
|
| 282 |
-
"quality_gate": result.quality_gate,
|
| 283 |
-
}
|
| 284 |
-
except HTTPException:
|
| 285 |
-
raise
|
| 286 |
-
except Exception as e:
|
| 287 |
-
logger.exception("Query processing failed")
|
| 288 |
-
raise HTTPException(
|
| 289 |
-
status_code=500, detail=f"An unexpected error occurred: {str(e)}"
|
| 290 |
-
)
|
| 291 |
-
|
| 292 |
-
|
| 293 |
# =============================================================================
|
| 294 |
# NiceGUI Frontend
|
| 295 |
# =============================================================================
|
|
@@ -306,10 +206,11 @@ ui.run_with(
|
|
| 306 |
favicon="logo/favicon.png",
|
| 307 |
dark=False,
|
| 308 |
reconnect_timeout=30.0,
|
|
|
|
| 309 |
)
|
| 310 |
|
| 311 |
|
| 312 |
if __name__ == "__main__":
|
| 313 |
import uvicorn
|
| 314 |
|
| 315 |
-
uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=
|
|
|
|
| 8 |
import sys
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
|
| 11 |
+
from config.config import get_settings
|
| 12 |
|
| 13 |
# Disable tokenizers parallelism to avoid warnings
|
| 14 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 15 |
|
| 16 |
from datetime import datetime
|
| 17 |
|
| 18 |
+
from fastapi import FastAPI
|
| 19 |
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
from fastapi.staticfiles import StaticFiles
|
| 21 |
from loguru import logger
|
| 22 |
from nicegui import ui
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
# Global concurrency control
|
| 25 |
MAX_CONCURRENT_SEARCHES = 2
|
|
|
|
| 164 |
title="Necthrall API",
|
| 165 |
description="AI-powered scientific research assistant",
|
| 166 |
version="3.0.0",
|
| 167 |
+
lifespan=lifespan,
|
| 168 |
)
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
# Mount static files
|
| 171 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 172 |
|
|
|
|
| 190 |
}
|
| 191 |
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
# =============================================================================
|
| 194 |
# NiceGUI Frontend
|
| 195 |
# =============================================================================
|
|
|
|
| 206 |
favicon="logo/favicon.png",
|
| 207 |
dark=False,
|
| 208 |
reconnect_timeout=30.0,
|
| 209 |
+
storage_secret=get_settings().NICEGUI_STORAGE_SECRET,
|
| 210 |
)
|
| 211 |
|
| 212 |
|
| 213 |
if __name__ == "__main__":
|
| 214 |
import uvicorn
|
| 215 |
|
| 216 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info", reload=False)
|
requirements.txt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:449ac3f9b72672955ffc2826ee3f224b04a9d9cb21ba54019784072919624f25
|
| 3 |
+
size 463
|
services/query_service.py
CHANGED
|
@@ -29,19 +29,7 @@ from agents.query_optimization_agent import QueryOptimizationAgent
|
|
| 29 |
from config.config import Settings
|
| 30 |
from models.state import Paper, Passage
|
| 31 |
from services.discovery_service import DiscoveryService
|
| 32 |
-
from services.exceptions import
|
| 33 |
-
AcquisitionError,
|
| 34 |
-
ProcessingError,
|
| 35 |
-
QualityGateError,
|
| 36 |
-
QueryOptimizationError,
|
| 37 |
-
QueryServiceError,
|
| 38 |
-
RankingError,
|
| 39 |
-
RerankingError,
|
| 40 |
-
RetrievalError,
|
| 41 |
-
SemanticScholarError,
|
| 42 |
-
SynthesisError,
|
| 43 |
-
VerificationError,
|
| 44 |
-
)
|
| 45 |
from services.ingestion_service import IngestionService
|
| 46 |
from services.rag_service import RAGService
|
| 47 |
|
|
|
|
| 29 |
from config.config import Settings
|
| 30 |
from models.state import Paper, Passage
|
| 31 |
from services.discovery_service import DiscoveryService
|
| 32 |
+
from services.exceptions import QueryServiceError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
from services.ingestion_service import IngestionService
|
| 34 |
from services.rag_service import RAGService
|
| 35 |
|
tests/integration/test_api_endpoint.py
DELETED
|
@@ -1,504 +0,0 @@
|
|
| 1 |
-
"""Integration tests for the /query API endpoint.
|
| 2 |
-
|
| 3 |
-
Tests the FastAPI endpoint that exposes the full 10-stage pipeline.
|
| 4 |
-
Validates the response schema critical for Frontend.
|
| 5 |
-
|
| 6 |
-
Test Coverage:
|
| 7 |
-
- Happy path: Valid POST request returns 200 with expected JSON structure
|
| 8 |
-
- Validation: Empty query returns 422 (Pydantic validation error)
|
| 9 |
-
- Error handling: Pipeline failure returns 500 with clean error message
|
| 10 |
-
|
| 11 |
-
Run these tests with:
|
| 12 |
-
pytest tests/integration/test_api_endpoint.py -v
|
| 13 |
-
|
| 14 |
-
Windows Note:
|
| 15 |
-
On Windows, these tests may be skipped due to a torch DLL loading issue.
|
| 16 |
-
This occurs when pytest's conftest.py loads certain libraries before main.py,
|
| 17 |
-
causing torch's c10.dll to fail initialization. These tests work correctly:
|
| 18 |
-
- In CI/CD environments (Linux/Docker)
|
| 19 |
-
- When running the app directly (python main.py)
|
| 20 |
-
- In non-Windows environments
|
| 21 |
-
|
| 22 |
-
To run these tests on Windows, try running them in isolation:
|
| 23 |
-
python -m pytest tests/integration/test_api_endpoint.py -v --forked
|
| 24 |
-
|
| 25 |
-
Or run the main.py directly and test with curl/httpie.
|
| 26 |
-
"""
|
| 27 |
-
|
| 28 |
-
from __future__ import annotations
|
| 29 |
-
|
| 30 |
-
import os
|
| 31 |
-
import sys
|
| 32 |
-
|
| 33 |
-
# CRITICAL: Set environment variables BEFORE any imports that might use parallel processing
|
| 34 |
-
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 35 |
-
|
| 36 |
-
from typing import TYPE_CHECKING, List
|
| 37 |
-
from unittest.mock import AsyncMock, MagicMock, patch
|
| 38 |
-
|
| 39 |
-
import pytest
|
| 40 |
-
|
| 41 |
-
# Lazy imports - only for type hints, actual imports happen in fixtures
|
| 42 |
-
if TYPE_CHECKING:
|
| 43 |
-
from llama_index.core.schema import NodeWithScore, TextNode
|
| 44 |
-
|
| 45 |
-
# Check if we can import main without DLL errors (Windows issue)
|
| 46 |
-
_main_import_error = None
|
| 47 |
-
try:
|
| 48 |
-
# Set environment first
|
| 49 |
-
os.environ["SEMANTIC_SCHOLAR_API_KEY"] = os.environ.get(
|
| 50 |
-
"SEMANTIC_SCHOLAR_API_KEY", "test_key"
|
| 51 |
-
)
|
| 52 |
-
os.environ["PRIMARY_LLM_API_KEY"] = os.environ.get(
|
| 53 |
-
"PRIMARY_LLM_API_KEY", "test_key"
|
| 54 |
-
)
|
| 55 |
-
os.environ["SECONDARY_LLM_API_KEY"] = os.environ.get(
|
| 56 |
-
"SECONDARY_LLM_API_KEY", "test_key"
|
| 57 |
-
)
|
| 58 |
-
os.environ["QUERY_OPTIMIZATION_MODEL"] = os.environ.get(
|
| 59 |
-
"QUERY_OPTIMIZATION_MODEL", "test_model"
|
| 60 |
-
)
|
| 61 |
-
os.environ["SYNTHESIS_MODEL"] = os.environ.get("SYNTHESIS_MODEL", "test_model")
|
| 62 |
-
os.environ["SKIP_DOTENV_LOADER"] = "1"
|
| 63 |
-
from main import app as _app # noqa: F401 - Test import
|
| 64 |
-
except OSError as e:
|
| 65 |
-
if "DLL" in str(e):
|
| 66 |
-
_main_import_error = str(e)
|
| 67 |
-
else:
|
| 68 |
-
raise
|
| 69 |
-
|
| 70 |
-
# Skip all tests if we can't import main due to Windows DLL issues
|
| 71 |
-
pytestmark = pytest.mark.skipif(
|
| 72 |
-
_main_import_error is not None,
|
| 73 |
-
reason=f"Windows DLL error prevents main.py import: {_main_import_error}",
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# ============================================================================
|
| 78 |
-
# Fixtures
|
| 79 |
-
# ============================================================================
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
@pytest.fixture
|
| 83 |
-
def set_test_env():
|
| 84 |
-
"""Set minimal test environment variables for config validation."""
|
| 85 |
-
original_values = {
|
| 86 |
-
"SEMANTIC_SCHOLAR_API_KEY": os.environ.get("SEMANTIC_SCHOLAR_API_KEY"),
|
| 87 |
-
"PRIMARY_LLM_API_KEY": os.environ.get("PRIMARY_LLM_API_KEY"),
|
| 88 |
-
"SECONDARY_LLM_API_KEY": os.environ.get("SECONDARY_LLM_API_KEY"),
|
| 89 |
-
"QUERY_OPTIMIZATION_MODEL": os.environ.get("QUERY_OPTIMIZATION_MODEL"),
|
| 90 |
-
"SYNTHESIS_MODEL": os.environ.get("SYNTHESIS_MODEL"),
|
| 91 |
-
"SKIP_DOTENV_LOADER": os.environ.get("SKIP_DOTENV_LOADER"),
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
|
| 95 |
-
os.environ["PRIMARY_LLM_API_KEY"] = "test_key"
|
| 96 |
-
os.environ["SECONDARY_LLM_API_KEY"] = "test_key"
|
| 97 |
-
os.environ["QUERY_OPTIMIZATION_MODEL"] = "test_model"
|
| 98 |
-
os.environ["SYNTHESIS_MODEL"] = "test_model"
|
| 99 |
-
os.environ["SKIP_DOTENV_LOADER"] = "1"
|
| 100 |
-
|
| 101 |
-
yield
|
| 102 |
-
|
| 103 |
-
for key, value in original_values.items():
|
| 104 |
-
if value is None:
|
| 105 |
-
os.environ.pop(key, None)
|
| 106 |
-
else:
|
| 107 |
-
os.environ[key] = value
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
@pytest.fixture
|
| 111 |
-
def app(set_test_env):
|
| 112 |
-
"""Get the FastAPI app instance."""
|
| 113 |
-
from main import app
|
| 114 |
-
|
| 115 |
-
return app
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
@pytest.fixture
|
| 119 |
-
def client(app):
|
| 120 |
-
"""Create a test client for the FastAPI app."""
|
| 121 |
-
from fastapi.testclient import TestClient
|
| 122 |
-
|
| 123 |
-
return TestClient(app)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
@pytest.fixture
|
| 127 |
-
def mock_pipeline_result():
|
| 128 |
-
"""Create a mock PipelineResult with realistic data."""
|
| 129 |
-
from llama_index.core.schema import NodeWithScore, TextNode
|
| 130 |
-
|
| 131 |
-
from services.query_service import PipelineResult
|
| 132 |
-
|
| 133 |
-
# Create mock passages with NodeWithScore objects
|
| 134 |
-
mock_passages: List[NodeWithScore] = []
|
| 135 |
-
passage_texts = [
|
| 136 |
-
"Intermittent fasting has been shown to significantly reduce blood pressure, with systolic pressure decreasing by an average of 8.5 mmHg in clinical trials.",
|
| 137 |
-
"Time-restricted eating improves cardiac function and enhances left ventricular ejection fraction by approximately 4.2%.",
|
| 138 |
-
"Long-term adherence to fasting protocols is associated with reduced atherosclerotic burden and improved lipid profiles.",
|
| 139 |
-
]
|
| 140 |
-
|
| 141 |
-
for idx, text in enumerate(passage_texts):
|
| 142 |
-
node = TextNode(
|
| 143 |
-
text=text,
|
| 144 |
-
metadata={
|
| 145 |
-
"paper_id": f"paper_{idx + 1}",
|
| 146 |
-
"paper_title": f"Cardiovascular Effects Study {idx + 1}",
|
| 147 |
-
"section_name": "Results",
|
| 148 |
-
"citation_count": 100 + idx * 50,
|
| 149 |
-
},
|
| 150 |
-
)
|
| 151 |
-
mock_passages.append(NodeWithScore(node=node, score=0.95 - idx * 0.1))
|
| 152 |
-
|
| 153 |
-
return PipelineResult(
|
| 154 |
-
query="What are the cardiovascular effects of intermittent fasting?",
|
| 155 |
-
optimized_queries={
|
| 156 |
-
"primary": "cardiovascular effects intermittent fasting",
|
| 157 |
-
"broad": "fasting heart health",
|
| 158 |
-
"alternative": "time-restricted eating cardiovascular",
|
| 159 |
-
"final_rephrase": "cardiovascular effects of intermittent fasting",
|
| 160 |
-
},
|
| 161 |
-
quality_gate={"passed": True, "metrics": {}},
|
| 162 |
-
finalists=[
|
| 163 |
-
{
|
| 164 |
-
"paperId": "paper_1",
|
| 165 |
-
"title": "Cardiovascular Effects Study 1",
|
| 166 |
-
"citationCount": 150,
|
| 167 |
-
"year": 2023,
|
| 168 |
-
},
|
| 169 |
-
{
|
| 170 |
-
"paperId": "paper_2",
|
| 171 |
-
"title": "Cardiovascular Effects Study 2",
|
| 172 |
-
"citationCount": 200,
|
| 173 |
-
"year": 2022,
|
| 174 |
-
},
|
| 175 |
-
],
|
| 176 |
-
execution_time=5.5,
|
| 177 |
-
timing_breakdown={
|
| 178 |
-
"query_optimization": 0.5,
|
| 179 |
-
"semantic_scholar_search": 1.0,
|
| 180 |
-
"quality_gate": 0.1,
|
| 181 |
-
"composite_scoring": 0.2,
|
| 182 |
-
"pdf_acquisition": 1.5,
|
| 183 |
-
"processing": 1.0,
|
| 184 |
-
"retrieval": 0.5,
|
| 185 |
-
"reranking": 0.5,
|
| 186 |
-
"synthesis": 0.15,
|
| 187 |
-
"verification": 0.05,
|
| 188 |
-
},
|
| 189 |
-
success=True,
|
| 190 |
-
passages=mock_passages,
|
| 191 |
-
answer=(
|
| 192 |
-
"Intermittent fasting has been shown to reduce blood pressure significantly [1], "
|
| 193 |
-
"improve cardiac function [2], and reduce atherosclerotic burden [3]."
|
| 194 |
-
),
|
| 195 |
-
citation_verification={
|
| 196 |
-
"valid": True,
|
| 197 |
-
"citations_found": [1, 2, 3],
|
| 198 |
-
"invalid_citations": [],
|
| 199 |
-
},
|
| 200 |
-
)
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
@pytest.fixture
|
| 204 |
-
def mock_failed_pipeline_result():
|
| 205 |
-
"""Create a mock PipelineResult for a failed pipeline."""
|
| 206 |
-
from services.query_service import PipelineResult
|
| 207 |
-
|
| 208 |
-
return PipelineResult(
|
| 209 |
-
query="test query",
|
| 210 |
-
optimized_queries={},
|
| 211 |
-
quality_gate={},
|
| 212 |
-
finalists=[],
|
| 213 |
-
execution_time=1.0,
|
| 214 |
-
timing_breakdown={"query_optimization": 0.5},
|
| 215 |
-
success=False,
|
| 216 |
-
error_message="LLM API connection failed",
|
| 217 |
-
error_stage="synthesis",
|
| 218 |
-
passages=[],
|
| 219 |
-
answer=None,
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
# ============================================================================
|
| 224 |
-
# Happy Path Tests
|
| 225 |
-
# ============================================================================
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
@pytest.mark.integration
|
| 229 |
-
def test_query_endpoint_returns_200_with_valid_request(
|
| 230 |
-
client, app, mock_pipeline_result, set_test_env
|
| 231 |
-
):
|
| 232 |
-
"""Test valid POST request returns 200 and expected JSON structure.
|
| 233 |
-
|
| 234 |
-
Validates:
|
| 235 |
-
- Status code is 200
|
| 236 |
-
- Response contains all required fields: answer, citations, finalists, execution_time, timing_breakdown
|
| 237 |
-
- Citations have correct structure (id, text, metadata)
|
| 238 |
-
"""
|
| 239 |
-
# Mock the query service
|
| 240 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 241 |
-
mock_service.process_query = AsyncMock(return_value=mock_pipeline_result)
|
| 242 |
-
|
| 243 |
-
response = client.post(
|
| 244 |
-
"/query",
|
| 245 |
-
json={
|
| 246 |
-
"query": "What are the cardiovascular effects of intermittent fasting?"
|
| 247 |
-
},
|
| 248 |
-
)
|
| 249 |
-
|
| 250 |
-
# Assertions
|
| 251 |
-
assert (
|
| 252 |
-
response.status_code == 200
|
| 253 |
-
), f"Expected 200, got {response.status_code}: {response.text}"
|
| 254 |
-
|
| 255 |
-
data = response.json()
|
| 256 |
-
|
| 257 |
-
# Check required top-level fields
|
| 258 |
-
assert "answer" in data, "Response should contain 'answer' field"
|
| 259 |
-
assert "citations" in data, "Response should contain 'citations' field"
|
| 260 |
-
assert "finalists" in data, "Response should contain 'finalists' field"
|
| 261 |
-
assert "execution_time" in data, "Response should contain 'execution_time' field"
|
| 262 |
-
assert (
|
| 263 |
-
"timing_breakdown" in data
|
| 264 |
-
), "Response should contain 'timing_breakdown' field"
|
| 265 |
-
|
| 266 |
-
# Validate answer
|
| 267 |
-
assert isinstance(data["answer"], str), "answer should be a string"
|
| 268 |
-
assert len(data["answer"]) > 0, "answer should not be empty"
|
| 269 |
-
assert "[1]" in data["answer"], "answer should contain citation [1]"
|
| 270 |
-
|
| 271 |
-
# Validate citations structure
|
| 272 |
-
assert isinstance(data["citations"], list), "citations should be a list"
|
| 273 |
-
assert len(data["citations"]) > 0, "citations should not be empty"
|
| 274 |
-
|
| 275 |
-
for citation in data["citations"]:
|
| 276 |
-
assert "id" in citation, "citation should have 'id' field"
|
| 277 |
-
assert "text" in citation, "citation should have 'text' field"
|
| 278 |
-
assert "metadata" in citation, "citation should have 'metadata' field"
|
| 279 |
-
assert isinstance(citation["id"], int), "citation id should be an integer"
|
| 280 |
-
assert citation["id"] >= 1, "citation id should be >= 1"
|
| 281 |
-
assert isinstance(citation["text"], str), "citation text should be a string"
|
| 282 |
-
assert isinstance(
|
| 283 |
-
citation["metadata"], dict
|
| 284 |
-
), "citation metadata should be a dict"
|
| 285 |
-
|
| 286 |
-
# Validate finalists
|
| 287 |
-
assert isinstance(data["finalists"], list), "finalists should be a list"
|
| 288 |
-
assert len(data["finalists"]) > 0, "finalists should not be empty"
|
| 289 |
-
|
| 290 |
-
# Validate execution_time
|
| 291 |
-
assert isinstance(
|
| 292 |
-
data["execution_time"], (int, float)
|
| 293 |
-
), "execution_time should be a number"
|
| 294 |
-
assert data["execution_time"] > 0, "execution_time should be positive"
|
| 295 |
-
|
| 296 |
-
# Validate timing_breakdown
|
| 297 |
-
assert isinstance(
|
| 298 |
-
data["timing_breakdown"], dict
|
| 299 |
-
), "timing_breakdown should be a dict"
|
| 300 |
-
assert len(data["timing_breakdown"]) > 0, "timing_breakdown should not be empty"
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
@pytest.mark.integration
|
| 304 |
-
def test_query_endpoint_citation_metadata_includes_score(
|
| 305 |
-
client, app, mock_pipeline_result, set_test_env
|
| 306 |
-
):
|
| 307 |
-
"""Test that citation metadata includes the reranking score for frontend use."""
|
| 308 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 309 |
-
mock_service.process_query = AsyncMock(return_value=mock_pipeline_result)
|
| 310 |
-
|
| 311 |
-
response = client.post(
|
| 312 |
-
"/query",
|
| 313 |
-
json={"query": "test query"},
|
| 314 |
-
)
|
| 315 |
-
|
| 316 |
-
assert response.status_code == 200
|
| 317 |
-
data = response.json()
|
| 318 |
-
|
| 319 |
-
# Check that score is in metadata
|
| 320 |
-
for citation in data["citations"]:
|
| 321 |
-
assert (
|
| 322 |
-
"score" in citation["metadata"]
|
| 323 |
-
), "citation metadata should include 'score'"
|
| 324 |
-
assert isinstance(
|
| 325 |
-
citation["metadata"]["score"], (int, float)
|
| 326 |
-
), "score should be a number"
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# ============================================================================
|
| 330 |
-
# Validation Tests
|
| 331 |
-
# ============================================================================
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
@pytest.mark.integration
|
| 335 |
-
def test_query_endpoint_empty_query_returns_422(client, set_test_env):
|
| 336 |
-
"""Test that an empty query returns 422 (Pydantic validation error).
|
| 337 |
-
|
| 338 |
-
FastAPI/Pydantic validates min_length=1 and returns 422 Unprocessable Entity.
|
| 339 |
-
"""
|
| 340 |
-
response = client.post("/query", json={"query": ""})
|
| 341 |
-
|
| 342 |
-
assert response.status_code == 422, f"Expected 422, got {response.status_code}"
|
| 343 |
-
|
| 344 |
-
data = response.json()
|
| 345 |
-
assert "detail" in data, "Response should contain 'detail' field"
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
@pytest.mark.integration
|
| 349 |
-
def test_query_endpoint_missing_query_field_returns_422(client, set_test_env):
|
| 350 |
-
"""Test that missing query field returns 422."""
|
| 351 |
-
response = client.post("/query", json={})
|
| 352 |
-
|
| 353 |
-
assert response.status_code == 422, f"Expected 422, got {response.status_code}"
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
@pytest.mark.integration
|
| 357 |
-
def test_query_endpoint_query_too_long_returns_422(client, set_test_env):
|
| 358 |
-
"""Test that a query exceeding max_length returns 422."""
|
| 359 |
-
long_query = "a" * 501 # max_length is 500
|
| 360 |
-
|
| 361 |
-
response = client.post("/query", json={"query": long_query})
|
| 362 |
-
|
| 363 |
-
assert response.status_code == 422, f"Expected 422, got {response.status_code}"
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
# ============================================================================
|
| 367 |
-
# Error Handling Tests
|
| 368 |
-
# ============================================================================
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
@pytest.mark.integration
|
| 372 |
-
def test_query_endpoint_pipeline_failure_returns_500(
|
| 373 |
-
client, app, mock_failed_pipeline_result, set_test_env
|
| 374 |
-
):
|
| 375 |
-
"""Test that pipeline failure returns HTTP 500 with clean error message."""
|
| 376 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 377 |
-
mock_service.process_query = AsyncMock(return_value=mock_failed_pipeline_result)
|
| 378 |
-
|
| 379 |
-
response = client.post(
|
| 380 |
-
"/query",
|
| 381 |
-
json={"query": "test query"},
|
| 382 |
-
)
|
| 383 |
-
|
| 384 |
-
assert response.status_code == 500, f"Expected 500, got {response.status_code}"
|
| 385 |
-
|
| 386 |
-
data = response.json()
|
| 387 |
-
assert "detail" in data, "Response should contain 'detail' field"
|
| 388 |
-
assert "synthesis" in data["detail"], "Error should mention the failed stage"
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
@pytest.mark.integration
|
| 392 |
-
def test_query_endpoint_unexpected_exception_returns_500(client, app, set_test_env):
|
| 393 |
-
"""Test that unexpected exceptions return HTTP 500 with generic message."""
|
| 394 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 395 |
-
mock_service.process_query = AsyncMock(
|
| 396 |
-
side_effect=RuntimeError("Unexpected database error")
|
| 397 |
-
)
|
| 398 |
-
|
| 399 |
-
response = client.post(
|
| 400 |
-
"/query",
|
| 401 |
-
json={"query": "test query"},
|
| 402 |
-
)
|
| 403 |
-
|
| 404 |
-
assert response.status_code == 500, f"Expected 500, got {response.status_code}"
|
| 405 |
-
|
| 406 |
-
data = response.json()
|
| 407 |
-
assert "detail" in data, "Response should contain 'detail' field"
|
| 408 |
-
# Should not expose internal error details to client
|
| 409 |
-
assert "An unexpected error occurred" in data["detail"]
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
# ============================================================================
|
| 413 |
-
# Edge Case Tests
|
| 414 |
-
# ============================================================================
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
@pytest.mark.integration
|
| 418 |
-
def test_query_endpoint_no_answer_returns_fallback_message(client, app, set_test_env):
|
| 419 |
-
"""Test that when answer is None, a fallback message is returned."""
|
| 420 |
-
from models.state import Passage
|
| 421 |
-
from services.query_service import PipelineResult
|
| 422 |
-
|
| 423 |
-
# Create result with no answer
|
| 424 |
-
passage = Passage(paper_id="p1", text="Some passage text", score=0.9)
|
| 425 |
-
result_no_answer = PipelineResult(
|
| 426 |
-
query="test query",
|
| 427 |
-
optimized_queries={
|
| 428 |
-
"primary": "test",
|
| 429 |
-
"broad": "test",
|
| 430 |
-
"alternative": "test",
|
| 431 |
-
"final_rephrase": "test",
|
| 432 |
-
},
|
| 433 |
-
quality_gate={"passed": True},
|
| 434 |
-
finalists=[{"paperId": "p1", "title": "Test"}],
|
| 435 |
-
execution_time=1.0,
|
| 436 |
-
timing_breakdown={"query_optimization": 0.5},
|
| 437 |
-
success=True,
|
| 438 |
-
passages=[passage],
|
| 439 |
-
answer=None, # No answer generated
|
| 440 |
-
)
|
| 441 |
-
|
| 442 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 443 |
-
mock_service.process_query = AsyncMock(return_value=result_no_answer)
|
| 444 |
-
|
| 445 |
-
response = client.post("/query", json={"query": "test query"})
|
| 446 |
-
|
| 447 |
-
assert response.status_code == 200
|
| 448 |
-
data = response.json()
|
| 449 |
-
assert data["answer"] == "No answer could be generated from the available sources."
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
@pytest.mark.integration
|
| 453 |
-
def test_query_endpoint_empty_passages_returns_empty_citations(
|
| 454 |
-
client, app, set_test_env
|
| 455 |
-
):
|
| 456 |
-
"""Test that empty passages result in empty citations list."""
|
| 457 |
-
from services.query_service import PipelineResult
|
| 458 |
-
|
| 459 |
-
result_no_passages = PipelineResult(
|
| 460 |
-
query="test query",
|
| 461 |
-
optimized_queries={
|
| 462 |
-
"primary": "test",
|
| 463 |
-
"broad": "test",
|
| 464 |
-
"alternative": "test",
|
| 465 |
-
"final_rephrase": "test",
|
| 466 |
-
},
|
| 467 |
-
quality_gate={"passed": True},
|
| 468 |
-
finalists=[{"paperId": "p1", "title": "Test"}],
|
| 469 |
-
execution_time=1.0,
|
| 470 |
-
timing_breakdown={"query_optimization": 0.5},
|
| 471 |
-
success=True,
|
| 472 |
-
passages=[], # No passages
|
| 473 |
-
answer="I cannot answer this based on the provided sources.",
|
| 474 |
-
)
|
| 475 |
-
|
| 476 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 477 |
-
mock_service.process_query = AsyncMock(return_value=result_no_passages)
|
| 478 |
-
|
| 479 |
-
response = client.post("/query", json={"query": "test query"})
|
| 480 |
-
|
| 481 |
-
assert response.status_code == 200
|
| 482 |
-
data = response.json()
|
| 483 |
-
assert data["citations"] == [], "citations should be empty when no passages"
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
@pytest.mark.integration
|
| 487 |
-
def test_query_endpoint_response_time_reasonable(
|
| 488 |
-
client, app, mock_pipeline_result, set_test_env
|
| 489 |
-
):
|
| 490 |
-
"""Test that endpoint response time is reasonable (mocked pipeline)."""
|
| 491 |
-
import time
|
| 492 |
-
|
| 493 |
-
with patch.object(app.state, "query_service", create=True) as mock_service:
|
| 494 |
-
mock_service.process_query = AsyncMock(return_value=mock_pipeline_result)
|
| 495 |
-
|
| 496 |
-
start = time.time()
|
| 497 |
-
response = client.post("/query", json={"query": "test query"})
|
| 498 |
-
elapsed = time.time() - start
|
| 499 |
-
|
| 500 |
-
assert response.status_code == 200
|
| 501 |
-
# With mocked pipeline, response should be fast
|
| 502 |
-
assert elapsed < 1.0, f"Response took {elapsed:.2f}s, expected < 1s"
|
| 503 |
-
# With mocked pipeline, response should be fast
|
| 504 |
-
assert elapsed < 1.0, f"Response took {elapsed:.2f}s, expected < 1s"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/integration/test_query_endpoint.py
DELETED
|
@@ -1,379 +0,0 @@
|
|
| 1 |
-
"""Integration tests for the /query endpoint.
|
| 2 |
-
|
| 3 |
-
Tests the pipeline: query_optimization → semantic_scholar_search → quality_gate → composite_scoring.
|
| 4 |
-
Covers success paths, quality gate failures, and various error scenarios.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
from unittest.mock import AsyncMock, MagicMock, patch
|
| 9 |
-
|
| 10 |
-
import numpy as np
|
| 11 |
-
import pytest
|
| 12 |
-
from fastapi.testclient import TestClient
|
| 13 |
-
|
| 14 |
-
from config.config import get_settings
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
@pytest.fixture
|
| 18 |
-
def set_test_env():
|
| 19 |
-
"""Set minimal test environment variables for config validation"""
|
| 20 |
-
# Save original values
|
| 21 |
-
original_values = {
|
| 22 |
-
"SEMANTIC_SCHOLAR_API_KEY": os.environ.get("SEMANTIC_SCHOLAR_API_KEY"),
|
| 23 |
-
"PRIMARY_LLM_API_KEY": os.environ.get("PRIMARY_LLM_API_KEY"),
|
| 24 |
-
"SECONDARY_LLM_API_KEY": os.environ.get("SECONDARY_LLM_API_KEY"),
|
| 25 |
-
"QUERY_OPTIMIZATION_MODEL": os.environ.get("QUERY_OPTIMIZATION_MODEL"),
|
| 26 |
-
"SYNTHESIS_MODEL": os.environ.get("SYNTHESIS_MODEL"),
|
| 27 |
-
"RAG_EMBEDDING_MODEL": os.environ.get("RAG_EMBEDDING_MODEL"),
|
| 28 |
-
"SKIP_DOTENV_LOADER": os.environ.get("SKIP_DOTENV_LOADER"),
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
# Set test values
|
| 32 |
-
os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
|
| 33 |
-
os.environ["PRIMARY_LLM_API_KEY"] = "test_key"
|
| 34 |
-
os.environ["SECONDARY_LLM_API_KEY"] = "test_key"
|
| 35 |
-
os.environ["QUERY_OPTIMIZATION_MODEL"] = "test_model"
|
| 36 |
-
os.environ["SYNTHESIS_MODEL"] = "test_model"
|
| 37 |
-
os.environ["RAG_EMBEDDING_MODEL"] = "allenai-specter-2"
|
| 38 |
-
os.environ["SKIP_DOTENV_LOADER"] = "1"
|
| 39 |
-
|
| 40 |
-
yield
|
| 41 |
-
|
| 42 |
-
# Restore original values
|
| 43 |
-
for key, value in original_values.items():
|
| 44 |
-
if value is None:
|
| 45 |
-
os.environ.pop(key, None)
|
| 46 |
-
else:
|
| 47 |
-
os.environ[key] = value
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
@pytest.fixture
|
| 51 |
-
def app(set_test_env):
|
| 52 |
-
from main import app
|
| 53 |
-
|
| 54 |
-
# Mock the embedding model
|
| 55 |
-
mock_embedding_model = MagicMock()
|
| 56 |
-
mock_embedding_model.embed_dim = 384
|
| 57 |
-
mock_embedding_model.encode.return_value = np.random.rand(384).astype(np.float32)
|
| 58 |
-
|
| 59 |
-
# Mock get_text_embedding_batch to return list of embeddings
|
| 60 |
-
def mock_get_embeddings(texts):
|
| 61 |
-
return [np.random.rand(384).tolist() for _ in texts]
|
| 62 |
-
|
| 63 |
-
mock_embedding_model.get_text_embedding_batch = mock_get_embeddings
|
| 64 |
-
|
| 65 |
-
app.state.embedding_model = mock_embedding_model
|
| 66 |
-
|
| 67 |
-
# Initialize query service with mock
|
| 68 |
-
from services.query_service import QueryService
|
| 69 |
-
|
| 70 |
-
app.state.query_service = QueryService(get_settings(), mock_embedding_model)
|
| 71 |
-
|
| 72 |
-
return app
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
@pytest.fixture
|
| 76 |
-
def client(app):
|
| 77 |
-
return TestClient(app)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
@pytest.mark.integration
|
| 81 |
-
class TestQueryEndpoint:
|
| 82 |
-
"""Integration tests for the /query POST endpoint."""
|
| 83 |
-
|
| 84 |
-
def test_successful_query_with_finalists(self, client: TestClient):
|
| 85 |
-
"""Test case 1: Valid query returns finalists with all expected fields."""
|
| 86 |
-
# Mock all pipeline components for success path
|
| 87 |
-
with (
|
| 88 |
-
patch(
|
| 89 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 90 |
-
) as mock_opt_class,
|
| 91 |
-
patch(
|
| 92 |
-
"services.discovery_service.SemanticScholarClient"
|
| 93 |
-
) as mock_client_class,
|
| 94 |
-
patch("services.discovery_service.validate_quality") as mock_quality,
|
| 95 |
-
patch("services.discovery_service.RankingAgent") as mock_ranker_class,
|
| 96 |
-
):
|
| 97 |
-
|
| 98 |
-
# Setup mocks
|
| 99 |
-
mock_opt = MagicMock()
|
| 100 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 101 |
-
return_value={
|
| 102 |
-
"final_rephrase": "cardiovascular risks of intermittent fasting",
|
| 103 |
-
"primary": "intermittent fasting cardiovascular risks",
|
| 104 |
-
"broad": "fasting protocols health outcomes cardiovascular",
|
| 105 |
-
"alternative": "time-restricted eating cardiac complications",
|
| 106 |
-
}
|
| 107 |
-
)
|
| 108 |
-
mock_opt_class.return_value = mock_opt
|
| 109 |
-
|
| 110 |
-
mock_client = MagicMock()
|
| 111 |
-
mock_papers = [
|
| 112 |
-
{
|
| 113 |
-
"paperId": "p1",
|
| 114 |
-
"title": "Effects of Intermittent Fasting on Cardiovascular Health",
|
| 115 |
-
"abstract": "This study examines...",
|
| 116 |
-
"year": 2023,
|
| 117 |
-
"citationCount": 50,
|
| 118 |
-
"influentialCitationCount": 10,
|
| 119 |
-
"openAccessPdf": {"url": "https://example.com/p1.pdf"},
|
| 120 |
-
"embedding": {"specter": np.random.rand(384).tolist()},
|
| 121 |
-
"authors": [{"name": "Dr. Smith"}],
|
| 122 |
-
"venue": "Journal of Cardiology",
|
| 123 |
-
}
|
| 124 |
-
] * 30 # 30 papers to pass quality gate
|
| 125 |
-
mock_client.multi_query_search = AsyncMock(return_value=mock_papers)
|
| 126 |
-
mock_client_class.return_value = mock_client
|
| 127 |
-
|
| 128 |
-
mock_quality.return_value = {
|
| 129 |
-
"passed": True,
|
| 130 |
-
"metrics": {
|
| 131 |
-
"paper_count": 30,
|
| 132 |
-
"embedding_coverage": 1.0,
|
| 133 |
-
"abstract_coverage": 1.0,
|
| 134 |
-
"median_similarity": 0.8,
|
| 135 |
-
},
|
| 136 |
-
"reason": "Quality gate passed",
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
mock_ranker = MagicMock()
|
| 140 |
-
mock_ranker.rank_papers.return_value = mock_papers[:8] # Top 8 finalists
|
| 141 |
-
mock_ranker_class.return_value = mock_ranker
|
| 142 |
-
|
| 143 |
-
# Make request
|
| 144 |
-
response = client.post(
|
| 145 |
-
"/query", json={"query": "intermittent fasting cardiovascular risks"}
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
assert response.status_code == 200
|
| 149 |
-
data = response.json()
|
| 150 |
-
|
| 151 |
-
# Check response structure
|
| 152 |
-
assert data["query"] == "intermittent fasting cardiovascular risks"
|
| 153 |
-
assert "optimized_queries" in data
|
| 154 |
-
assert "quality_gate" in data
|
| 155 |
-
assert data["quality_gate"]["passed"] is True
|
| 156 |
-
assert len(data["finalists"]) == 8
|
| 157 |
-
assert data["execution_time"] > 0
|
| 158 |
-
assert "timing_breakdown" in data
|
| 159 |
-
assert all(
|
| 160 |
-
k in data["timing_breakdown"]
|
| 161 |
-
for k in [
|
| 162 |
-
"query_optimization",
|
| 163 |
-
"semantic_scholar_search",
|
| 164 |
-
"quality_gate",
|
| 165 |
-
"composite_scoring",
|
| 166 |
-
]
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
-
def test_quality_gate_failure_returns_early(self, client: TestClient):
|
| 170 |
-
"""Test case 2: Quality gate failure returns early with reason (no finalists)."""
|
| 171 |
-
with (
|
| 172 |
-
patch(
|
| 173 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 174 |
-
) as mock_opt_class,
|
| 175 |
-
patch(
|
| 176 |
-
"services.discovery_service.SemanticScholarClient"
|
| 177 |
-
) as mock_client_class,
|
| 178 |
-
patch("services.discovery_service.validate_quality") as mock_quality,
|
| 179 |
-
):
|
| 180 |
-
|
| 181 |
-
mock_opt = MagicMock()
|
| 182 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 183 |
-
return_value={
|
| 184 |
-
"final_rephrase": "test query",
|
| 185 |
-
"primary": "test query",
|
| 186 |
-
"broad": "test query",
|
| 187 |
-
"alternative": "test query",
|
| 188 |
-
}
|
| 189 |
-
)
|
| 190 |
-
mock_opt_class.return_value = mock_opt
|
| 191 |
-
|
| 192 |
-
mock_client = MagicMock()
|
| 193 |
-
mock_client.multi_query_search = AsyncMock(return_value=[]) # No papers
|
| 194 |
-
mock_client_class.return_value = mock_client
|
| 195 |
-
|
| 196 |
-
mock_quality.return_value = {
|
| 197 |
-
"passed": False,
|
| 198 |
-
"metrics": {
|
| 199 |
-
"paper_count": 0,
|
| 200 |
-
"embedding_coverage": 0.0,
|
| 201 |
-
"abstract_coverage": 0.0,
|
| 202 |
-
"median_similarity": 0.0,
|
| 203 |
-
},
|
| 204 |
-
"reason": "insufficient paper count (0 < 25)",
|
| 205 |
-
}
|
| 206 |
-
|
| 207 |
-
response = client.post("/query", json={"query": "test query"})
|
| 208 |
-
|
| 209 |
-
assert response.status_code == 200
|
| 210 |
-
data = response.json()
|
| 211 |
-
|
| 212 |
-
assert data["quality_gate"]["passed"] is False
|
| 213 |
-
assert data["finalists"] == []
|
| 214 |
-
assert "insufficient paper count" in data["quality_gate"]["reason"]
|
| 215 |
-
|
| 216 |
-
def test_query_optimization_error_returns_500(self, client: TestClient):
|
| 217 |
-
"""Test case 3: Query optimization failure returns 500 with user-friendly message."""
|
| 218 |
-
with patch(
|
| 219 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 220 |
-
) as mock_opt_class:
|
| 221 |
-
mock_opt = MagicMock()
|
| 222 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 223 |
-
side_effect=Exception("LLM service unavailable")
|
| 224 |
-
)
|
| 225 |
-
mock_opt_class.return_value = mock_opt
|
| 226 |
-
|
| 227 |
-
response = client.post("/query", json={"query": "test query"})
|
| 228 |
-
|
| 229 |
-
assert response.status_code == 500
|
| 230 |
-
data = response.json()
|
| 231 |
-
assert "Failed to optimize query" in data["detail"]
|
| 232 |
-
|
| 233 |
-
def test_semantic_scholar_error_returns_503(self, client: TestClient):
|
| 234 |
-
"""Test case 4: Semantic Scholar API failure returns 503 with user-friendly message."""
|
| 235 |
-
with (
|
| 236 |
-
patch(
|
| 237 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 238 |
-
) as mock_opt_class,
|
| 239 |
-
patch(
|
| 240 |
-
"services.discovery_service.SemanticScholarClient"
|
| 241 |
-
) as mock_client_class,
|
| 242 |
-
):
|
| 243 |
-
|
| 244 |
-
mock_opt = MagicMock()
|
| 245 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 246 |
-
return_value={
|
| 247 |
-
"final_rephrase": "test query",
|
| 248 |
-
"primary": "test query",
|
| 249 |
-
"broad": "test query",
|
| 250 |
-
"alternative": "test query",
|
| 251 |
-
}
|
| 252 |
-
)
|
| 253 |
-
mock_opt_class.return_value = mock_opt
|
| 254 |
-
|
| 255 |
-
mock_client = MagicMock()
|
| 256 |
-
mock_client.multi_query_search = AsyncMock(
|
| 257 |
-
side_effect=Exception("Semantic Scholar API unavailable")
|
| 258 |
-
)
|
| 259 |
-
mock_client_class.return_value = mock_client
|
| 260 |
-
|
| 261 |
-
response = client.post("/query", json={"query": "test query"})
|
| 262 |
-
|
| 263 |
-
assert response.status_code == 503
|
| 264 |
-
data = response.json()
|
| 265 |
-
assert "Semantic Scholar API is currently unavailable" in data["detail"]
|
| 266 |
-
|
| 267 |
-
def test_quality_gate_error_returns_500(self, client: TestClient):
|
| 268 |
-
"""Test case 5: Quality gate validation error returns 500."""
|
| 269 |
-
with (
|
| 270 |
-
patch(
|
| 271 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 272 |
-
) as mock_opt_class,
|
| 273 |
-
patch(
|
| 274 |
-
"services.discovery_service.SemanticScholarClient"
|
| 275 |
-
) as mock_client_class,
|
| 276 |
-
patch("services.discovery_service.validate_quality") as mock_quality,
|
| 277 |
-
):
|
| 278 |
-
|
| 279 |
-
mock_opt = MagicMock()
|
| 280 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 281 |
-
return_value={
|
| 282 |
-
"final_rephrase": "test query",
|
| 283 |
-
"primary": "test query",
|
| 284 |
-
"broad": "test query",
|
| 285 |
-
"alternative": "test query",
|
| 286 |
-
}
|
| 287 |
-
)
|
| 288 |
-
mock_opt_class.return_value = mock_opt
|
| 289 |
-
|
| 290 |
-
mock_client = MagicMock()
|
| 291 |
-
mock_client.multi_query_search = AsyncMock(
|
| 292 |
-
return_value=[{"paperId": "test"}] * 30
|
| 293 |
-
)
|
| 294 |
-
mock_client_class.return_value = mock_client
|
| 295 |
-
|
| 296 |
-
mock_quality.side_effect = Exception("Embedding validation failed")
|
| 297 |
-
|
| 298 |
-
response = client.post("/query", json={"query": "test query"})
|
| 299 |
-
|
| 300 |
-
assert response.status_code == 500
|
| 301 |
-
data = response.json()
|
| 302 |
-
assert "Failed to validate paper quality" in data["detail"]
|
| 303 |
-
|
| 304 |
-
def test_ranking_error_returns_500(self, client: TestClient):
|
| 305 |
-
"""Test case 6: Ranking error returns 500."""
|
| 306 |
-
with (
|
| 307 |
-
patch(
|
| 308 |
-
"services.discovery_service.QueryOptimizationAgent"
|
| 309 |
-
) as mock_opt_class,
|
| 310 |
-
patch(
|
| 311 |
-
"services.discovery_service.SemanticScholarClient"
|
| 312 |
-
) as mock_client_class,
|
| 313 |
-
patch("services.discovery_service.validate_quality") as mock_quality,
|
| 314 |
-
patch("services.discovery_service.RankingAgent") as mock_ranker_class,
|
| 315 |
-
):
|
| 316 |
-
|
| 317 |
-
mock_opt = MagicMock()
|
| 318 |
-
mock_opt.generate_dual_queries = AsyncMock(
|
| 319 |
-
return_value={
|
| 320 |
-
"final_rephrase": "test query",
|
| 321 |
-
"primary": "test query",
|
| 322 |
-
"broad": "test query",
|
| 323 |
-
"alternative": "test query",
|
| 324 |
-
}
|
| 325 |
-
)
|
| 326 |
-
mock_opt_class.return_value = mock_opt
|
| 327 |
-
|
| 328 |
-
mock_client = MagicMock()
|
| 329 |
-
mock_client.multi_query_search = AsyncMock(
|
| 330 |
-
return_value=[{"paperId": "test"}] * 30
|
| 331 |
-
)
|
| 332 |
-
mock_client_class.return_value = mock_client
|
| 333 |
-
|
| 334 |
-
mock_quality.return_value = {
|
| 335 |
-
"passed": True,
|
| 336 |
-
"metrics": {
|
| 337 |
-
"paper_count": 30,
|
| 338 |
-
"embedding_coverage": 1.0,
|
| 339 |
-
"abstract_coverage": 1.0,
|
| 340 |
-
"median_similarity": 0.8,
|
| 341 |
-
},
|
| 342 |
-
"reason": "Quality gate passed",
|
| 343 |
-
}
|
| 344 |
-
|
| 345 |
-
mock_ranker = MagicMock()
|
| 346 |
-
mock_ranker.rank_papers.side_effect = Exception("Ranking algorithm failed")
|
| 347 |
-
mock_ranker_class.return_value = mock_ranker
|
| 348 |
-
|
| 349 |
-
response = client.post("/query", json={"query": "test query"})
|
| 350 |
-
|
| 351 |
-
assert response.status_code == 500
|
| 352 |
-
data = response.json()
|
| 353 |
-
assert "Failed to rank papers" in data["detail"]
|
| 354 |
-
|
| 355 |
-
def test_empty_query_returns_422(self, client: TestClient):
|
| 356 |
-
"""Test case 7: Empty query returns 422 Bad Request."""
|
| 357 |
-
response = client.post("/query", json={"query": ""})
|
| 358 |
-
assert response.status_code == 422 # Pydantic validation error
|
| 359 |
-
|
| 360 |
-
def test_query_too_long_returns_422(self, client: TestClient):
|
| 361 |
-
"""Test case 8: Query exceeding 500 characters returns 422 Bad Request."""
|
| 362 |
-
long_query = "a" * 501
|
| 363 |
-
response = client.post("/query", json={"query": long_query})
|
| 364 |
-
assert response.status_code == 422 # Pydantic validation error
|
| 365 |
-
|
| 366 |
-
def test_unexpected_error_returns_500(self, client: TestClient):
|
| 367 |
-
"""Test case 9: Unexpected error returns 500 with generic message."""
|
| 368 |
-
with patch.object(
|
| 369 |
-
client.app.state.query_service,
|
| 370 |
-
"process_query",
|
| 371 |
-
side_effect=Exception("Unexpected error"),
|
| 372 |
-
):
|
| 373 |
-
response = client.post("/query", json={"query": "test query"})
|
| 374 |
-
|
| 375 |
-
assert response.status_code == 500
|
| 376 |
-
data = response.json()
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Integration tests for QueryService.
|
| 2 |
+
|
| 3 |
+
Tests the pipeline: query_optimization → semantic_scholar_search → quality_gate → composite_scoring.
|
| 4 |
+
Covers success paths, quality gate failures, and various error scenarios.
|
| 5 |
+
Tests the service layer directly without HTTP endpoints.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
from unittest.mock import AsyncMock, MagicMock, patch
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
from config.config import get_settings
|
| 15 |
+
from models.state import Paper
|
| 16 |
+
from services.discovery_service import DiscoveryResult
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.fixture
|
| 20 |
+
def set_test_env():
|
| 21 |
+
"""Set minimal test environment variables for config validation"""
|
| 22 |
+
# Save original values
|
| 23 |
+
original_values = {
|
| 24 |
+
"SEMANTIC_SCHOLAR_API_KEY": os.environ.get("SEMANTIC_SCHOLAR_API_KEY"),
|
| 25 |
+
"PRIMARY_LLM_API_KEY": os.environ.get("PRIMARY_LLM_API_KEY"),
|
| 26 |
+
"SECONDARY_LLM_API_KEY": os.environ.get("SECONDARY_LLM_API_KEY"),
|
| 27 |
+
"QUERY_OPTIMIZATION_MODEL": os.environ.get("QUERY_OPTIMIZATION_MODEL"),
|
| 28 |
+
"SYNTHESIS_MODEL": os.environ.get("SYNTHESIS_MODEL"),
|
| 29 |
+
"RAG_EMBEDDING_MODEL": os.environ.get("RAG_EMBEDDING_MODEL"),
|
| 30 |
+
"SKIP_DOTENV_LOADER": os.environ.get("SKIP_DOTENV_LOADER"),
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Set test values
|
| 34 |
+
os.environ["SEMANTIC_SCHOLAR_API_KEY"] = "test_key"
|
| 35 |
+
os.environ["PRIMARY_LLM_API_KEY"] = "test_key"
|
| 36 |
+
os.environ["SECONDARY_LLM_API_KEY"] = "test_key"
|
| 37 |
+
os.environ["QUERY_OPTIMIZATION_MODEL"] = "test_model"
|
| 38 |
+
os.environ["SYNTHESIS_MODEL"] = "test_model"
|
| 39 |
+
os.environ["RAG_EMBEDDING_MODEL"] = "allenai-specter-2"
|
| 40 |
+
os.environ["SKIP_DOTENV_LOADER"] = "1"
|
| 41 |
+
|
| 42 |
+
yield
|
| 43 |
+
|
| 44 |
+
# Restore original values
|
| 45 |
+
for key, value in original_values.items():
|
| 46 |
+
if value is None:
|
| 47 |
+
os.environ.pop(key, None)
|
| 48 |
+
else:
|
| 49 |
+
os.environ[key] = value
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.fixture
|
| 53 |
+
def query_service(set_test_env):
|
| 54 |
+
"""Create QueryService with mocked embedding model."""
|
| 55 |
+
# Mock the embedding model
|
| 56 |
+
mock_embedding_model = MagicMock()
|
| 57 |
+
mock_embedding_model.embed_dim = 384
|
| 58 |
+
mock_embedding_model.encode.return_value = np.random.rand(384).astype(np.float32)
|
| 59 |
+
|
| 60 |
+
# Mock get_text_embedding_batch to return list of embeddings
|
| 61 |
+
def mock_get_embeddings(texts):
|
| 62 |
+
return [np.random.rand(384).tolist() for _ in texts]
|
| 63 |
+
|
| 64 |
+
mock_embedding_model.get_text_embedding_batch = mock_get_embeddings
|
| 65 |
+
|
| 66 |
+
# Initialize query service with mock
|
| 67 |
+
from services.query_service import QueryService
|
| 68 |
+
|
| 69 |
+
return QueryService(get_settings(), mock_embedding_model)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@pytest.mark.integration
|
| 73 |
+
class TestQueryServiceIntegration:
|
| 74 |
+
"""Integration tests for QueryService.process_query() method."""
|
| 75 |
+
|
| 76 |
+
@pytest.mark.asyncio
|
| 77 |
+
async def test_successful_query_with_finalists(self, query_service):
|
| 78 |
+
"""Test case 1: Valid query returns finalists with all expected fields."""
|
| 79 |
+
# Create mock papers
|
| 80 |
+
mock_papers = [
|
| 81 |
+
Paper(
|
| 82 |
+
paperId=f"p{i}",
|
| 83 |
+
title=f"Paper {i}",
|
| 84 |
+
abstract="Test abstract",
|
| 85 |
+
year=2023,
|
| 86 |
+
citationCount=50,
|
| 87 |
+
influentialCitationCount=10,
|
| 88 |
+
openAccessPdf={"url": f"https://example.com/p{i}.pdf"},
|
| 89 |
+
embedding={"specter": np.random.rand(384).tolist()},
|
| 90 |
+
authors=[{"name": "Dr. Smith"}],
|
| 91 |
+
venue="Test Journal",
|
| 92 |
+
)
|
| 93 |
+
for i in range(8)
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
# Mock the discovery service to return success
|
| 97 |
+
mock_discovery_result = DiscoveryResult(
|
| 98 |
+
optimized_queries={
|
| 99 |
+
"final_rephrase": "cardiovascular risks of intermittent fasting",
|
| 100 |
+
"primary": "intermittent fasting cardiovascular risks",
|
| 101 |
+
"broad": "fasting protocols health outcomes cardiovascular",
|
| 102 |
+
"alternative": "time-restricted eating cardiac complications",
|
| 103 |
+
},
|
| 104 |
+
quality_gate={
|
| 105 |
+
"passed": True,
|
| 106 |
+
"metrics": {
|
| 107 |
+
"paper_count": 30,
|
| 108 |
+
"embedding_coverage": 1.0,
|
| 109 |
+
"abstract_coverage": 1.0,
|
| 110 |
+
"median_similarity": 0.8,
|
| 111 |
+
},
|
| 112 |
+
"reason": "Quality gate passed",
|
| 113 |
+
},
|
| 114 |
+
finalists=mock_papers,
|
| 115 |
+
timing_breakdown={
|
| 116 |
+
"query_optimization": 0.1,
|
| 117 |
+
"semantic_scholar_search": 0.5,
|
| 118 |
+
"quality_gate": 0.1,
|
| 119 |
+
"composite_scoring": 0.2,
|
| 120 |
+
},
|
| 121 |
+
refinement_count=0,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
with patch.object(
|
| 125 |
+
query_service.discovery_service,
|
| 126 |
+
"discover",
|
| 127 |
+
return_value=mock_discovery_result,
|
| 128 |
+
):
|
| 129 |
+
# Call service directly
|
| 130 |
+
result = await query_service.process_query(
|
| 131 |
+
"intermittent fasting cardiovascular risks", deep_mode=False
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Assert on PipelineResult object
|
| 135 |
+
assert result.success is True
|
| 136 |
+
assert result.query == "intermittent fasting cardiovascular risks"
|
| 137 |
+
assert result.optimized_queries is not None
|
| 138 |
+
assert result.quality_gate["passed"] is True
|
| 139 |
+
assert len(result.finalists) == 8
|
| 140 |
+
assert result.execution_time > 0
|
| 141 |
+
assert "query_optimization" in result.timing_breakdown
|
| 142 |
+
assert "semantic_scholar_search" in result.timing_breakdown
|
| 143 |
+
|
| 144 |
+
@pytest.mark.asyncio
|
| 145 |
+
async def test_quality_gate_failure_returns_early(self, query_service):
|
| 146 |
+
"""Test case 2: Quality gate failure returns early with reason (no finalists)."""
|
| 147 |
+
# Mock the discovery service to return quality gate failure
|
| 148 |
+
mock_discovery_result = DiscoveryResult(
|
| 149 |
+
optimized_queries={
|
| 150 |
+
"final_rephrase": "test query",
|
| 151 |
+
"primary": "test query",
|
| 152 |
+
"broad": "test query",
|
| 153 |
+
"alternative": "test query",
|
| 154 |
+
},
|
| 155 |
+
quality_gate={
|
| 156 |
+
"passed": False,
|
| 157 |
+
"metrics": {
|
| 158 |
+
"paper_count": 0,
|
| 159 |
+
"embedding_coverage": 0.0,
|
| 160 |
+
"abstract_coverage": 0.0,
|
| 161 |
+
"median_similarity": 0.0,
|
| 162 |
+
},
|
| 163 |
+
"reason": "No papers found",
|
| 164 |
+
},
|
| 165 |
+
finalists=[],
|
| 166 |
+
timing_breakdown={
|
| 167 |
+
"query_optimization": 0.1,
|
| 168 |
+
"semantic_scholar_search": 0.5,
|
| 169 |
+
"quality_gate": 0.1,
|
| 170 |
+
},
|
| 171 |
+
refinement_count=1,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
with patch.object(
|
| 175 |
+
query_service.discovery_service,
|
| 176 |
+
"discover",
|
| 177 |
+
return_value=mock_discovery_result,
|
| 178 |
+
):
|
| 179 |
+
# Call service directly
|
| 180 |
+
result = await query_service.process_query("test query")
|
| 181 |
+
|
| 182 |
+
# Assert on PipelineResult object
|
| 183 |
+
assert result.success is True # Pipeline handled the failure gracefully
|
| 184 |
+
assert result.quality_gate["passed"] is False
|
| 185 |
+
assert len(result.finalists) == 0
|
| 186 |
+
assert "No papers found" in result.quality_gate["reason"]
|
| 187 |
+
|
| 188 |
+
@pytest.mark.asyncio
|
| 189 |
+
async def test_query_optimization_error_stops_pipeline(self, query_service):
|
| 190 |
+
"""Test case 3: Query optimization failure stops pipeline with error details."""
|
| 191 |
+
# Import the custom exception
|
| 192 |
+
from services.exceptions import QueryOptimizationError
|
| 193 |
+
|
| 194 |
+
# Mock the discovery service to raise QueryOptimizationError
|
| 195 |
+
with patch.object(
|
| 196 |
+
query_service.discovery_service,
|
| 197 |
+
"discover",
|
| 198 |
+
side_effect=QueryOptimizationError(
|
| 199 |
+
"Failed to optimize query: LLM service unavailable"
|
| 200 |
+
),
|
| 201 |
+
):
|
| 202 |
+
# Call service directly
|
| 203 |
+
result = await query_service.process_query("test query")
|
| 204 |
+
|
| 205 |
+
# Assert on PipelineResult object
|
| 206 |
+
assert result.success is False
|
| 207 |
+
assert result.error_stage == "query_optimization"
|
| 208 |
+
assert "Failed to optimize query" in result.error_message
|
| 209 |
+
|
| 210 |
+
@pytest.mark.asyncio
|
| 211 |
+
async def test_semantic_scholar_error_stops_pipeline(self, query_service):
|
| 212 |
+
"""Test case 4: Semantic Scholar API failure stops pipeline with error details."""
|
| 213 |
+
# Import the custom exception
|
| 214 |
+
from services.exceptions import SemanticScholarError
|
| 215 |
+
|
| 216 |
+
# Mock the discovery service to raise SemanticScholarError
|
| 217 |
+
with patch.object(
|
| 218 |
+
query_service.discovery_service,
|
| 219 |
+
"discover",
|
| 220 |
+
side_effect=SemanticScholarError(
|
| 221 |
+
"Semantic Scholar API is currently unavailable"
|
| 222 |
+
),
|
| 223 |
+
):
|
| 224 |
+
# Call service directly
|
| 225 |
+
result = await query_service.process_query("test query")
|
| 226 |
+
|
| 227 |
+
# Assert on PipelineResult object
|
| 228 |
+
assert result.success is False
|
| 229 |
+
assert result.error_stage == "semantic_scholar_search"
|
| 230 |
+
assert "Semantic Scholar API" in result.error_message
|
| 231 |
+
|
| 232 |
+
@pytest.mark.asyncio
|
| 233 |
+
async def test_quality_gate_error_stops_pipeline(self, query_service):
|
| 234 |
+
"""Test case 5: Quality gate validation error stops pipeline with error details."""
|
| 235 |
+
# Import the custom exception
|
| 236 |
+
from services.exceptions import QualityGateError
|
| 237 |
+
|
| 238 |
+
# Mock the discovery service to raise QualityGateError
|
| 239 |
+
with patch.object(
|
| 240 |
+
query_service.discovery_service,
|
| 241 |
+
"discover",
|
| 242 |
+
side_effect=QualityGateError(
|
| 243 |
+
"Failed to validate paper quality: Embedding validation failed"
|
| 244 |
+
),
|
| 245 |
+
):
|
| 246 |
+
# Call service directly
|
| 247 |
+
result = await query_service.process_query("test query")
|
| 248 |
+
|
| 249 |
+
# Assert on PipelineResult object
|
| 250 |
+
assert result.success is False
|
| 251 |
+
assert result.error_stage == "quality_gate"
|
| 252 |
+
assert "Failed to validate paper quality" in result.error_message
|
| 253 |
+
|
| 254 |
+
@pytest.mark.asyncio
|
| 255 |
+
async def test_ranking_error_stops_pipeline(self, query_service):
|
| 256 |
+
"""Test case 6: Ranking error stops pipeline with error details."""
|
| 257 |
+
# Import the custom exception
|
| 258 |
+
from services.exceptions import RankingError
|
| 259 |
+
|
| 260 |
+
# Mock the discovery service to raise RankingError
|
| 261 |
+
with patch.object(
|
| 262 |
+
query_service.discovery_service,
|
| 263 |
+
"discover",
|
| 264 |
+
side_effect=RankingError("Failed to rank papers: Ranking algorithm failed"),
|
| 265 |
+
):
|
| 266 |
+
# Call service directly
|
| 267 |
+
result = await query_service.process_query("test query")
|
| 268 |
+
|
| 269 |
+
# Assert on PipelineResult object
|
| 270 |
+
assert result.success is False
|
| 271 |
+
assert result.error_stage == "composite_scoring"
|
| 272 |
+
assert "Failed to rank papers" in result.error_message
|
| 273 |
+
|
| 274 |
+
@pytest.mark.asyncio
|
| 275 |
+
async def test_unexpected_error_stops_pipeline(self, query_service):
|
| 276 |
+
"""Test case 7: Unexpected error stops pipeline with generic error message."""
|
| 277 |
+
with patch.object(
|
| 278 |
+
query_service.discovery_service,
|
| 279 |
+
"discover",
|
| 280 |
+
side_effect=Exception("Unexpected error"),
|
| 281 |
+
):
|
| 282 |
+
# Call service directly
|
| 283 |
+
result = await query_service.process_query("test query")
|
| 284 |
+
|
| 285 |
+
# Assert on PipelineResult object
|
| 286 |
+
assert result.success is False
|
| 287 |
+
assert result.error_message is not None
|
| 288 |
+
assert "Unexpected error" in result.error_message
|
ui/pages.py
CHANGED
|
@@ -3,7 +3,6 @@
|
|
| 3 |
import asyncio
|
| 4 |
import datetime
|
| 5 |
import time
|
| 6 |
-
from collections import defaultdict
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
import httpx
|
|
@@ -22,36 +21,35 @@ from ui.components import (
|
|
| 22 |
from ui.constants import KOFI_WIDGET, POSTHOG_SCRIPT
|
| 23 |
from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
|
| 24 |
|
| 25 |
-
# Global store: IP -> List of timestamps
|
| 26 |
-
_rate_limit_store = defaultdict(list)
|
| 27 |
|
| 28 |
-
|
| 29 |
-
def is_rate_limited(
|
| 30 |
-
ip_address: str, limit: int = None, window_seconds: int = None
|
| 31 |
-
) -> bool:
|
| 32 |
"""
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
"""
|
| 38 |
settings = get_settings()
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
if window_seconds is None:
|
| 42 |
-
window_seconds = settings.RATE_LIMIT_WINDOW_SECONDS
|
| 43 |
|
| 44 |
now = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# Filter out timestamps older than the window
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
return False
|
| 55 |
|
| 56 |
|
| 57 |
# Path to logo directory
|
|
@@ -301,9 +299,8 @@ Necthrall understands natural scientific language. You don't need keywords, just
|
|
| 301 |
return True
|
| 302 |
|
| 303 |
async def handle_search():
|
| 304 |
-
# Server-Side
|
| 305 |
-
|
| 306 |
-
if is_rate_limited(client_ip):
|
| 307 |
ui.notify(
|
| 308 |
"Rate limit exceeded. Please try again later.", type="negative"
|
| 309 |
)
|
|
|
|
| 3 |
import asyncio
|
| 4 |
import datetime
|
| 5 |
import time
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
import httpx
|
|
|
|
| 21 |
from ui.constants import KOFI_WIDGET, POSTHOG_SCRIPT
|
| 22 |
from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
|
| 23 |
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def check_and_update_limit() -> bool:
|
|
|
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
+
Check if user has exceeded rate limit using persistent user storage.
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
True if search is allowed (under limit), False if rate limited.
|
| 31 |
"""
|
| 32 |
settings = get_settings()
|
| 33 |
+
limit = settings.RATE_LIMIT_QUERIES_PER_HOUR
|
| 34 |
+
window_seconds = settings.RATE_LIMIT_WINDOW_SECONDS
|
|
|
|
|
|
|
| 35 |
|
| 36 |
now = time.time()
|
| 37 |
+
|
| 38 |
+
# Retrieve search history from user storage
|
| 39 |
+
search_history = app.storage.user.get("search_history", [])
|
| 40 |
+
|
| 41 |
# Filter out timestamps older than the window
|
| 42 |
+
search_history = [t for t in search_history if now - t < window_seconds]
|
| 43 |
+
|
| 44 |
+
# Check if limit exceeded
|
| 45 |
+
if len(search_history) >= limit:
|
| 46 |
+
return False
|
| 47 |
|
| 48 |
+
# Add current timestamp and save back
|
| 49 |
+
search_history.append(now)
|
| 50 |
+
app.storage.user["search_history"] = search_history
|
| 51 |
|
| 52 |
+
return True
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
# Path to logo directory
|
|
|
|
| 299 |
return True
|
| 300 |
|
| 301 |
async def handle_search():
|
| 302 |
+
# Server-Side User Rate Limit Check (using persistent storage)
|
| 303 |
+
if not check_and_update_limit():
|
|
|
|
| 304 |
ui.notify(
|
| 305 |
"Rate limit exceeded. Please try again later.", type="negative"
|
| 306 |
)
|