# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-compaction-has-silently-severed-a-causal-dependency-across-the-window-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-hierarchical-compaction-has-silently-severed-a-causal-dependency-across-the-window-boundary.warrant.json
# Markdown SHA-256:   0cfa4c09cb4fc1a8e7480cbd2a575046f87421ea71d79650d5363f2955639002
# Code AST SHA-256:   4f551c54392ed2366f30c4cd855f60dc99dbee5510bf063c4f1b75255e583cfe
# Verified Classes:   ProvenanceClosureViolation, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceClosureViolation(RuntimeError):
    """Raised when compaction would retain a reference whose binding is evicted."""
    pass


@dataclass
class Span:
    turn: int
    text: str
    establishes: set[str] = field(default_factory=set)   # ids/literals this span binds
    references: set[str] = field(default_factory=set)    # ids/literals this span consumes
    is_constraint: bool = False


def check_compaction_soundness(evicted: list[Span], retained_tail: list[Span]) -> None:
    """
    Enforce: every reference in the retained tail must have its binding either
    retained or explicitly marked UNBOUND. Constraints consumed by retained
    tokens must be pinned, not dropped.
    """
    retained_bindings: set[str] = set()
    for s in retained_tail:
        retained_bindings |= s.establishes

    evicted_bindings: dict[str, Span] = {}
    for s in evicted:
        for b in s.establishes:
            evicted_bindings[b] = s

    dangling: list[tuple[str, Span]] = []
    for s in retained_tail:
        for ref in s.references:
            if ref in retained_bindings:
                continue
            if ref in evicted_bindings:
                dangling.append((ref, evicted_bindings[ref]))

    if dangling:
        # Any dangling ref whose source is a constraint is a hard failure:
        # the summarizer would silently drop a guard the tail depends on.
        hard = [(r, src) for r, src in dangling if src.is_constraint]
        if hard:
            ref, src = hard[0]
            raise ProvenanceClosureViolation(
                f"retained reference '{ref}' depends on constraint established "
                f"at evicted turn {src.turn}; must be pinned verbatim, not summarized"
            )
        # Non-constraint dangling refs: require UNBOUND sentinel instead of silent drop.
        ref, src = dangling[0]
        raise ProvenanceClosureViolation(
            f"retained reference '{ref}' has evicted binding at turn {src.turn}; "
            f"insert UNBOUND('{ref}') sentinel or retain the binding"
        )


def constraint_to_state_ratio(span_texts: list[tuple[str, bool]]) -> float:
    """Ratio of constraint tokens to state tokens in a summary generation."""
    c = sum(len(t.split()) for t, is_c in span_texts if is_c)
    s = sum(len(t.split()) for t, is_c in span_texts if not is_c)
    return c / max(s, 1)
