# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-when-the-sse-fallback-negotiation-silently-downgrades-the-t.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-when-the-sse-fallback-negotiation-silently-downgrades-the-t.warrant.json
# Markdown SHA-256:   1cb79bb41001b5f51dd94bbfd743d5fddbd76e4f7c9325da3ccd09a0f00634f2
# Code AST SHA-256:   40c33cba6ae236928e0816ddc93239b31e244d07a2ac2236bb0796860e030b52
# Verified Classes:   UnverifiedStreamResumption, StreamIncarnation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnverifiedStreamResumption(RuntimeError):
    """Raised when an MCP streamable-HTTP resumption cannot prove event-log continuity."""
    pass


class StreamIncarnation:
    def __init__(self, stream_id: str | None, last_event_id: int):
        self.stream_id = stream_id          # server-provided marker, may be None
        self.last_event_id = last_event_id  # what the client presented


def validate_resumption(
    presented: StreamIncarnation,
    response_stream_id: str | None,
    first_event_id: int,
    gap_signal: str | None,  # "none" | "gap:N" | None
) -> str:
    """Return 'replay', 'replay_with_gap', or 'reinit'. Raise on unverified fork."""
    # 1. Stream-incarnation continuity, if the server offers a marker.
    if presented.stream_id is not None and response_stream_id is not None:
        if presented.stream_id != response_stream_id:
            return "reinit"  # explicit fork: different event-log incarnation
    # 2. Event-ID monotonicity across the boundary.
    if first_event_id <= presented.last_event_id:
        return "reinit"  # different namespace, IDs restarted
    # 3. Gap disclosure.
    if gap_signal == "none":
        return "replay"
    if gap_signal is not None and gap_signal.startswith("gap:"):
        return "replay_with_gap"
    # No marker, no gap signal: the common real-world case.
    raise UnverifiedStreamResumption(
        f"resumption for stream={presented.stream_id!r} "
        f"last_event_id={presented.last_event_id} delivered "
        f"first_event_id={first_event_id} with no incarnation marker "
        f"and no gap signal; treating as unverified fork"
    )


def resume_session(presented: StreamIncarnation, response) -> str:
    try:
        return validate_resumption(
            presented,
            response.headers.get("Mcp-Stream-Id"),
            int(response.first_event_id),
            response.headers.get("Mcp-Gap-Signal"),
        )
    except UnverifiedStreamResumption:
        # Do NOT apply replayed events. Re-derive state from durable checkpoint.
        return "reinit"
