# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-v1-0-task-whose-taskstate-transition-arrives-via-a-replayed-push-notification-webhook-before-the-synchron.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-v1-0-task-whose-taskstate-transition-arrives-via-a-replayed-push-notification-webhook-before-the-synchron.warrant.json
# Markdown SHA-256:   e891316958e05ab09c0a19bf2fccdd96df7b0085298d1d3f704ab68fc57bb0a9
# Code AST SHA-256:   1918b124167d278a258760981d6cf3902095feab10ea93ef2164ac367345c949
# Verified Classes:   TerminalRegressionError, WebhookTokenMismatch, TaskRecord, TaskReducer
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

import hmac
import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional

TERMINAL_STATES = frozenset({"completed", "failed", "canceled"})
NON_TERMINAL_STATES = frozenset({"submitted", "working", "input-required"})


class TerminalRegressionError(RuntimeError):
    """Raised when a non-terminal observation is applied to a task already
    committed as terminal. This is the A2A push/pull reordering condition:
    a late `tasks/get` response carrying `working` arriving after the
    webhook delivered `completed`. Pollers must catch and discard; the
    dispatcher must not, because it indicates a re-dispatch is imminent."""


class WebhookTokenMismatch(RuntimeError):
    """Raised when a push-notification POST presents a token that does not
    match the registration for the referenced task id, or references a
    task id this client never dispatched. Treat as state-poisoning attempt."""


@dataclass
class TaskRecord:
    task_id: str
    state: str
    timestamp: str
    artifacts: list = field(default_factory=list)
    # Monotone client-side sequence assigned at commit time.
    commit_seq: int = 0


class TaskReducer:
    """Single writer for A2A task records. Both the `tasks/get` poll handler
    and the push-notification webhook handler MUST route through `apply`.
    Enforces terminal absorption and idempotent webhook replay."""

    def __init__(self) -> None:
        self._records: dict[str, TaskRecord] = {}
        self._registrations: dict[str, str] = {}  # task_id -> webhook token
        self._seq = 0
        self._lock = threading.Lock()

    def register_webhook(self, task_id: str, token: str) -> None:
        with self._lock:
            self._registrations[task_id] = token

    def apply(
        self,
        task_id: str,
        state: str,
        timestamp: str,
        artifacts: Optional[list] = None,
        *,
        source: str,  # "pull" | "push"
    ) -> TaskRecord:
        if state not in TERMINAL_STATES | NON_TERMINAL_STATES:
            raise ValueError(f"unknown TaskState: {state!r}")
        with self._lock:
            prior = self._records.get(task_id)

            if prior is not None and prior.state in TERMINAL_STATES:
                if state in TERMINAL_STATES:
                    # Idempotent replay of the same terminal state: accept the
                    # first, ignore subsequent identical deliveries.
                    if state == prior.state and timestamp == prior.timestamp:
                        return prior
                    # Two distinct terminal states (e.g. completed then canceled)
                    # is a server-side inconsistency; keep the first committed.
                    return prior
                # The exact failure trace: late `working` after `completed`.
                raise TerminalRegressionError(
                    f"task {task_id!r} already terminal ({prior.state}); "
                    f"refusing {source} observation of {state!r} at {timestamp}"
                )

            if prior is not None and prior.state == state and timestamp == prior.timestamp:
                return prior  # no-op replay

            self._seq += 1
            rec = TaskRecord(
                task_id=task_id,
                state=state,
                timestamp=timestamp,
                artifacts=list(artifacts or (prior.artifacts if prior else [])),
                commit_seq=self._seq,
            )
            self._records[task_id] = rec
            return rec

    def handle_webhook(self, task_id: str, token: str, payload: dict) -> TaskRecord:
        expected = self._registrations.get(task_id)
        if expected is None:
            raise WebhookTokenMismatch(
                f"webhook for undispatched task {task_id!r}; possible injection"
            )
        if not hmac.compare_digest(expected, token):
            raise WebhookTokenMismatch(f"token mismatch for task {task_id!r}")
        status = payload["status"]
        return self.apply(
            task_id=task_id,
            state=status["state"],
            timestamp=status["timestamp"],
            artifacts=payload.get("artifacts"),
            source="push",
        )

    def handle_poll(self, task_id: str, payload: dict) -> Optional[TaskRecord]:
        """Poll handler: a late `working` after `completed` is expected and
        must be discarded, NOT propagated. Returning None signals 'no change'."""
        status = payload["status"]
        try:
            return self.apply(
                task_id=task_id,
                state=status["state"],
                timestamp=status["timestamp"],
                artifacts=payload.get("artifacts"),
                source="pull",
            )
        except TerminalRegressionError:
            return None  # stale pull; the webhook already committed terminal


def _demo() -> None:
    r = TaskReducer()
    r.register_webhook("task-7f3a", token="tok-abc")
    now = datetime.now(timezone.utc).isoformat()

    # t=0.3s: webhook delivers completed first.
    r.handle_webhook(
        "task-7f3a", "tok-abc",
        {"status": {"state": "completed", "timestamp": now}, "artifacts": [{"x": 1}]},
    )
    # t=1.4s: the late tasks/get response arrives carrying `working`.
    # handle_poll swallows TerminalRegressionError and returns None.
    assert r.handle_poll(
        "task-7f3a",
        {"status": {"state": "working", "timestamp": now}},
    ) is None

    # A direct apply from the dispatcher must NOT be swallowed.
    try:
        r.apply("task-7f3a", "working", now, source="pull")
    except TerminalRegressionError:
        pass
    else:
        raise AssertionError("dispatcher path must surface regression")

    # Forged webhook for a task we never dispatched.
    try:
        r.handle_webhook("task-ffff", "tok-abc", {"status": {"state": "completed", "timestamp": now}})
    except WebhookTokenMismatch:
        pass
    else:
        raise AssertionError("undispatched task id must be rejected")


if __name__ == "__main__":
    _demo()
