# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-push-notification-as-authoritative-rather-than-advisory-the-resumption-token-divergence-boundary-in-long-running-ta.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-push-notification-as-authoritative-rather-than-advisory-the-resumption-token-divergence-boundary-in-long-running-ta.warrant.json
# Markdown SHA-256:   f132d71aa38e6701b42806483d4a37d18be59e83bce9ec48504a7dbd6b9438ef
# Code AST SHA-256:   00a328d06556a3d9c24cd22c5b456c20a7fe2e33b81fb9b0643080123d851ba9
# Verified Classes:   ResumptionTokenDivergence, PushEvent, Snapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ResumptionTokenDivergence(RuntimeError):
    """Raised when local task state and the authoritative snapshot disagree
    on terminality or resumption identity, blocking a safe resume."""
    pass


@dataclass
class PushEvent:
    task_id: str
    state: str
    timestamp: float
    progress: float = 0.0


@dataclass
class Snapshot:
    task_id: str
    context_id: str
    state: str
    timestamp: float
    artifacts: list = field(default_factory=list)


TERMINAL = {"completed", "failed", "canceled"}


def reconcile_on_cold_start(
    snapshot: Snapshot,
    buffered: list[PushEvent],
    held_token: tuple[str, str],
) -> str:
    """Decide the authoritative resumption action. Returns one of
    'reconcile_artifacts', 'resume', or 'overlay_then_reconfirm'."""
    # Invariant 1: resumption-token equality gates every resume path.
    if (snapshot.task_id, snapshot.context_id) != held_token:
        raise ResumptionTokenDivergence(
            f"snapshot token {(snapshot.task_id, snapshot.context_id)} "
            f"!= held token {held_token}; refusing resume to avoid "
            f"conflating a re-dispatched task with the original"
        )

    # Invariant 2: snapshot terminality is a hard gate over push overlay.
    if snapshot.state in TERMINAL:
        # Discard all buffered events at or before snapshot timestamp.
        # Any later event forces a fresh tasks/get, never a direct overlay.
        later = [e for e in buffered if e.timestamp > snapshot.timestamp]
        if later:
            raise ResumptionTokenDivergence(
                "push event postdates terminal snapshot; re-fetch required "
                "before any state mutation"
            )
        return "reconcile_artifacts"

    # Invariant 3: non-terminal overlay must be timestamp-ordered and
    # strictly newer than the snapshot, then re-confirmed.
    ordered = sorted(
        (e for e in buffered if e.timestamp > snapshot.timestamp),
        key=lambda e: e.timestamp,
    )
    if not ordered:
        return "resume"
    if any(e.state in TERMINAL for e in ordered):
        # A buffered terminal event contradicts a non-terminal snapshot:
        # the snapshot is stale, not the event. Re-fetch, do not overlay.
        raise ResumptionTokenDivergence(
            "buffered terminal event contradicts non-terminal snapshot; "
            "snapshot is stale, re-fetch before resume"
        )
    return "overlay_then_reconfirm"


# Trace of the observed failure: snapshot is terminal, buffered queue
# contains an out-of-order 'working' event that an arrival-order overlay
# would apply last, regressing state and triggering a rejected resume.
try:
    snap = Snapshot("task-77", "ctx-3", "completed", timestamp=time.time())
    queue = [
        PushEvent("task-77", "working", timestamp=snap.timestamp - 900, progress=0.4),
        PushEvent("task-77", "working", timestamp=snap.timestamp - 300, progress=0.8),
        PushEvent("task-77", "completed", timestamp=snap.timestamp),
    ]
    action = reconcile_on_cold_start(snap, queue, ("task-77", "ctx-3"))
    print(action)  # -> reconcile_artifacts (no duplicate re-dispatch)
except ResumptionTokenDivergence as exc:
    raise
