# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-ancestry-when-a-model-driven-pruning-policy-rewrites-its-own-context-window-between-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-ancestry-when-a-model-driven-pruning-policy-rewrites-its-own-context-window-between-checkpoints.warrant.json
# Markdown SHA-256:   a7fb06dcc104b93ccff15aa36e0ce3cf776d076e3ba4a25943cb0c67c077bdd9
# Code AST SHA-256:   f8092300df7c45d61c71bf30e6e192541df004f86364142d9015bb1bead3097d
# Verified Classes:   Provenance, CausalAncestryError, Span, Checkpoint, DurableStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Provenance(Enum):
    OBSERVED = "observed"      # re-readable from a durable source
    DERIVED = "derived"        # paraphrase of an observed span
    UNKNOWN = "unknown"        # elided with no resolvable input


class CausalAncestryError(RuntimeError):
    """Raised when a checkpoint restore cannot reconstruct the causal chain
    from a live token back to an immutable source event."""


@dataclass
class Span:
    span_id: str
    content: str
    provenance: Provenance
    input_ref: Optional[str] = None          # content-addressed key into durable store
    digest_hash: Optional[str] = None        # hash of the digest text, if derived


@dataclass
class Checkpoint:
    window: list[Span]
    inverse_log: list[dict] = field(default_factory=list)


class DurableStore:
    """Content-addressed store for span bytes. If a span's bytes are evicted,
    its input_ref no longer resolves and the checkpoint is lossy."""
    def __init__(self) -> None:
        self._blobs: dict[str, str] = {}

    def put(self, content: str) -> str:
        key = hashlib.sha256(content.encode()).hexdigest()
        self._blobs[key] = content
        return key

    def get(self, key: str) -> Optional[str]:
        return self._blobs.get(key)

    def evict(self, key: str) -> None:
        self._blobs.pop(key, None)


def prune_span(
    span: Span,
    digest_text: str,
    store: DurableStore,
    evict_input: bool,
) -> Span:
    """Model-driven pruning: replace an observed span with a digest.
    The invariant requires input_ref to survive. If evict_input is True,
    the digest's source is destroyed and the span becomes UNKNOWN on restore."""
    if span.provenance is not Provenance.OBSERVED:
        raise CausalAncestryError(
            f"refusing to prune non-observed span {span.span_id}: "
            f"provenance={span.provenance.value}"
        )
    input_ref = span.input_ref or store.put(span.content)
    if evict_input:
        store.evict(input_ref)
    return Span(
        span_id=span.span_id,
        content=digest_text,
        provenance=Provenance.DERIVED,
        input_ref=input_ref,
        digest_hash=hashlib.sha256(digest_text.encode()).hexdigest(),
    )


def restore_checkpoint(cp: Checkpoint, store: DurableStore, restore_context: str) -> list[Span]:
    """Re-derive every derived span from its input_ref under restore-time context.
    A missing input_ref is a hard failure: the checkpoint is lossy and the
    instance must not proceed believing it has full ancestry."""
    restored: list[Span] = []
    for span in cp.window:
        if span.provenance is Provenance.DERIVED:
            source = store.get(span.input_ref) if span.input_ref else None
            if source is None:
                # Do not silently promote; surface as a gap.
                restored.append(Span(
                    span_id=span.span_id,
                    content=f"[amnesia: prior digest of {span.span_id} unresolvable]",
                    provenance=Provenance.UNKNOWN,
                ))
                continue
            # Drift check: re-derive and compare. Mismatch is a signal, not a cache miss.
            rederived = hashlib.sha256((source + restore_context).encode()).hexdigest()
            if span.digest_hash and rederived != span.digest_hash:
                raise CausalAncestryError(
                    f"provenance drift on {span.span_id}: stored digest hash "
                    f"{span.digest_hash[:8]} != rederived {rederived[:8]} under "
                    f"restore context"
                )
            restored.append(span)
        else:
            restored.append(span)

    # Invariant: no live OBSERVED span may be shadowed by a DERIVED digest
    # that claims to describe the same span_id.
    observed_ids = {s.span_id for s in restored if s.provenance is Provenance.OBSERVED}
    for s in restored:
        if s.provenance is Provenance.DERIVED and s.span_id in observed_ids:
            raise CausalAncestryError(
                f"derived digest shadows observed span {s.span_id}; "
                f"ancestry chain is ambiguous"
            )
    return restored


def checkpoint_is_reversible(cp: Checkpoint, store: DurableStore) -> bool:
    for span in cp.window:
        if span.provenance is Provenance.DERIVED:
            if not span.input_ref or store.get(span.input_ref) is None:
                return False
    return True
