# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-push-notification-webhook-has-silently-re-entered-a-terminal-task-state-under-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-push-notification-webhook-has-silently-re-entered-a-terminal-task-state-under-a2a-v1-0.warrant.json
# Markdown SHA-256:   e1608d0b76d63fa2d0295fee2962eab5cceece550376b8706e25675120becd6b
# Code AST SHA-256:   16f6502d1108978f178b65d1c6bf9e08c818f076015176d33312526e9fd062f4
# Verified Classes:   TerminalLatchError, TaskState, Notification, ReceiverState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class TerminalLatchError(RuntimeError):
    """Raised when a receiver's state latch would drop a legitimate re-opened task."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


TERMINAL = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


@dataclass
class Notification:
    task_id: str
    sequence_number: int
    state: TaskState
    timestamp: float


@dataclass
class ReceiverState:
    max_seq: dict[str, int] = field(default_factory=dict)
    current_state: dict[str, TaskState] = field(default_factory=dict)
    latched_terminal: dict[str, bool] = field(default_factory=dict)


def ingest(state: ReceiverState, note: Notification) -> str:
    """Apply one webhook notification. Returns an outcome tag for logging."""
    prior_seq = state.max_seq.get(note.task_id, -1)

    # True duplicate / retry: drop, but do not treat as terminal latch.
    if note.sequence_number <= prior_seq:
        return "duplicate"

    prior_state = state.current_state.get(note.task_id)
    was_latched = state.latched_terminal.get(note.task_id, False)

    # The boundary condition: a higher-sequence notification that moves the
    # task OUT of a terminal state must un-latch, not be discarded.
    if was_latched and note.state not in TERMINAL:
        state.latched_terminal[note.task_id] = False
        state.current_state[note.task_id] = note.state
        state.max_seq[note.task_id] = note.sequence_number
        return "unlatched_on_reopen"

    # A terminal latch that never clears is the failure mode this guards against.
    if was_latched and note.state in TERMINAL and prior_state in TERMINAL:
        # Same terminal state re-reported at a higher seq (at-least-once retry
        # with a fresh seq). Accept as idempotent, do not re-fire side effects.
        state.max_seq[note.task_id] = note.sequence_number
        return "idempotent_terminal"

    state.current_state[note.task_id] = note.state
    state.max_seq[note.task_id] = note.sequence_number
    state.latched_terminal[note.task_id] = note.state in TERMINAL
    return "applied"


def reconcile_with_get(state: ReceiverState, task_id: str, authoritative: TaskState) -> None:
    """Guardrail: a tasks/get that disagrees with the latch means the latch is stale."""
    if state.latched_terminal.get(task_id) and authoritative not in TERMINAL:
        # We latched terminal but the authoritative machine says otherwise.
        # This is the exact condition that produces silent hangs.
        raise TerminalLatchError(
            f"task {task_id!r} latched terminal but authoritative state is "
            f"{authoritative.value!r}; receiver dropped a re-open notification"
        )
    state.current_state[task_id] = authoritative
    state.latched_terminal[task_id] = authoritative in TERMINAL
