# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-token-budget-eviction-as-a-lossy-checkpoint-rather-than-a-cache-miss.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-token-budget-eviction-as-a-lossy-checkpoint-rather-than-a-cache-miss.warrant.json
# Markdown SHA-256:   b1003c03e7c6d3fba42cecf3dd0f0e52b6ee27de241ca9e06927c45e630d3d38
# Code AST SHA-256:   b609b921e24393bef38cc69b7a612b98d3b597ff5102df5291d27a58a9dc3ec2
# Verified Classes:   NonDerivableEvictionError, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class NonDerivableEvictionError(RuntimeError):
    """Raised when a scheduler attempts to evict a non-derivable segment
    without externalizing it and leaving a tombstone. This is the exact
    condition under which silent re-derivation corrupts commitments."""
    pass


class Segment:
    def __init__(self, seg_id, tokens, derivable, content):
        self.seg_id = seg_id
        self.tokens = tokens
        self.derivable = derivable      # tag set at insertion, never inferred
        self.content = content
        self.externalized = False


def evict_to_budget(segments, budget, durable_store, tombstones):
    """Evict lowest-priority segments until total tokens <= budget.
    Segments are pre-sorted ascending by priority score by the caller.
    Non-derivable segments MUST be externalized before removal; if the
    durable store cannot accept them, we halt rather than lose them."""
    total = sum(s.tokens for s in segments)
    survivors = list(segments)
    for seg in segments:                # ascending priority
        if total <= budget:
            break
        if not seg.derivable:
            try:
                durable_store.put(seg.seg_id, seg.content)
            except Exception as exc:
                # Cannot externalize -> must not silently evict.
                raise NonDerivableEvictionError(
                    f"cannot externalize non-derivable segment {seg.seg_id!r} "
                    f"under budget pressure; halting to prevent lossy checkpoint"
                ) from exc
            seg.externalized = True
            tombstones[seg.seg_id] = "PRESENT_BUT_EXTERNALIZED"
        survivors.remove(seg)
        total -= seg.tokens
    if total > budget:
        raise NonDerivableEvictionError(
            f"budget {budget} unreachable without evicting protected segments; "
            f"remaining non-derivable tokens={total}"
        )
    return survivors


def lookup_commitment(seg_id, tombstones, durable_store):
    """Returns the externalized commitment or raises on false-negative."""
    state = tombstones.get(seg_id)
    if state == "PRESENT_BUT_EXTERNALIZED":
        return durable_store.get(seg_id)
    if state is None:
        # Absent tombstone is ambiguous: could be never-created OR lost.
        # We refuse to treat this as 'no prior decision' silently.
        raise NonDerivableEvictionError(
            f"lookup for {seg_id!r} found no tombstone; refusing to "
            f"re-derive a commitment that may have been evicted silently"
        )
    return None
