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), )