# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-a2a-push-notification-callback-acknowledges-a-task-state-the-sender-never-published.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-a2a-push-notification-callback-acknowledges-a-task-state-the-sender-never-published.warrant.json
# Markdown SHA-256:   fd38fa1c4d3088aabf54675ca216da7769c15a82512b69973770b903819a0654
# Code AST SHA-256:   1301f93f1e471bcf6ec3da6f112b94524eeebbf13d1950d6ed3031f868b8826a
# Verified Classes:   PhantomTransitionError, Callback, ReconcileGatedMirror
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PhantomTransitionError(RuntimeError):
    """Raised when a push callback asserts a state the sender's canonical record
    contradicts, or when a callback arrives out of causal order and cannot be
    reconciled without violating the mirrored state machine's monotonicity."""
    pass


@dataclass
class Callback:
    task_id: str
    epoch: str
    seq: int          # monotonic, stamped at transition time, in metadata.a2a_seq
    state: str        # "submitted" | "working" | "input-required" | "completed" | "failed" | "canceled"
    received_at: float = field(default_factory=time.time)


# Transition table for the mirrored state machine. Terminal states have no
# outgoing edges; "input-required" is reachable only from "working".
TRANSITIONS: dict[str, set[str]] = {
    "submitted":      {"working", "canceled", "failed"},
    "working":        {"input-required", "completed", "failed", "canceled"},
    "input-required": {"working", "canceled", "failed"},
    "completed":      set(),
    "failed":         set(),
    "canceled":       set(),
}


class ReconcileGatedMirror:
    def __init__(self, fetch_canonical: Callable[[str], dict]):
        # fetch_canonical(task_id) -> {"state": str, "epoch": str}
        self._fetch = fetch_canonical
        self._mirror: dict[tuple[str, str], str] = {}          # (task_id, epoch) -> state
        self._watermark: dict[tuple[str, str], int] = {}       # (task_id, epoch) -> last applied seq

    def on_callback(self, cb: Callback) -> str:
        key = (cb.task_id, cb.epoch)
        last = self._watermark.get(key, -1)

        # Stale callback: superseded by a transition we already applied.
        # Drop silently — this is the phantom-transition guard.
        if cb.seq <= last:
            return self._mirror.get(key, "submitted")

        canonical = self._fetch(cb.task_id)
        if canonical["epoch"] != cb.epoch:
            # Task ID reused across epochs; callback belongs to a dead epoch.
            raise PhantomTransitionError(
                f"callback for task {cb.task_id} epoch {cb.epoch} "
                f"but canonical record is epoch {canonical['epoch']}"
            )

        current = self._mirror.get(key, "submitted")
        target = canonical["state"]

        if target == current:
            self._watermark[key] = cb.seq
            return current

        if target not in TRANSITIONS.get(current, set()):
            raise PhantomTransitionError(
                f"task {cb.task_id} epoch {cb.epoch}: canonical state {target!r} "
                f"is not reachable from mirrored state {current!r}; "
                f"callback asserted {cb.state!r} at seq {cb.seq}"
            )

        self._mirror[key] = target
        self._watermark[key] = cb.seq
        return target
