# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-escrow-release-deadlock-when-an-agent-s-settlement-warrant-outlives-its-own-dispute-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-escrow-release-deadlock-when-an-agent-s-settlement-warrant-outlives-its-own-dispute-replay-window.warrant.json
# Markdown SHA-256:   48050cdd56049636e39d9b0b2023d1b861b8e07f194d6deb3ee7d1cbc4d28b17
# Code AST SHA-256:   549d81815be8f45522f9f82a1a9d200c486012b2ca87afba3df935c0831240f5
# Verified Classes:   EscrowDeadlockRisk, Warrant, DisputeContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class EscrowDeadlockRisk(RuntimeError):
    """Raised when a warrant/dispute timing configuration cannot settle."""
    pass


@dataclass(frozen=True)
class Warrant:
    escrow_id: str
    task_spec_hash: str
    nonce: str
    issued_at: float
    expiry: float


@dataclass(frozen=True)
class DisputeContext:
    warrant: Warrant
    opened_at: float
    arbiter_max_latency: float
    reissue_margin: float
    has_durable_reissue_state: bool
    has_warrant_independent_release: bool


def assert_settleable(ctx: DisputeContext) -> None:
    """Pre-flight gate. Must pass before arbiter commits replay compute."""
    w = ctx.warrant
    settle_deadline = ctx.opened_at + ctx.arbiter_max_latency

    # Condition 1: warrant must outlive adjudication + reissue margin.
    if settle_deadline + ctx.reissue_margin > w.expiry:
        if not ctx.has_warrant_independent_release:
            raise EscrowDeadlockRisk(
                f"escrow {w.escrow_id}: dispute opened at {ctx.opened_at:.0f} "
                f"cannot settle before warrant expiry {w.expiry:.0f} "
                f"(deadline {settle_deadline:.0f} + margin {ctx.reissue_margin:.0f}); "
                f"no warrant-independent release path -> permanent lock risk"
            )

    # Condition 2: even if timing fits, re-issuance must survive context eviction.
    if not ctx.has_durable_reissue_state and settle_deadline > w.expiry:
        raise EscrowDeadlockRisk(
            f"escrow {w.escrow_id}: re-issuance depends on volatile agent context; "
            f"warrant expired before adjudication completed"
        )


def open_dispute(ctx: DisputeContext) -> str:
    assert_settleable(ctx)  # fail closed, never accept an unsettleable dispute
    return f"dispute_accepted:{ctx.warrant.escrow_id}"
