File size: 25,737 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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
from __future__ import annotations

import re
import time
from collections import defaultdict
from typing import Literal

import numpy as np

from app.engine.bm25 import ENGLISH_STOPWORDS, tokenize_with_spans
from app.engine.embedder import TextEmbedder
from app.engine.search import (
    _build_exclusion_mask,
    _get_query_vector,
    compute_dense_scores,
    evaluate_metadata_mask,
    fast_eval_hybrid_ranks,
)
from app.engine.vocab_lab import rewrite_query_for_branches
from app.schemas import (
    BootstrapProbesRequest,
    BootstrapProbesResponse,
    CorpusQuickFindHit,
    CorpusQuickFindRequest,
    CorpusQuickFindResponse,
    LabelPoolCandidate,
    LabelPoolRequest,
    LabelPoolResponse,
    SampleQuestionItem,
)
from app.storage.project_store import LoadedRun

_URL_RE = re.compile(r"(?:https?://|www\.)\S+", re.IGNORECASE)
_HTML_RE = re.compile(r"<[^>]+>")
_CODE_RE = re.compile(r"```[\s\S]*?```|`[^`]*`")
_BRACKET_RE = re.compile(r"\[[^\]]*\]|\{[^}]*\}")
_SEP_RE = re.compile(r"[:|/\\\t\r\n]+")
_WS_RE = re.compile(r"\s+")
_SENT_SPLIT_RE = re.compile(r"[.!?\n;]+")
_DOC_ID_RE = re.compile(r"^#?(\d+)$")
_WORD_SPAN_RE = re.compile(r"\S+")
_TRAILING_DANGLING = frozenset({"a", "an", "and", "at", "by", "for", "from", "in", "of", "on", "or", "the", "to", "with"})
_STRIP_EDGE_CHARS = " \t\r\n.,;:!?-–—\"'()[]{}|/\\"


def compute_unlabeled_diagnostic_priority(
    dense_scores: np.ndarray,
    bm25_scores: np.ndarray,
    risk_flags: list[str],
    eligible_mask: np.ndarray | None = None,
) -> tuple[bool, float, float]:
    """
    Compute (dense_bm25_disagree, dense_bm25_overlap, priority_score) for an unlabeled query.
    Higher priority_score (0-100) indicates higher diagnostic value to label first.
    """
    n = len(dense_scores)
    if n == 0:
        overlap = 0.0
        disagree = False
    else:
        if eligible_mask is not None:
            active_ids = np.flatnonzero(eligible_mask)
        else:
            active_ids = np.arange(n, dtype=np.int32)

        if len(active_ids) == 0:
            overlap = 0.0
            disagree = False
        else:
            b_sub = bm25_scores[active_ids]
            max_bm25 = float(np.max(b_sub)) if b_sub.size > 0 else 0.0
            if max_bm25 > 0.0:
                k_top = min(5, len(active_ids))
                d_sub = dense_scores[active_ids]
                d_top5 = set(active_ids[np.argsort(-d_sub)[:k_top]].tolist())
                pos_b = active_ids[b_sub > 0.0]
                b_top5 = set(pos_b[np.argsort(-bm25_scores[pos_b])[:5]].tolist())
                overlap = round(len(d_top5 & b_top5) / float(k_top), 4)
                disagree = overlap <= 0.2
            else:
                overlap = 0.0
                disagree = False

    score = 0.0
    if disagree:
        score += 35.0 * (1.0 - overlap)
    if "zero_bm25" in risk_flags:
        score += 30.0
    if "hub_hijack" in risk_flags:
        score += 25.0
    if "flat_plateau" in risk_flags:
        score += 20.0
    if "dead_zone" in risk_flags:
        score += 15.0

    priority = round(max(0.0, min(100.0, score)), 1)
    return disagree, overlap, priority


