# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-initiated-context-rewrite-as-a-lossy-state-transition-requiring-re-derivation-rather-than-an-in-p.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-initiated-context-rewrite-as-a-lossy-state-transition-requiring-re-derivation-rather-than-an-in-p.warrant.json
# Markdown SHA-256:   00f724d77aae4c2e461e30deaeefa5bacfb22dfe44e88ffb3ffe5e6f902667e5
# Code AST SHA-256:   56f268b4d8648bbf4e57bde28141da9c5f25dd2bae7ba6709b5036ba316d4cc7
# Verified Classes:   RewriteInvalidatesWarrant, Span, Assertion, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class RewriteInvalidatesWarrant(RuntimeError):
    """Raised when a context rewrite would orphan a live assertion's warrant."""


@dataclass
class Span:
    sid: str
    text: str
    lossy: bool = False


@dataclass
class Assertion:
    aid: str
    claim: str
    warrant_sids: set[str]
    stale: bool = False


@dataclass
class Context:
    spans: dict[str, Span] = field(default_factory=dict)
    assertions: dict[str, Assertion] = field(default_factory=dict)

    def dependents(self, sid: str) -> list[Assertion]:
        return [a for a in self.assertions.values() if sid in a.warrant_sids]

    def rewrite(self, sid: str, new_text: str, lossy: bool) -> None:
        deps = self.dependents(sid)
        if deps and lossy:
            # A lossy projection of a span that live assertions cite is a
            # state transition, not a mutation. Refuse unless dependents are
            # first marked stale, so no conclusion survives on a broken warrant.
            raise RewriteInvalidatesWarrant(
                f"lossy rewrite of {sid} would orphan "
                f"{[a.aid for a in deps]}; mark stale and re-derive first"
            )
        self.spans[sid] = Span(sid, new_text, lossy=lossy)
        for a in deps:
            a.stale = True  # extensional rewrite still forces re-check


def prune(ctx: Context, sid: str, summary: str) -> None:
    if sid not in ctx.spans:
        raise RewriteInvalidatesWarrant(f"unknown span {sid}")
    ctx.rewrite(sid, summary, lossy=True)
