# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-mcp-http-native-streamable-session-resumption-has-silently-forked-an-sse-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-mcp-http-native-streamable-session-resumption-has-silently-forked-an-sse-event-stream.warrant.json
# Markdown SHA-256:   77fe62d33c98790478af0d5d4c61bda089c4ba3dfbe7ba8a6b1c4b13bf6d452f
# Code AST SHA-256:   9224188b20f4675bd47e871b589bb191a215b4fc4173bb4a5f38fece881e7a8c
# Verified Classes:   StreamForkError, SessionLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class StreamForkError(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven continuous with the client ledger."""


@dataclass
class SessionLedger:
    cursor: str | None = None
    issued_calls: set[str] = field(default_factory=set)
    received_results: set[str] = field(default_factory=set)
    retention_seconds: int = 60
    disconnect_elapsed_seconds: int = 0


def assert_resume_continuity(
    ledger: SessionLedger,
    first_replayed_event_id: str | None,
    expected_next_event_id: str | None,
    server_declared_replay: bool,
) -> None:
    # Condition 1: server must implement replay, not continuation-tail.
    if not server_declared_replay:
        raise StreamForkError(
            "server does not declare replay semantics; a 200 on reconnect "
            "cannot be treated as event continuity"
        )

    # Condition 2: retention window must exceed the disconnect window.
    if ledger.disconnect_elapsed_seconds >= ledger.retention_seconds:
        raise StreamForkError(
            f"disconnect {ledger.disconnect_elapsed_seconds}s >= retention "
            f"{ledger.retention_seconds}s; event log may have been evicted and "
            "server may have silently tailed from a newer position"
        )

    # Condition 3: the first replayed event must be the exact successor of the cursor.
    if first_replayed_event_id != expected_next_event_id:
        raise StreamForkError(
            f"resume forked: expected first event {expected_next_event_id!r}, "
            f"got {first_replayed_event_id!r}; history diverged at cursor "
            f"{ledger.cursor!r}"
        )


def reconcile_result(ledger: SessionLedger, result_call_id: str) -> None:
    # A result for a call the client never issued is a hard violation,
    # not a recoverable anomaly: the server replayed a suffix we did not produce.
    if result_call_id not in ledger.issued_calls:
        raise StreamForkError(
            f"received tool_result for unissued call {result_call_id!r}; "
            "server replayed events from a forked history"
        )
    ledger.received_results.add(result_call_id)


def close_session(ledger: SessionLedger) -> None:
    outstanding = ledger.issued_calls - ledger.received_results
    if outstanding:
        raise StreamForkError(
            f"session closed with unresolved calls {sorted(outstanding)}; "
            "must reconcile via query_call_status before abandoning session"
        )
