# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-evicts-its-own-working-set-while-sibling-sub-agents-still-hold-live-references-into-the-parent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-evicts-its-own-working-set-while-sibling-sub-agents-still-hold-live-references-into-the-parent-context.warrant.json
# Markdown SHA-256:   dc36ac739e320433a880c72326eb10069b22469f1878fdbf987ad5a7088aaa9a
# Code AST SHA-256:   ae0ee94101b629f6873a72bab2f1a2c1d16bb6aae9897d091b65946506042b25
# Verified Classes:   DanglingContextReference, SharedContextStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DanglingContextReference(RuntimeError):
    """Raised when eviction would invalidate a live inbound reference from a concurrent sub-agent."""
    pass


class SharedContextStore:
    def __init__(self):
        self._spans = {}          # span_id -> payload
        self._refcount = {}       # span_id -> int

    def register_reference(self, span_id: str, owner: str) -> None:
        # MUST be called at handle-write time, before the writer's turn yields.
        if span_id not in self._spans:
            raise DanglingContextReference(
                f"{owner} registered a reference to absent span {span_id}"
            )
        self._refcount[span_id] = self._refcount.get(span_id, 0) + 1

    def release_reference(self, span_id: str, owner: str) -> None:
        if self._refcount.get(span_id, 0) <= 0:
            raise DanglingContextReference(
                f"{owner} released span {span_id} with zero refcount"
            )
        self._refcount[span_id] -= 1

    def evict(self, span_id: str, requesting_agent: str) -> None:
        live = self._refcount.get(span_id, 0)
        if live > 0:
            # Do NOT summarize. Surface the conflict upward.
            raise DanglingContextReference(
                f"agent {requesting_agent} attempted eviction of span {span_id} "
                f"with {live} live inbound reference(s); eviction refused, "
                f"escalate to orchestrator or block on release"
            )
        self._spans.pop(span_id, None)
        self._refcount.pop(span_id, None)


def safe_evict(store: SharedContextStore, span_id: str, agent: str) -> str:
    try:
        store.evict(span_id, agent)
        return "evicted"
    except DanglingContextReference as e:
        # Convert silent corruption into a visible stall / escalation.
        return f"stalled: {e}"
