"""Backend-owned evidence admission, ordering and execution source identities.""" from contextlib import contextmanager from dataclasses import dataclass, field import math from threading import RLock from uuid import UUID, uuid4 import time from typing import Any from app.modules.knowledge.lexical import LEXICAL_POLICY MAX_BRANCH_CANDIDATES = 50 MAX_CHUNKS = 10 MAX_EVIDENCE_CHARACTERS = 12000 RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}" def merge_candidates(semantic, exact): by_id = {} for row in semantic: by_id[row["chunk_id"]] = dict(row, exact_match=False) for row in exact: by_id[row["chunk_id"]] = dict(row, exact_match=True) return sorted(by_id.values(), key=lambda row: ( not row["exact_match"], row["cosine_distance"], str(row["chunk_id"]))) def admit_candidates(rows, cutoff=None): admitted, used = [], 0 for row in rows: if cutoff is not None and row["cosine_distance"] > cutoff: continue size = len(row["text"]) if size + used > MAX_EVIDENCE_CHARACTERS: continue admitted.append(row) used += size if len(admitted) == MAX_CHUNKS: break return admitted @dataclass(frozen=True) class CalibratedCutoff: profile: dict distance: float calibration_id: str retrieval_policy: str = RETRIEVAL_POLICY def __post_init__(self): if (type(self.distance) not in (int, float) or not math.isfinite(self.distance) or not 0 <= self.distance <= 2 or not self.calibration_id): raise ValueError("Measured finite cosine cutoff and calibration identity required") @dataclass class SearchExecution: """Created by the trusted caller, never populated from model arguments.""" user_id: UUID request_id: str = field(default_factory=lambda: str(uuid4())) trace_callback: Any = None trace_events: list = field(default_factory=list) _start_monotonic: float = field(default_factory=time.monotonic, init=False, repr=False) _authority: dict | None = field(default=None, init=False, repr=False) _epoch: int | None = field(default=None, init=False, repr=False) _refs: dict = field(default_factory=dict, init=False, repr=False) _lock: RLock = field(default_factory=RLock, init=False, repr=False) def record_trace(self, stage: str, **details): with self._lock: now_mono = time.monotonic() elapsed_ms = round((now_mono - self._start_monotonic) * 1000, 2) event = { "stage": stage, "elapsed_ms": elapsed_ms, "timestamp_utc": time.time(), "request_id": self.request_id, **details, } self.trace_events.append(event) if self.trace_callback is not None: try: self.trace_callback(event) except Exception: pass return event def capture(self, current, epoch): with self._lock: if self._authority is None: self._authority, self._epoch = dict(current), epoch return self._authority == current and self._epoch == epoch def matches(self, current, epoch): with self._lock: return self._authority is not None and self._authority == current and self._epoch == epoch @contextmanager def source_handoff(self): """Stage reference mappings; publish only after authorized commit.""" with self._lock: prepared = dict(self._refs) yield lambda rows: self._sources(rows, prepared) self._refs = prepared def sources(self, rows): with self._lock: return self._sources(rows, self._refs) @staticmethod def _sources(rows, refs): sources = [] for row in rows: key = (row["document_id"], row["chunk_id"]) if key not in refs: refs[key] = f"S{len(refs) + 1}" sources.append(dict(source_ref=refs[key], document_id=str(row["document_id"]), chunk_id=str(row["chunk_id"]), title=row["title"], text=row["text"], location=dict(page=row["location"].get("page"), section=row["location"].get("section")))) return sources