# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-pin-the-task-state-revision-across-an-a2a-push-notification-rebind-or-the-resumed-task-silently-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-pin-the-task-state-revision-across-an-a2a-push-notification-rebind-or-the-resumed-task-silently-forks.warrant.json
# Markdown SHA-256:   ce410c236eacf7fc02ad62491dcdd56d5e9e88d331f230b343ddc3d6541de309
# Code AST SHA-256:   fb719ba0cb19d4ca48c160830ead77699b4c4419d58d5d854ba3d2d2d4f57b8e
# Verified Classes:   TaskRevisionFork, Binding, LocalTaskView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaskRevisionFork(RuntimeError):
    """Raised when a client would apply task-state relative to a stale revision base
    after a push-notification rebind crossed a client-blocking state."""


@dataclass
class Binding:
    config_id: str
    url: str
    token: str


@dataclass
class LocalTaskView:
    task_id: str
    state: str
    revision_base_ts: float          # server status.timestamp adopted as base
    binding: Binding
    local_seq: int = 0               # per-binding delivery counter; NOT a consistency token
    applied_event_binding_ids: set = field(default_factory=set)


CLIENT_BLOCKING = {"input-required", "auth-required"}


def rebind_push_config(
    view: LocalTaskView,
    new_binding: Binding,
    server_status: Optional[dict],
) -> LocalTaskView:
    """
    Rebind a task's push-notification config safely.

    Invariant enforced: a rebind that changes binding identity must reconcile
    against the authoritative server Task before any post-rebind event is applied.
    """
    binding_changed = new_binding.config_id != view.binding.config_id
    crosses_blocking = view.state in CLIENT_BLOCKING

    if binding_changed and crosses_blocking:
        # The dangerous region: new config id + client-blocking state.
        # Reconciliation is mandatory; without it the task forks.
        if server_status is None:
            raise TaskRevisionFork(
                f"task {view.task_id}: rebind to config {new_binding.config_id!r} "
                f"crosses blocking state {view.state!r} without tasks/get reconciliation; "
                f"refusing to rebind (would fork revision base {view.revision_base_ts})"
            )
        server_ts = float(server_status["timestamp"])
        if server_ts < view.revision_base_ts:
            # Server snapshot appears older than our base. This is the self-sealing
            # trap: do NOT trust local_seq. Server timestamp is the only total order.
            # A lower ts here means our base was corrupted by a stale duplicate.
            raise TaskRevisionFork(
                f"task {view.task_id}: server status.timestamp {server_ts} < "
                f"local base {view.revision_base_ts}; local base was advanced by a "
                f"stale cross-binding duplicate — reset base to server, do not reject"
            )
        # Adopt server as the new authoritative base; drop per-binding counters.
        view.state = server_status["state"]
        view.revision_base_ts = server_ts
        view.local_seq = 0

    # Keep config_id stable across pure endpoint migration so the server can
    # resume from its last-acknowledged event for this config id.
    view.binding = new_binding
    view.applied_event_binding_ids.add(new_binding.config_id)
    return view


def apply_status_event(view: LocalTaskView, event: dict) -> LocalTaskView:
    """Apply a pushed TaskStatusUpdateEvent, rejecting cross-binding stale duplicates."""
    event_binding = event["binding_config_id"]
    if event_binding not in view.applied_event_binding_ids:
        raise TaskRevisionFork(
            f"task {view.task_id}: event from retired binding {event_binding!r} "
            f"arrived after rebind to {view.binding.config_id!r}; "
            f"must be dead-lettered, not applied"
        )
    if float(event["timestamp"]) < view.revision_base_ts:
        raise TaskRevisionFork(
            f"task {view.task_id}: event timestamp {event['timestamp']} precedes "
            f"reconciled base {view.revision_base_ts}; stale replay"
        )
    view.state = event["state"]
    view.revision_base_ts = float(event["timestamp"])
    view.local_seq += 1
    return view
