"""Deterministic, source-audited merging of two fact extractors. Model agreement is evidence about a prediction, not a probability of truth. This module does not read gold facts, learn aliases, rewrite dates or invent canonical values. Choose a policy on dev_calib before evaluating held-out data. """ from __future__ import annotations from copy import deepcopy from dataclasses import asdict, dataclass from datetime import datetime, timezone from difflib import SequenceMatcher import math import re from .graph.retrieval import normalize MODES = ("primary", "union", "grounded_union", "consensus") _NEGATION = frozenset({"не", "нет", "без", "нельзя", "никогда"}) @dataclass(frozen=True) class MergePolicy: mode: str = "grounded_union" value_similarity: float = .92 secondary_min_confidence: float | None = None def __post_init__(self): if self.mode not in MODES: raise ValueError(f"Unknown ensemble mode: {self.mode}") if isinstance(self.value_similarity, bool) or not .8 <= self.value_similarity <= 1: raise ValueError("value_similarity must be in [.8, 1]") score = self.secondary_min_confidence if score is not None and (isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score) or not 0 <= score <= 1): raise ValueError("secondary_min_confidence must be finite and in [0, 1]") def to_dict(self): return asdict(self) def _time(value): if value is None: return None parsed = datetime.fromisoformat(value) if parsed.tzinfo: parsed = parsed.astimezone(timezone.utc) return parsed.isoformat() def _compatible_words(left, right, threshold): left, right = normalize(left), normalize(right) if not left or not right: return left == right if set(re.findall(r"\d+", left)) != set(re.findall(r"\d+", right)): return False if left.count("+") != right.count("+"): return False if set(left.split()) & _NEGATION != set(right.split()) & _NEGATION: return False return left == right or SequenceMatcher(None, left, right, autojunk=False).ratio() >= threshold def source_evidence(call, fact): """Validate only a model-supplied citation against the original utterance. A unique literal quote may recover missing offsets. A turn ID by itself is insufficient grounding for adding a new secondary fact. """ source = fact.get("source") or {} turns = [t for t in call["turns"] if t["idx"] == source.get("turn_idx")] if len(turns) != 1: return {"status": "invalid_turn", "source": deepcopy(source)} text = turns[0]["text"] span, quote = source.get("span"), source.get("quote") if span is not None: valid = (isinstance(span, list) and len(span) == 2 and all(type(x) is int for x in span) and 0 <= span[0] < span[1] <= len(text) and isinstance(quote, str) and text[span[0]:span[1]] == quote) return {"status": "exact_span" if valid else "invalid_span", "source": deepcopy(source)} if isinstance(quote, str) and quote.strip(): matches = list(re.finditer(re.escape(quote), text)) if len(matches) == 1: recovered = {**source, "span": [matches[0].start(), matches[0].end()]} return {"status": "unique_literal_quote", "source": recovered} return {"status": "missing_or_ambiguous_quote", "source": deepcopy(source)} return {"status": "turn_only", "source": deepcopy(source)} def same_fact(left, right, policy): """Conservative cross-model duplicate check, preserving objects and episodes. IDs belong to individual models, so compare explicit types/names. Require the same date interval and source turn: equal state values at separate points in a conversation are not assumed to be the same episode. """ if left.get("attribute") != right.get("attribute"): return False if (left.get("polarity", 1) > 0) != (right.get("polarity", 1) > 0): return False lo, ro = left.get("object") or {}, right.get("object") or {} if lo.get("type") != ro.get("type"): return False ln, rn = normalize(lo.get("name") or ""), normalize(ro.get("name") or "") if not ln or not rn: if lo.get("type") != "client" or ln != rn: return False elif not _compatible_words(ln, rn, 1.): return False if not _compatible_words(left.get("value") or "", right.get("value") or "", policy.value_similarity): return False for field in ("valid_from", "valid_to"): if _time(left.get(field)) != _time(right.get(field)): return False return (left.get("source") or {}).get("turn_idx") == (right.get("source") or {}).get("turn_idx") def _scores(facts, values): values = [None] * len(facts) if values is None else list(values) if len(values) != len(facts): raise ValueError("Confidence count does not match fact count") for value in values: if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1): raise ValueError("Fact confidence must be finite, in [0, 1], or missing") return values def merge_fact_predictions(call, primary, secondary, *, policy=None, primary_scores=None, secondary_scores=None, names=("FactSetNet", "CalOn")): """Return schema facts and separate provenance, without reading call['facts']. Primary facts retain their own canonical value, date and source. Cross-model duplicates count once, with two provenance records. Extra secondary facts may require exact grounding and independently calibrated confidence. """ policy = policy or MergePolicy() primary, secondary = list(primary), list(secondary) ps, ss = _scores(primary, primary_scores), _scores(secondary, secondary_scores) pairs, used = {}, set() for i, fact in enumerate(primary): matches = [j for j, other in enumerate(secondary) if j not in used and same_fact(fact, other, policy)] if matches: # Stable one-to-one pairing; never collapse two same-name instances # from a single model into one fact. pairs[i] = matches[0] used.add(matches[0]) facts, trace = [], [] for i, fact in enumerate(primary): evidence = source_evidence(call, fact) supported = i in pairs accepted = policy.mode != "consensus" or supported row = {"model": names[0], "input_index": i, "confidence": ps[i], "evidence": evidence["status"], "decision": "kept" if accepted else "dropped", "reason": "model_agreement" if supported else "primary_only"} if supported: row["support"] = {"model": names[1], "input_index": pairs[i], "confidence": ss[pairs[i]]} if accepted: row["output_index"] = len(facts) facts.append(deepcopy(fact)) trace.append(row) for j, fact in enumerate(secondary): if j in used: continue evidence = source_evidence(call, fact) reason = "secondary_only" accepted = policy.mode in {"union", "grounded_union"} if policy.mode == "grounded_union" and evidence["status"] not in {"exact_span", "unique_literal_quote"}: accepted, reason = False, "secondary_not_literally_grounded" if policy.secondary_min_confidence is not None: if ss[j] is None: accepted, reason = False, "secondary_confidence_missing" elif ss[j] < policy.secondary_min_confidence: accepted, reason = False, "secondary_confidence_below_threshold" row = {"model": names[1], "input_index": j, "confidence": ss[j], "evidence": evidence["status"], "decision": "kept" if accepted else "dropped", "reason": reason} if accepted: row["output_index"] = len(facts) copied = deepcopy(fact) if evidence["status"] == "unique_literal_quote": copied["source"] = evidence["source"] facts.append(copied) trace.append(row) return facts, trace