# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-expands-a-compaction-anchor-whose-summarization-budget-was-silently-reassigned.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-expands-a-compaction-anchor-whose-summarization-budget-was-silently-reassigned.warrant.json
# Markdown SHA-256:   f23a6b9edb6ede05da25fe514455d0fc931d09258497f75716b53b81f5a3ea8d
# Code AST SHA-256:   6f2732a263f0a713734ac4ed92d0164b185c447a81fe4e397eca376d5c7fdf09
# Verified Classes:   AnchorInsolvencyError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AnchorInsolvencyError(RuntimeError):
    """Raised when a re-expansion anchor's backed budget is less than its declared budget."""

def reexpand_anchor(anchor, global_residual, evictable_context):
    declared = anchor.declared_budget
    backed = min(global_residual, anchor.backed_budget)

    if backed < declared:
        shortfall = declared - backed
        if evictable_context.available >= shortfall:
            evictable_context.evict(shortfall)
            backed = declared
        else:
            raise AnchorInsolvencyError(
                f"anchor {anchor.span_id} declared {declared} tokens but only "
                f"{backed} are backed (shortfall {shortfall}); refusing to "
                f"truncate-and-continue, which would corrupt downstream tool args"
            )

    return anchor.span.slice(tokens=backed)


def dereference(anchor, global_residual, evictable_context):
    try:
        return reexpand_anchor(anchor, global_residual, evictable_context)
    except AnchorInsolvencyError as e:
        # Propagate as a CONTEXT error, not a tool error, so the reasoning
        # loop can branch on it instead of retrying the tool call.
        raise AnchorInsolvencyError(
            f"context-layer failure, not tool failure: {e}"
        ) from e
