# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-last-event-id-resume-as-a-fork-rather-than-a-continuation-and-how-does-silent-even.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-streamable-http-last-event-id-resume-as-a-fork-rather-than-a-continuation-and-how-does-silent-even.warrant.json
# Markdown SHA-256:   91c33809842e7825270ff8b9f48be16b39261337b668eab347009299c26be3df
# Code AST SHA-256:   985abb6ff0d66ba16de263770f8789530eae09a43f5862cce5cc5e99cf1ddd34
# Verified Classes:   ResumeForkError, SessionLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ResumeForkError(RuntimeError):
    """Raised when an SSE resume cannot be proven to be a continuation.

    The replayed stream diverges from the client's authoritative history:
    an event ID was reused, a gap position is missing, or the disconnection
    exceeded the server's replay-retention window. Treating such a resume as
    a continuation risks duplicate side effects and phantom in-flight state.
    """


@dataclass
class SessionLog:
    """Client-side authoritative view of one MCP session's event stream."""

    seen_ids: set[str] = field(default_factory=set)
    last_id: str | None = None
    replay_retention_s: float | None = None  # None => unknown, assume unsafe

    def note(self, event_id: str) -> None:
        if event_id in self.seen_ids:
            raise ResumeForkError(
                f"event id {event_id!r} reissued within session: "
                "ID space is not session-monotonic; resume is a fork"
            )
        self.seen_ids.add(event_id)
        self.last_id = event_id


def reconcile_resume(
    log: SessionLog,
    replayed_ids: list[str],
    disconnected_for_s: float,
    effect_bearing: set[str],
) -> list[str]:
    """Decide which replayed events may be applied, or raise on a fork.

    Returns the subset of replayed IDs safe to apply immediately. Effect-bearing
    events on a suspect resume are withheld pending out-of-band reconciliation.
    """
    if log.replay_retention_s is None:
        raise ResumeForkError(
            "server advertises no replay-retention window; "
            "cannot prove the gap was not truncated"
        )
    if disconnected_for_s > log.replay_retention_s:
        raise ResumeForkError(
            f"disconnected {disconnected_for_s}s exceeds retention "
            f"{log.replay_retention_s}s; replayed events may be incomplete"
        )

    safe: list[str] = []
    for eid in replayed_ids:
        if eid in log.seen_ids:
            # Reuse across the reconnect boundary: the client already consumed
            # this ID from a different logical stream. Fork, not continuation.
            raise ResumeForkError(
                f"resume reissued previously-seen id {eid!r}; "
                "server likely reset a per-stream counter"
            )
        if eid in effect_bearing:
            # Withhold: must confirm current tool status out-of-band first.
            continue
        safe.append(eid)
        log.note(eid)
    return safe
