# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-silently-collapsing-reasoning-fidelity-under-retrieval-freshness-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-silently-collapsing-reasoning-fidelity-under-retrieval-freshness-pressure.warrant.json
# Markdown SHA-256:   3a0485f8d3024bc17cfab0c4ebf970671d53176f73baf320b876450ce5a070f5
# Code AST SHA-256:   2c37a26835b5a6db13bd9e1516fff9e121f52425c0e39596a09eda6bb76ca9d5
# Verified Classes:   PremisePersistenceViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PremisePersistenceViolation(RuntimeError):
    """Raised when a compaction would evict a span still cited by a pending step."""
    pass


class Span:
    def __init__(self, span_id, tokens, tags, cited_by_pending):
        self.span_id = span_id
        self.tokens = tokens
        self.tags = tags
        self.cited_by_pending = cited_by_pending  # set of step ids


def commit_compaction(arbiter_state, span, pending_steps):
    """
    Arbiter commit path. Must refuse any compaction that breaks premise persistence,
    regardless of token pressure. Token-neutral trades are not fidelity-neutral.
    """
    if span.tags.get("premise") or span.tags.get("constraint"):
        raise PremisePersistenceViolation(
            f"refusing to compact pinned span {span.span_id} (tags={span.tags})"
        )

    live_citations = span.cited_by_pending & pending_steps
    if live_citations:
        raise PremisePersistenceViolation(
            f"span {span.span_id} is cited by pending steps {sorted(live_citations)}; "
            f"compaction would strip its inferential role, not just its content"
        )

    # Only reachable when no pending step depends on this span's role.
    arbiter_state.compacted.append(span.span_id)
    arbiter_state.tokens_freed += span.tokens
    return arbiter_state


def arbitrate_step(arbiter_state, retrieval_request, pending_steps):
    """
    Wrap retrieval behind the premise-persistence check. A retrieval that cannot be
    paid for without violating the invariant must be deferred or escalated, never
    silently funded by compacting a cited span.
    """
    projected = arbiter_state.tokens_used + retrieval_request.tokens
    if projected <= arbiter_state.soft_target:
        arbiter_state.tokens_used = projected
        return "retrieved"

    eviction_candidates = arbiter_state.oldest_non_pinned()
    for span in eviction_candidates:
        try:
            commit_compaction(arbiter_state, span, pending_steps)
            arbiter_state.tokens_used += retrieval_request.tokens
            return "retrieved_after_compaction"
        except PremisePersistenceViolation:
            continue

    raise PremisePersistenceViolation(
        f"retrieval of {retrieval_request.tokens} tokens would exceed soft target "
        f"({arbiter_state.soft_target}) and every eviction candidate is cited by a "
        f"pending step; defer retrieval or escalate to hard-ceiling policy"
    )
