# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-push-notification-resurrection-after-terminal-task-states.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-push-notification-resurrection-after-terminal-task-states.warrant.json
# Markdown SHA-256:   f5cd6bd44a5aadad0bd34a4dc5817900e96f84efcffe5c16ab5e8b9159e5e374
# Code AST SHA-256:   96ac1abf784fc7036ceb80eff5c8654f1262bd652dd4053a6b24928e6f6db9b6
# Verified Classes:   PushNotificationResurrectionError, TaskEventGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PushNotificationResurrectionError(RuntimeError):
    """Raised when a webhook event would regress a task out of a terminal state."""
    pass


TERMINAL_STATES = frozenset({"completed", "failed", "canceled"})


class TaskEventGate:
    """Client-side gate enforcing monotonic sequence + absorbing terminal invariants."""

    def __init__(self):
        # taskId -> (high_water_sequence, applied_state)
        self._marks: dict[str, tuple[int, str]] = {}

    def apply(self, task_id: str, sequence: int, state: str) -> str:
        """Apply an inbound TaskStatusUpdateEvent; return the resulting state.

        Raises PushNotificationResurrectionError if the event would regress
        a terminal task or arrive out of sequence in a way the gate cannot bound.
        """
        if sequence < 0:
            raise PushNotificationResurrectionError(
                f"task {task_id}: negative sequence {sequence}"
            )

        mark = self._marks.get(task_id)
        if mark is None:
            self._marks[task_id] = (sequence, state)
            return state

        high_water, applied_state = mark

        # Absorbing-terminal guard: any event after terminal is a resurrection.
        if applied_state in TERMINAL_STATES:
            raise PushNotificationResurrectionError(
                f"task {task_id}: event seq={sequence} state={state!r} "
                f"arrived after terminal state {applied_state!r}; "
                f"dropping to prevent resurrection"
            )

        # Monotonic guard: stale retries carry the original sequence.
        if sequence <= high_water:
            # Duplicate or stale retry; do not regress applied state.
            return applied_state

        self._marks[task_id] = (sequence, state)
        return state

    def force_terminal(self, task_id: str, sequence: int, state: str) -> None:
        """Commit a terminal state from an authoritative tasks/get response."""
        if state not in TERMINAL_STATES:
            raise PushNotificationResurrectionError(
                f"task {task_id}: force_terminal called with non-terminal {state!r}"
            )
        self._marks[task_id] = (sequence, state)
