# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-context-surgery-when-the-salience-ranker-and-the-rewrite-planner-disagree-about-a-token-s-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-context-surgery-when-the-salience-ranker-and-the-rewrite-planner-disagree-about-a-token-s-provenance.warrant.json
# Markdown SHA-256:   53799e9bc01da7442802df63e27d41cb562206838831ecb9ffbd21782aebea81
# Code AST SHA-256:   9b4120af6938f39b2d0ec4d4b9e91565a0c97a98bb8566638393393a3451c919
# Verified Classes:   ProvenanceInversionError, Token, ContextStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceInversionError(RuntimeError):
    """Raised when a surgery pass would evict the last live carrier of a constraint."""
    pass


@dataclass
class Token:
    tid: str
    pinned: bool = False
    # source span ids this token was derived from; empty = original/authoritative
    source_spans: tuple[str, ...] = ()


@dataclass
class ContextStore:
    tokens: dict[str, Token] = field(default_factory=dict)

    def live_carrier_exists(self, span: str, exclude: Optional[str] = None) -> bool:
        """True iff some token other than `exclude` reaches `span` through
        a path whose terminal token is pinned or is an original (no source_spans)."""
        for tid, tok in self.tokens.items():
            if tid == exclude:
                continue
            if span in tok.source_spans or tid == span:
                # terminal anchor: original token, or a pinned derived token
                if not tok.source_spans or tok.pinned:
                    return True
                # derived and unpinned: recurse through its sources
                if any(self.live_carrier_exists(s, exclude=tid) for s in tok.source_spans):
                    return True
        return False


def commit_surgery(store: ContextStore, evict_spans: list[str],
                   proposed_summaries: list[Token]) -> None:
    """Validate provenance reachability, then apply eviction + summaries atomically."""
    # Stage summaries first so their edges are visible to the reachability check.
    staged = {t.tid: t for t in proposed_summaries}
    for tid, tok in staged.items():
        store.tokens[tid] = tok

    for span in evict_spans:
        # The summary derived from this span is excluded from the check: it is
        # not a carrier unless it is pinned (and pinning is checked inside).
        if not store.live_carrier_exists(span):
            # roll back staged summaries for this span before raising
            for tid, tok in staged.items():
                if span in tok.source_spans:
                    store.tokens.pop(tid, None)
            raise ProvenanceInversionError(
                f"refusing eviction of span {span!r}: only surviving carrier is an "
                f"unpinned derived summary; pin the source or the summary's "
                f"discharge condition first"
            )

    for span in evict_spans:
        store.tokens.pop(span, None)
