# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-release-escrow-it-cannot-independently-re-verify-the-metered-delivery-attestation-gap-in-agent-to-agent-settlement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-release-escrow-it-cannot-independently-re-verify-the-metered-delivery-attestation-gap-in-agent-to-agent-settlement.warrant.json
# Markdown SHA-256:   934b44d4389d38b149938be2d01b8b880f2af560c0c08e2c94e419e83cb4d528
# Code AST SHA-256:   c02284ca991bb38e0776733a582611edc16e89b635bdf85b54d2ecab79f755cf
# Verified Classes:   AttestationGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AttestationGapError(RuntimeError):
    """Raised when escrow release would be authorized by a valid signature
    over a quantity the payer cannot independently verify."""
    pass


def release_escrow(
    attestation,
    shadow_meter_tokens,
    oracle_contract_class,
    escrow_terms,
    epsilon=0.05,
):
    # Step 1: cryptographic authentication (necessary, not sufficient).
    if not attestation.verify():
        raise AttestationGapError("attestation signature invalid; refuse release")

    q_attested = attestation.quantity

    # Step 2: independent verification path.
    shadow_ok = (
        shadow_meter_tokens is not None
        and shadow_meter_tokens >= q_attested * (1 - epsilon)
    )
    measurement_ok = oracle_contract_class == "measurement"
    priced_risk = escrow_terms.get("pricing_model") == "attestation_only"

    if shadow_ok or measurement_ok or priced_risk:
        return {"action": "release", "quantity": q_attested}

    # Step 3: we are in the Metered-Delivery Attestation Gap.
    # Signatures are honest; the quantity is unverifiable by the payer.
    raise AttestationGapError(
        "valid attestation but no independent measurement path: "
        f"q_attested={q_attested}, shadow={shadow_meter_tokens}, "
        f"oracle={oracle_contract_class}. Refuse release; "
        "escalate to dispute with shadow-meter bound and oracle class."
    )
