# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-quorum-of-committed-agents-from-double-spending-a-shared-tool-budget-under-byzantine-partial-views.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-quorum-of-committed-agents-from-double-spending-a-shared-tool-budget-under-byzantine-partial-views.warrant.json
# Markdown SHA-256:   80bf63a169f7fe0e94e0648e3a231b094ce9c08b57c66bf00226ef3314e3760d
# Code AST SHA-256:   e803dd4197c6b7ca9912ca9b06a34fd586319f8fbfc6aea66d00344a9e3370f6
# Verified Classes:   BudgetConservationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class BudgetConservationError(RuntimeError):
    pass


def sign_commitment(proposal, local_root, last_signed_root, budget, committed):
    # Invariant 1: monotonic root chaining. Reject stale or forked roots.
    if not is_descendant(local_root, last_signed_root):
        raise BudgetConservationError(
            f"stale root: proposal root {local_root} is not a descendant "
            f"of last-signed root {last_signed_root}; refusing to sign "
            f"across a gossip partition"
        )

    # Invariant 2: conserved quantity. The proposal must fit within the
    # budget as attested by the *local* root, including pending commitments.
    projected = committed[local_root] + proposal.spend
    if projected > budget:
        raise BudgetConservationError(
            f"over-commit: projected {projected} exceeds budget {budget} "
            f"at root {local_root}; certificate would double-spend"
        )

    # Invariant 3: the certificate must embed the root so downstream
    # signers can chain and re-check the arithmetic.
    return sign(proposal.with_root(local_root), projected)
