# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-compaction-boundary-has-severed-an-active-causal-pointer-rather-than-merely-shortened-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-compaction-boundary-has-severed-an-active-causal-pointer-rather-than-merely-shortened-context.warrant.json
# Markdown SHA-256:   d60566c9ac6016f2b250d73ac044a3f7e13ae4ce43e4125b5042f138c9f2ff9b
# Code AST SHA-256:   e229224223ea12f979d3459c5678d8d5a3e800e93cd5ad5db870cef5bf79cd8f
# Verified Classes:   CausalPointerSevered, Span, PlanNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CausalPointerSevered(RuntimeError):
    """Raised when a compaction fold would evict a span that a live plan node dereferences."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    is_binding: bool          # structured name=value call frame
    reconstructible: bool     # cheaply re-derivable via tool call
    referenced_by: list = field(default_factory=list)  # downstream plan node ids


@dataclass
class PlanNode:
    node_id: str
    depends_on_span: str | None   # span whose value this node dereferences


def assert_fold_admissible(evict_set: list[Span], plan: list[PlanNode],
                           post_budget: int, pinned_cost: int) -> None:
    """Fold is admissible only if every dereferenced, non-reconstructible binding is pinned."""
    live_refs = {n.depends_on_span for n in plan if n.depends_on_span}
    for span in evict_set:
        if span.span_id not in live_refs:
            continue
        if span.reconstructible:
            continue  # safe: can be re-fetched downstream
        if not span.is_binding:
            # value survives as prose but the binding is gone -> pointer severed
            raise CausalPointerSevered(
                f"span {span.span_id} is dereferenced by a live plan node but is not a "
                f"binding; summarizing it converts a handle to prose and severs the pointer"
            )
        # binding is live and non-reconstructible: it must be pinned, not evicted
        raise CausalPointerSevered(
            f"span {span.span_id} is a live non-reconstructible binding; "
            f"pin it in live_bindings, do not fold it"
        )
    if pinned_cost > post_budget:
        raise CausalPointerSevered(
            f"pinning required bindings costs {pinned_cost} > post-compaction budget "
            f"{post_budget}; checkpoint and restart the plan segment instead of folding through a pin"
        )
