# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-negotiation-deadlock-in-agent-to-agent-sla-escrow-contracts-before-settlement-finality.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-negotiation-deadlock-in-agent-to-agent-sla-escrow-contracts-before-settlement-finality.warrant.json
# Markdown SHA-256:   6315da48490da1d46f4506d197d2e072636e3982ede47fd885f1d4a5aab60d2b
# Code AST SHA-256:   bad9b7e5566ebd2b9363d5e99fcdfda4aa98d8630d567928044646b56df23752
# Verified Classes:   EscrowLivenessViolation, Turn
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EscrowLivenessViolation(RuntimeError):
    """Raised when a negotiation acceptance would settle against an unattested reservation."""


@dataclass
class Turn:
    turn: int
    offer_price: float
    offer_latency_ms: int
    attested_reservation: Optional[float]  # signed at turn 0, None if compacted away


def validate_settlement(
    turns: list[Turn],
    accepted_price: float,
    opening_reservation: float,
    concession_quantum: float = 1.5,
    stall_threshold: int = 3,
) -> None:
    """
    Enforce the escrow-finality invariant: settlement is valid only if the
    accepted offer is consistent with the opening attested reservation, and
    the negotiation did not pass through a liveness stall that preceded a
    context-compaction event.
    """
    if not turns:
        raise EscrowLivenessViolation("empty negotiation history; cannot attest finality")

    # Detect concession collapse: consecutive turns with sub-quantum delta.
    zero_delta_run = 0
    stall_turn: Optional[int] = None
    for prev, cur in zip(turns, turns[1:]):
        delta = abs(cur.offer_price - prev.offer_price)
        if delta < concession_quantum:
            zero_delta_run += 1
            if zero_delta_run >= stall_threshold and stall_turn is None:
                stall_turn = cur.turn
        else:
            zero_delta_run = 0

    # Detect compaction: any turn after opening whose attestation went null.
    compaction_turn = next(
        (t.turn for t in turns[1:] if t.attested_reservation is None), None
    )

    if stall_turn is not None and compaction_turn is not None and compaction_turn > stall_turn:
        raise EscrowLivenessViolation(
            f"liveness stall at turn {stall_turn} followed by context compaction at "
            f"turn {compaction_turn}; settlement at {accepted_price} cannot be "
            f"attested against opening reservation {opening_reservation}"
        )

    if abs(accepted_price - opening_reservation) > concession_quantum:
        raise EscrowLivenessViolation(
            f"accepted price {accepted_price} diverges from attested opening "
            f"reservation {opening_reservation} by more than concession quantum "
            f"{concession_quantum}; reservation was likely rewritten during compaction"
        )


def settle(
    turns: list[Turn],
    accepted_price: float,
    opening_reservation: float,
) -> str:
    validate_settlement(turns, accepted_price, opening_reservation)
    return f"SETTLED at {accepted_price}, attested against {opening_reservation}"
