# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-escrow-release-atomicity-when-an-sla-bound-delegation-contract-is-renegotiated-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-escrow-release-atomicity-when-an-sla-bound-delegation-contract-is-renegotiated-mid-flight.warrant.json
# Markdown SHA-256:   c572fd616fa099fa0a68b72e6e1f08f6969fbbb941259278b76d1e7e6f2691cd
# Code AST SHA-256:   3b904d9ac771671df72ac637396a9bac3d27bb3fe5f6b3a88a9da47e730184c7
# Verified Classes:   EscrowContractSkewError, Contract, Attestation, EscrowLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Optional


class EscrowContractSkewError(RuntimeError):
    """Raised when an escrow release is evaluated against a contract version
    that is not the one the completion attestation was signed under, or when
    an amendment breaks contract lineage monotonicity."""
    pass


@dataclass(frozen=True)
class Contract:
    hash: str
    amends: Optional[str]          # parent hash, None for genesis
    deadline_s: int
    min_valid_ratio: float


@dataclass(frozen=True)
class Attestation:
    task_id: str
    contract_hash: str             # pinned at signing time
    valid_ratio: float
    signature: str


class EscrowLedger:
    def __init__(self) -> None:
        self._contracts: Dict[str, Contract] = {}
        self._active_hash: Dict[str, str] = {}   # task_id -> current hash
        self._lineage: Dict[str, set] = {}       # task_id -> set of valid hashes

    def open(self, task_id: str, contract: Contract) -> None:
        self._contracts[contract.hash] = contract
        self._active_hash[task_id] = contract.hash
        self._lineage[task_id] = {contract.hash}

    def amend(self, task_id: str, amendment: Contract) -> None:
        current = self._active_hash.get(task_id)
        if current is None:
            raise EscrowContractSkewError(f"no open contract for task {task_id}")
        # Lineage monotonicity: amendment must reference the active hash.
        if amendment.amends != current:
            raise EscrowContractSkewError(
                f"amendment {amendment.hash} amends {amendment.amends!r} "
                f"but active is {current!r}; refusing to fork lineage"
            )
        # Atomic: register contract AND extend lineage AND flip active pointer
        # in one logical step so the release oracle can resolve either version.
        self._contracts[amendment.hash] = amendment
        self._lineage[task_id].add(amendment.hash)
        self._active_hash[task_id] = amendment.hash

    def release(self, task_id: str, att: Attestation) -> bool:
        # Release is a pure function of the attestation's pinned hash.
        if att.contract_hash not in self._lineage.get(task_id, set()):
            raise EscrowContractSkewError(
                f"attestation pins {att.contract_hash} which is not in the "
                f"active lineage for task {task_id}; possible stale or "
                f"forged contract reference"
            )
        contract = self._contracts[att.contract_hash]
        if att.valid_ratio < contract.min_valid_ratio:
            return False
        return True


# Demonstration of the failure the guardrail prevents:
# worker completes under C2 (96.2% valid, threshold 95%), but a naive
# oracle keyed to C1 (threshold 98%) would reject. With attestation-pinned
# release, the attestation names C2 and the oracle resolves C2.
if __name__ == "__main__":
    ledger = EscrowLedger()
    c1 = Contract("0x..c1", None, 900, 0.98)
    ledger.open("task-7", c1)
    c2 = Contract("0x..c2", "0x..c1", 1500, 0.95)
    ledger.amend("task-7", c2)
    att = Attestation("task-7", "0x..c2", 0.962, "sig")
    assert ledger.release("task-7", att) is True

    stale = Attestation("task-7", "0x..c1", 0.962, "sig")
    # 96.2% < 98%: correctly rejected under the version it names.
    assert ledger.release("task-7", stale) is False

    forged = Attestation("task-7", "0x..c9", 0.999, "sig")
    try:
        ledger.release("task-7", forged)
    except EscrowContractSkewError as e:
        print(f"blocked: {e}")
