# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-sse-resume-is-replaying-a-divergent-tool-call-stream-rather-than-continuing-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-sse-resume-is-replaying-a-divergent-tool-call-stream-rather-than-continuing-it.warrant.json
# Markdown SHA-256:   bfa858b712f6387ef472f0fa866bb9dee51c766a777459ec778130595a7a15f8
# Code AST SHA-256:   54d9205236b35549640d5b313803127b3192a394e0d1b63bbad8b81437b9bd03
# Verified Classes:   ResumptionDivergenceError, StreamCursor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Optional


class ResumptionDivergenceError(RuntimeError):
    """Raised when a reconnected SSE stream is structurally a session restart,
    not a transport-level replay, and the agent must not treat it as continuity."""


@dataclass
class StreamCursor:
    last_acknowledged_id: int = 0
    seen_request_ids: set = field(default_factory=set)
    seen_side_effect_phases: set = field(default_factory=set)


def classify_resumption(
    cursor: StreamCursor,
    first_replayed_frame: dict,
    prior_side_effect_phases: set,
) -> str:
    """Classify a reconnected SSE stream as 'replay' or 'restart'.

    first_replayed_frame is the parsed JSON of the first `event: message` frame
    after reconnect, including its SSE `id` field.
    """
    event_id = first_replayed_frame.get("id")
    if event_id is None:
        raise ResumptionDivergenceError(
            "reconnected stream emitted a frame with no SSE id; "
            "cannot establish replay continuity"
        )

    # Condition 1: monotonic continuation of the acknowledged event sequence.
    if event_id <= cursor.last_acknowledged_id:
        raise ResumptionDivergenceError(
            f"event id regression: replayed id {event_id} <= "
            f"last acknowledged {cursor.last_acknowledged_id}; "
            f"server evicted buffer and restarted sub-stream"
        )

    payload = first_replayed_frame.get("data", {})
    rpc_id = payload.get("id")
    phase = payload.get("params", {}).get("phase")

    # Condition 3: no re-observation of an already-seen side-effect phase.
    if phase is not None and phase in prior_side_effect_phases:
        raise ResumptionDivergenceError(
            f"side-effect phase {phase!r} re-observed on reconnect for "
            f"request {rpc_id!r}; tool execution was restarted, not resumed"
        )

    # Condition 2: request id must be one we still consider in-flight.
    if rpc_id is not None and rpc_id not in cursor.seen_request_ids:
        raise ResumptionDivergenceError(
            f"replayed frame references unknown request id {rpc_id!r}; "
            f"stream belongs to a different execution context"
        )

    return "replay"


def handle_reconnect(
    cursor: StreamCursor,
    frames: list,
    prior_side_effect_phases: set,
) -> str:
    if not frames:
        raise ResumptionDivergenceError("reconnect produced zero frames")
    verdict = classify_resumption(cursor, frames[0], prior_side_effect_phases)
    if verdict == "restart":
        # Unreachable given the raises above, but kept explicit for the
        # orchestrator contract.
        raise ResumptionDivergenceError("stream classified as restart")
    return verdict
