File size: 29,040 Bytes
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
from __future__ import annotations

import time
from pathlib import Path

import numpy as np
from fastapi.testclient import TestClient

from app.engine.bm25 import MultiFieldBM25Index
from app.engine.diagnostics import compute_corpus_diagnostics
from app.engine.embedder import BaseEmbeddingBackend, TextEmbedder
from app.engine.fix_stack import (
    _ScoreCache,
    _apply_lever_patch,
    _eval_questions,
    _evaluate_coalition_lattice,
    _fit_levers_on_fold,
    compile_fix_stack,
    compute_exact_pairwise_interactions,
    compute_exact_shapley_values,
)
from app.engine.search import fast_eval_hybrid_ranks, run_hybrid_search
from app.engine.suite import build_export_bundle
from app.main import app
from app.schemas import (
    ExportRequest,
    FixStackExportSummary,
    FixStackRequest,
    RunManifest,
    SampleQuestionItem,
    SearchRequest,
    VocabRule,
)
from app.storage.project_store import LoadedRun


class _VectorMapBackend(BaseEmbeddingBackend):
    """Deterministic controllable embedding backend for exact IR interaction tests."""

    def __init__(self, text_to_vec: dict[str, np.ndarray], dim: int = 16) -> None:
        self.backend_name = "cpu"
        self.device_label = "Synthetic Vector CPU"
        self.dim = dim
        self.max_seq_len = 64
        self.tokenizer = None
        self._map = text_to_vec

    def encode_batch(self, texts: list[str]) -> np.ndarray:
        out = np.zeros((len(texts), self.dim), dtype=np.float32)
        for i, txt in enumerate(texts):
            v = self._map.get(txt)
            if v is None:
                # Fallback deterministic unit vector
                v = np.zeros(self.dim, dtype=np.float32)
                v[abs(hash(txt)) % self.dim] = 1.0
            norm = float(np.linalg.norm(v))
            out[i] = v / max(norm, 1e-9)
        return out


def _make_custom_run(
    run_id: str,
    titles: list[str],
    bodies: list[str],
    embeddings: np.ndarray,
    embedder: TextEmbedder,
    run_dir: Path,
) -> LoadedRun:
    indexed = [f"{t}: {b}" for t, b in zip(titles, bodies)]
    docs_by_field = {"title": titles, "body": bodies}
    labels = ["cat"] * len(indexed)
    telemetry = embedder.inspect_truncation_and_fertility(indexed)
    bm25 = MultiFieldBM25Index.build(docs_by_field, fields=["title", "body"])
    diag = compute_corpus_diagnostics(
        embeddings=embeddings.astype(np.float32),
        texts=indexed,
        telemetry=telemetry,
        labels=labels,
        use_umap=False,
    )
    manifest = RunManifest(
        run_id=run_id,
        run_name=run_id,
        created_at="2026-11-22T00:00:00Z",
        dataset_id=f"synthetic/{run_id}",
        config=None,
        split="train",
        max_rows=len(indexed),
        doc_count=len(indexed),
        dense_fields=["title", "body"],
        dense_template="{title}: {body}",
        bm25_fields=["title", "body"],
        bm25_initial_weights={"title": 1.0, "body": 1.0},
        metadata_fields=["category"],
        label_field="category",
        model_id="test/custom",
        doc_prefix="",
        query_prefix="",
        backend_used="cpu",
        device_label="Test CPU",
        embed_seconds=0.01,
        docs_per_sec=1000.0,
        health=diag.health,
        clusters=diag.clusters,
        contours=diag.contours,
        coord_bounds=diag.coord_bounds,
    )
    from app.storage.project_store import ProjectStore

    store = ProjectStore(runs_dir=run_dir / "runs", suites_dir=run_dir / "suites")
    return store.save_run(
        manifest=manifest,
        embeddings=embeddings.astype(np.float32),
        diag=diag,
        telemetry=telemetry,
        bm25=bm25,
        indexed_texts=indexed,
        docs_by_field=docs_by_field,
        metadata_by_field={"category": labels},
        labels=labels,
    )


