# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-rewriting-policy-has-silently-invalidated-a-referenced-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-rewriting-policy-has-silently-invalidated-a-referenced-artifact.warrant.json
# Markdown SHA-256:   b8547bf987068468827984164787165d5911d196f3198cad29615ee7ab3f3c21
# Code AST SHA-256:   99bab9091e455afc4eb4b642c47cb139880886cfe7e043335dc2f87567ccb63c
# Verified Classes:   DanglingReferentError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class DanglingReferentError(RuntimeError):
    """Raised when a context rewrite leaves an identifier live but unbound."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    introduces: set[str] = field(default_factory=set)  # identifiers defined here
    references: set[str] = field(default_factory=set)  # identifiers used here


def binding_check(
    rewrite_output: str,
    rewritten_span_id: str,
    surviving_spans: Iterable[Span],
    mentioned_ids: set[str],
    unbound_tags: set[str],
) -> None:
    """
    Enforce the invariant: every identifier mentioned in a rewrite must be
    either still bound in a surviving span or explicitly tagged UNBOUND.
    Called at eviction time, before the rewrite is committed.
    """
    bound: set[str] = set()
    for span in surviving_spans:
        if span.span_id == rewritten_span_id:
            continue  # the span being rewritten cannot bind its own referents
        bound |= span.introduces

    dangling = {
        ident
        for ident in mentioned_ids
        if ident not in bound and f"UNBOUND:{ident}" not in unbound_tags
    }
    if dangling:
        raise DanglingReferentError(
            f"rewrite of {rewritten_span_id} leaves identifiers live but unbound: "
            f"{sorted(dangling)}. Retain the defining span or emit UNBOUND tags "
            f"before committing the rewrite."
        )


def apply_rewrite(
    span: Span,
    new_text: str,
    surviving_spans: list[Span],
    mentioned_ids: set[str],
    unbound_tags: set[str],
) -> Span:
    binding_check(new_text, span.span_id, surviving_spans, mentioned_ids, unbound_tags)
    return Span(span_id=span.span_id, text=new_text, introduces=set(), references=mentioned_ids)
