# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-agent-has-silently-invalidated-its-own-referent-bindings.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-agent-has-silently-invalidated-its-own-referent-bindings.warrant.json
# Markdown SHA-256:   9858a4e2bb40fae081439f3739153089dff7a4fa2258acdd117409f1bf3ccd01
# Code AST SHA-256:   68ba34721052c218942cda5747fcdd6d7f3fb8afd740efb9577412f8c31236b6
# Verified Classes:   BindingInvalidatedError, Binding, Window
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class BindingInvalidatedError(RuntimeError):
    """Raised when a self-edit removes a span a live binding depends on
    without writing a tombstone, or when a step dereferences a binding
    whose referent no longer exists in the window."""
    pass


@dataclass
class Binding:
    name: str
    literal: str          # the token that must survive in the window
    resolved: bool = True


@dataclass
class Window:
    spans: Dict[str, str] = field(default_factory=dict)  # span_id -> text

    def contains_literal(self, literal: str) -> bool:
        return any(literal in text for text in self.spans.values())


def prune(window: Window, drop_span_ids: Set[str],
          bindings: Dict[str, Binding]) -> Dict[str, Binding]:
    """Remove spans, but first verify no live binding loses its referent
    without being tombstoned. Returns the (possibly rewritten) bindings."""
    surviving_text = "".join(
        text for sid, text in window.spans.items() if sid not in drop_span_ids
    )
    for name, b in bindings.items():
        if not b.resolved:
            continue
        if b.literal not in surviving_text:
            # Referent is being pruned. Caller must either refuse or tombstone.
            raise BindingInvalidatedError(
                f"prune would drop referent for binding '{name}' "
                f"(literal={b.literal!r}); tombstone or freeze it first"
            )
    for sid in drop_span_ids:
        window.spans.pop(sid, None)
    return bindings


def tombstone_and_prune(window: Window, drop_span_ids: Set[str],
                        bindings: Dict[str, Binding]) -> Dict[str, Binding]:
    """Safe variant: bindings whose referents are dropped are marked
    unresolved and must be re-acquired before next dereference."""
    surviving_text = "".join(
        text for sid, text in window.spans.items() if sid not in drop_span_ids
    )
    for name, b in bindings.items():
        if b.resolved and b.literal not in surviving_text:
            b.resolved = False  # tombstone: forces re-acquisition
    for sid in drop_span_ids:
        window.spans.pop(sid, None)
    return bindings


def dereference(bindings: Dict[str, Binding], name: str) -> str:
    b = bindings.get(name)
    if b is None:
        raise BindingInvalidatedError(f"no binding named '{name}'")
    if not b.resolved:
        raise BindingInvalidatedError(
            f"binding '{name}' was tombstoned by a prior prune; "
            f"re-acquire before use"
        )
    return b.literal


# --- trigger trace ---
w = Window(spans={"s9": '{"order_id": "4471", "status": "PENDING"}',
                  "s10": '{"cust": "acme"}'})
binds = {"order_id": Binding(name="order_id", literal="4471")}

# Naive prune (as a budget-only policy would do) -> loud failure:
try:
    prune(w, {"s9"}, binds)
except BindingInvalidatedError as e:
    print("caught:", e)

# Correct path: tombstone, then force re-acquisition before deref.
binds = tombstone_and_prune(w, {"s9"}, binds)
try:
    dereference(binds, "order_id")
except BindingInvalidatedError as e:
    print("caught:", e)  # -> must re-fetch order 4471 before refunding