def test_live_mrf_parity_and_score_cache_exactness(
    synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder
):
    """AC #1: Live MRF parity across fast_eval_hybrid_ranks, run_hybrid_search, and _ScoreCache."""
    req = SearchRequest(
        query="waterproof trail running shoes",
        mode="convex",
        alpha=0.5,
        normalization="minmax",
        fetch_k=20,
        top_k=8,
        mrf_rerank_enabled=True,
        mrf_beta=0.45,
        mrf_rerank_k=15,
    )
    res_live = run_hybrid_search(synthetic_run, synthetic_embedder, req)
    live_ids = [r.doc_id for r in res_live.waterfall_rows]

    fast_ids, _, _, _ = fast_eval_hybrid_ranks(synthetic_run, synthetic_embedder, req)
    assert fast_ids[: req.top_k] == live_ids[: req.top_k]

    cache = _ScoreCache(synthetic_run, synthetic_embedder, req)
    cached_ids = cache.rank_query(req.query, req)
    assert cached_ids[: req.top_k] == fast_ids[: req.top_k]

    # Also verify parity with vocab rewrite + MRF composed together
    req_rew = req.model_copy(
        update={
            "query": "mbg purchase",
            "query_rewrites": [
                VocabRule(
                    id="r_mbg",
                    match="mbg",
                    replacement="money back guarantee",
                    rule_type="expand",
                    scope="bm25",
                    enabled=True,
                )
            ],
        }
    )
    res_live_rew = run_hybrid_search(synthetic_run, synthetic_embedder, req_rew)
    fast_ids_rew, _, _, _ = fast_eval_hybrid_ranks(synthetic_run, synthetic_embedder, req_rew)
    assert fast_ids_rew[: req.top_k] == [r.doc_id for r in res_live_rew.waterfall_rows[: req.top_k]]


def test_exact_shapley_efficiency_and_dummy_player():
    """AC #2: Exact additive efficiency identity + dummy-player zero contribution & zero interaction."""
    # 3 levers: lever 0 & lever 1 interact; lever 2 is a pure dummy player (no effect on any subset)
    base_v = {
        0b000: 0.30,
        0b001: 0.45,
        0b010: 0.40,
        0b011: 0.72,  # strong synergy (+0.17)
        0b100: 0.30,
        0b101: 0.45,
        0b110: 0.40,
        0b111: 0.72,
    }
    phi = compute_exact_shapley_values([0, 1, 2], base_v)
    assert abs(sum(phi.values()) - (base_v[0b111] - base_v[0b000])) < 1e-12
    assert abs(phi[2]) < 1e-12

    inter = compute_exact_pairwise_interactions(3, base_v)
    assert abs(inter[(0, 2)][0]) < 1e-12
    assert abs(inter[(1, 2)][0]) < 1e-12
    assert abs(inter[(0, 1)][0] - 0.17) < 1e-12


