# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-stream-resumable-progress-from-replayed-side-effects-when-an-mcp-tool-call-spans-a-reconnect-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-stream-resumable-progress-from-replayed-side-effects-when-an-mcp-tool-call-spans-a-reconnect-boundary.warrant.json
# Markdown SHA-256:   afbf09642cf9ab1f9681f433a5fef2692717d4dd67a703ca984e5362a36fe21e
# Code AST SHA-256:   a22b94ec6499830a66e80d07a9982614639f9839def22a8b6261bd4e68978e1d
# Verified Classes:   ResumptionAuthorityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionAuthorityError(RuntimeError):
    """Raised when replayed stream events disagree with executor ground truth."""
    pass


def reconcile_on_reconnect(
    replayed_events: list[dict],
    executor_status: dict,
    call_id: str,
) -> dict:
    """
    Decide whether a replayed SSE stream may be treated as the authoritative
    record of a long-running MCP tool call.

    replayed_events: events delivered after Last-Event-ID, in order.
    executor_status: ground-truth status queried from the tool executor,
                     keyed by call_id. Must include 'state' and 'call_id'.
    """
    if executor_status.get("call_id") != call_id:
        raise ResumptionAuthorityError(
            f"executor status is for {executor_status.get('call_id')!r}, "
            f"not {call_id!r}; replay cannot be attributed to this call"
        )

    terminal_events = [
        e for e in replayed_events if e.get("type") in ("result", "error")
    ]
    state = executor_status["state"]

    if terminal_events and state == "running":
        # Stream says done; executor says still working. Do not trust either
        # alone — this is the phantom-completion signature.
        raise ResumptionAuthorityError(
            f"call {call_id}: replayed terminal event "
            f"{terminal_events[-1].get('id')} but executor state is 'running'"
        )

    if state == "cancelled" and not any(
        e.get("type") == "cancelled" for e in replayed_events
    ):
        # Executor aborted; replay omitted the cancellation marker. The client
        # would otherwise wait forever for events that will never arrive.
        raise ResumptionAuthorityError(
            f"call {call_id}: executor cancelled but no cancellation marker "
            f"in replayed stream; client would hang"
        )

    if state == "completed" and not terminal_events:
        # Executor finished but the terminal event was lost from the buffer.
        # Safe to synthesize only because executor is the authority.
        return {"authority": "executor", "call_id": call_id, "synthesized": True}

    return {"authority": "stream", "call_id": call_id, "synthesized": False}
