Builds PaperTrail from the base skeleton into a full evidence-verification platform for the "Built with Claude: Life Sciences" hackathon (Builder Track). New named-user features (Build Beyond the Bench): - Lab Notebook Companion — rough bench notes -> structured, searchable, grounded experiment records (lib/labNotebook, /console/lab-notebook, migration 0059) - Clinical Trial Matcher — de-identified patient notes -> ranked eligible ClinicalTrials.gov trials with per-criterion inclusion/exclusion reasoning (lib/trialMatcher, /console/trial-matcher, migrations 0060) Platform: - Deterministic verification moat (biostats recompute, exact-span grounding) - 11 biomedical evidence engines (FAERS, GWAS, Open Targets, ChEMBL, ClinVar, PharmGKB, PubTator, DDI, repurposing, biomarker, unified verifier) - Evidence Intelligence (KG, dossier, provenance/export, RWE) + enterprise governance (RBAC, /api/v1 gateway, metering, audit chain, retention) - 17 OSS projects assimilated into native TypeScript on our stack (backend/engines retained + credited in NOTICE) - Multi-format upload (PDF/DOCX/XLSX/CSV/MD/TXT), logo, marketing site - Next.js 16 upgrade, benchmark harness (honest smoke-test caveat) Licensing: Apache-2.0 (LICENSE + NOTICE).
169 lines
6.6 KiB
Python
169 lines
6.6 KiB
Python
import asyncio
|
|
import json
|
|
import sys
|
|
import types
|
|
import pytest
|
|
|
|
from app.config.settings import Config
|
|
from app.services.llm.rate_limiter import GatewayRateLimiter
|
|
from app.services.llm.retry_policy import RetryPolicy
|
|
from app.services.llm.token_estimator import TokenEstimator
|
|
from app.services.llm.trace_store import TraceStore
|
|
|
|
|
|
def _load_searcher_class():
|
|
sys.modules.setdefault("ijson", types.ModuleType("ijson"))
|
|
openai_stub = types.ModuleType("openai")
|
|
openai_stub.OpenAI = object
|
|
sys.modules.setdefault("openai", openai_stub)
|
|
from semantic_scholar.utils.searcher import S2Searcher
|
|
|
|
return S2Searcher
|
|
|
|
|
|
def test_token_estimator_produces_non_zero_counts():
|
|
estimator = TokenEstimator()
|
|
text_tokens = estimator.estimate_text_tokens("A claim about scientific evidence.")
|
|
chat_tokens = estimator.estimate_chat_tokens(
|
|
[
|
|
{"role": "system", "content": "You are a helpful assistant."},
|
|
{"role": "user", "content": "Summarize this claim."},
|
|
],
|
|
model_hint="gpt-4o",
|
|
)
|
|
assert text_tokens > 0
|
|
assert chat_tokens > text_tokens
|
|
|
|
|
|
def test_retry_policy_backoff_increases_and_is_bounded():
|
|
policy = RetryPolicy(max_retries=5, backoff_base_seconds=1.0, backoff_max_seconds=4.0, backoff_jitter=0.0)
|
|
delays = [policy.compute_backoff_seconds(i) for i in range(1, 6)]
|
|
assert delays == [1.0, 2.0, 4.0, 4.0, 4.0]
|
|
|
|
|
|
def test_trace_store_concurrent_appends_are_valid_jsonl(tmp_path):
|
|
store = TraceStore(root_dir=str(tmp_path), enabled=True)
|
|
|
|
async def writer(idx: int):
|
|
await store.append("batch1", "claim1", {"trace_id": str(idx), "idx": idx})
|
|
|
|
async def run():
|
|
await asyncio.gather(*(writer(i) for i in range(100)))
|
|
|
|
asyncio.run(run())
|
|
trace_file = tmp_path / "batch1" / "traces" / "claim1.jsonl"
|
|
assert trace_file.exists()
|
|
lines = trace_file.read_text(encoding="utf-8").splitlines()
|
|
assert len(lines) == 100
|
|
decoded = [json.loads(line) for line in lines]
|
|
assert sorted(item["idx"] for item in decoded) == list(range(100))
|
|
|
|
|
|
def test_rate_limiter_basic_reservation():
|
|
limiter = GatewayRateLimiter(max_concurrency=1, requests_per_minute=1000, tokens_per_minute=100000)
|
|
|
|
async def run():
|
|
async with limiter.reserve(estimated_tokens=10):
|
|
return True
|
|
|
|
assert asyncio.run(run()) is True
|
|
|
|
|
|
def test_validate_config_accepts_out_of_range_numeric_values(monkeypatch):
|
|
monkeypatch.setattr(Config, "LLM_PROVIDER", "openai", raising=False)
|
|
monkeypatch.setattr(Config, "LLM_API_KEY", "test", raising=False)
|
|
monkeypatch.setattr(Config, "SECRET_KEY", "secret", raising=False)
|
|
monkeypatch.setattr(Config, "USER_EMAIL", "user@example.com", raising=False)
|
|
monkeypatch.setattr(Config, "SEMANTIC_SCHOLAR_API_KEY", "test", raising=False)
|
|
monkeypatch.setattr(Config, "REQUIRE_PASSWORD", False, raising=False)
|
|
monkeypatch.setattr(Config, "LLM_BACKOFF_BASE_SECONDS", 10.0, raising=False)
|
|
monkeypatch.setattr(Config, "LLM_BACKOFF_MAX_SECONDS", 1.0, raising=False)
|
|
monkeypatch.setattr(Config, "LLM_BACKOFF_JITTER", 9.0, raising=False)
|
|
monkeypatch.setattr(Config, "LLM_TIMEOUT_SECONDS", 999999, raising=False)
|
|
|
|
Config.validate_config()
|
|
|
|
|
|
def test_validate_config_rejects_non_numeric_backoff(monkeypatch):
|
|
monkeypatch.setattr(Config, "LLM_PROVIDER", "openai", raising=False)
|
|
monkeypatch.setattr(Config, "LLM_API_KEY", "test", raising=False)
|
|
monkeypatch.setattr(Config, "SECRET_KEY", "secret", raising=False)
|
|
monkeypatch.setattr(Config, "USER_EMAIL", "user@example.com", raising=False)
|
|
monkeypatch.setattr(Config, "SEMANTIC_SCHOLAR_API_KEY", "test", raising=False)
|
|
monkeypatch.setattr(Config, "REQUIRE_PASSWORD", False, raising=False)
|
|
monkeypatch.setattr(Config, "LLM_BACKOFF_BASE_SECONDS", "abc", raising=False)
|
|
|
|
with pytest.raises(ValueError):
|
|
Config.validate_config()
|
|
|
|
|
|
def test_validate_config_allows_startup_without_semantic_scholar_key(monkeypatch):
|
|
monkeypatch.setattr(Config, "LLM_PROVIDER", "openai", raising=False)
|
|
monkeypatch.setattr(Config, "LLM_API_KEY", "test", raising=False)
|
|
monkeypatch.setattr(Config, "SECRET_KEY", "secret", raising=False)
|
|
monkeypatch.setattr(Config, "USER_EMAIL", "user@example.com", raising=False)
|
|
monkeypatch.setattr(Config, "SEMANTIC_SCHOLAR_API_KEY", "", raising=False)
|
|
monkeypatch.setattr(Config, "REQUIRE_PASSWORD", False, raising=False)
|
|
|
|
Config.validate_config()
|
|
|
|
|
|
def test_get_paper_content_reports_missing_release():
|
|
S2Searcher = _load_searcher_class()
|
|
searcher = S2Searcher.__new__(S2Searcher)
|
|
searcher.current_release = None
|
|
searcher.has_local_data = False
|
|
|
|
result = searcher.get_paper_content("123")
|
|
|
|
assert result["status"] == "inaccessible"
|
|
assert result["reason_code"] == "missing_release"
|
|
assert result["lookup_details"]["attempts"] == []
|
|
|
|
|
|
def test_searcher_latest_release_keeps_full_mini_release_id(tmp_path):
|
|
S2Searcher = _load_searcher_class()
|
|
base_dir = tmp_path / "datasets"
|
|
index_dir = base_dir / "binary_indices"
|
|
index_dir.mkdir(parents=True)
|
|
(index_dir / "2026-05-26-mini-mendelian-v1_metadata.json").write_text("{}", encoding="utf-8")
|
|
(base_dir / "mini").mkdir()
|
|
|
|
searcher = S2Searcher.__new__(S2Searcher)
|
|
searcher.base_dir = base_dir
|
|
|
|
assert searcher._get_latest_local_release() == "2026-05-26-mini-mendelian-v1"
|
|
|
|
|
|
def test_get_paper_content_reports_dataset_attempts_when_no_text(monkeypatch):
|
|
S2Searcher = _load_searcher_class()
|
|
# This test covers local dataset attempt reporting; pin the optional remote
|
|
# fallback off so it's deterministic regardless of the ambient toggle.
|
|
monkeypatch.setattr(Config, "FETCH_REMOTE_CONTENT_ON_MISS", False, raising=False)
|
|
|
|
class FakeIndexer:
|
|
def lookup(self, release_id, dataset, id_type, search_id):
|
|
if dataset == "s2orc_v2":
|
|
return {"body": {}}
|
|
if dataset == "abstracts":
|
|
return {"abstract": ""}
|
|
if dataset == "tldrs":
|
|
return {"text": ""}
|
|
return None
|
|
|
|
searcher = S2Searcher.__new__(S2Searcher)
|
|
searcher.current_release = "2025-01-01"
|
|
searcher.has_local_data = True
|
|
searcher.indexer = FakeIndexer()
|
|
|
|
result = searcher.get_paper_content("456")
|
|
|
|
assert result["status"] == "inaccessible"
|
|
assert result["reason_code"] == "no_accessible_content"
|
|
attempts = result["lookup_details"]["attempts"]
|
|
assert attempts == [
|
|
{"dataset": "s2orc_v2", "status": "record_without_text", "detail": "body.text missing"},
|
|
{"dataset": "abstracts", "status": "record_without_text", "detail": "abstract missing"},
|
|
{"dataset": "tldrs", "status": "record_without_text", "detail": "text missing"},
|
|
]
|