# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-terminal-a2a-task-after-a-lost-webhook-ack-the-completed-working-resurrection-and-the-idempotency-key-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-terminal-a2a-task-after-a-lost-webhook-ack-the-completed-working-resurrection-and-the-idempotency-key-collapse.warrant.json
# Markdown SHA-256:   e762b6f259935ba8df7d3827739d4e735ecf5093b4cec02767a11f28f3a0f709
# Code AST SHA-256:   13eab7a0f4291d4d5b57fa0257ffac4acb13f675cd7de571fd6b5ff81e88d9ec
# Verified Classes:   StatusRegressionError, StatusLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

TaskState = Literal["submitted", "working", "completed", "failed", "canceled"]
TERMINAL = frozenset({"completed", "failed", "canceled"})


class StatusRegressionError(RuntimeError):
    """Raised when a notification would move a task's state backward or
    sideways in time. This is a protocol violation or a stale-outbox
    redelivery; it must be surfaced, never silently dropped."""


@dataclass
class StatusLedger:
    task_id: str
    state: TaskState
    timestamp: int
    notification_id: str
    _history: list[tuple[TaskState, int, str]] = field(default_factory=list)

    def apply(self, incoming_state: TaskState, incoming_ts: int,
              notification_id: str) -> None:
        # Absorbing terminal states under the timestamp guard.
        if self.state in TERMINAL and incoming_ts <= self.timestamp:
            # Stale redelivery of a pre-terminal outbox entry.
            raise StatusRegressionError(
                f"task {self.task_id}: terminal {self.state}@{self.timestamp} "
                f"would be resurrected by {incoming_state}@{incoming_ts} "
                f"(notification {notification_id})"
            )

        if incoming_ts < self.timestamp:
            raise StatusRegressionError(
                f"task {self.task_id}: timestamp inversion "
                f"{incoming_ts} < {self.timestamp} "
                f"({incoming_state} after {self.state})"
            )

        if incoming_ts == self.timestamp:
            if incoming_state != self.state:
                # Coarse-clock collision: two states, one timestamp.
                # Fail closed; do not pick a winner.
                raise StatusRegressionError(
                    f"task {self.task_id}: equal-timestamp divergent state "
                    f"{self.state} vs {incoming_state} at t={incoming_ts}; "
                    f"quarantine required"
                )
            return  # idempotent no-op, safe to ACK

        self._history.append((self.state, self.timestamp, self.notification_id))
        self.state = incoming_state
        self.timestamp = incoming_ts
        self.notification_id = notification_id


def handle_webhook(ledger: StatusLedger, payload: dict) -> int:
    status = payload["status"]
    try:
        ledger.apply(status["state"], status["timestamp"], payload["id"])
    except StatusRegressionError:
        # Must return non-2xx so the server's outbox does not mark the
        # stale entry as drained, and must alert. Do not swallow.
        raise
    return 200
