# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-deleting-the-only-copy-of-a-fact-mid-reasoning.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-deleting-the-only-copy-of-a-fact-mid-reasoning.warrant.json
# Markdown SHA-256:   4f1e917be8899f840f6fd853aaed1dc2f82b10cedc4443cbb2f04df3de83737d
# Code AST SHA-256:   78185c54625c1416d6f5000fc3ec8d0f66c80c4fb33ad254690c0ac9981221d3
# Verified Classes:   ContextPinViolation, Segment, Obligation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ContextPinViolation(RuntimeError):
    """Raised when an open obligation reads a context segment that was
    evicted or lossily summarized without a resolvable durable pointer."""


@dataclass
class Segment:
    seg_id: str
    content: str
    pinned_fields: set[str] = field(default_factory=set)
    durable_pointer: Optional[str] = None  # e.g. tool_call_id; None => sole copy


@dataclass
class Obligation:
    name: str
    pins: set[str]  # seg_ids this obligation depends on
    terminal: bool = False


def evict(buffer: dict[str, Segment], obligations: list[Obligation],
          candidate_ids: list[str]) -> list[str]:
    """Evict only segments with empty live-pin sets. Returns evicted ids."""
    live_pins: set[str] = set()
    for ob in obligations:
        if not ob.terminal:
            live_pins |= ob.pins

    evicted: list[str] = []
    for sid in candidate_ids:
        seg = buffer.get(sid)
        if seg is None:
            continue
        if sid in live_pins:
            # Pinned: may only be lossily summarized if a durable pointer exists.
            if seg.durable_pointer is None:
                continue  # refuse to evict the sole copy of a live dependency
        del buffer[sid]
        evicted.append(sid)
    return evicted


def read_for_obligation(buffer: dict[str, Segment], ob: Obligation,
                        seg_id: str) -> str:
    """Read a value an open obligation depends on, or fail loudly."""
    seg = buffer.get(seg_id)
    if seg is not None:
        return seg.content
    # Segment gone. Safe only if the obligation can re-fetch from durable storage.
    raise ContextPinViolation(
        f"obligation '{ob.name}' read evicted segment '{seg_id}' with no "
        f"resolvable durable pointer; refusing to reconstruct from summary"
    )
