# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-context-pruning-has-crossed-from-compression-into-evidence-destruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-model-driven-context-pruning-has-crossed-from-compression-into-evidence-destruction.warrant.json
# Markdown SHA-256:   10fec1ab33cb18f85d9314aa9c2831e83bef4fbfeff3d1cf8786374cdfebc3a9
# Code AST SHA-256:   0a72dd98d0859bc88914e88656da3aeac8f55f1a267b457b5861d8b279a95a0f
# Verified Classes:   EvidenceDestructionError, Span, Summary
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class EvidenceDestructionError(RuntimeError):
    """Raised when a pruning decision would replace recoverable evidence with an unverifiable summary."""


@dataclass
class Span:
    span_id: str
    payload: str
    discriminating_fields: list[str] = field(default_factory=list)
    durable_handle: Optional[str] = None  # resolvable pointer into external store


@dataclass
class Summary:
    span_id: str
    text: str
    retained_fields: list[str]
    provenance: Optional[str]


def prune_span(span: Span, summary: Summary, store_resolves: bool) -> Summary:
    # Recoverability test: the summary's provenance must dereference to the original bytes.
    if not store_resolves or summary.provenance is None:
        raise EvidenceDestructionError(
            f"span {span.span_id}: summary provenance does not resolve to durable store; "
            f"pruning would destroy byte-recoverable evidence"
        )

    # Discriminator test: every discriminating field must survive into the summary.
    lost = [f for f in span.discriminating_fields if f not in summary.retained_fields]
    if lost:
        raise EvidenceDestructionError(
            f"span {span.span_id}: summary dropped discriminating fields {lost}; "
            f"downstream branches become undecidable"
        )

    # Recursive re-summarization guard: a summary may not be summarized again.
    if summary.span_id.startswith("summary::"):
        raise EvidenceDestructionError(
            f"span {span.span_id}: recursive re-summarization compounds discriminator loss"
        )

    return summary


def checkpoint_and_handle(span: Span, store) -> Span:
    handle = store.put(span.payload)
    if not store.resolves(handle):
        raise EvidenceDestructionError(
            f"span {span.span_id}: checkpointed handle {handle} is not dereferenceable"
        )
    return Span(
        span_id=span.span_id,
        payload=f"[handle:{handle}]",
        discriminating_fields=span.discriminating_fields,
        durable_handle=handle,
    )