def _clean_probe_phrase(text: str, min_words: int = 4, max_words: int = 11) -> str | None:
    """Extract a clean natural-language probe phrase; rejects URL/HTML/code/symbol garbage."""
    if not text:
        return None
    s = _URL_RE.sub(" ", text)
    s = _HTML_RE.sub(" ", s)
    s = _CODE_RE.sub(" ", s)
    s = _BRACKET_RE.sub(" ", s)
    s = _SEP_RE.sub(" ", s)
    s = _WS_RE.sub(" ", s).strip(_STRIP_EDGE_CHARS)
    if not s:
        return None

    raw_words = [w.strip(_STRIP_EDGE_CHARS) for w in s.split()]
    words = [w for w in raw_words if w]
    if len(words) < min_words:
        return None

    if len(words) > max_words:
        words = words[:max_words]
        while len(words) > min_words and words[-1].lower() in _TRAILING_DANGLING:
            words.pop()

    phrase = " ".join(words).strip(_STRIP_EDGE_CHARS)
    if not phrase:
        return None

    alpha_space = sum(1 for ch in phrase if ch.isalpha() or ch.isspace())
    if alpha_space / len(phrase) < 0.70:
        return None

    alpha_words = sum(1 for w in words if sum(1 for ch in w if ch.isalpha()) >= 2)
    if alpha_words < min_words:
        return None

    return phrase


def _stratify_doc_ids(
    run: LoadedRun,
    doc_ids: list[int],
    prefer_uncovered: set[int] | None = None,
) -> list[int]:
    """Deterministic round-robin ordering across UMAP clusters."""
    by_cluster: dict[int, list[int]] = defaultdict(list)
    for d in sorted(doc_ids):
        cid = int(run.cluster_ids[d]) if d < len(run.cluster_ids) else -1
        by_cluster[cid].append(d)

    cids = sorted(by_cluster.keys())
    if prefer_uncovered:
        cids.sort(key=lambda c: (0 if c not in prefer_uncovered else 1, c))

    ordered: list[int] = []
    idx = 0
    while True:
        added = False
        for cid in cids:
            bucket = by_cluster[cid]
            if idx < len(bucket):
                ordered.append(bucket[idx])
                added = True
        if not added:
            break
        idx += 1
    return ordered


def _extract_truncated_tail_probe(run: LoadedRun, doc_id: int) -> str | None:
    raw = run.indexed_texts[doc_id]
    if not raw:
        return None
    offset = (
        run.truncated_char_offsets[doc_id]
        if doc_id < len(run.truncated_char_offsets)
        else None
    )
    if offset is None or offset <= 0 or offset >= len(raw):
        offset = int(len(raw) * 0.65)
    # Advance past a partially cut word right at the truncation boundary
    if offset > 0 and offset < len(raw) and not raw[offset - 1].isspace() and not raw[offset].isspace():
        next_ws = raw.find(" ", offset)
        if next_ws != -1 and next_ws + 1 < len(raw):
            offset = next_ws + 1
    tail = raw[offset:].strip()
    if not tail:
        return None
    for clause in _SENT_SPLIT_RE.split(tail):
        phrase = _clean_probe_phrase(clause, min_words=5, max_words=10)
        if phrase:
            return phrase
    return _clean_probe_phrase(tail, min_words=4, max_words=10)


def _extract_anti_hub_probe(run: LoadedRun, doc_id: int) -> str | None:
    # Prefer body text (skipping title/first sentence) to stress-test dense recall
    body = ""
    for field_name, vals in run.docs_by_field.items():
        if field_name not in ("title", "name", "headline", "question") and doc_id < len(vals):
            candidate = vals[doc_id].strip()
            if candidate:
                body = candidate
                break
    raw = body or run.indexed_texts[doc_id]
    clauses = [c.strip() for c in _SENT_SPLIT_RE.split(raw) if c.strip()]
    if len(clauses) >= 2:
        for clause in clauses[1:]:
            phrase = _clean_probe_phrase(clause, min_words=4, max_words=11)
            if phrase:
                return phrase
    for clause in clauses:
        phrase = _clean_probe_phrase(clause, min_words=4, max_words=11)
        if phrase:
            return phrase
    return _clean_probe_phrase(raw, min_words=4, max_words=11)


