# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-severing-the-provenance-chain-of-a-still-referenced-span.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-model-driven-context-pruning-from-severing-the-provenance-chain-of-a-still-referenced-span.warrant.json
# Markdown SHA-256:   5f77425762110f861da034022a5ef56f95307859f302f5813da2cd0690315ea0
# Code AST SHA-256:   00118aa364ea713db376330d0cbce6d6033fed32b0cbd5abbbc2928412cd1c79
# Verified Classes:   DanglingReferenceError, Span, ContextStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DanglingReferenceError(RuntimeError):
    """Raised when a pruning/rewrite would sever a live reference to a span."""
    pass


class Span:
    def __init__(self, span_id: str, content: str):
        self.span_id = span_id
        self.content = content


class ContextStore:
    def __init__(self):
        self.spans: dict[str, Span] = {}
        # live obligations -> span ids they still reference
        self.obligations: dict[str, set[str]] = {}

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

    def register_obligation(self, name: str, refs: set[str]) -> None:
        self.obligations[name] = set(refs)

    def resolve_obligation(self, name: str) -> None:
        # consuming an obligation drops its references
        self.obligations.pop(name, None)

    def live_references(self) -> set[str]:
        refs: set[str] = set()
        for r in self.obligations.values():
            refs |= r
        return refs

    def prune(self, candidate_ids: set[str], rewrite_fn) -> list[str]:
        """Prune only spans with zero live in-degree. Referenced spans are
        resolved-then-evicted by the caller or deferred; never silently dropped."""
        live = self.live_references()
        blocked = candidate_ids & live
        if blocked:
            raise DanglingReferenceError(
                f"refusing to prune live-referenced spans: {sorted(blocked)}; "
                f"resolve obligations first"
            )
        pruned = []
        for sid in candidate_ids:
            if sid in self.spans:
                rewrite_fn(self.spans[sid])
                del self.spans[sid]
                pruned.append(sid)
        return pruned

    def resolve_reference(self, obligation: str, span_id: str) -> str:
        """Inline a span's payload into an obligation so it can be evicted."""
        if span_id not in self.spans:
            # hard error — never fall back to nearest-neighbor
            raise DanglingReferenceError(
                f"obligation {obligation!r} references missing span {span_id!r}"
            )
        payload = self.spans[span_id].content
        self.obligations[obligation].discard(span_id)
        return payload


# --- trace of the failure ---
store = ContextStore()
store.add_span(Span("span_3", "k candidates: 0.038, 0.041, 0.044; selected 0.044"))
store.register_obligation("step_7", {"span_3"})

try:
    # naive compaction tries to summarize the calibration block away
    store.prune({"span_3"}, rewrite_fn=lambda s: setattr(s, "content", "calibration done"))
except DanglingReferenceError as e:
    print("blocked:", e)
    # resolve-then-evict is the only legal path
    value = store.resolve_reference("step_7", "span_3")
    store.prune({"span_3"}, rewrite_fn=lambda s: setattr(s, "content", "calibration done"))
    print("inlined into step_7:", value)
