# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-escrow-release-divergence-when-a-counterparty-agent-renegotiates-sla-mid-transaction-under-a-stale-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-escrow-release-divergence-when-a-counterparty-agent-renegotiates-sla-mid-transaction-under-a-stale-warrant.warrant.json
# Markdown SHA-256:   246e7dc35972f9de02f1687841d294334bf90f6d24e178366f84c52d8a9edc3b
# Code AST SHA-256:   e1ec512149f0fb215fdd8537b92f479b9df35bc6209e5dad3c86d1afeca97423
# Verified Classes:   EscrowWarrantDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EscrowWarrantDivergence(RuntimeError):
    pass

def apply_sla_amendment(escrow_state, amendment, cached_warrant, refetch_warrant):
    # amendment: dict with 'terms', 'warrant_epoch', 'signer', 'counter_sigs'
    # cached_warrant: dict with 'epoch', 'key'
    if amendment["warrant_epoch"] != cached_warrant["epoch"]:
        fresh = refetch_warrant(amendment["signer"])
        if fresh is None or fresh["epoch"] != amendment["warrant_epoch"]:
            raise EscrowWarrantDivergence(
                f"amendment epoch {amendment['warrant_epoch']} does not match "
                f"cached {cached_warrant['epoch']} and refetch failed"
            )
        cached_warrant = fresh

    required = {"buyer", "seller"}
    if not required.issubset(set(amendment["counter_sigs"].keys())):
        raise EscrowWarrantDivergence(
            "amendment lacks bilateral counter-signature; "
            "treating as PROPOSED, not applied"
        )

    # atomic tuple update: terms + epoch + signatures move together
    escrow_state["bound_terms"] = {
        "terms": amendment["terms"],
        "warrant_epoch": amendment["warrant_epoch"],
        "counter_sigs": amendment["counter_sigs"],
    }
    return escrow_state

def release(escrow_state, current_warrant):
    bound = escrow_state.get("bound_terms")
    if bound is None:
        raise EscrowWarrantDivergence("no bound terms; release refused")
    if bound["warrant_epoch"] != current_warrant["epoch"]:
        raise EscrowWarrantDivergence(
            f"release epoch {current_warrant['epoch']} != bound epoch "
            f"{bound['warrant_epoch']}; escrow terms may be stale"
        )
    return bound["terms"]