def _extract_distinctive_term_probe(run: LoadedRun, doc_id: int) -> str | None:
    raw = run.indexed_texts[doc_id]
    if not raw:
        return None
    toks = tokenize_with_spans(raw)
    if not toks:
        return None

    best_span: tuple[int, int] | None = None
    best_idf = -1.0
    for surface, stem, start, end in toks:
        if len(surface) < 4 or not any(ch.isalpha() for ch in surface):
            continue
        tid = run.bm25.vocab.get(stem)
        if tid is None:
            continue
        idf_val = float(run.bm25.idf[tid])
        if idf_val > best_idf:
            best_idf = idf_val
            best_span = (start, end)

    if best_span is None:
        return None

    word_matches = list(_WORD_SPAN_RE.finditer(raw))
    target_idx = 0
    for i, m in enumerate(word_matches):
        if m.start() <= best_span[0] < m.end() or m.start() >= best_span[0]:
            target_idx = i
            break

    win_start = max(0, target_idx - 3)
    win_end = min(len(word_matches), win_start + 8)
    win_start = max(0, win_end - 8)
    snippet = " ".join(m.group(0) for m in word_matches[win_start:win_end])
    return _clean_probe_phrase(snippet, min_words=4, max_words=10)


def _extract_title_lead_probe(run: LoadedRun, doc_id: int) -> str | None:
    for pref_field in ("title", "name", "headline", "question"):
        if pref_field in run.docs_by_field and doc_id < len(run.docs_by_field[pref_field]):
            title = run.docs_by_field[pref_field][doc_id].strip()
            phrase = _clean_probe_phrase(title, min_words=4, max_words=11)
            if phrase:
                return phrase
    raw = run.indexed_texts[doc_id]
    for clause in _SENT_SPLIT_RE.split(raw):
        phrase = _clean_probe_phrase(clause, min_words=4, max_words=11)
        if phrase:
            return phrase
    return _clean_probe_phrase(raw, min_words=4, max_words=11)


