# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-mid-episode-and-the-token-budget-is-charged-against-the-wrong-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-policy-mid-episode-and-the-token-budget-is-charged-against-the-wrong-ledger.warrant.json
# Markdown SHA-256:   729c64b80d208c6ea2a58d27e75ccfca6b518f53c74456344bbb7d25e5092d2f
# Code AST SHA-256:   c00eefba3bf208d9080694f07a8f210014dc9361314deada14be3c9f47dea128
# Verified Classes:   PolicyCommitUnfundedError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicyCommitUnfundedError(RuntimeError):
    """Raised when a self-authored context policy is committed without a
    matching execution reservation against the shared budget ledger."""
    pass


def commit_context_policy(
    policy: dict,
    declared_exec_cost: int,
    authoring_spent: int,
    budget_remaining: int,
) -> int:
    """
    Reserve-before-commit guard for model-authored context policies.

    Invariant: a policy may not become canonical unless the ledger can fund
    BOTH the authoring already spent AND the declared execution cost, in one
    atomic step. Returns the reserved execution allowance on success.
    """
    if declared_exec_cost <= 0:
        raise PolicyCommitUnfundedError(
            f"policy declares non-positive execution cost {declared_exec_cost}; "
            "refusing to commit an unpriceable rewrite"
        )

    total_required = authoring_spent + declared_exec_cost
    if total_required > budget_remaining:
        raise PolicyCommitUnfundedError(
            f"policy commit rejected: authoring={authoring_spent} + "
            f"execution_reservation={declared_exec_cost} = {total_required} "
            f"exceeds remaining budget {budget_remaining}. "
            "Author a cheaper policy; do not commit an unfunded rewrite."
        )

    # Atomic: reservation is deducted at commit, not deferred to execution.
    reserved = declared_exec_cost
    policy["state"] = "committed"
    policy["execution_reservation"] = reserved
    return reserved


def execute_policy(policy: dict, reserved: int, actual_exec_cost: int) -> None:
    """Execute under the reservation; truncation is a hard rollback, not a
    silent partial commit."""
    if actual_exec_cost > reserved:
        policy["state"] = "rolled_back"
        raise PolicyCommitUnfundedError(
            f"execution cost {actual_exec_cost} exceeded reservation {reserved}; "
            "policy rolled back to prior committed version to prevent "
            "evict-before-summarize corruption"
        )
    policy["state"] = "executed"
