# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-to-preserve-evidential-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-model-driven-context-rewrite-to-preserve-evidential-provenance.warrant.json
# Markdown SHA-256:   1d3324cb3e2805e77444cf1dbfec3387b41b60e334296d89b9ce688ccb74666c
# Code AST SHA-256:   35b0270c859d39e55e0ea4efd0a50e8c67fddee85a63e2b105108ea852c6efad
# Verified Classes:   ProvenanceRewriteRefused, Span, RewritePlan, ContextStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceRewriteRefused(RuntimeError):
    """Raised when a model-driven context rewrite would destroy the sole
    retrievable copy of a value referenced by an unresolved goal."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str


@dataclass
class RewritePlan:
    remove: list[str]           # span_ids the model proposes to evict
    summaries: dict[str, str]   # span_id -> paraphrase (untrusted)
    rationale: str = ""         # NOT evidence


@dataclass
class ContextStore:
    live: dict[str, Span] = field(default_factory=dict)
    external: dict[str, Span] = field(default_factory=dict)  # out-of-window, id-addressable

    def retrievable(self, span_id: str) -> bool:
        return span_id in self.live or span_id in self.external


def commit_rewrite(
    store: ContextStore,
    plan: RewritePlan,
    open_goal_refs: Iterable[str],
) -> None:
    """Apply a rewrite only if every removed span stays reachable and no
    open goal loses its last verbatim carrier. Evaluated OUTSIDE the model."""
    refs = set(open_goal_refs)

    # 1. Reachability must hold AFTER commit. A span that is itself live and
    #    being removed is NOT reachable unless it also exists externally.
    for span_id in plan.remove:
        if span_id in store.live and span_id not in store.external:
            raise ProvenanceRewriteRefused(
                f"span {span_id!r} would be evicted with no external copy; "
                f"paraphrase {plan.summaries.get(span_id)!r} is not provenance"
            )

    # 2. No open goal may lose its last verbatim carrier.
    for span_id in plan.remove:
        span = store.live.get(span_id)
        if span is None:
            continue
        for ref in refs:
            if ref in span.text and not any(
                ref in s.text for sid, s in store.live.items()
                if sid not in plan.remove
            ):
                raise ProvenanceRewriteRefused(
                    f"rewrite removes sole carrier of open-goal value {ref!r} "
                    f"(span {span_id!r}); rationale {plan.rationale!r} is not evidence"
                )

    # 3. Commit atomically only after both invariants hold.
    for span_id in plan.remove:
        store.live.pop(span_id, None)


def run_compactor(store, plan, refs):
    try:
        commit_rewrite(store, plan, refs)
        return "committed"
    except ProvenanceRewriteRefused as exc:
        # Loud refusal: orchestrator can spill or widen budget instead of livelock.
        return f"refused: {exc}"
