# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-lossy-auto-compaction-and-escalate-to-full-context-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-lossy-auto-compaction-and-escalate-to-full-context-reconstruction.warrant.json
# Markdown SHA-256:   3979ed0d462bfb136aa0b3d44c5a609a3f304f7e4c93bd1d601bd55309ee6730
# Code AST SHA-256:   b8e99a0a32cda70ef02470af38996bd28f2ff722f96c74eec24e58587962aabd
# Verified Classes:   CompactionDriftError, Constraint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CompactionDriftError(RuntimeError):
    """Raised when a lossy summary no longer maps to durable retrieval keys."""


@dataclass(frozen=True)
class Constraint:
    key: str
    value: str
    provenance: str | None  # record id / span hash; None means summary-derived


def _key_matches(summary_key: str, store_keys: set[str], threshold: float = 0.0) -> bool:
    # Exact-token match by default; callers may pass a store-specific matcher.
    return summary_key in store_keys


def verify_compaction(
    summary_constraints: list[Constraint],
    store_keys: set[str],
    budget_tokens: int,
    constraint_tokens: int,
    prior_generation_hashes: list[str],
) -> str:
    if budget_tokens < constraint_tokens:
        raise CompactionDriftError(
            f"budget {budget_tokens} < constraint-bearing {constraint_tokens}; "
            "refuse compaction, escalate to full reconstruction"
        )

    for c in summary_constraints:
        if c.provenance is None:
            raise CompactionDriftError(
                f"constraint {c.key!r} is summary-derived with no provenance; "
                "treat as untrusted and reconstruct from store"
            )
        if not _key_matches(c.key, store_keys):
            raise CompactionDriftError(
                f"retrieval-key drift: {c.key!r} not present in durable store keys; "
                "summary paraphrased an identifier"
            )

    digest = hashlib.sha256(
        "".join(sorted(f"{c.key}={c.value}" for c in summary_constraints)).encode()
    ).hexdigest()
    if digest in prior_generation_hashes:
        raise CompactionDriftError(
            "compaction re-ingested a prior generation verbatim; drift would compound"
        )
    return digest


def compact_or_escalate(
    summary_constraints: list[Constraint],
    store_keys: set[str],
    budget_tokens: int,
    constraint_tokens: int,
    prior_generation_hashes: list[str],
    task_is_irreversible: bool,
) -> str:
    if task_is_irreversible and any(c.provenance is None for c in summary_constraints):
        raise CompactionDriftError(
            "irreversible task with summary-derived constraints; "
            "full-context reconstruction required before any side effect"
        )
    return verify_compaction(
        summary_constraints,
        store_keys,
        budget_tokens,
        constraint_tokens,
        prior_generation_hashes,
    )
