# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-taskstatusupdateevent-as-authoritative-the-terminal-state-race-in-a2a-v1-0-task-lifecycle-conformance.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-taskstatusupdateevent-as-authoritative-the-terminal-state-race-in-a2a-v1-0-task-lifecycle-conformance.warrant.json
# Markdown SHA-256:   5cd7347e8f5306930789105607e9303864cca3258b42a0828f25b7dee8779a7a
# Code AST SHA-256:   e4ab5a9f3bde0d3a4d978474e92614542ac61d98dc9f979c0543150bdf6a1d0d
# Verified Classes:   TaskState, TerminalStateRegression, StatusUpdate, TaskRecord, ConformantReducer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


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


TERMINAL: frozenset[TaskState] = frozenset(
    {TaskState.COMPLETED, TaskState.CANCELED, TaskState.FAILED}
)


class TerminalStateRegression(TaskStateError := RuntimeError):
    """Raised when a reducer would move a task out of a terminal state."""


@dataclass
class StatusUpdate:
    task_id: str
    state: TaskState
    final: bool
    timestamp: float
    source: str  # "stream" | "poll"
    sequence: Optional[int] = None


@dataclass
class TaskRecord:
    task_id: str
    state: TaskState = TaskState.SUBMITTED
    last_sequence: int = -1
    last_timestamp: float = 0.0
    terminal_observed_at: Optional[float] = None
    history: list[tuple[str, TaskState]] = field(default_factory=list)


class ConformantReducer:
    """Absorption-first reducer. The absorption check MUST dominate sequencing."""

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

    def _get(self, task_id: str) -> TaskRecord:
        rec = self._tasks.get(task_id)
        if rec is None:
            rec = TaskRecord(task_id=task_id)
            self._tasks[task_id] = rec
        return rec

    def apply(self, update: StatusUpdate) -> TaskRecord:
        rec = self._get(update.task_id)

        # RULE 1 (absorption-first): if the task is terminal, no update may
        # regress it, regardless of timestamp, sequence, or source channel.
        # This must run BEFORE any sequencing comparison.
        if rec.state in TERMINAL and update.state not in TERMINAL:
            raise TerminalStateRegression(
                f"regression attempt on task {update.task_id}: "
                f"{rec.state.value} -> {update.state.value} "
                f"via {update.source} at t={update.timestamp:.3f} "
                f"(terminal observed at t={rec.terminal_observed_at:.3f})"
            )

        # RULE 2 (sequencing): only when the task is non-terminal may a
        # newer snapshot be accepted. Stream events dominate any poll
        # response issued before the stream event's receipt.
        if rec.state not in TERMINAL:
            if update.source == "poll" and rec.terminal_observed_at is not None:
                # A poll response that resolves after a terminal stream event
                # is stale by construction; drop it rather than trust its clock.
                return rec
            if update.sequence is not None and update.sequence <= rec.last_sequence:
                return rec
            if update.timestamp < rec.last_timestamp:
                return rec

        # RULE 3: terminal payload tolerance — accept final events with or
        # without an embedded Task; the event's status alone is sufficient.
        rec.state = update.state
        rec.last_timestamp = max(rec.last_timestamp, update.timestamp)
        if update.sequence is not None:
            rec.last_sequence = max(rec.last_sequence, update.sequence)
        if update.state in TERMINAL:
            rec.terminal_observed_at = time.monotonic()
        rec.history.append((update.source, update.state))
        return rec


def replay_interop_trace(reducer: ConformantReducer) -> None:
    """Replays the observed Rust-server trace that double-executed a side effect."""
    tid = "tsk_7"
    # t=1200: stream reports working
    reducer.apply(StatusUpdate(tid, TaskState.WORKING, False, 1.200, "stream"))
    # t=1395: stream reports completed, final
    reducer.apply(StatusUpdate(tid, TaskState.COMPLETED, True, 1.395, "stream"))
    # t=1402: stale poll response arrives reporting working — must NOT regress
    try:
        reducer.apply(StatusUpdate(tid, TaskState.WORKING, False, 1.402, "poll"))
    except TerminalStateRegression:
        # Expected: the guard fires. In a production reducer this is a
        # no-op drop, not an exception; here we surface it for the test.
        pass
    rec = reducer._tasks[tid]
    if rec.state is not TaskState.COMPLETED:
        raise TerminalStateRegression(
            f"reducer regressed to {rec.state.value} after terminal"
        )


if __name__ == "__main__":
    replay_interop_trace(ConformantReducer())
