# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-silently-severed-retrieval-backed-context-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-silently-severed-retrieval-backed-context-reconstruction.warrant.json
# Markdown SHA-256:   91f8ef6519d20a9ff94e859aedc28c36a93bdfd77427dae1a99870754459c4fa
# Code AST SHA-256:   947f2d0c146c35ac80d8c7c08bf90c93bfc59a687dbac32dafe0999dac2d6008
# Verified Classes:   ReconstructionMismatch, Chunk, Summary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Optional

LITERAL_PATTERN = re.compile(r"\b\d+(?:\.\d+)?\b|[A-Z][A-Za-z0-9_]{2,}|[a-z]+_[a-z_]+\b")


class ReconstructionMismatch(RuntimeError):
    """Raised when a retrieval result cannot faithfully reconstruct an evicted span."""


@dataclass
class Chunk:
    span_id: str
    text: str
    metadata_literals: set[str] = field(default_factory=set)


@dataclass
class Summary:
    span_id: str
    text: str
    load_bearing: set[str] = field(default_factory=set)

    def __post_init__(self) -> None:
        self.load_bearing = set(LITERAL_PATTERN.findall(self.text))


def register_summary_contract(summary: Summary, chunk: Chunk) -> None:
    """Enforce at eviction time: summary literals must be index keys on the chunk."""
    missing = summary.load_bearing - chunk.metadata_literals
    if missing:
        raise ReconstructionMismatch(
            f"span {summary.span_id}: summary commits to literals {sorted(missing)} "
            f"absent from chunk metadata; eviction would be unreconstructable"
        )


def reconstruct(
    summary: Summary,
    retrieved: Optional[Chunk],
    similarity: float,
    confidence_threshold: float = 0.72,
    fallback_floor: float = 0.55,
) -> Chunk:
    if retrieved is None or similarity < fallback_floor:
        raise ReconstructionMismatch(
            f"span {summary.span_id}: no chunk above fallback floor "
            f"(sim={similarity:.2f}); escalate to full re-fetch"
        )
    if similarity < confidence_threshold:
        # Fallback neighbor returned: verify literal containment before trusting.
        present = summary.load_bearing & retrieved.metadata_literals
        if present != summary.load_bearing:
            raise ReconstructionMismatch(
                f"span {summary.span_id}: low-confidence hit (sim={similarity:.2f}) "
                f"missing literals {sorted(summary.load_bearing - present)}; "
                f"treat as unverified, do not act"
            )
    return retrieved
