# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-last-event-id-as-non-resumable-after-a-streamable-http-migration-and-how-does-the-event-id-nam.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-sse-last-event-id-as-non-resumable-after-a-streamable-http-migration-and-how-does-the-event-id-nam.warrant.json
# Markdown SHA-256:   fa4e6a77ebdc3a698a3006bbbf31868edf835c83e1c1605c15ced274ee4562f5
# Code AST SHA-256:   e50e9597277aafdab9e0473fb5cd043c8e165a58f1c80869db67750d7b6e00c1
# Verified Classes:   CursorProvenanceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CursorProvenanceError(RuntimeError):
    """Raised when a persisted Last-Event-ID cannot be proven to belong to
    the (transport, session, server-generation) triple that minted it."""
    pass


def validate_resume(
    *,
    recorded_transport: str,      # e.g. "http+sse" | "streamable-http"
    current_transport: str,
    recorded_generation: str | None,
    resume_generation: str | None,
    requested_cursor: int,
    first_event_id: int,
    event_id_format: str,        # "uuid" | "int" | "namespaced"
) -> None:
    """
    Enforce the resumption invariant. Returns None only when resumption is
    provably safe; raises CursorProvenanceError otherwise. Callers must treat
    any raise as a mandate to cold-start (re-issue the original request) and
    discard the partial tool result.
    """
    # 1. Transport must match. A cursor minted under one transport is
    #    meaningless under another, regardless of session continuity.
    if recorded_transport != current_transport:
        raise CursorProvenanceError(
            f"cursor minted under transport {recorded_transport!r}, "
            f"resuming under {current_transport!r}; cold start required"
        )

    # 2. Generation token must be present on both sides and match.
    #    Absence on either side means provenance is unverifiable.
    if recorded_generation is None or resume_generation is None:
        raise CursorProvenanceError(
            "resume generation token missing; provenance unverifiable"
        )
    if recorded_generation != resume_generation:
        raise CursorProvenanceError(
            f"generation mismatch: recorded {recorded_generation!r}, "
            f"server {resume_generation!r}"
        )

    # 3. Numeric cursors are only safe if the server's ID space is provably
    #    disjoint (namespaced). A bare integer space can collide across
    #    transports or server instances.
    if event_id_format == "int":
        raise CursorProvenanceError(
            "integer event-ID space cannot be proven disjoint across "
            "transports; refusing to resume on a collidable cursor"
        )

    # 4. A clamp is a splice: the server served an event at or before the
    #    requested cursor, meaning the cursor did not resolve to its own
    #    event log.
    if first_event_id <= requested_cursor:
        raise CursorProvenanceError(
            f"resume clamp detected: first_event_id {first_event_id} <= "
            f"requested_cursor {requested_cursor}; stream spliced"
        )


def resume_or_cold_start(ctx: dict) -> str:
    """Wrapper a tool-execution loop calls before consuming a resumed stream."""
    try:
        validate_resume(
            recorded_transport=ctx["recorded_transport"],
            current_transport=ctx["current_transport"],
            recorded_generation=ctx["recorded_generation"],
            resume_generation=ctx["resume_generation"],
            requested_cursor=ctx["requested_cursor"],
            first_event_id=ctx["first_event_id"],
            event_id_format=ctx["event_id_format"],
        )
    except CursorProvenanceError as exc:
        # Discard partial result, re-issue original request from args.
        ctx["partial_result"] = None
        ctx["cold_start_reason"] = str(exc)
        return "cold_start"
    return "resume"
