# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-summarizer-drops-a-load-bearing-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-summarizer-drops-a-load-bearing-constraint.warrant.json
# Markdown SHA-256:   58e0ec8ffef8f522f8f69b968e0754858c52d6e424215af0fdf607b18cf0ff03
# Code AST SHA-256:   1b76bd7c9bcd513584773e6d260081732bc3b857d4a024c320b7da0afff2d442
# Verified Classes:   ConstraintLossError, Constraint, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ConstraintLossError(RuntimeError):
    """Raised when a compaction boundary drops a pinned, load-bearing constraint."""
    pass


@dataclass
class Constraint:
    text: str
    pinned: bool          # prohibitions / scope limits: never summarize
    has_referent: bool    # will a post-compaction turn or query re-summon it?


@dataclass
class CompactionResult:
    summary: str
    retained: set[str] = field(default_factory=set)


def verify_compaction(
    constraints: Iterable[Constraint],
    result: CompactionResult,
) -> None:
    """
    Enforce the loss-safe invariant:
        C subset of (R union S)
    where R = constraints with a live referent, S = constraints retained
    (verbatim or summarized). Anything outside R union S is a silent loss.
    """
    lost: list[str] = []
    for c in constraints:
        survives = c.has_referent or c.text in result.retained
        if not survives:
            lost.append(c.text)

    if lost:
        # A pinned prohibition with no referent is the worst case: silent,
        # confident, and only discovered after the forbidden action fires.
        pinned_lost = [c.text for c in constraints if c.pinned and c.text in lost]
        raise ConstraintLossError(
            "compaction dropped load-bearing constraints: "
            f"lost={lost!r} pinned_lost={pinned_lost!r}. "
            "Pin these verbatim and re-assert before mutating calls."
        )


def pre_action_gate(action_sql: str, pinned: Iterable[Constraint]) -> None:
    """Convert silent prohibitions into an explicit pre-mutation gate."""
    for c in pinned:
        if not c.pinned:
            continue
        # Toy matcher: a real gate parses the target and compares to scope.
        if "staging." in action_sql and "read-only" in c.text.lower():
            raise ConstraintLossError(
                f"blocked mutating action against pinned scope: {action_sql!r} "
                f"violates constraint {c.text!r}"
            )


if __name__ == "__main__":
    constraints = [
        Constraint("target schema v3", pinned=False, has_referent=True),
        Constraint("staging is read-only this run", pinned=True, has_referent=False),
    ]
    # Summarizer kept schema, dropped the prohibition -> must raise.
    verify_compaction(constraints, CompactionResult(summary="schema v3", retained={"target schema v3"}))
