# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-priority-inversion-eviction-from-silently-deleting-the-only-copy-of-an-uncheckpointed-tool-result-during-mid-turn-context-com.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-priority-inversion-eviction-from-silently-deleting-the-only-copy-of-an-uncheckpointed-tool-result-during-mid-turn-context-com.warrant.json
# Markdown SHA-256:   bab4c3b7b4b7631bb7484f081190fca98db5605a6358c455e75d0fc99a187c23
# Code AST SHA-256:   85d582d81363ef6f97fe230ad507d1efa241da0e8d6b4ccb83284adc5387ccf1
# Verified Classes:   UnrecoverableEvictionError, Segment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrecoverableEvictionError(RuntimeError):
    """Raised when compaction attempts to evict a segment with no durable backing copy."""
    pass


class Segment:
    def __init__(self, seg_id, token_len, backing=None, parse_unit="atomic", class_prior=0.0):
        self.seg_id = seg_id
        self.token_len = token_len
        self.backing = backing              # durable pointer or None
        self.parse_unit = parse_unit        # "atomic" | "streamable"
        self.class_prior = class_prior      # expected future reference count
        self.reference_count = 0
        self.pinned = backing is None       # admission gate: pin unrecoverable


def arbitrate(segments, budget, in_flight_tool=False):
    if in_flight_tool:
        # Defer compaction while a tool future is pending; a large segment
        # is about to arrive and the model has minimal context to judge stubs.
        return segments, "deferred: tool future in flight"

    total = sum(s.token_len for s in segments)
    if total <= budget:
        return segments, "under budget"

    # Sort evictable segments by lifecycle-stable priority; pinned segments
    # are excluded from candidacy entirely, not merely down-ranked.
    evictable = [s for s in segments if not s.pinned]
    evictable.sort(key=lambda s: (
        -(s.class_prior + s.reference_count),   # stable prior, not raw count
        s.token_len,                            # smaller first among ties
    ))

    kept, evicted = [], []
    freed = 0
    for s in evictable:
        if total - freed <= budget:
            break
        if s.parse_unit == "atomic" and s.backing is None:
            # Should be unreachable given the pin gate, but fail closed.
            raise UnrecoverableEvictionError(
                f"cannot evict atomic segment {s.seg_id} with no backing copy"
            )
        freed += s.token_len
        evicted.append(s)

    if total - freed > budget:
        # Pinned segments alone exceed budget: surface exhaustion, do not delete.
        raise UnrecoverableEvictionError(
            f"budget {budget} unreachable without evicting pinned segments; "
            f"resident={total}, freed={freed}"
        )

    evicted_ids = {s.seg_id for s in evicted}
    kept = [s for s in segments if s.seg_id not in evicted_ids]
    return kept, f"evicted {len(evicted)} recoverable segments, freed {freed}"
