from __future__ import annotations import copy from pathlib import Path import numpy as np from fastapi.testclient import TestClient from app.api import suite as suite_api from app.engine.bootstrap import ( _clean_probe_phrase, build_label_pool, compute_unlabeled_diagnostic_priority, generate_starter_probes, quick_find_corpus_docs, ) from app.engine.embedder import TextEmbedder from app.engine.fixer import auto_tune_suite from app.engine.suite import triage_sample_suite from app.main import app from app.schemas import ( BootstrapProbesRequest, CorpusQuickFindRequest, LabelPoolRequest, SampleQuestionItem, SearchRequest, SuiteAutoTuneRequest, SuiteTriageRequest, ) from app.storage.project_store import LoadedRun, project_store def _make_client( synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, monkeypatch, tmp_path: Path, ) -> TestClient: run_id = synthetic_run.manifest.run_id monkeypatch.setitem(project_store._cache, run_id, synthetic_run) monkeypatch.setattr(project_store, "suites_dir", tmp_path / "api_suites") (tmp_path / "api_suites").mkdir(parents=True, exist_ok=True) monkeypatch.setattr( suite_api, "_load_run_and_embedder", lambda rid: (synthetic_run, synthetic_embedder), ) return TestClient(app) def test_clean_probe_phrase_hygiene(): assert _clean_probe_phrase("https://example.com/foo/bar 12345 !!!") is None assert _clean_probe_phrase("
404
```SELECT *```") is None assert _clean_probe_phrase("1234 5678 9012 3456 7890") is None assert _clean_probe_phrase("short phrase") is None clean = _clean_probe_phrase( "Check https://docs.example.com for waterproof trail running shoes guidance today." ) assert clean is not None assert "http" not in clean.lower() assert 4 <= len(clean.split()) <= 11 alpha_ratio = sum(1 for c in clean if c.isalpha() or c.isspace()) / len(clean) assert alpha_ratio >= 0.70 def test_generate_starter_probes_stratified_unlabeled_and_deterministic( synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, ): run = copy.copy(synthetic_run) run.hubness_nk = synthetic_run.hubness_nk.copy() run.cluster_ids = np.array([i % 4 for i in range(len(run.indexed_texts))], dtype=np.int32) # Ensure at least two unreachable anti-hubs exist run.hubness_nk[3] = 0 run.hubness_nk[12] = 0 req = BootstrapProbesRequest(count=12, existing_queries=[]) res1 = generate_starter_probes(run, req) res2 = generate_starter_probes(run, req) # Strictly deterministic assert [p.model_dump() for p in res1.probes] == [p.model_dump() for p in res2.probes] assert res1.bucket_counts == res2.bucket_counts assert len(res1.probes) == 12 assert res1.clusters_covered >= 3 # Strict unlabeled invariant (NEVER creates fake synthetic ground truth) for p in res1.probes: assert p.expected_doc_ids == [] assert p.expect_abstain is False assert p.draft_source_doc_id is not None assert 0 <= p.draft_source_doc_id < len(run.indexed_texts) assert p.probe_kind in {"title_lead", "truncated_tail", "anti_hub", "distinctive_term"} assert len(p.query.split()) >= 4 alpha_ratio = sum(1 for c in p.query if c.isalpha() or c.isspace()) / len(p.query) assert alpha_ratio >= 0.70 # Stratified buckets include truncated_tail (doc 18) and anti_hub (docs 3/12) assert res1.bucket_counts.get("truncated_tail", 0) >= 1 assert res1.bucket_counts.get("anti_hub", 0) >= 1 assert res1.bucket_counts.get("distinctive_term", 0) >= 1 trunc_probes = [p for p in res1.probes if p.probe_kind == "truncated_tail"] assert trunc_probes[0].draft_source_doc_id == 18 # Truncated tail phrase should come from post-cutoff text, not title assert "Long Product Manual" not in trunc_probes[0].query # Case-insensitive deduplication against existing_queries existing = [res1.probes[0].query.upper(), res1.probes[1].query.lower()] res_dedup = generate_starter_probes( run, BootstrapProbesRequest(count=12, existing_queries=existing) ) returned_low = {p.query.lower() for p in res_dedup.probes} assert res1.probes[0].query.lower() not in returned_low assert res1.probes[1].query.lower() not in returned_low # Triage & Auto-Tune treat newly bootstrapped probes as unlabeled (0 labeled) cfg = SearchRequest(query="", mode="convex", alpha=0.6, normalization="minmax", top_k=10) triage_res = triage_sample_suite( run, synthetic_embedder, SuiteTriageRequest(questions=res1.probes, search=cfg) ) assert triage_res.labeled_count == 0 assert len(triage_res.unlabeled_risks) == len(res1.probes) auto_res = auto_tune_suite( run, synthetic_embedder, SuiteAutoTuneRequest(questions=res1.probes, search=cfg) ) assert auto_res.baseline_metrics.count == 0 def test_active_disagreement_priority_and_triage_sorting( synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, ): # Direct unit test on compute_unlabeled_diagnostic_priority n = 10 d_agree = np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], dtype=np.float32) b_agree = np.array([10, 9, 8, 7, 6, 0, 0, 0, 0, 0], dtype=np.float32) dis_a, ov_a, pri_a = compute_unlabeled_diagnostic_priority(d_agree, b_agree, []) assert dis_a is False assert ov_a == 1.0 assert pri_a == 0.0 # Disjoint Top-5 -> dense_bm25_disagree=True, overlap=0.0, priority=35.0 b_disagree = np.array([0, 0, 0, 0, 0, 10, 9, 8, 7, 6], dtype=np.float32) dis_d, ov_d, pri_d = compute_unlabeled_diagnostic_priority(d_agree, b_disagree, []) assert dis_d is True assert ov_d == 0.0 assert pri_d == 35.0 assert pri_d > pri_a # Combined risk flags stack and clamp cleanly to [0, 100] _, _, pri_hi = compute_unlabeled_diagnostic_priority( d_agree, b_disagree, ["zero_bm25", "hub_hijack", "flat_plateau", "dead_zone"], ) assert pri_hi == 100.0 # End-to-end triage_sample_suite prioritization test questions = [ # Trivial agreement query (dense & bm25 both strongly match footwear docs) SampleQuestionItem(id="q_trivial", query="waterproof trail running shoes", expected_doc_ids=[]), # Zero BM25 + dead zone OOV query SampleQuestionItem(id="q_zero_bm25", query="xylophone zeppelinfjord qqqzzz", expected_doc_ids=[]), # Cross-topic query where dense and BM25 strongly disagree (truncated tail word 'warranty' + quantum) SampleQuestionItem( id="q_disagree", query="quantum photon laser lifetime warranty", expected_doc_ids=[], ), ] cfg = SearchRequest(query="", mode="convex", alpha=0.6, normalization="minmax", top_k=10) triage = triage_sample_suite( synthetic_run, synthetic_embedder, SuiteTriageRequest(questions=questions, search=cfg) ) assert len(triage.unlabeled_risks) == 3 # Must be sorted descending by priority_score scores = [r.priority_score for r in triage.unlabeled_risks] assert scores == sorted(scores, reverse=True) by_id = {r.id: r for r in triage.unlabeled_risks} assert "zero_bm25" in by_id["q_zero_bm25"].risk_flags assert by_id["q_zero_bm25"].priority_score > by_id["q_trivial"].priority_score def test_build_label_pool_rescues_branch_disagreements_and_respects_cap( synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, ): # Case 1: Doc #18 ("Long Product Manual") has 'warranty' past truncation cutoff -> # BM25 ranks doc #18 at #1, while Dense-only misses it completely (outside Top-5). req_bm25_rescue = LabelPoolRequest( query="extended lifetime warranty coverage", search=SearchRequest(query="extended lifetime warranty coverage", mode="dense", top_k=10), draft_source_doc_id=18, existing_expected_doc_ids=[], max_candidates=8, ) pool_res = build_label_pool(synthetic_run, synthetic_embedder, req_bm25_rescue) assert len(pool_res.candidates) <= 8 by_doc = {c.doc_id: c for c in pool_res.candidates} assert 18 in by_doc c18 = by_doc[18] assert c18.bm25_rank == 1 assert "bm25" in c18.sources assert c18.is_draft_source is True assert c18.is_truncated is True assert "warranty" in c18.snippet.lower() assert any("warrant" in t.lower() for t in c18.matched_terms) # Case 2: Dense-only #1 doc outside current Hybrid Top-5 (mode="bm25" misses semantic synonym) # Query uses 'reimburse' (topic 0) + 'sneaker' (not in billing docs) so BM25 ranks footwear, # while Dense matches billing docs or footwear differently. Even cleaner: query with BM25-only mode # where Dense #1 is outside BM25 Top-5. req_dense_rescue = LabelPoolRequest( query="reimbursement policy money back", search=SearchRequest(query="reimbursement policy money back", mode="bm25", top_k=10), existing_expected_doc_ids=[15, 16], max_candidates=6, ) pool_res2 = build_label_pool(synthetic_run, synthetic_embedder, req_dense_rescue) assert len(pool_res2.candidates) <= 6 # Existing expected docs are pinned first regardless of cap assert [c.doc_id for c in pool_res2.candidates[:2]] == [15, 16] assert "existing" in pool_res2.candidates[0].sources # Dense #1 is guaranteed in the pool assert any(c.dense_rank == 1 and "dense" in c.sources for c in pool_res2.candidates) # Case 3: Geometry leg activates when cone_collapse_warning or hub_count > 0 run_geo = copy.copy(synthetic_run) run_geo.manifest = synthetic_run.manifest.model_copy( update={ "health": synthetic_run.manifest.health.model_copy( update={"cone_collapse_warning": True, "hub_count": 2} ) } ) pool_geo = build_label_pool( run_geo, synthetic_embedder, LabelPoolRequest( query="waterproof trail running shoes", search=SearchRequest(query="waterproof trail running shoes", mode="convex", alpha=0.6), max_candidates=8, ), ) assert pool_geo.branch_counts["geometry"] == 2 assert any("geometry" in c.sources for c in pool_geo.candidates) def test_quick_find_corpus_docs_id_bm25_and_oov_substring(synthetic_run: LoadedRun): run = copy.copy(synthetic_run) run.indexed_texts = list(synthetic_run.indexed_texts) # Inject an OOV error code that wasn't indexed in BM25 vocab run.indexed_texts[10] = run.indexed_texts[10] + " Diagnostic code ERR-4091-XZ triggered." # 1. Exact #doc_id lookup res_id = quick_find_corpus_docs(run, CorpusQuickFindRequest(query="#5", limit=6)) assert len(res_id.hits) >= 1 assert res_id.hits[0].doc_id == 5 assert res_id.hits[0].match_kind == "doc_id" # Bare numeric ID also works res_bare = quick_find_corpus_docs(run, CorpusQuickFindRequest(query="18", limit=6)) assert res_bare.hits[0].doc_id == 18 assert res_bare.hits[0].match_kind == "doc_id" assert res_bare.hits[0].is_truncated is True # 2. BM25 keyword lookup res_bm25 = quick_find_corpus_docs( run, CorpusQuickFindRequest(query="kubernetes pvc mount", limit=4) ) assert any(h.doc_id == 10 and h.match_kind == "bm25" for h in res_bm25.hits) # 3. OOV substring fallback (ERR-4091-XZ not in BM25 index) res_sub = quick_find_corpus_docs( run, CorpusQuickFindRequest(query="ERR-4091-XZ", limit=6) ) assert len(res_sub.hits) == 1 assert res_sub.hits[0].doc_id == 10 assert res_sub.hits[0].match_kind == "substring" assert "ERR-4091-XZ" in res_sub.hits[0].snippet # 4. exclude_doc_ids honored res_excl = quick_find_corpus_docs( run, CorpusQuickFindRequest(query="ERR-4091-XZ", limit=6, exclude_doc_ids=[10]) ) assert res_excl.hits == [] def test_bootstrap_pooling_and_quick_find_api_routes( synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, monkeypatch, tmp_path: Path, ): client = _make_client(synthetic_run, synthetic_embedder, monkeypatch, tmp_path) run_id = synthetic_run.manifest.run_id # 1. POST /suite/bootstrap-probes r_boot = client.post( f"/api/projects/{run_id}/suite/bootstrap-probes", json={"count": 8, "existing_queries": []}, ) assert r_boot.status_code == 200 boot_data = r_boot.json() assert len(boot_data["probes"]) == 8 assert all(p["expected_doc_ids"] == [] for p in boot_data["probes"]) # 2. POST /suite/label-pool first_probe = boot_data["probes"][0] r_pool = client.post( f"/api/projects/{run_id}/suite/label-pool", json={ "query": first_probe["query"], "search": { "query": first_probe["query"], "mode": "convex", "alpha": 0.6, "normalization": "minmax", "top_k": 10, }, "draft_source_doc_id": first_probe["draft_source_doc_id"], "existing_expected_doc_ids": [], "max_candidates": 8, }, ) assert r_pool.status_code == 200 pool_data = r_pool.json() assert 1 <= len(pool_data["candidates"]) <= 8 assert "dense_bm25_overlap" in pool_data assert "branch_counts" in pool_data # 3. POST /suite/corpus-find r_find = client.post( f"/api/projects/{run_id}/suite/corpus-find", json={"query": "#18", "limit": 6, "exclude_doc_ids": []}, ) assert r_find.status_code == 200 find_data = r_find.json() assert find_data["hits"][0]["doc_id"] == 18 assert find_data["hits"][0]["match_kind"] == "doc_id" # 4. 404 on unknown run_id r_404 = client.post( "/api/projects/nonexistent_run_xyz/suite/bootstrap-probes", json={"count": 6}, ) assert r_404.status_code == 404