# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-marginal-retrieval-to-preserve-reserve-token-solvency.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-marginal-retrieval-to-preserve-reserve-token-solvency.warrant.json
# Markdown SHA-256:   360bee929a7141fcbae966eed2d17d8ff15201a60879739949f339c6413e14e0
# Code AST SHA-256:   bd5ed7c11f109bd718119793167763b4141269c5a5156a425c74588daf697b90
# Verified Classes:   ReserveInsolvencyError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ReserveInsolvencyError(RuntimeError):
    """Raised when a retrieval admission would breach the reserve floor."""
    pass


def admit_retrieval(
    cost: int,
    budget_remaining: int,
    remaining_tool_calls: int,
    tool_call_cost_estimate: int,
    synthesis_estimate: int,
    safety_margin: int = 512,
) -> bool:
    reserve_floor = (
        remaining_tool_calls * tool_call_cost_estimate
        + synthesis_estimate
        + safety_margin
    )
    if budget_remaining <= reserve_floor:
        # No retrieval is admissible; instance must commit to synthesis.
        if cost > 0:
            raise ReserveInsolvencyError(
                f"budget_remaining={budget_remaining} <= reserve_floor={reserve_floor}; "
                f"refusing retrieval of cost={cost}. Commit to synthesis or signal "
                f"insufficient_budget explicitly."
            )
        return False
    return cost <= budget_remaining - reserve_floor


def schedule_retrieval(candidates, budget_remaining, **kw):
    admitted = []
    for doc in candidates:
        try:
            if admit_retrieval(doc.cost, budget_remaining, **kw):
                admitted.append(doc)
                budget_remaining -= doc.cost
        except ReserveInsolvencyError:
            # Boundary reached: stop retrieving, preserve reserve.
            break
    return admitted, budget_remaining
