# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-cryptographic-operation-rather-than-a-summarization-step-and-what-anchor-retent.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-cryptographic-operation-rather-than-a-summarization-step-and-what-anchor-retent.warrant.json
# Markdown SHA-256:   c6142be8ae0485b1aad91fa4f1d978939e6902fec3da5822370a5740141dfcd0
# Code AST SHA-256:   a8c10e6cca72650971ecc71d301720bb0bbce0c8b28efa2bf49dd2fe9fa35ba0
# Verified Classes:   AnchorEvictionError, Field, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class AnchorEvictionError(RuntimeError):
    """Raised when compaction would drop a field that a fail-open verifier depends on."""


@dataclass(frozen=True)
class Field:
    name: str
    value: Any
    pinned: bool          # participates in fail-open verification -> byte-exact retention required
    reconstructible: bool # can be re-fetched from an authoritative source by warrant_id


@dataclass
class Warrant:
    warrant_id: str
    fields: list[Field] = field(default_factory=list)

    def anchors(self) -> list[Field]:
        return [f for f in self.fields if f.pinned and not f.reconstructible]


def compact(warrant: Warrant, budget_tokens: int, token_cost) -> tuple[dict, list[str]]:
    """
    Typed compaction: pinned+non-reconstructible fields bypass the salience model.
    Returns (post_compaction_state, unresolved_markers). Fails closed on ambiguity.
    """
    retained: dict[str, Any] = {}
    unresolved: list[str] = []
    spent = 0

    # Phase 1: anchors are non-negotiable. Serialize verbatim or mark UNRESOLVED.
    for f in warrant.anchors():
        cost = token_cost(f.value)
        if spent + cost > budget_tokens:
            # Cannot fit the anchor. Do NOT summarize it. Mark unresolved and require re-fetch.
            unresolved.append(f.name)
            retained[f.name] = "UNRESOLVED"
            raise AnchorEvictionError(
                f"anchor '{f.name}' of warrant {warrant.warrant_id} exceeds budget; "
                f"warrant must be re-fetched from issuer before execution"
            )
        retained[f.name] = f.value
        spent += cost

    # Phase 2: reconstructible and unpinned fields may be summarized/evicted freely.
    for f in warrant.fields:
        if f in warrant.anchors():
            continue
        retained[f.name] = "<summarized>" if not f.reconstructible else f"<ref:{f.name}>"

    return retained, unresolved


def execute(warrant: Warrant, budget_tokens: int, token_cost) -> dict:
    state, unresolved = compact(warrant, budget_tokens, token_cost)
    if unresolved:
        # Fail closed: never execute on a warrant whose anchors did not survive.
        raise AnchorEvictionError(
            f"refusing execution of {warrant.warrant_id}: unresolved anchors {unresolved}"
        )
    # Post-condition: every anchor present and byte-exact.
    for f in warrant.anchors():
        if state.get(f.name) != f.value:
            raise AnchorEvictionError(f"anchor '{f.name}' mutated during compaction")
    return state
