# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-task-state-divergence-when-a-push-notification-webhook-rebinds-to-a-restarted-remote-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-task-state-divergence-when-a-push-notification-webhook-rebinds-to-a-restarted-remote-agent.warrant.json
# Markdown SHA-256:   b48186673e6ce32aa1d3621bf692a2f0fe543b6f73c563c92dbea0d604fac59c
# Code AST SHA-256:   087a9fa34c46af3b003da0e02d51773ecb93267f78ccca52f882fb3bdc3e1708
# Verified Classes:   BindingGenerationMismatch, TaskWatchdog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BindingGenerationMismatch(RuntimeError):
    """Raised when a tasks/get response shows the webhook binding did not survive
    the remote agent's instance generation, invalidating any liveness inference."""
    pass


class TaskWatchdog:
    POLL_INTERVAL_S = 15
    WATCHDOG_TIMEOUT_S = 30  # must be >= 2 * POLL_INTERVAL_S

    def __init__(self, task_id: str, expected_token: str):
        if self.WATCHDOG_TIMEOUT_S < 2 * self.POLL_INTERVAL_S:
            raise BindingGenerationMismatch(
                "watchdog_timeout must be >= 2 * poll_interval; otherwise the "
                "watchdog fires on binding silence before authoritative state is read"
            )
        self.task_id = task_id
        self.expected_token = expected_token
        self.last_poll_ts = 0.0

    def on_poll_response(self, resp: dict, now: float) -> None:
        cfg = resp.get("pushNotificationConfig")
        if cfg is None or cfg.get("token") != self.expected_token:
            # Binding did not survive remote restart: re-bind, do NOT re-send task.
            raise BindingGenerationMismatch(
                f"task {self.task_id}: binding token {cfg and cfg.get('token')!r} "
                f"!= expected {self.expected_token!r}; remote instance generation changed"
            )
        self.last_poll_ts = now

    def on_watchdog_tick(self, now: float, last_webhook_ts: float) -> str:
        # Webhook silence is NOT a liveness signal. Only stale polling is.
        if now - self.last_poll_ts < self.WATCHDOG_TIMEOUT_S:
            return "continue"
        if now - last_webhook_ts < self.WATCHDOG_TIMEOUT_S:
            # A webhook arrived recently but poll is stale: re-poll, never re-send.
            return "repoll"
        # Only now, with authoritative staleness, may we consider intervention —
        # and even then the caller must tasks/get first, not message/send.
        raise BindingGenerationMismatch(
            f"task {self.task_id}: no authoritative poll for {now - self.last_poll_ts:.1f}s; "
            "issuing message/send here would risk double-submit against a terminal task"
        )
