# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-lossy-summary-has-silently-widened-its-recall-guarantee-into-a-hallucination-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-lossy-summary-has-silently-widened-its-recall-guarantee-into-a-hallucination-surface.warrant.json
# Markdown SHA-256:   9eb164ec0fecc266a94c7daa9f02d98b60baecb1eaeb7cc8249bceadd754da78
# Code AST SHA-256:   baf004d9422eaed7634f93bd1cde8eee57f74040b6620227440e3f275d903a9c
# Verified Classes:   Fidelity, RecallWideningError, SummarySegment
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class Fidelity(Enum):
    VERBATIM = "verbatim"        # source text preserved exactly
    ANCHORED = "anchored"        # paraphrase + resolvable anchor_ref to source span
    STRUCTURED = "structured"    # value extracted into typed field at compaction
    PARAPHRASE = "paraphrase"    # topic shape only; no value guarantee


class RecallWideningError(RuntimeError):
    """Raised when an assertion requires value recall but only a
    paraphrase-class summary segment covers it. This is the boundary
    that must fire instead of silently answering from a paraphrase."""


@dataclass
class SummarySegment:
    text: str
    fidelity: Fidelity
    anchor_ref: Optional[str] = None   # handle to original source span
    structured_value: Optional[str] = None


VALUE_BEARING = {Fidelity.VERBATIM, Fidelity.ANCHORED, Fidelity.STRUCTURED}


def assert_value(segments: list[SummarySegment], field: str) -> str:
    """Attempt to answer a value-recall query from compacted context.

    Invariant enforced: R(S) subset of A(S). We may only ASSERT a specific
    value if at least one covering segment can actually back it. Otherwise
    we raise, converting silent widening into a bounded, observable event.
    """
    for seg in segments:
        if field not in seg.text:
            continue
        if seg.fidelity in VALUE_BEARING:
            if seg.fidelity is Fidelity.STRUCTURED and seg.structured_value is not None:
                return seg.structured_value
            if seg.fidelity is Fidelity.ANCHORED and seg.anchor_ref is None:
                # Anchored claim with no handle is itself a contract breach.
                raise RecallWideningError(
                    f"segment claims ANCHORED for {field!r} but carries no anchor_ref"
                )
            return seg.text  # verbatim/anchored: value is recoverable

        # Paraphrase-class segment covers the field but cannot back a value.
        raise RecallWideningError(
            f"value recall for {field!r} would assert from PARAPHRASE segment "
            f"(no anchor, no structured value); re-fetch source span required"
        )

    raise RecallWideningError(f"no segment covers {field!r}; cannot assert")


def resolve_with_refetch(segments, field, fetcher):
    """Boundary handler: on widening, re-fetch the anchored source."""
    try:
        return assert_value(segments, field)
    except RecallWideningError:
        for seg in segments:
            if field in seg.text and seg.anchor_ref:
                return fetcher(seg.anchor_ref)  # recover ground truth
        raise  # unrecoverable: propagate, do not guess
