# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-terminal-task-state-from-a-stale-push-notification-webhook-after-a2a-v1-0-task-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-terminal-task-state-from-a-stale-push-notification-webhook-after-a2a-v1-0-task-resumption.warrant.json
# Markdown SHA-256:   547d207cc2ec196934433ed153e93bab8110b690a40350ab88f8efe58570b3af
# Code AST SHA-256:   5d52cff3e74fa9f46aed3e0925b84ca63f1c06369e015a2e10ff6d4dee27c41c
# Verified Classes:   StaleWebhookStateError, TaskLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class StaleWebhookStateError(RuntimeError):
    """Raised when a webhook event would move the ledger backwards in time."""


@dataclass
class TaskLedger:
    # last authoritatively-confirmed timestamp per task, from tasks/get
    last_ts: Dict[str, int] = field(default_factory=dict)
    state: Dict[str, str] = field(default_factory=dict)

    def apply_webhook(self, task_id: str, evt_state: str, evt_ts: int, authoritative_ts: int, authoritative_state: str) -> None:
        # Reject any event that is not strictly newer than the authoritative timeline.
        prev = self.last_ts.get(task_id, -1)
        if evt_ts <= prev:
            # Stale replay (e.g. outbox FIFO after reconnect). Drop silently.
            return
        # Webhook is only a hint; the ledger advances to tasks/get's view, never the payload's.
        if authoritative_ts < evt_ts:
            raise StaleWebhookStateError(
                f"task {task_id}: webhook ts={evt_ts} state={evt_state} "
                f"exceeds authoritative ts={authoritative_ts}; refusing to advance"
            )
        self.last_ts[task_id] = authoritative_ts
        self.state[task_id] = authoritative_state


def on_status_update(ledger: TaskLedger, task_id: str, evt_state: str, evt_ts: int, fetch_authoritative) -> None:
    authoritative = fetch_authoritative(task_id)  # tasks/get
    ledger.apply_webhook(task_id, evt_state, evt_ts, authoritative["ts"], authoritative["state"])
