# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-evict-a-live-plan-to-satisfy-a-preempting-priority-budget-and-why-the-eviction-trace-not-the-token-count-is-the-real-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-evict-a-live-plan-to-satisfy-a-preempting-priority-budget-and-why-the-eviction-trace-not-the-token-count-is-the-real-invariant.warrant.json
# Markdown SHA-256:   0b4acf26f3d79be24c58822535396a022e189849ca6c21553b090633de7a2daa
# Code AST SHA-256:   3d1815daf15b02197c9b0c8de022209911bccc3d9fb94e44627a5855d2a9de5d
# Verified Classes:   PlanCriticalEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PlanCriticalEvictionError(RuntimeError):
    """Raised when a preemption would evict a segment with a live inbound
    dependency edge from a resident plan node, severing plan continuity."""
    pass


def select_victim(reclaimable, live_edges, incoming_tokens, budget, resident):
    """
    reclaimable: list of segments, each a dict with 'id', 'tokens', 'priority'
    live_edges:  set of segment ids that are targets of live plan dependency edges
    Returns a victim id, or None if the preemption can be satisfied by spilling.
    Raises PlanCriticalEvictionError if the only arithmetic-valid victims are
    plan-critical and no spill path exists.
    """
    need = resident + incoming_tokens - budget
    if need <= 0:
        return None  # no preemption required

    # Order victims: prefer zero-inbound-edge, largest, lowest priority.
    candidates = sorted(
        reclaimable,
        key=lambda s: (s["id"] in live_edges, -s["tokens"], s["priority"]),
    )

    reclaimed = 0
    chosen = []
    for seg in candidates:
        if seg["id"] in live_edges:
            # Do NOT silently sever a live premise. Stop and escalate.
            raise PlanCriticalEvictionError(
                f"preemption needs {need} tokens but the only remaining "
                f"arithmetic-valid victim '{seg['id']}' carries a live plan "
                f"edge; spill or checkpoint the dependent plan instead"
            )
        chosen.append(seg["id"])
        reclaimed += seg["tokens"]
        if reclaimed >= need:
            return chosen

    raise PlanCriticalEvictionError(
        f"cannot reclaim {need} tokens without evicting a plan-critical "
        f"segment; budget cannot be satisfied safely"
    )
