# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-state-regression-after-a-push-notification-webhook-410-gone.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-state-regression-after-a-push-notification-webhook-410-gone.warrant.json
# Markdown SHA-256:   5e61c53f118cc25468a82102f3285b7d76a439e86057e09013bea65ee3fe73ca
# Code AST SHA-256:   3e08bd97cbf2f18bda423d661eee80ae3318265b6891b1a8802022ace0300abb
# Verified Classes:   A2AStateRegressionError, TaskWatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class A2AStateRegressionError(RuntimeError):
    """Raised when a task's local state machine would accept a terminal
    event without proof that no intermediate events were missed."""


@dataclass
class TaskWatch:
    task_id: str
    config_id: Optional[str]
    last_event_seq: Optional[int]          # None if server provides no sequence
    last_status_ts: float                  # server's status.timestamp, epoch secs
    last_event_recv: float                 # client clock, epoch secs
    local_artifact_chunks: dict = field(default_factory=dict)
    expected_event_interval: float = 60.0
    stall_polls: int = 0


def detect_delivery_death(watch: TaskWatch, now: Optional[float] = None) -> bool:
    """Structural signal: config registered, non-terminal state, but
    status.timestamp has not advanced across two polls."""
    now = now or time.time()
    stale = (now - watch.last_status_ts) > 2 * watch.expected_event_interval
    no_recent_event = (now - watch.last_event_recv) > 2 * watch.expected_event_interval
    return bool(watch.config_id) and stale and no_recent_event


def reconcile_on_reregister(
    watch: TaskWatch,
    snapshot_artifacts: dict,
    incoming_terminal_event: dict,
) -> None:
    """Gate terminal transitions on snapshot-reconcile after re-registration.

    snapshot_artifacts: the `artifacts` array from tasks/get, keyed by chunk id.
    incoming_terminal_event: the event that would move us to completed/failed.
    """
    if incoming_terminal_event.get("state") not in ("completed", "failed", "canceled"):
        return  # non-terminal transitions are always safe to apply

    # If the server supplies a sequence number, we can prove continuity.
    if watch.last_event_seq is not None and "sequence" in incoming_terminal_event:
        if incoming_terminal_event["sequence"] != watch.last_event_seq + 1:
            raise A2AStateRegressionError(
                f"task {watch.task_id}: terminal event seq "
                f"{incoming_terminal_event['sequence']} does not follow "
                f"last seen seq {watch.last_event_seq}; events were missed "
                f"between delivery death and re-registration"
            )
        return

    # No sequence number: fall back to snapshot reconciliation.
    # Any local chunk not present in the snapshot is suspect and must be
    # refetched before we can trust the terminal event.
    suspect = set(watch.local_artifact_chunks) - set(snapshot_artifacts)
    if suspect:
        raise A2AStateRegressionError(
            f"task {watch.task_id}: {len(suspect)} local artifact chunk(s) "
            f"{sorted(suspect)} absent from server snapshot after "
            f"re-registration; terminal event is not proof of continuity. "
            f"Refetch full artifact before accepting completion."
        )

    # Even with no suspect chunks, if we re-registered mid-task we cannot
    # prove we saw every intermediate status transition. Require an
    # explicit snapshot-ack from the server before closing.
    if watch.config_id and watch.stall_polls >= 2:
        raise A2AStateRegressionError(
            f"task {watch.task_id}: terminal event accepted after "
            f"re-registration with no sequence number and no snapshot-ack; "
            f"state regression cannot be ruled out"
        )


def on_webhook_post(watch: TaskWatch, event: dict) -> None:
    """Entry point for a webhook delivery. 410 is handled upstream by the
    receiver; this function only sees events that arrived."""
    watch.last_event_recv = time.time()
    if "sequence" in event:
        watch.last_event_seq = event["sequence"]
    if event.get("state") == "working":
        watch.stall_polls = 0
    reconcile_on_reregister(watch, event.get("snapshot", {}), event)
    # apply transition only after reconcile gate passes
    watch.local_artifact_chunks.update(event.get("artifacts", {}))
