# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-budget-starvation-when-priority-reallocation-races-concurrent-sub-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-budget-starvation-when-priority-reallocation-races-concurrent-sub-agents.warrant.json
# Markdown SHA-256:   581f17de7313a1e3024b14d992e66dfe2814d6d8e2f1967c2091b63b48aeffea
# Code AST SHA-256:   481880b55fe31d8a090c93c6ca35c3328982d3807b5d2bd4530622d963599ab8
# Verified Classes:   ContextReallocationViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextReallocationViolation(RuntimeError):
    """Raised when priority reallocation mutates an in-flight agent's committed context."""
    pass


def reallocate_budget(agent, requested_tokens, pool, at_turn_boundary):
    if not at_turn_boundary:
        # Reclamation mid-turn is forbidden regardless of priority delta.
        raise ContextReallocationViolation(
            f"agent {agent.id} is mid-turn; cannot reclaim {requested_tokens} tokens. "
            "Defer the requesting agent's next turn instead."
        )

    reclaimed = pool.reclaim(agent.id, requested_tokens)
    # Atomic referential integrity: any evicted region must invalidate
    # every scratchpad/plan/tool-arg reference into it.
    stale_refs = agent.references_into(reclaimed.evicted_regions)
    if stale_refs:
        agent.invalidate_references(stale_refs)
        agent.force_replan(reason="context_truncated")

    # Grounding check must verify content presence, not identifier presence.
    for citation in agent.active_citations():
        if not pool.contains_content(citation.artifact_id):
            raise ContextReallocationViolation(
                f"agent {agent.id} cites {citation.artifact_id} whose content "
                "is no longer in context; identifier-presence check would "
                "have passed and produced a fabricated synthesis."
            )
    return reclaimed