def test_synergy_vocab_x_fusion_routing(tmp_path: Path):
    """AC #3: Acronym queries miss BM25 until vocab rewrites them, then adaptive routing routes them sharply to BM25 while semantic queries stay Dense."""
    dim = 16
    rng = np.random.default_rng(7)

    # 12 docs:
    # Docs 0..3: Acronym targets (BM25 matches strongly after vocab rewrite; Dense is weak/noisy!)
    # Docs 4..7: Semantic targets (Dense matches strongly; BM25 has weak/distractor lexical overlap!)
    # Docs 8..11: Distractors (strong Dense distractors for acronym queries + lexical distractors for semantic queries)
    titles = [
        "Error Code Alpha",
        "Error Code Beta",
        "Error Code Gamma",
        "Error Code Delta",
        "Travel Reimbursement Guide",
        "Parental Leave Policy",
        "Remote Equipment Stipend",
        "Annual Wellness Benefit",
        "General Operations Manual",
        "General Operations Manual II",
        "Quarterly Support Notes",
        "Team Onboarding Notes",
    ]
    bodies = [
        "Resolve zqxalpha fault by resetting primary database lock table immediately.",
        "Resolve zqxbeta fault by flushing distributed cache shard metadata.",
        "Resolve zqxgamma fault by rotating expired tls certificate bundle.",
        "Resolve zqxdelta fault by draining stalled message broker queue.",
        "Submit hotel airfare receipts for company trip payout approval.",
        "New parents receive sixteen weeks paid family care time off.",
        "Order ergonomic monitor desk keyboard for home workspace setup.",
        "Claim gym membership fitness reimbursement through benefits portal.",
        "Generic troubleshooting steps for fault handling and common support tickets.",
        "Generic operations playbook for fault handling and common service alerts.",
        "Notes about trip receipts and home office requests across departments.",
        "Notes about family time off and fitness membership inquiries across teams.",
    ]

    # Build controlled unit embeddings
    embs = np.zeros((len(titles), dim), dtype=np.float32)
    for i in range(len(titles)):
        v = rng.normal(0.0, 0.05, size=dim).astype(np.float32)
        embs[i] = v

    # Acronym queries (0..3) have dense vectors aligned with distractors 8 & 9, NOT docs 0..3!
    acro_distractor_dir = np.zeros(dim, dtype=np.float32)
    acro_distractor_dir[0] = 1.0
    embs[8] = acro_distractor_dir + np.array([0, 0.05] + [0] * (dim - 2), dtype=np.float32)
    embs[9] = acro_distractor_dir + np.array([0, -0.05] + [0] * (dim - 2), dtype=np.float32)
    for i in range(4):
        v = np.zeros(dim, dtype=np.float32)
        v[10 + i] = 1.0
        embs[i] = v

    # Semantic targets (4..7) have strong unique dense directions (dims 2..5)
    for idx, d in enumerate(range(4, 8)):
        v = np.zeros(dim, dtype=np.float32)
        v[2 + idx] = 1.0
        embs[d] = v

    # Distractors 10 & 11 sit slightly away from semantic queries in dense space
    embs[10] = np.zeros(dim, dtype=np.float32)
    embs[10][14] = 1.0
    embs[11] = np.zeros(dim, dtype=np.float32)
    embs[11][15] = 1.0

    # Normalize all doc embeddings
    embs = embs / np.maximum(np.linalg.norm(embs, axis=1, keepdims=True), 1e-9)

    q_texts = [
        # 4 acronym queries (BM25=0 without vocab; Dense prefers distractors 8, 9)
        "ERR-A01 fault",
        "ERR-B02 fault",
        "ERR-C03 fault",
        "ERR-D04 fault",
        # 4 semantic queries (Dense nails docs 4..7; BM25 prefers distractors 10, 11 due to lexical overlap!)
        "notes trip receipts",
        "notes family time off",
        "notes home office requests",
        "notes fitness membership inquiries",
    ]
    q_map: dict[str, np.ndarray] = {}
    for i in range(4):
        q_map[q_texts[i]] = acro_distractor_dir.copy()
    for idx in range(4):
        v = np.zeros(dim, dtype=np.float32)
        v[2 + idx] = 1.0
        q_map[q_texts[4 + idx]] = v

    embedder = TextEmbedder(model_id="test/synergy", backend_override=_VectorMapBackend(q_map, dim=dim))
    run = _make_custom_run("syn_synergy", titles, bodies, embs, embedder, tmp_path)

    questions = [
        SampleQuestionItem(id=f"q{i}", query=q_texts[i], expected_doc_ids=[i])
        for i in range(8)
    ]
    vocab_rules = [
        VocabRule(id="v1", match="ERR-A01", replacement="zqxalpha", rule_type="expand", scope="bm25", enabled=True),
        VocabRule(id="v2", match="ERR-B02", replacement="zqxbeta", rule_type="expand", scope="bm25", enabled=True),
        VocabRule(id="v3", match="ERR-C03", replacement="zqxgamma", rule_type="expand", scope="bm25", enabled=True),
        VocabRule(id="v4", match="ERR-D04", replacement="zqxdelta", rule_type="expand", scope="bm25", enabled=True),
    ]

    # Start with high static alpha=0.80 so semantic queries pass, acronym queries fail even after vocab alone
    # until adaptive_alpha routes acronym queries sharply to BM25!
    base_search = SearchRequest(
        query="",
        mode="convex",
        alpha=0.80,
        normalization="minmax",
        fetch_k=12,
        top_k=1,
    )
    resp = compile_fix_stack(
        run,
        embedder,
        FixStackRequest(
            questions=questions,
            search=base_search,
            vocab_rules=vocab_rules,
            include_hygiene=False,
            include_mrf=False,
            include_auto_vocab=False,
            strict_zero_regression=True,
        ),
    )

    # Verify exact Shapley additive identity on recommended stack
    selected_levers = [lv for lv in resp.levers if lv.selected]
    assert abs(sum(lv.shapley_mrr for lv in selected_levers) - (resp.recommended_mrr - resp.baseline_mrr)) < 1e-6
    assert abs(sum(lv.shapley_hit for lv in selected_levers) - (resp.recommended_hit_at_k - resp.baseline_hit_at_k)) < 1e-6

    # Verify vocab x fusion_routing synergy detected with positive interaction
    syn_pairs = [
        it
        for it in resp.interactions
        if {it.lever_a, it.lever_b} == {"vocab", "fusion_routing"}
    ]
    assert len(syn_pairs) == 1
    assert syn_pairs[0].kind == "synergy"
    assert syn_pairs[0].shapley_interaction_mrr > 0.01
    assert resp.recommended_regressed_count == 0
    assert resp.recommended_mrr > resp.baseline_mrr + 0.15


