# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-arbitrate-between-context-compaction-and-re-retrieval-before-the-token-ceiling-is-breached-and-what-invariant-preve.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-arbitrate-between-context-compaction-and-re-retrieval-before-the-token-ceiling-is-breached-and-what-invariant-preve.warrant.json
# Markdown SHA-256:   337fc7b71f6ac8e20757fe832eedbd6abb11579084af8814e35bf44d3ebfee9a
# Code AST SHA-256:   eb8a4fd51da52010f040f44e38e7bec1c26f5bb8c56a1c06771ee005a9626482
# Verified Classes:   RecallCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RecallCollapseError(RuntimeError):
    """Raised when compaction would foreclose an affordable retrieval,
    or when a summary is used as ground truth for a fact it lost."""
    pass


def arbitrate_context(
    remaining_budget: int,
    compaction_cost: int,
    retrieval_cost: int,
    finest_fact_cost: int,
    span_provably_unneeded: bool = False,
) -> str:
    """Decide whether to compact, retrieve, or halt at a budget boundary.

    Returns one of: 'compact', 'retrieve_now', 'compact_other', 'halt'.
    Raises RecallCollapseError if the caller attempts an unsafe compaction.
    """
    if span_provably_unneeded:
        return "compact"

    reserve = retrieval_cost + finest_fact_cost
    band_lo = compaction_cost
    band_hi = compaction_cost + reserve

    if remaining_budget >= band_hi:
        return "compact"

    if band_lo < remaining_budget < band_hi:
        # Danger band: compaction affordable, retrieval not (after compaction).
        # Forbid compacting this span; retrieve now or compact elsewhere.
        if remaining_budget >= retrieval_cost + finest_fact_cost:
            return "retrieve_now"
        return "compact_other"

    if remaining_budget <= band_lo:
        return "halt"

    raise RecallCollapseError(
        f"unreachable arbitration state: R={remaining_budget} "
        f"C={compaction_cost} Q={retrieval_cost} F={finest_fact_cost}"
    )


def compact_span(span_tokens: int, remaining_budget: int, **kwargs) -> str:
    decision = arbitrate_context(remaining_budget=remaining_budget, **kwargs)
    if decision == "halt":
        raise RecallCollapseError(
            "context exhausted: compaction and retrieval both unaffordable; "
            "emit ContextExhausted rather than truncate silently"
        )
    if decision == "retrieve_now":
        raise RecallCollapseError(
            "compaction forbidden in danger band: retrieve the raw fact now "
            "while it is still affordable, then pin it"
        )
    if decision == "compact_other":
        raise RecallCollapseError(
            "compaction of this span forecloses retrieval; select a "
            "provably-unneeded span instead"
        )
    return "compacted"
