# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-corruption-during-in-place-context-rewrite-and-diff-based-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-corruption-during-in-place-context-rewrite-and-diff-based-pruning.warrant.json
# Markdown SHA-256:   b33e2544e41cb5c104aa64615c51f4d886f3912048d368fb9b24d98656ccd9db
# Code AST SHA-256:   bca65577f4b7621ceec7afcf663533a351386046cd0b273dfe2d12c3df027ffd
# Verified Classes:   ContextIntegrityError, Span, ContextGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ContextIntegrityError(RuntimeError):
    """Raised when a context mutation breaks reference closure or anchor stability."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    deps: set[str] = field(default_factory=set)   # span_ids this span references
    anchor_hash: str = ""                          # content hash of referenced external object


def content_hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


class ContextGraph:
    def __init__(self) -> None:
        self.spans: dict[str, Span] = {}

    def add(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def prune(self, drop_ids: set[str]) -> None:
        # Invariant 1: dependency closure. No retained span may reference a dropped span.
        for sid, span in self.spans.items():
            if sid in drop_ids:
                continue
            dangling = span.deps & drop_ids
            if dangling:
                raise ContextIntegrityError(
                    f"prune violates closure: retained span {sid!r} depends on "
                    f"dropped span(s) {sorted(dangling)}; externalize instead of dropping"
                )
        for sid in drop_ids:
            self.spans.pop(sid, None)

    def rewrite(self, span_id: str, new_text: str, new_anchor_hash: str | None = None) -> None:
        # Invariant 2: dependent invalidation. A rewrite that changes the anchor hash
        # invalidates every dependent, which must be re-derived, not silently retained.
        span = self.spans[span_id]
        old_hash = span.anchor_hash
        span.text = new_text
        if new_anchor_hash is not None:
            span.anchor_hash = new_anchor_hash
        if old_hash and new_anchor_hash and old_hash != new_anchor_hash:
            dependents = [s for s in self.spans.values() if span_id in s.deps]
            if dependents:
                raise ContextIntegrityError(
                    f"rewrite of {span_id!r} changed anchor hash "
                    f"({old_hash[:8]} -> {new_anchor_hash[:8]}); "
                    f"dependents {[d.span_id for d in dependents]} are stale and must be re-derived"
                )

    def verify(self) -> None:
        # Invariant 3: every retained reference resolves to a span with a matching anchor hash.
        for sid, span in self.spans.items():
            for dep in span.deps:
                target = self.spans.get(dep)
                if target is None:
                    raise ContextIntegrityError(
                        f"span {sid!r} references missing span {dep!r} (dangling reference)"
                    )
                if span.anchor_hash and target.anchor_hash and span.anchor_hash != target.anchor_hash:
                    raise ContextIntegrityError(
                        f"span {sid!r} anchor hash {span.anchor_hash[:8]} does not match "
                        f"target {dep!r} hash {target.anchor_hash[:8]} (re-bound reference)"
                    )
