# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-task-terminal-loss-in-a2a-streaming-lifecycles-when-structured-event-schemas-disagree-on-terminality.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-task-terminal-loss-in-a2a-streaming-lifecycles-when-structured-event-schemas-disagree-on-terminality.warrant.json
# Markdown SHA-256:   636aacfc1a92a28d97506246df2bdaa93ffb81cb3861e82fd50ed4fc1e826593
# Code AST SHA-256:   22634ec0b6810c1e6b55c66dfbef8e7bf801b820965ffc731961f575c28bea35
# Verified Classes:   TaskTerminalLoss, StreamClose
# Defensive Guards:   2 fail-closed invariants (zero external deps)

def reduce(stream):
    last_state = "submitted"
    for ev in stream:
        last_state = ev["status"]["state"] if "status" in ev else last_state
        if ev.get("final"):
            return ("done", ev)
    return ("done", {"status": {"state": last_state}})  # <-- the bug

from dataclasses import dataclass
from typing import Iterable, Literal, Optional

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


class TaskTerminalLoss(RuntimeError):
    """Raised when an A2A stream closes without a reconciled semantic terminal status."""


@dataclass
class StreamClose:
    cause: Literal[
        "semantic_terminal",
        "transport_eof_after_terminal",
        "idle_timeout",
        "client_cancel",
        "error",
    ]


def reconcile_task(
    events: Iterable[dict],
    close: StreamClose,
    fetch_task_state,  # callable(task_id) -> Optional[str]; None if unreachable
    task_id: str,
    max_retries: int = 2,
) -> str:
    """
    Reduce an A2A event stream to a reconciled terminal state, or raise.
    Invariant: transport terminality is never a proxy for semantic terminality.
    """
    last_state: Optional[str] = None
    saw_final_flag = False

    for ev in events:
        status = ev.get("status")
        if status and "state" in status:
            last_state = status["state"]
        if ev.get("final") is True:
            saw_final_flag = True
            # final flag is a consequence, not a cause: it must agree with state
            if last_state not in TERMINAL_STATES:
                raise TaskTerminalLoss(
                    f"task {task_id}: final=true with non-terminal state {last_state!r}"
                )

    if last_state in TERMINAL_STATES:
        return last_state

    # Stream ended without semantic terminality. Do NOT default to success.
    for attempt in range(max_retries + 1):
        observed = fetch_task_state(task_id)
        if observed in TERMINAL_STATES:
            return observed
        if observed is None:
            break  # executor unreachable; cannot reconcile

    raise TaskTerminalLoss(
        f"task {task_id}: stream closed ({close.cause}) with last_state={last_state!r}, "
        f"saw_final_flag={saw_final_flag}; reconciliation failed after "
        f"{max_retries + 1} attempts. Task must be marked 'unknown', not 'completed'."
    )
