# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-auto-compaction-boundary-has-been-crossed-before-retrieval-backed-recovery-can-fire.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-auto-compaction-boundary-has-been-crossed-before-retrieval-backed-recovery-can-fire.warrant.json
# Markdown SHA-256:   14813a56976fc9a706c34a747810c5e49192d17428996985a18a053e2aa1551c
# Code AST SHA-256:   c81be8ceef40f26a958ed10ed461721ae29f34f178021442830eb23e3ef57a3a
# Verified Classes:   CompactionBoundaryViolation, Span, Summary
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class CompactionBoundaryViolation(RuntimeError):
    """Raised when a compaction would convert recoverable loss into silent loss."""


@dataclass
class Span:
    span_id: str
    tokens: int
    anchors: set[str]          # identifiers, numerics, negations, constraint verbs
    action_gating: bool        # auth constraints, quotas, idempotency keys


@dataclass
class Summary:
    span_id: str
    tokens: int
    anchors: set[str]
    has_omission_ledger: bool


def evaluate_compaction(span: Span, summary: Summary) -> str:
    if summary.span_id != span.span_id:
        raise CompactionBoundaryViolation(
            f"summary {summary.span_id} does not correspond to span {span.span_id}"
        )
    if span.tokens <= 0:
        raise CompactionBoundaryViolation(f"span {span.span_id} has non-positive token count")

    rho = summary.tokens / span.tokens
    kappa = (
        len(summary.anchors & span.anchors) / len(span.anchors)
        if span.anchors
        else 1.0
    )
    mu = summary.has_omission_ledger

    # Action-gating facts must never be summarized without an omission ledger.
    if span.action_gating and not mu:
        raise CompactionBoundaryViolation(
            f"span {span.span_id} contains action-gating facts but summary "
            f"carries no omission ledger (rho={rho:.3f}, kappa={kappa:.3f})"
        )

    if mu and kappa >= 0.6:
        return "compact_in_place"

    if rho < 0.1 and kappa < 0.4:
        return "checkpoint_and_restart"

    # Aggressive compression without ledger, or anchor loss without a
    # restart-worthy ratio: neither safe to compact nor worth a cold restart.
    raise CompactionBoundaryViolation(
        f"span {span.span_id} falls in the silent-loss band "
        f"(rho={rho:.3f}, kappa={kappa:.3f}, ledger={mu}); "
        f"refusing in-place compaction"
    )


def audit_session(
    elided_span_ids: Sequence[str],
    touched_span_ids: Sequence[str],
    retrieval_calls: int,
) -> None:
    touched_elided = set(elided_span_ids) & set(touched_span_ids)
    if touched_elided and retrieval_calls == 0:
        raise CompactionBoundaryViolation(
            f"session acted on elided spans {sorted(touched_elided)} "
            f"with zero retrieval calls; continuity invariant violated"
        )
