# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-projection-rather-than-a-safe-truncation-and-how-does-the-eviction-frontier-si.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-projection-rather-than-a-safe-truncation-and-how-does-the-eviction-frontier-si.warrant.json
# Markdown SHA-256:   1738b8c1b18a3a6d46e283e55d631369b6c38eeba6f8225a6ce951ee338bc203
# Code AST SHA-256:   7a04ce2ed11e0895b66e65ee324580fe8981dd0f63878337cd2f29a1a7ffa132
# Verified Classes:   AnchorProjectionError, Span, CompactionPlan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AnchorProjectionError(RuntimeError):
    """Raised when auto-compaction would project (paraphrase) a decoding anchor
    instead of pinning it verbatim or preserving a re-fetch pointer."""


# Literals that decode a retained gist. Cheap to keep, catastrophic to lose.
ANCHOR_KINDS = frozenset({
    "unit", "sign", "numeric_format", "schema_version",
    "id_binding", "ordering_key", "tool_call_id",
})


@dataclass
class Span:
    span_id: str
    tokens: int
    anchors: dict[str, str] = field(default_factory=dict)  # kind -> literal
    refetch_pointer: str | None = None  # e.g. tool_call_id enabling replay


@dataclass
class CompactionPlan:
    projected: list[Span]
    pinned_anchors: dict[str, str]
    pinned_pointers: list[str]


def compact(spans: Iterable[Span], budget: int) -> CompactionPlan:
    """Anchor-aware compaction. Projects gist-bearing spans; pins every anchor
    verbatim and preserves re-fetch pointers. Fails closed if the pinned block
    plus projected budget cannot fit — never projects an anchor to make room."""
    projected: list[Span] = []
    pinned_anchors: dict[str, str] = {}
    pinned_pointers: list[str] = []
    projected_tokens = 0

    for span in spans:
        # Deterministically pin anchors BEFORE any summarization touches the span.
        for kind, literal in span.anchors.items():
            if kind not in ANCHOR_KINDS:
                raise AnchorProjectionError(
                    f"unknown anchor kind {kind!r} in span {span.span_id}; "
                    "cannot guarantee verbatim pinning"
                )
            pinned_anchors[f"{span.span_id}:{kind}"] = literal
        if span.refetch_pointer:
            pinned_pointers.append(span.refetch_pointer)

        # Project only the residual, anchor-free body of the span.
        residual = span.tokens
        projected_tokens += residual
        projected.append(span)

        # Invariant: a projected gist must remain decodable. If it carries
        # anchors, they must be pinned (done above) OR re-fetchable.
        if span.anchors and not span.refetch_pointer:
            # Pinned verbatim is sufficient; no pointer required.
            pass

    pinned_tokens = sum(len(a) for a in pinned_anchors.values()) // 4
    if projected_tokens + pinned_tokens > budget:
        # Budget pressure must NOT be resolved by projecting anchors.
        # Fail closed and escalate to checkpoint/resume or span-shedding.
        raise AnchorProjectionError(
            f"compaction would exceed budget ({projected_tokens + pinned_tokens} > {budget}) "
            "with anchors pinned; refusing to project anchors to fit. "
            "Escalate: checkpoint-and-resume or shed anchor-free spans."
        )

    return CompactionPlan(projected, pinned_anchors, pinned_pointers)


def verify_decodable(plan: CompactionPlan, required: Iterable[str]) -> None:
    """Downstream guard: any computation consuming a projected gist must have
    its decoding anchors pinned or re-fetchable through a surviving pointer."""
    for anchor_key in required:
        span_id, _, kind = anchor_key.partition(":")
        if anchor_key in plan.pinned_anchors:
            continue
        # Fall back to re-fetch: is the span replayable?
        if any(p.startswith(span_id) for p in plan.pinned_pointers):
            continue
        raise AnchorProjectionError(
            f"gist for span {span_id!r} consumed without anchor {kind!r} "
            "pinned or re-fetchable; state-continuity breach"
        )
