# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-push-notification-callback-as-authoritative-state-and-when-must-it-discard-it-as-a-stale-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-push-notification-callback-as-authoritative-state-and-when-must-it-discard-it-as-a-stale-repl.warrant.json
# Markdown SHA-256:   02e3a0610cbc8bcd9e549779e800e1a667b43a45d7f5d76f3295c36de7a46bce
# Code AST SHA-256:   7518023d273fb167d611fd8ba8d71cb7498d63c0b2e26573ab3123c39c389790
# Verified Classes:   StalePushCallbackError, TaskProjection
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StalePushCallbackError(RuntimeError):
    """Raised when a push-notification callback cannot be applied as authoritative state."""
    def __init__(self, task_id: str, reason: str, callback_ts: float, committed_ts: float):
        self.task_id = task_id
        self.reason = reason
        self.callback_ts = callback_ts
        self.committed_ts = committed_ts
        super().__init__(
            f"task={task_id} callback_ts={callback_ts} committed_ts={committed_ts} reason={reason}"
        )


class TaskProjection:
    def __init__(self):
        self.status_ts: float = -1.0
        self.seq_high_water: int = -1
        self.terminal: bool = False


def apply_push_callback(
    projection: TaskProjection,
    task_id: str,
    callback_ts: float,
    state: str,
    seq: int,
    signature_valid: bool,
    key_in_validity_window: bool,
) -> TaskProjection:
    if not signature_valid:
        raise StalePushCallbackError(task_id, "signature_invalid", callback_ts, projection.status_ts)
    if not key_in_validity_window:
        raise StalePushCallbackError(task_id, "signing_key_expired", callback_ts, projection.status_ts)
    if projection.terminal:
        # Terminal states are absorbing; any later callback is a stale replay.
        raise StalePushCallbackError(task_id, "task_already_terminal", callback_ts, projection.status_ts)
    if callback_ts <= projection.status_ts:
        raise StalePushCallbackError(task_id, "timestamp_not_strictly_newer", callback_ts, projection.status_ts)
    if seq <= projection.seq_high_water:
        raise StalePushCallbackError(task_id, "sequence_below_high_water", callback_ts, projection.status_ts)

    projection.status_ts = callback_ts
    projection.seq_high_water = seq
    projection.terminal = state in ("completed", "failed", "canceled")
    return projection
