# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-budget-allocators-from-silently-evicting-tool-schemas-mid-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-budget-allocators-from-silently-evicting-tool-schemas-mid-reasoning-loop.warrant.json
# Markdown SHA-256:   e3c12be9b6603696e6b688aaa820fde629ca7076b6292d99653ea9cc6e4c8575
# Code AST SHA-256:   9f7b69bdfc328b2f02344f95fd92aa18f8ed3af64e4246b185e5ecb6c3e1e2f4
# Verified Classes:   SchemaEvictionSubstitutionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaEvictionSubstitutionError(RuntimeError):
    """Raised when an emitted tool call does not match the plan node's declared tool."""
    pass


def reconcile_step(plan_node: dict, emitted_call: dict, live_schema_names: set[str]) -> None:
    declared = plan_node.get("declared_tools", [])
    invoked = emitted_call.get("tool_name")

    # Invariant 1: the invoked tool must be one the plan declared for this node.
    if invoked not in declared:
        raise SchemaEvictionSubstitutionError(
            f"step {plan_node.get('step')}: invoked {invoked!r} but plan declared {declared!r}; "
            f"live schemas were {sorted(live_schema_names)} — likely budget-allocator eviction"
        )

    # Invariant 2: the declared tool must still be present in context.
    if invoked not in live_schema_names:
        raise SchemaEvictionSubstitutionError(
            f"step {plan_node.get('step')}: declared tool {invoked!r} was evicted from context; "
            f"allocator violated plan-pin invariant"
        )


def allocate_budget(plan: list[dict], live_schemas: set[str], memory_chunks: list[str],
                    system_prompt_tokens: int, budget: int) -> dict:
    # Compute the pin set: every schema referenced by an unretired plan node,
    # including both branches of unresolved conditionals.
    pinned: set[str] = set()
    for node in plan:
        if node.get("retired"):
            continue
        pinned.update(node.get("declared_tools", []))

    if not pinned and any(not n.get("retired") for n in plan):
        # Plan exists but declares no tools — allocator cannot compute a safe pin set
        # for a tool-using loop. Refuse to evict schemas.
        raise SchemaEvictionSubstitutionError(
            "plan present but tool references unenumerable; "
            "schema pool must be treated as a fixed floor"
        )

    evictable_schemas = live_schemas - pinned
    # Only memory and unreferenced schemas may be evicted; pinned schemas are floor.
    return {
        "pinned_schemas": sorted(pinned),
        "evictable_schemas": sorted(evictable_schemas),
        "evictable_memory": memory_chunks,
        "system_prompt_tokens": system_prompt_tokens,
        "budget": budget,
    }
