# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-a2a-task-lifecycle-divergence-between-push-notification-webhook-delivery-and-the-authoritative-task-state-ma.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-a2a-task-lifecycle-divergence-between-push-notification-webhook-delivery-and-the-authoritative-task-state-ma.warrant.json
# Markdown SHA-256:   99af39499226cc7496c8e3c5f7a6b7aef468a13e2f6ab8c030644a61e8320355
# Code AST SHA-256:   b0f5d52fcc3816730b5fa5d2d6e0894c11229bd6fdae02fbfda67535fdf2cf83
# Verified Classes:   TaskStateDivergenceError, WebhookEvent, TaskRecord, ReconcilingTaskClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaskStateDivergenceError(RuntimeError):
    """Raised when a webhook-derived task state cannot be reconciled with the
    authoritative tasks/get state. Indicates the client must NOT commit the
    terminal state to durable memory."""


@dataclass
class WebhookEvent:
    task_id: str
    context_id: str
    state: str
    timestamp: float
    final: bool


@dataclass
class TaskRecord:
    task_id: str
    last_seen_ts: float = 0.0
    local_state: str = "submitted"
    terminal_committed: bool = False
    pending_reconcile: list = field(default_factory=list)


class ReconcilingTaskClient:
    """Client that treats webhooks as hints and tasks/get as truth."""

    def __init__(self, fetch_authoritative, liveness_timeout_s: float = 30.0):
        self._fetch = fetch_authoritative  # callable(task_id) -> dict
        self._liveness_timeout_s = liveness_timeout_s
        self._records: dict[str, TaskRecord] = {}

    def on_webhook(self, ev: WebhookEvent) -> None:
        rec = self._records.setdefault(ev.task_id, TaskRecord(ev.task_id))

        # Signal A: ordering. Regressing/equal timestamps never advance state.
        if ev.timestamp <= rec.last_seen_ts:
            rec.pending_reconcile.append(ev)
            return  # do not advance; reconcile later

        # Signal B: terminal events require authoritative confirmation.
        if ev.final:
            authoritative = self._fetch(ev.task_id)
            if authoritative.get("status", {}).get("state") != ev.state:
                raise TaskStateDivergenceError(
                    f"task {ev.task_id}: webhook says {ev.state!r} but "
                    f"tasks/get says {authoritative.get('status', {}).get('state')!r}"
                )
            if authoritative["status"]["timestamp"] < ev.timestamp:
                raise TaskStateDivergenceError(
                    f"task {ev.task_id}: authoritative timestamp "
                    f"{authoritative['status']['timestamp']} < event {ev.timestamp}"
                )
            rec.local_state = ev.state
            rec.last_seen_ts = ev.timestamp
            rec.terminal_committed = True
            return

        rec.local_state = ev.state
        rec.last_seen_ts = ev.timestamp

    def check_liveness(self, now: Optional[float] = None) -> None:
        """Signal C: silence is unknown, not 'working'."""
        now = time.time() if now is None else now
        for rec in self._records.values():
            if rec.terminal_committed:
                continue
            if now - rec.last_seen_ts > self._liveness_timeout_s:
                authoritative = self._fetch(rec.task_id)
                auth_state = authoritative.get("status", {}).get("state")
                if auth_state != rec.local_state:
                    raise TaskStateDivergenceError(
                        f"task {rec.task_id}: liveness gap; local {rec.local_state!r} "
                        f"vs authoritative {auth_state!r}"
                    )
                rec.last_seen_ts = now
