# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-task-update-after-a-push-notification-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-task-update-after-a-push-notification-replay.warrant.json
# Markdown SHA-256:   76a1f3ce1b731578155d2f818cc37dbb28b1381144f9045b8da933044481f082
# Code AST SHA-256:   86ff4f676cbf9ef001cfab09608c2902b1a258e8c5071c27f4e250103f3f701e
# Verified Classes:   SupersededEventMisclassified, TaskRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SupersededEventMisclassified(RuntimeError):
    """Raised when a stale-but-addressed A2A status event is 4xx'd instead of ACK'd."""
    pass


@dataclass
class TaskRecord:
    task_id: str
    context_id: str
    state: str
    status_ts: float
    seen_nonces: set = field(default_factory=set)
    event_log: list = field(default_factory=list)


def handle_push_notification(
    task: Optional[TaskRecord],
    envelope_nonce: str,
    envelope_issued_at: float,
    event_task_id: str,
    event_context_id: str,
    event_state: str,
    event_status_ts: float,
    expected_context_id: str,
) -> int:
    # Guard 1: addressability. Only an unknown task or context mismatch is a 4xx.
    if task is None or task.task_id != event_task_id:
        return 404
    if event_context_id != expected_context_id or task.context_id != expected_context_id:
        return 409

    # Guard 2: transport replay. Durable dedup, ACK 200, never 4xx.
    if envelope_nonce in task.seen_nonces:
        return 200
    task.seen_nonces.add(envelope_nonce)

    # Guard 3: lifecycle monotonicity. Stale != invalid. Log, do not mutate, ACK 200.
    if event_status_ts <= task.status_ts:
        task.event_log.append(
            {"nonce": envelope_nonce, "state": event_state,
             "ts": event_status_ts, "classification": "superseded"}
        )
        # The bug this article documents: returning 409 here strands the sender.
        # Correct behavior is to ACK 200 and record the superseded transition.
        return 200

    # Forward progress: apply.
    task.state = event_state
    task.status_ts = event_status_ts
    task.event_log.append(
        {"nonce": envelope_nonce, "state": event_state,
         "ts": event_status_ts, "classification": "applied"}
    )
    return 200


def replay_superseded_terminal(task: TaskRecord, old_completed_event: dict) -> None:
    """Regression harness: replaying an older terminal event must not 4xx."""
    code = handle_push_notification(
        task=task,
        envelope_nonce=old_completed_event["nonce"],
        envelope_issued_at=old_completed_event["ts"],
        event_task_id=task.task_id,
        event_context_id=task.context_id,
        event_state="completed",
        event_status_ts=old_completed_event["ts"],
        expected_context_id=task.context_id,
    )
    if code == 409:
        raise SupersededEventMisclassified(
            f"task {task.task_id}: superseded terminal {old_completed_event['nonce']} "
            f"was 409'd; sender will abandon delivery and downstream barrier will wedge"
        )
    assert code == 200, f"unexpected {code}"
    assert task.state == "failed", "superseded event must not regress current state"