def test_redundancy_detection_and_parsimony_pruning(tmp_path: Path):
    """AC #4: Both CSLS (`geometry_bm25`) and `hygiene` rescue the exact same hub-hijacked queries -> redundancy detected & only 1 kept."""
    dim = 16
    # Build 14 docs:
    # Docs 0..5: distinct topic targets on orthogonal axes 0..5
    # Docs 6..12: background cluster all pointing heavily toward hub doc 13 (so doc 13 has huge local_knn_mean!)
    # Doc 13: Dense hub hijacker slightly closer to queries 0..5 in raw cosine than targets 0..5,
    #         BUT because doc 13 sits in the dense centroid of docs 6..12, CSLS penalizes doc 13 heavily!
    #         AND excluding doc 13 via hygiene ALSO rescues the exact same 6 queries!
    titles = [f"Topic Doc {i}" for i in range(6)] + [f"Background {i}" for i in range(7)] + ["Universal Hub"]
    bodies = [f"Unique topic content alpha{i}" for i in range(6)] + [
        f"Background filler text {i}" for i in range(7)
    ] + ["Generic portal summary page"]

    embs = np.zeros((14, dim), dtype=np.float32)
    # Hub axis on dims 6..11 (dense cluster of 7 background docs + hub)
    hub_dir = np.zeros(dim, dtype=np.float32)
    hub_dir[6] = 1.0
    # Hub doc 13 blends hub_dir with small uniform projection onto topic axes 0..5 so raw cos(q_i, hub) > raw cos(q_i, target_i)
    hub_vec = np.zeros(dim, dtype=np.float32)
    hub_vec[6] = 0.72
    for t in range(6):
        hub_vec[t] = 0.28
    embs[13] = hub_vec / np.linalg.norm(hub_vec)

    # Background docs 6..12 cluster tightly around hub_vec so hub doc 13 has very high local_knn_mean (~0.98)
    for k in range(7):
        v = embs[13].copy()
        v[7 + (k % 8)] += 0.04 * (k + 1)
        embs[6 + k] = v / np.linalg.norm(v)

    # Target docs 0..5 point along their own isolated axes (very low local_knn_mean!)
    # Query i points along axis i with slight tilt toward hub_dir so:
    # raw cos(q_i, target_i) ~= 0.62, raw cos(q_i, hub_13) ~= 0.68 -> hub hijacks rank #1!
    # Under CSLS: target_i penalty ~= 0.05 -> CSLS ~= 1.19; hub_13 penalty ~= 0.96 -> CSLS ~= 0.40 -> target_i wins rank #1!
    q_map: dict[str, np.ndarray] = {}
    questions: list[SampleQuestionItem] = []
    for i in range(6):
        t_vec = np.zeros(dim, dtype=np.float32)
        t_vec[i] = 1.0
        embs[i] = t_vec

        qv = np.zeros(dim, dtype=np.float32)
        qv[i] = 0.62
        qv[6] = 0.78
        qv /= np.linalg.norm(qv)
        q_txt = f"semantic probe {i}"
        q_map[q_txt] = qv
        questions.append(SampleQuestionItem(id=f"hq{i}", query=q_txt, expected_doc_ids=[i]))

    embedder = TextEmbedder(model_id="test/hub", backend_override=_VectorMapBackend(q_map, dim=dim))
    run = _make_custom_run("syn_hub", titles, bodies, embs, embedder, tmp_path)

    # Dense mode so only geometry_bm25 (CSLS) and hygiene (exclude doc 13) compete
    base_search = SearchRequest(
        query="",
        mode="dense",
        fetch_k=14,
        top_k=1,
    )
    resp = compile_fix_stack(
        run,
        embedder,
        FixStackRequest(
            questions=questions,
            search=base_search,
            include_auto_vocab=False,
            include_hygiene=True,
            include_mrf=False,
            strict_zero_regression=True,
            parsimony_lambda=0.008,
        ),
    )

    by_id = {lv.lever_id: lv for lv in resp.levers}
    assert "geometry_bm25" in by_id and "hygiene" in by_id

    # Redundancy/interference interaction MUST be detected
    red_pairs = [
        it
        for it in resp.interactions
        if {it.lever_a, it.lever_b} == {"geometry_bm25", "hygiene"}
    ]
    assert len(red_pairs) == 1
    assert red_pairs[0].kind in ("redundant", "interference")

    # Parsimony MUST keep ONLY 1 of the two overlapping levers, pruning the other with plain-English reason
    selected_pair = [lid for lid in ("geometry_bm25", "hygiene") if by_id[lid].selected]
    pruned_pair = [lid for lid in ("geometry_bm25", "hygiene") if not by_id[lid].selected]
    assert len(selected_pair) == 1
    assert len(pruned_pair) == 1
    assert by_id[pruned_pair[0]].prune_reason is not None
    assert len(by_id[pruned_pair[0]].prune_reason) > 5
    # Verify exact Shapley efficiency
    sel = [lv for lv in resp.levers if lv.selected]
    assert abs(sum(lv.shapley_mrr for lv in sel) - (resp.recommended_mrr - resp.baseline_mrr)) < 1e-6


