# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-bid-escrow-double-spend-when-subcontracting-agents-renegotiate-after-a-capability-revocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-bid-escrow-double-spend-when-subcontracting-agents-renegotiate-after-a-capability-revocation.warrant.json
# Markdown SHA-256:   34b41c1f5352337a1c0ba585f3c51a926a293f6097cbf88514a1a5ca59849152
# Code AST SHA-256:   28def94c156696dc91cc23bd3e6fcbe81a72c708a80b307c6f6f329656814ef4
# Verified Classes:   EscrowDoubleSpendError, EscrowLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EscrowDoubleSpendError(RuntimeError):
    """Raised when a re-auction would create a second live escrow for a task_ref
    whose prior escrow was superseded (not released) after a capability epoch advance."""
    pass


class EscrowLedger:
    def __init__(self, ceiling: int):
        self.ceiling = ceiling
        self.live = {}          # task_ref -> escrow dict
        self.released = []      # audit trail
        self.committed = 0

    def release_stale(self, task_ref: str, observed_epoch: int) -> None:
        esc = self.live.get(task_ref)
        if esc is None:
            return
        # compare-and-release: only release if the worker's epoch has advanced
        if esc["worker_epoch"] < observed_epoch:
            self.committed -= esc["amount"]
            self.released.append({**esc, "state": "RELEASED",
                                  "reason": "capability_epoch_advanced"})
            del self.live[task_ref]

    def open_escrow(self, task_ref: str, worker_id: str,
                    amount: int, worker_epoch: int) -> None:
        # invariant: at most one live escrow per task_ref
        if task_ref in self.live:
            prior = self.live[task_ref]
            raise EscrowDoubleSpendError(
                f"task_ref={task_ref} already has live escrow "
                f"{prior['amount']}u held by {prior['worker_id']} "
                f"(epoch={prior['worker_epoch']}); refusing to open "
                f"{amount}u for {worker_id} (epoch={worker_epoch}). "
                f"Release the prior escrow before re-auctioning."
            )
        if self.committed + amount > self.ceiling:
            raise EscrowDoubleSpendError(
                f"escrow {amount}u would exceed ceiling "
                f"({self.committed}+{amount}>{self.ceiling})"
            )
        self.live[task_ref] = {
            "task_ref": task_ref, "worker_id": worker_id,
            "amount": amount, "worker_epoch": worker_epoch,
            "state": "AWARDED",
        }
        self.committed += amount


def reauction_after_invalidate(ledger: EscrowLedger, task_ref: str,
                               new_worker: str, new_amount: int,
                               new_epoch: int, observed_epoch: int) -> None:
    # a BID_INVALIDATE arrived; the correct order is release-then-open,
    # never supersede-then-open
    ledger.release_stale(task_ref, observed_epoch)
    if task_ref in ledger.live:
        raise EscrowDoubleSpendError(
            f"re-auction for {task_ref} attempted while prior escrow still live; "
            f"revocation subscription may be missing for the escrowed worker"
        )
    ledger.open_escrow(task_ref, new_worker, new_amount, new_epoch)
