# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-referent-loss-when-model-driven-pruning-rewrites-the-context-that-its-own-instructions-point-into.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-referent-loss-when-model-driven-pruning-rewrites-the-context-that-its-own-instructions-point-into.warrant.json
# Markdown SHA-256:   51a8f3c80816fca20067fc93f4c9c8fed5e08445172ce3e73a80b9ca5fc72b10
# Code AST SHA-256:   3c1ef718519531afe3455d4fc55edb8cdf9cbe26a30e8c1ea8b9c1dbc5b3adaa
# Verified Classes:   ReferentLossError, Instruction, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Any


class ReferentLossError(RuntimeError):
    """Raised when a prune would leave a live instruction's oblique
    reference unresolvable, or resolving to a different object."""
    pass


@dataclass
class Instruction:
    id: str
    # oblique references: description -> resolver that maps context -> object
    refs: dict[str, Callable[[dict], Any]]


@dataclass
class Context:
    segments: dict[str, Any] = field(default_factory=dict)


def resolve_refs(instr: Instruction, ctx: Context) -> dict[str, Any]:
    out = {}
    for name, resolver in instr.refs.items():
        try:
            out[name] = resolver(ctx.segments)
        except (KeyError, LookupError):
            out[name] = _UNRESOLVED
    return out


_UNRESOLVED = object()


def audited_prune(
    ctx: Context,
    live_instructions: list[Instruction],
    evict: set[str],
    rewrite: Callable[[dict], dict],
) -> Context:
    """Prune+rewrite as an atomic transaction gated on reference resolvability."""
    # 1. snapshot resolutions BEFORE
    before = {i.id: resolve_refs(i, ctx) for i in live_instructions}

    # 2. build candidate post-prune context
    survivors = {k: v for k, v in ctx.segments.items() if k not in evict}
    candidate = Context(segments=rewrite(survivors))

    # 3. resolve AFTER and compare
    for instr in live_instructions:
        after = resolve_refs(instr, candidate)
        for name, pre in before[instr.id].items():
            post = after[name]
            if pre is _UNRESOLVED:
                continue  # was already dangling; not this prune's fault
            if post is _UNRESOLVED:
                raise ReferentLossError(
                    f"prune would orphan ref {name!r} of instruction "
                    f"{instr.id!r}: antecedent evicted, no surviving binding"
                )
            if post is not pre:
                raise ReferentLossError(
                    f"prune would rebind ref {name!r} of instruction "
                    f"{instr.id!r}: was {pre!r}, decoy resolves to {post!r}"
                )

    # 4. commit only if every live reference survived intact
    return candidate
