# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-terminal-a2a-task-transition-against-a-webhook-that-arrives-after-taskstate-completed-was-already-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-terminal-a2a-task-transition-against-a-webhook-that-arrives-after-taskstate-completed-was-already-acknowledged.warrant.json
# Markdown SHA-256:   167adf1196e607b1737d2b2b0225f5fb3e187725e6bc73db3e163c1914c0f3d5
# Code AST SHA-256:   a8069b3d4253bbb532b6a0cbf7c5fd1bc389ec3b2d0f01a392348fd1c7183e65
# Verified Classes:   TaskState, StaleEventRejected, TaskRecord, OrdinalGuardedTaskStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


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


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


class StaleEventRejected(RuntimeError):
    """Raised when a webhook event would regress a task's committed ordinal."""


@dataclass
class TaskRecord:
    task_id: str
    state: TaskState = TaskState.WORKING
    committed_ordinal: float = 0.0  # +inf once terminality observed via poll
    applied_seqs: set[int] = field(default_factory=set)


class OrdinalGuardedTaskStore:
    """Enforces monotonic non-decreasing state ordinal and absorbing terminality."""

    def __init__(self) -> None:
        self._tasks: dict[str, TaskRecord] = {}

    def get_or_create(self, task_id: str) -> TaskRecord:
        return self._tasks.setdefault(task_id, TaskRecord(task_id=task_id))

    def commit_terminal_from_poll(self, task_id: str, state: TaskState) -> None:
        """tasks/get returned a terminal state. This is authoritative and ordinal-maximal."""
        if state not in TERMINAL_STATES:
            raise StaleEventRejected(
                f"commit_terminal_from_poll called with non-terminal state {state!r}"
            )
        rec = self.get_or_create(task_id)
        rec.state = state
        rec.committed_ordinal = float("inf")  # strictly greater than any finite seq
        return None

    def apply_webhook(
        self,
        task_id: str,
        seq: int,
        state: TaskState,
        final: bool,
    ) -> None:
        rec = self.get_or_create(task_id)

        # Duplicate delivery of an already-applied event: idempotent no-op.
        if seq in rec.applied_seqs:
            return None

        # Ordinal monotonicity: reject any event that does not advance the committed ordinal.
        if seq <= rec.committed_ordinal:
            raise StaleEventRejected(
                f"task {task_id}: webhook seq={seq} state={state.value} "
                f"is <= committed_ordinal={rec.committed_ordinal} "
                f"(committed_state={rec.state.value}); dropping as regressive"
            )

        # Terminality is absorbing: no non-terminal event may follow a terminal one.
        if rec.state in TERMINAL_STATES and state not in TERMINAL_STATES:
            raise StaleEventRejected(
                f"task {task_id}: refusing to resurrect terminal state "
                f"{rec.state.value} back to {state.value} via seq={seq}"
            )

        # A webhook claiming terminality must be marked final; otherwise the
        # push contract is violated and we cannot trust it as authoritative.
        if state in TERMINAL_STATES and not final:
            raise StaleEventRejected(
                f"task {task_id}: terminal state {state.value} arrived with "
                f"final=False at seq={seq}; push contract violated"
            )

        rec.state = state
        rec.committed_ordinal = float(seq)
        rec.applied_seqs.add(seq)

        if state in TERMINAL_STATES:
            rec.committed_ordinal = float("inf")
        return None


# --- Reproduction of the observed trace -------------------------------------

def reproduce_failure() -> None:
    store = OrdinalGuardedTaskStore()

    # t=41s: seq=7 working event is emitted but stalls in transit.
    # t=44s: server transitions to completed.
    # t=45s: client polls and learns terminality.
    store.commit_terminal_from_poll("T", TaskState.COMPLETED)

    # t=58s: the stalled seq=7 working event finally lands.
    try:
        store.apply_webhook("T", seq=7, state=TaskState.WORKING, final=False)
    except StaleEventRejected as e:
        # Correct behavior: drop the regressive event, keep state=completed.
        print(f"guarded: {e}")
    rec = store.get_or_create("T")
    assert rec.state is TaskState.COMPLETED, "terminality must be absorbing"
    assert rec.committed_ordinal == float("inf")

    # Negative control: without the guard, state would now be WORKING and the
    # worker would be re-armed against a GC'd task, later misreported as FAILED.
    unguarded = TaskRecord(task_id="T", state=TaskState.WORKING)
    unguarded.state = TaskState.WORKING  # last-writer-wins regression
    assert unguarded.state is TaskState.WORKING


if __name__ == "__main__":
    reproduce_failure()
