# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-shared-memory-write-when-its-local-differential-privacy-budget-is-exhausted-but-the-peer-s-attestation-claims-a-fresh.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-shared-memory-write-when-its-local-differential-privacy-budget-is-exhausted-but-the-peer-s-attestation-claims-a-fresh.warrant.json
# Markdown SHA-256:   b6523c1e270e020418566aec1d64ade82fceabd30c69a7812881f9e9de990364
# Code AST SHA-256:   cc10637d180f72caa8be7d2ad9446315fdb6c23c1a1291a81f104ab76b6cace6
# Verified Classes:   BudgetBoundaryViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BudgetBoundaryViolation(RuntimeError):
    """Raised when a federated memory write would breach the receiver's local DP ledger."""
    pass


def admit_batch(receiver_ledger, tenant, batch, epsilon_max, confirmed_epochs):
    """
    receiver_ledger: dict tenant -> (epoch, eps_spent, delta_spent)
    batch: list of writes, each with .cost and .sender_epoch and .sender_remaining_eps
    confirmed_epochs: set of epochs the receiver has independently observed for this tenant
    """
    epoch, eps_spent, _ = receiver_ledger.get(tenant, (0, 0.0, 0.0))
    total_cost = sum(w.cost for w in batch)

    # Rule 1: local exhaustion is authoritative and overrides any peer attestation.
    if eps_spent + total_cost > epsilon_max:
        raise BudgetBoundaryViolation(
            f"tenant={tenant} local eps_spent={eps_spent} + batch={total_cost} "
            f"exceeds eps_max={epsilon_max}; peer remaining_eps is not authority"
        )

    # Rule 2: unconfirmed epoch advance is treated as replay/desync, not as a reset.
    sender_epoch = batch[0].sender_epoch
    if sender_epoch > epoch and sender_epoch not in confirmed_epochs:
        raise BudgetBoundaryViolation(
            f"tenant={tenant} sender_epoch={sender_epoch} > local_epoch={epoch} "
            f"and rotation not independently confirmed; refusing unverified reset"
        )

    # Rule 3: stale attestation describes a superseded ledger.
    if sender_epoch < epoch:
        raise BudgetBoundaryViolation(
            f"tenant={tenant} sender_epoch={sender_epoch} < local_epoch={epoch}; "
            f"attestation is stale"
        )

    # Atomic admission: all or nothing. A prefix admission desynchronizes the pool.
    receiver_ledger[tenant] = (epoch, eps_spent + total_cost, _)
    return True
