# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-syscall-level-sandbox-denial-as-a-side-effect-debit-rather-than-a-no-op-and-reconcile-the-budget-ledger-befor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-syscall-level-sandbox-denial-as-a-side-effect-debit-rather-than-a-no-op-and-reconcile-the-budget-ledger-befor.warrant.json
# Markdown SHA-256:   36bf7e8a170e6eb63a25f31c69f33368e9dcb11dc636177c63de03ac478f9ac6
# Code AST SHA-256:   a7ed6adb7d7afed1a4c96c5d207508c1da6369434ccff129e80c0fccba6738db
# Verified Classes:   LedgerDivergenceError, CommitReceipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LedgerDivergenceError(RuntimeError):
    """Raised when the agent's side-effect ledger cannot be reconciled
    against the sandbox's authoritative committed-SEU counter."""
    pass


@dataclass(frozen=True)
class CommitReceipt:
    syscall: str
    admitted: bool
    committed: int          # committed bytes or entries; 0 if denied
    requested: int


def reconcile_call(
    local_ledger: int,
    budget: int,
    receipt: Optional[CommitReceipt],
    errno: int,
) -> int:
    """Return the corrected ledger after one tool call.

    Debits iff the syscall reached the sandbox commit hook, using the
    receipt's committed amount -- never the errno and never the request.
    """
    if receipt is None:
        # No receipt: assume worst case (full request committed) and halt.
        raise LedgerDivergenceError(
            f"missing commit receipt for syscall with errno={errno}; "
            f"cannot reconcile ledger at {local_ledger}/{budget}"
        )

    if not receipt.admitted:
        # True policy rejection: no-op against the ledger.
        return local_ledger

    # Admitted: debit committed amount, even when errno != 0.
    new_ledger = local_ledger + receipt.committed
    if new_ledger > budget:
        raise LedgerDivergenceError(
            f"reconciliation overran budget: {new_ledger} > {budget} "
            f"after {receipt.syscall} (committed={receipt.committed})"
        )
    return new_ledger


def resume_from_checkpoint(
    serialized_ledger: int,
    sandbox_committed: int,
    budget: int,
) -> int:
    """Cold-start resume: the sandbox counter is authoritative."""
    if sandbox_committed < serialized_ledger:
        raise LedgerDivergenceError(
            f"sandbox counter {sandbox_committed} is behind serialized "
            f"ledger {serialized_ledger}; checkpoint is corrupt"
        )
    if sandbox_committed > budget:
        raise LedgerDivergenceError(
            f"sandbox already at {sandbox_committed}/{budget} on resume; "
            f"no mutating budget remains"
        )
    return sandbox_committed