def test_leakage_free_cv_invariance_and_overfit_warning(tmp_path: Path):
    """AC #5: Mutating held-out fold labels NEVER changes training-fold fit, and brittle tweaks trigger overfit_warning."""
    dim = 16
    # 12 docs: 6 target docs (0..5) + 6 UNIQUE query-specific hijackers (6..11)
    # Query i's expected doc is i, and doc (6 + i) hijacks ONLY query i (never any other query!).
    # In-sample: hygiene excludes all 6 query-specific hijackers -> huge in-sample MRR jump (+0.50)!
    # Out-of-fold (LOOCV): when query i is held out, its unique hijacker (6 + i) is NEVER seen failing on train_qs,
    # so fold hygiene NEVER excludes (6 + i) -> out-of-fold MRR gain == 0.0 -> overfit_warning!
    titles = [f"Target {i}" for i in range(6)] + [f"Specific Distractor {i}" for i in range(6)]
    bodies = [f"Content for target item {i}" for i in range(6)] + [
        f"Noise distractor for query {i}" for i in range(6)
    ]

    embs = np.zeros((12, dim), dtype=np.float32)
    q_map: dict[str, np.ndarray] = {}
    questions: list[SampleQuestionItem] = []

    for i in range(6):
        # Orthogonal subspace per query i using dims (2*i, 2*i+1)
        t_vec = np.zeros(dim, dtype=np.float32)
        t_vec[2 * i] = 0.80
        t_vec[2 * i + 1] = 0.60
        embs[i] = t_vec / np.linalg.norm(t_vec)

        d_vec = np.zeros(dim, dtype=np.float32)
        d_vec[2 * i] = 0.99
        d_vec[2 * i + 1] = 0.14
        embs[6 + i] = d_vec / np.linalg.norm(d_vec)

        qv = np.zeros(dim, dtype=np.float32)
        qv[2 * i] = 1.0
        q_txt = f"isolated query {i}"
        q_map[q_txt] = qv
        questions.append(SampleQuestionItem(id=f"oq{i}", query=q_txt, expected_doc_ids=[i]))

    embedder = TextEmbedder(model_id="test/overfit", backend_override=_VectorMapBackend(q_map, dim=dim))
    run = _make_custom_run("syn_overfit", titles, bodies, embs, embedder, tmp_path)

    base_search = SearchRequest(query="", mode="dense", fetch_k=12, top_k=1)
    fs_req = FixStackRequest(
        questions=questions,
        search=base_search,
        include_auto_vocab=False,
        include_hygiene=True,
        include_mrf=False,
        strict_zero_regression=True,
    )

    # 1. Leakage-free fold invariance: mutate held-out query 5's expected_doc_ids and verify train fold [0..4] is byte-identical
    cache = _ScoreCache(run, embedder, base_search)
    train_qs_a = questions[:5]
    train_base_a = _eval_questions(cache, train_qs_a, base_search)
    levers_a = _fit_levers_on_fold(run, embedder, cache, train_qs_a, base_search, train_base_a, fs_req, [])
    _, mask_a = _evaluate_coalition_lattice(cache, train_qs_a, base_search, train_base_a, levers_a, True, fs_req.parsimony_lambda)
    _, patch_a = _apply_lever_patch(base_search, levers_a, mask_a)

    # Mutate held-out query 5 completely
    mutated_questions = list(questions[:5]) + [
        SampleQuestionItem(id="oq5", query=questions[5].query, expected_doc_ids=[0])
    ]
    fs_req_mut = fs_req.model_copy(update={"questions": mutated_questions})
    levers_b = _fit_levers_on_fold(run, embedder, cache, mutated_questions[:5], base_search, train_base_a, fs_req_mut, [])
    _, mask_b = _evaluate_coalition_lattice(cache, mutated_questions[:5], base_search, train_base_a, levers_b, True, fs_req_mut.parsimony_lambda)
    _, patch_b = _apply_lever_patch(base_search, levers_b, mask_b)
    assert [(lv.lever_id, lv.patch) for lv in levers_a] == [(lv.lever_id, lv.patch) for lv in levers_b]
    assert patch_a == patch_b

    # 2. Overfit warning check: in-sample MRR jumps strongly (+0.50), but LOOCV MRR does NOT improve -> overfit_warning!
    resp = compile_fix_stack(run, embedder, fs_req)
    assert resp.recommended_mrr - resp.baseline_mrr >= 0.04
    assert resp.cv_evaluated is True
    assert resp.cv_mode == "loocv"
    assert resp.cv_mrr_after is not None and resp.cv_mrr_before is not None
    assert resp.cv_mrr_after <= resp.cv_mrr_before
    assert resp.verdict == "overfit_warning"
    assert resp.verdict != "verified_ship"