def generate_starter_probes(
    run: LoadedRun,
    req: BootstrapProbesRequest,
) -> BootstrapProbesResponse:
    """
    Deterministically extract clean, cluster-stratified, zero-LLM starter probes
    as UNLABELED drafts (expected_doc_ids=[]). Never creates fake synthetic labels.
    """
    t0 = time.perf_counter()
    n = len(run.indexed_texts)
    if n == 0:
        return BootstrapProbesResponse(
            probes=[],
            bucket_counts={},
            clusters_covered=0,
            elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
        )

    target = req.count
    special_cap = max(1, target // 4)
    seen_queries: set[str] = {q.strip().lower() for q in req.existing_queries if q.strip()}
    used_docs: set[int] = set()
    covered_clusters: set[int] = set()
    probes: list[SampleQuestionItem] = []
    bucket_counts: dict[str, int] = {}

    def _try_add(
        doc_id: int,
        phrase: str | None,
        kind: Literal["title_lead", "truncated_tail", "anti_hub", "distinctive_term"],
    ) -> bool:
        if not phrase or len(probes) >= target:
            return False
        key = phrase.strip().lower()
        if key in seen_queries:
            return False
        seen_queries.add(key)
        used_docs.add(doc_id)
        if doc_id < len(run.cluster_ids):
            covered_clusters.add(int(run.cluster_ids[doc_id]))
        probes.append(
            SampleQuestionItem(
                id=f"draft-{len(probes) + 1}-{doc_id}",
                query=phrase,
                expected_doc_ids=[],
                notes="",
                expect_abstain=False,
                draft_source_doc_id=doc_id,
                probe_kind=kind,
            )
        )
        bucket_counts[kind] = bucket_counts.get(kind, 0) + 1
        return True

    # 1. truncated_tail bucket (exposes Tier-2 silent truncation immediately)
    trunc_ids = [d for d in range(n) if bool(run.is_truncated[d])]
    added_trunc = 0
    for d in _stratify_doc_ids(run, trunc_ids):
        if added_trunc >= special_cap or len(probes) >= target:
            break
        if _try_add(d, _extract_truncated_tail_probe(run, d), "truncated_tail"):
            added_trunc += 1

    # 2. anti_hub bucket (unreachable hubness_nk == 0 docs)
    anti_hub_ids = [d for d in range(n) if int(run.hubness_nk[d]) == 0 and d not in used_docs]
    added_ah = 0
    for d in _stratify_doc_ids(run, anti_hub_ids, prefer_uncovered=covered_clusters):
        if added_ah >= special_cap or len(probes) >= target:
            break
        if _try_add(d, _extract_anti_hub_probe(run, d), "anti_hub"):
            added_ah += 1

    # 3. distinctive_term bucket (high-IDF jargon/entity stress test)
    rem_ids = [d for d in range(n) if d not in used_docs]
    added_dt = 0
    for d in _stratify_doc_ids(run, rem_ids, prefer_uncovered=covered_clusters):
        if added_dt >= special_cap or len(probes) >= target:
            break
        if _try_add(d, _extract_distinctive_term_probe(run, d), "distinctive_term"):
            added_dt += 1

    # 4. title_lead bucket (fills remaining slots across uncovered clusters first)
    rem_ids = [d for d in range(n) if d not in used_docs]
    for d in _stratify_doc_ids(run, rem_ids, prefer_uncovered=covered_clusters):
        if len(probes) >= target:
            break
        _try_add(d, _extract_title_lead_probe(run, d), "title_lead")

    return BootstrapProbesResponse(
        probes=probes,
        bucket_counts=bucket_counts,
        clusters_covered=len(covered_clusters),
        elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
    )


def _build_centered_snippet(
    text: str,
    query: str,
    max_len: int = 180,
) -> tuple[str, list[str]]:
    """Build a ~180-char excerpt centered on the best matched query term and return matched terms."""
    clean_text = _WS_RE.sub(" ", text).strip()
    if not clean_text:
        return "", []

    q_toks = tokenize_with_spans(query)
    q_stems = {stem for _, stem, _, _ in q_toks}
    q_raws = [raw.lower() for raw, _, _, _ in q_toks if len(raw) >= 2]
    if not q_raws:
        q_raws = [w.lower() for w in query.split() if len(w) >= 2 and w.lower() not in ENGLISH_STOPWORDS]

    match_positions: list[tuple[int, int, str]] = []
    if q_stems:
        for surface, stem, start, end in tokenize_with_spans(clean_text):
            if stem in q_stems:
                match_positions.append((start, end, surface))

    # Fallback direct case-insensitive substring search (handles OOV codes/SKUs)
    if not match_positions and query.strip():
        low = clean_text.lower()
        for needle in [query.strip().lower(), *q_raws]:
            if len(needle) < 2:
                continue
            pos = low.find(needle)
            if pos != -1:
                match_positions.append((pos, pos + len(needle), clean_text[pos : pos + len(needle)]))
                break

    matched_terms: list[str] = []
    seen_lower: set[str] = set()
    for _, _, surf in match_positions:
        k = surf.lower()
        if k not in seen_lower:
            seen_lower.add(k)
            matched_terms.append(surf)
            if len(matched_terms) >= 8:
                break

    if len(clean_text) <= max_len:
        return clean_text, matched_terms

    if not match_positions:
        return clean_text[:max_len].rstrip() + "…", matched_terms

    anchor = match_positions[0][0]
    start = max(0, anchor - max_len // 3)
    end = min(len(clean_text), start + max_len)
    if end - start < max_len and start > 0:
        start = max(0, end - max_len)

    if start > 0:
        sp = clean_text.find(" ", start, min(len(clean_text), start + 18))
        if sp != -1 and sp < anchor:
            start = sp + 1
    if end < len(clean_text):
        sp = clean_text.rfind(" ", max(start + 20, end - 18), end)
        if sp != -1:
            end = sp

    prefix = "…" if start > 0 else ""
    suffix = "…" if end < len(clean_text) else ""
    return f"{prefix}{clean_text[start:end].strip()}{suffix}", matched_terms


def _cluster_label_for(run: LoadedRun, doc_id: int) -> str:
    if doc_id < len(run.cluster_ids):
        cid = int(run.cluster_ids[doc_id])
        return run.cluster_label_map.get(cid, f"Cluster {cid}")
    return "Unclustered"


def build_label_pool(
    run: LoadedRun,
    embedder: TextEmbedder,
    req: LabelPoolRequest,
) -> LabelPoolResponse:
    """
    4-leg TREC-style candidate pooler (Dense Top-4, BM25 Top-4, Hybrid Top-4,
    Geometry-corrected Top-2) ordered by reciprocal branch support to prevent
    confirmation bias toward a broken current Hybrid configuration.
    """
    t0 = time.perf_counter()
    n = len(run.indexed_texts)
    query = req.query.strip()
    if n == 0 or not query:
        return LabelPoolResponse(
            query=query,
            candidates=[],
            dense_bm25_overlap=0.0,
            branch_counts={"dense": 0, "bm25": 0, "hybrid": 0, "geometry": 0},
            elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
        )

    keep_mask = _build_exclusion_mask(n, req.search.excluded_doc_ids)
    meta_mask = evaluate_metadata_mask(run, req.search)
    filter_active = bool(req.search.metadata_filters) or (req.search.allowed_doc_ids is not None)
    if keep_mask is not None:
        eligible_mask = meta_mask & keep_mask
    elif filter_active:
        eligible_mask = meta_mask
    else:
        eligible_mask = np.ones(n, dtype=bool)

    eligible_ids = np.flatnonzero(eligible_mask)
    if len(eligible_ids) == 0:
        return LabelPoolResponse(
            query=query,
            candidates=[],
            dense_bm25_overlap=0.0,
            branch_counts={"dense": 0, "bm25": 0, "hybrid": 0, "geometry": 0},
            elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
        )

    if req.search.query_rewrites:
        dense_query, bm25_query, _ = rewrite_query_for_branches(query, req.search.query_rewrites)
    else:
        dense_query = bm25_query = query

    active_prefix = (
        req.search.query_prefix_override
        if req.search.query_prefix_override is not None
        else run.manifest.query_prefix
    )
    q_vec = _get_query_vector(run, embedder, dense_query, active_prefix)
    dense_scores, _ = compute_dense_scores(
        run,
        q_vec,
        abtt_d=req.search.abtt_d,
        mean_center=req.search.mean_center,
        csls_enabled=req.search.csls_enabled,
    )
    field_weights = (
        req.search.field_weights if req.search.field_weights else run.manifest.bm25_initial_weights
    )
    bm25_scores = run.bm25.score_all(
        bm25_query,
        k1=req.search.bm25_k1,
        b=req.search.bm25_b,
        field_weights=field_weights,
    )
    q_req = req.search.model_copy(update={"query": query, "top_k": max(req.search.top_k, 20)})
    hybrid_ranked, _, _, _ = fast_eval_hybrid_ranks(
        run, embedder, q_req, precomputed_dense=dense_scores, precomputed_bm25=bm25_scores
    )

    dense_order = eligible_ids[np.argsort(-dense_scores[eligible_ids])]
    dense_rank_map = {int(d): r + 1 for r, d in enumerate(dense_order)}

    pos_bm25_ids = eligible_ids[bm25_scores[eligible_ids] > 0.0]
    bm25_order = pos_bm25_ids[np.argsort(-bm25_scores[pos_bm25_ids])]
    bm25_rank_map = {int(d): r + 1 for r, d in enumerate(bm25_order)}

    hybrid_rank_map = {int(d): r + 1 for r, d in enumerate(hybrid_ranked)}

    # Overlap between Dense Top-5 and BM25 Top-5
    if len(bm25_order) > 0:
        k_ov = min(5, len(eligible_ids))
        d_top5 = set(dense_order[:k_ov].tolist())
        b_top5 = set(bm25_order[:5].tolist())
        dense_bm25_overlap = round(len(d_top5 & b_top5) / float(k_ov), 4)
    else:
        dense_bm25_overlap = 0.0

    # 4 retrieval legs
    dense_top4 = [int(d) for d in dense_order[:4]]
    bm25_top4 = [int(d) for d in bm25_order[:4]]
    hybrid_top4 = [int(d) for d in hybrid_ranked[:4]]

    geo_top2: list[int] = []
    geo_rank_map: dict[int, int] = {}
    if run.manifest.health.cone_collapse_warning or run.manifest.health.hub_count > 0:
        geo_scores, _ = compute_dense_scores(
            run, q_vec, abtt_d=1, mean_center=True, csls_enabled=True
        )
        geo_order = eligible_ids[np.argsort(-geo_scores[eligible_ids])]
        geo_top2 = [int(d) for d in geo_order[:2]]
        geo_rank_map = {int(d): r + 1 for r, d in enumerate(geo_order)}

    existing_valid = [
        int(d) for d in dict.fromkeys(req.existing_expected_doc_ids) if 0 <= int(d) < n
    ]
    existing_set = set(existing_valid)
    draft_src = (
        int(req.draft_source_doc_id)
        if req.draft_source_doc_id is not None and 0 <= int(req.draft_source_doc_id) < n
        else None
    )

    sources_by_doc: dict[
        int,
        list[Literal["dense", "bm25", "hybrid", "geometry", "draft_source", "existing"]],
    ] = defaultdict(list)

    def _add_source(
        doc_id: int,
        src: Literal["dense", "bm25", "hybrid", "geometry", "draft_source", "existing"],
    ) -> None:
        if src not in sources_by_doc[doc_id]:
            sources_by_doc[doc_id].append(src)

    for d in existing_valid:
        _add_source(d, "existing")
    for d in dense_top4:
        _add_source(d, "dense")
    for d in bm25_top4:
        _add_source(d, "bm25")
    for d in hybrid_top4:
        _add_source(d, "hybrid")
    for d in geo_top2:
        _add_source(d, "geometry")
    if draft_src is not None:
        _add_source(draft_src, "draft_source")

    dense_top4_set = set(dense_top4)
    bm25_top4_set = set(bm25_top4)
    hybrid_top4_set = set(hybrid_top4)
    geo_top2_set = set(geo_top2)

    def _reciprocal_support(d: int) -> float:
        s = 0.0
        if d in dense_top4_set:
            s += 1.0 / (1.0 + dense_rank_map[d])
        if d in bm25_top4_set:
            s += 1.0 / (1.0 + bm25_rank_map[d])
        if d in hybrid_top4_set:
            s += 1.0 / (1.0 + hybrid_rank_map[d])
        if d in geo_top2_set:
            s += 1.0 / (1.0 + geo_rank_map[d])
        if draft_src is not None and d == draft_src:
            s += 0.22
        return s

    ranked_pool = sorted(
        sources_by_doc.keys(),
        key=lambda d: (0 if d in existing_set else 1, -_reciprocal_support(d), d),
    )

    cap = max(req.max_candidates, len(existing_valid))
    selected_ids = ranked_pool[:cap]

    candidates: list[LabelPoolCandidate] = []
    for d in selected_ids:
        snippet, matched_terms = _build_centered_snippet(run.indexed_texts[d], query, max_len=180)
        h_rank = hybrid_rank_map.get(d)
        candidates.append(
            LabelPoolCandidate(
                doc_id=d,
                title_preview=run.doc_title_preview(d),
                snippet=snippet,
                cluster_label=_cluster_label_for(run, d),
                dense_rank=dense_rank_map.get(d),
                bm25_rank=bm25_rank_map.get(d),
                hybrid_rank=h_rank,
                rescued_by_geometry=bool(d in geo_top2_set and (h_rank is None or h_rank > 5)),
                is_truncated=bool(run.is_truncated[d]),
                is_hub=bool(int(run.hubness_nk[d]) >= run.manifest.health.hub_threshold),
                is_draft_source=bool(draft_src is not None and d == draft_src),
                matched_terms=matched_terms,
                sources=sources_by_doc[d],
            )
        )

    return LabelPoolResponse(
        query=query,
        candidates=candidates,
        dense_bm25_overlap=dense_bm25_overlap,
        branch_counts={
            "dense": len(dense_top4),
            "bm25": len(bm25_top4),
            "hybrid": len(hybrid_top4),
            "geometry": len(geo_top2),
        },
        elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
    )


def quick_find_corpus_docs(
    run: LoadedRun,
    req: CorpusQuickFindRequest,
) -> CorpusQuickFindResponse:
    """
    Fast inline corpus lookup for labeling Stage-1 blind misses:
      1. Exact doc ID (#123 or 123)
      2. BM25 keyword match
      3. Case-insensitive substring fallback (OOV codes, SKUs, partial tokens)
    """
    t0 = time.perf_counter()
    n = len(run.indexed_texts)
    q = req.query.strip()
    if n == 0 or not q:
        return CorpusQuickFindResponse(
            query=q,
            hits=[],
            elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
        )

    seen: set[int] = set(req.exclude_doc_ids)
    hits: list[CorpusQuickFindHit] = []

    def _append_hit(doc_id: int, kind: Literal["doc_id", "bm25", "substring"]) -> None:
        seen.add(doc_id)
        snippet_q = "" if kind == "doc_id" else q
        snippet, _ = _build_centered_snippet(run.indexed_texts[doc_id], snippet_q, max_len=160)
        hits.append(
            CorpusQuickFindHit(
                doc_id=doc_id,
                title_preview=run.doc_title_preview(doc_id),
                snippet=snippet,
                cluster_label=_cluster_label_for(run, doc_id),
                is_truncated=bool(run.is_truncated[doc_id]),
                match_kind=kind,
            )
        )

    # 1. Exact doc ID match
    m_id = _DOC_ID_RE.match(q)
    if m_id:
        did = int(m_id.group(1))
        if 0 <= did < n and did not in seen:
            _append_hit(did, "doc_id")

    # 2. BM25 keyword search
    if len(hits) < req.limit:
        b_scores = run.bm25.score_all(q, field_weights=run.manifest.bm25_initial_weights)
        pos_ids = np.flatnonzero(b_scores > 0.0)
        if pos_ids.size > 0:
            order = pos_ids[np.argsort(-b_scores[pos_ids])]
            for d in order:
                if len(hits) >= req.limit:
                    break
                di = int(d)
                if di not in seen:
                    _append_hit(di, "bm25")

    # 3. Case-insensitive substring fallback for OOV tokens / codes
    if len(hits) < req.limit:
        q_low = q.lower()
        for di, text in enumerate(run.indexed_texts):
            if len(hits) >= req.limit:
                break
            if di in seen:
                continue
            if q_low in text.lower():
                _append_hit(di, "substring")

    if len(hits) < req.limit:
        parts = [p for p in q.lower().split() if len(p) >= 2]
        if len(parts) > 1:
            for di, text in enumerate(run.indexed_texts):
                if len(hits) >= req.limit:
                    break
                if di in seen:
                    continue
                low = text.lower()
                if all(p in low for p in parts):
                    _append_hit(di, "substring")

    return CorpusQuickFindResponse(
        query=q,
        hits=hits,
        elapsed_ms=round((time.perf_counter() - t0) * 1000.0, 2),
    )