# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-last-event-id-resumption-when-the-sse-to-streamable-http-migration-silently-forks-the-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-last-event-id-resumption-when-the-sse-to-streamable-http-migration-silently-forks-the-event-stream.warrant.json
# Markdown SHA-256:   fb37308cc10cfc42227cb7af5d897ab00625204c17bbe4af36fc7945a85749ce
# Code AST SHA-256:   b0c8af5aee1ed44b0286ea1236e2114c9c7b9a3fd25b3cda8e82ff2b56886eae
# Verified Classes:   ResumptionForkError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumptionForkError(RuntimeError):
    """Raised when a streamable-HTTP resume returns a first event ID that
    does not strictly exceed the client's last-seen ID, indicating the
    server's event-ID namespace was reset (e.g. SSE->streamable-HTTP
    migration) and the stream has forked rather than resumed."""
    pass


def validate_resume(
    last_seen_id: int,
    first_replayed_id: int,
    server_declares_strict_resumption: bool,
) -> str:
    """
    Enforce the cursor-continuity invariant for MCP Last-Event-ID resume.

    Returns one of:
      "resume"   -> safe to continue on this stream
      "dedupe"   -> replayed IDs are true duplicates; dedupe and continue
    Raises ResumptionForkError when the stream has forked and the client
    must re-initialize the session instead of continuing.
    """
    if first_replayed_id > last_seen_id:
        return "resume"

    # first_replayed_id <= last_seen_id: either duplicate or fork.
    if server_declares_strict_resumption:
        return "dedupe"

    # No strict-resumption capability: cannot prove the low IDs are
    # duplicates rather than a reset namespace. This is the migration
    # fork. Refuse to continue on this stream.
    raise ResumptionForkError(
        f"resume forked: last_seen_id={last_seen_id} "
        f"first_replayed_id={first_replayed_id} "
        f"strict_capability={server_declares_strict_resumption}; "
        f"re-initialize session and re-fetch tool/resource manifests"
    )


def resume_stream(client, session_id: str) -> None:
    resp = client.get_stream(session_id, last_event_id=client.last_seen_id)
    first_id = resp.peek_first_event_id()
    action = validate_resume(
        last_seen_id=client.last_seen_id,
        first_replayed_id=first_id,
        server_declares_strict_resumption=resp.capabilities.get(
            "resumption", ""
        ) == "strict",
    )
    if action == "resume":
        client.consume(resp)
    elif action == "dedupe":
        client.consume(resp, skip_ids_le=client.last_seen_id)
    # ResumptionForkError propagates to the caller, which must run
    # client.reinitialize() before any further tool calls.
