# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-resumption-identity-before-treating-an-mcp-streamable-http-session-as-stateless.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-resumption-identity-before-treating-an-mcp-streamable-http-session-as-stateless.warrant.json
# Markdown SHA-256:   2eaaa3b9db13ff9b79f3a23c7fe5d0081e471839a28972f98f328736ebd140e4
# Code AST SHA-256:   b76f3e21353c2ff46dbf5ef0e9051d22e6f5e8a2417db9701f52a127a381aefb
# Verified Classes:   UnrecoverableStreamGap
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnrecoverableStreamGap(RuntimeError):
    """Raised when an SSE reconnect shows an ID discontinuity with no replay marker,
    meaning the server is stateless and cannot replay the missing events."""
    pass


def reconcile_reconnect(
    last_event_id: int,
    first_returned_id: int,
    server_declared_replay_window: int | None,
    operation_is_idempotent: bool,
) -> str:
    """
    Decide whether to resume, restart, or reconcile after an MCP streamable-HTTP
    SSE reconnect. Returns one of: "resume", "restart", "reconcile_sidechannel".
    """
    if first_returned_id == last_event_id or first_returned_id == last_event_id + 1:
        return "resume"

    # ID gap detected. Determine whether the server could have replayed.
    gap = first_returned_id - last_event_id - 1
    if server_declared_replay_window is not None and gap <= server_declared_replay_window:
        # Server claims it should have replayed; a gap here means it failed to.
        raise UnrecoverableStreamGap(
            f"Server declared replay window {server_declared_replay_window} but "
            f"skipped {gap} events between {last_event_id} and {first_returned_id}; "
            f"treating as data loss, not quiet interval."
        )

    if operation_is_idempotent:
        return "restart"

    # Non-idempotent and gap is real: do not resume, do not blindly restart.
    # Re-read the mutated resource instead of re-running the tool.
    return "reconcile_sidechannel"


def apply_reconnect_decision(decision: str, op_id: str) -> None:
    if decision not in {"resume", "restart", "reconcile_sidechannel"}:
        raise UnrecoverableStreamGap(
            f"Unknown reconnect decision {decision!r} for operation {op_id}; "
            f"refusing to advance state on an unresolved stream gap."
        )
