# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-taskstatusupdateevent-whose-final-flag-disagrees-with-the-terminality-implied-by-its-state-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-a2a-v1-0-taskstatusupdateevent-whose-final-flag-disagrees-with-the-terminality-implied-by-its-state-a.warrant.json
# Markdown SHA-256:   27d1ef7d9a7350e5bcccb079087fbfd5c6d5779f5e312a613f8f98387ae0b1e4
# Code AST SHA-256:   25f5fe22368bc6b76844d3137972193438dfd662b539bb5d6562397aaebf5256
# Verified Classes:   TaskFinalityMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaskFinalityMismatch(RuntimeError):
    """Raised when a TaskStatusUpdateEvent's `final` flag contradicts its `state`."""
    pass


TERMINAL_STATES = frozenset({"completed", "failed", "canceled"})


def validate_status_event(event: dict, ledger: dict) -> None:
    """
    Validate a TaskStatusUpdateEvent received over a final-terminating channel
    (streaming close or webhook delivery with no resubscribe primitive).

    `ledger` maps taskId -> last observed TaskState. Mutated in place on success.
    """
    task_id = event.get("taskId")
    state = event.get("status", {}).get("state")
    is_final = event.get("final", False)

    if task_id is None or state is None:
        raise TaskFinalityMismatch(
            f"malformed TaskStatusUpdateEvent: taskId={task_id!r} state={state!r}"
        )

    prior = ledger.get(task_id)

    # A terminal state already observed: any further non-terminal 'final' event
    # is an idempotent duplicate or a late straggler; do not regress the ledger.
    if prior in TERMINAL_STATES:
        return

    if is_final and state not in TERMINAL_STATES:
        # The channel will close, but the task is not done. The receiver has no
        # resubscribe primitive here, so this is unrecoverable without an
        # out-of-band completion channel. Escalate; do not coerce.
        raise TaskFinalityMismatch(
            f"task {task_id!r}: final=true but state={state!r} is non-terminal; "
            f"prior={prior!r}. Receiver cannot resolve locally."
        )

    ledger[task_id] = state