def test_edge_cases_zero_reg_calibration_determinism_and_speed(
    synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder
):
    """AC #6 & #7: Edge cases (0 labels, 2 labels, expect_abstain, zero-reg guard, determinism, <1.5s)."""
    base_search = SearchRequest(query="", mode="convex", alpha=0.5, fetch_k=20, top_k=3)

    # 1. labeled_count == 0 -> needs_labels
    r0 = compile_fix_stack(
        synthetic_run,
        synthetic_embedder,
        FixStackRequest(questions=[], search=base_search),
    )
    assert r0.verdict == "needs_labels"
    assert r0.labeled_count == 0
    assert r0.cv_evaluated is False

    # 2. labeled_count == 2 -> cv skipped, never verified_ship
    q2 = [
        SampleQuestionItem(id="q1", query="mbg refund", expected_doc_ids=[0]),
        SampleQuestionItem(id="q2", query="waterproof trail shoes", expected_doc_ids=[5]),
    ]
    r2 = compile_fix_stack(
        synthetic_run,
        synthetic_embedder,
        FixStackRequest(
            questions=q2,
            search=base_search.model_copy(update={"alpha": 0.9}),
            vocab_rules=[
                VocabRule(
                    id="r1",
                    match="mbg",
                    replacement="money back guarantee",
                    rule_type="expand",
                    scope="bm25",
                    enabled=True,
                )
            ],
        ),
    )
    assert r2.cv_evaluated is False
    assert r2.cv_mode == "skipped"
    assert r2.verdict != "verified_ship"
    assert r2.recommended_regressed_count == 0

    # 3. expect_abstain post-stack calibration + strict zero-regression + determinism + wall-clock <1.5s
    q_suite = [
        SampleQuestionItem(id="q1", query="money back guarantee", expected_doc_ids=[0]),
        SampleQuestionItem(id="q2", query="waterproof trail running shoes", expected_doc_ids=[5]),
        SampleQuestionItem(id="q3", query="K8S-PVC-04 persistent volume", expected_doc_ids=[10]),
        SampleQuestionItem(id="q4", query="quantum entanglement fiber optics", expected_doc_ids=[15]),
        SampleQuestionItem(id="q5", query="extended lifetime warranty", expected_doc_ids=[18]),
        SampleQuestionItem(id="q6", query="helm rolling upgrade replicas", expected_doc_ids=[12]),
        SampleQuestionItem(
            id="q_abs1",
            query="chocolate souffle baking temperature",
            expected_doc_ids=[],
            expect_abstain=True,
        ),
        SampleQuestionItem(
            id="q_abs2",
            query="medieval castle moat architecture",
            expected_doc_ids=[],
            expect_abstain=True,
        ),
    ]
    req_full = FixStackRequest(
        questions=q_suite,
        search=base_search,
        strict_zero_regression=True,
        include_calibration=True,
    )
    t0 = time.perf_counter()
    res_a = compile_fix_stack(synthetic_run, synthetic_embedder, req_full)
    dt_ms = (time.perf_counter() - t0) * 1000.0
    res_b = compile_fix_stack(synthetic_run, synthetic_embedder, req_full)

    assert dt_ms < 1500.0, f"compile_fix_stack took {dt_ms:.1f}ms (>1500ms budget)"
    assert res_a.recommended_regressed_count == 0
    assert res_a.calibration_note is not None
    assert res_a.calibration_note.tau_after is not None
    # Byte-identical deterministic outputs (excluding elapsed_ms)
    assert res_a.model_dump(exclude={"elapsed_ms"}) == res_b.model_dump(exclude={"elapsed_ms"})


def test_api_endpoint_and_unified_pipeline_export(
    synthetic_run: LoadedRun, synthetic_embedder: TextEmbedder, monkeypatch
):
    """AC #8: FastAPI route POST /api/projects/{run_id}/suite/fix-stack + executable run_verified_search_pipeline export."""
    run_id = synthetic_run.manifest.run_id
    monkeypatch.setattr(
        "app.api.suite._load_run_and_embedder",
        lambda rid: (synthetic_run, synthetic_embedder),
    )

    client = TestClient(app)
    payload = {
        "questions": [
            {"id": "q1", "query": "money back guarantee", "expected_doc_ids": [0]},
            {"id": "q2", "query": "waterproof trail running shoes", "expected_doc_ids": [5]},
            {"id": "q3", "query": "K8S-PVC-04 persistent volume", "expected_doc_ids": [10]},
            {"id": "q4", "query": "quantum entanglement optics", "expected_doc_ids": [15]},
        ],
        "search": {"query": "", "mode": "convex", "alpha": 0.5, "fetch_k": 20, "top_k": 3},
        "strict_zero_regression": True,
    }
    res = client.post(f"/api/projects/{run_id}/suite/fix-stack", json=payload)
    assert res.status_code == 200
    body = res.json()
    assert body["labeled_count"] == 4
    assert body["cv_evaluated"] is True
    assert body["cv_mode"] == "loocv"
    assert body["recommended_regressed_count"] == 0

    # Export unified pipeline with all active stages (rewrites + exclusions + dynamic alpha + MRF + confidence_cutoff)
    export_req = ExportRequest(
        search=SearchRequest(
            query="mbg refund",
            mode="convex",
            alpha=0.5,
            normalization="minmax",
            top_k=3,
            fetch_k=20,
            query_rewrites=[
                VocabRule(
                    id="r1",
                    match="mbg",
                    replacement="money back guarantee",
                    rule_type="expand",
                    scope="bm25",
                    enabled=True,
                )
            ],
            excluded_doc_ids=[19],
            adaptive_alpha=True,
            mrf_rerank_enabled=True,
            mrf_beta=0.35,
            mrf_rerank_k=10,
            confidence_cutoff=0.25,
        ),
        fix_stack_summary=FixStackExportSummary(
            verdict="verified_ship",
            verdict_headline="Verified across 4 held-out splits — safe to apply.",
            labeled_count=4,
            active_lever_labels=["Synonym & Vocab Rules", "Phrase Proximity Rerank"],
            baseline_mrr=0.45,
            after_mrr=0.82,
            baseline_hit_at_k=0.50,
            after_hit_at_k=1.0,
            fixed_count=2,
            regressed_count=0,
            cv_evaluated=True,
            cv_mrr_before=0.45,
            cv_mrr_after=0.78,
            cv_mrr_ci_low=0.12,
            cv_mrr_ci_high=0.54,
            lever_contributions=[
                {"label": "Synonym & Vocab Rules", "mrr_contribution": 0.22, "splits": "4/4 splits"},
                {"label": "Phrase Proximity Rerank", "mrr_contribution": 0.15, "splits": "4/4 splits"},
            ],
            pruned_notes=["Corpus Hygiene Mask: Overlaps with Hub & Cone Geometry"],
        ),
    )
    bundle = build_export_bundle(synthetic_run, export_req)
    assert "mrf_rerank" in bundle.recipe_json
    assert "fix_stack" in bundle.recipe_json
    assert "### Verified Fix Plan" in bundle.markdown_snapshot
    assert "Synonym & Vocab Rules" in bundle.markdown_snapshot
    assert "run_verified_search_pipeline" in bundle.python_snippet

    # Execute exported Python snippet cleanly on synthetic inputs!
    ns: dict = {}
    exec(bundle.python_snippet, ns)
    assert "run_verified_search_pipeline" in ns

    doc_texts = [
        "Customers receive full money back guarantee within 30 days.",
        "Waterproof trail running shoes for wet mountain paths.",
        "Kubernetes persistent volume claim troubleshooting guide.",
        "Generic noise hub document.",
    ] * 5  # 20 docs so doc_id 19 exists and is excluded
    dense_scores = np.linspace(0.2, 0.9, len(doc_texts))
    dense_scores[0] = 0.95
    bm25_scores = np.zeros(len(doc_texts))
    bm25_scores[0] = 8.5
    bm25_scores[1] = 1.2

    out = ns["run_verified_search_pipeline"](
        "mbg guarantee",
        doc_texts,
        dense_scores,
        bm25_scores,
        top_k=3,
    )
    assert out["abstain"] is False
    assert "money back guarantee" in out["bm25_query"].lower()
    result_ids = [doc_id for doc_id, _ in out["results"]]
    assert 19 not in result_ids
    assert result_ids[0] == 0