# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-forked-mcp-streamable-session-when-the-sse-to-post-upgrade-races-the-resumption-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-forked-mcp-streamable-session-when-the-sse-to-post-upgrade-races-the-resumption-cursor.warrant.json
# Markdown SHA-256:   3a5bca3f65a383ea1ec394a887b1e5fd02e69660a23c65ec401e200d81533f13
# Code AST SHA-256:   e0204d8da197d9101bfbd527b85990ff12d75270b1fcb6c6e9050115f380ea51
# Verified Classes:   SessionForkError, Leg
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SessionForkError(RuntimeError):
    """Raised when a POST leg allocates a session ID that diverges from the
    session ID of the SSE GET currently replaying. Merging the two halves is
    unsafe; the caller must abort the POST leg and re-open as a fresh session."""


@dataclass(frozen=True)
class Leg:
    session_id: str
    transport: str  # "sse_get" | "post"
    last_event_id: int | None = None


def reconcile_resumption(
    sse: Leg,
    post: Leg,
    replay_complete: bool,
) -> str:
    """Return the session ID the client should continue with.

    Invariant: a resumed session must present one session ID across both legs,
    and the POST may only be issued after replay_complete is True.
    """
    if sse.transport != "sse_get" or post.transport != "post":
        raise SessionForkError(
            f"leg roles swapped: sse={sse.transport} post={post.transport}"
        )

    if not replay_complete:
        raise SessionForkError(
            "POST issued before SSE replay reached Last-Event-ID; "
            "server may allocate a fresh session for the POST leg"
        )

    if sse.session_id != post.session_id:
        # This is the fork. Do NOT merge. Abort the POST leg.
        raise SessionForkError(
            f"session fork: sse={sse.session_id} post={post.session_id}; "
            f"abort POST leg, re-open GET as fresh session with {post.session_id}"
        )

    # Same ID on both legs and replay completed: safe to continue.
    return sse.session_id


def session_fingerprint(session_id: str, last_event_id: int) -> str:
    return hashlib.sha256(f"{session_id}:{last_event_id}".encode()).hexdigest()[:16]


# Example: the observed failure trace.
try:
    reconcile_resumption(
        sse=Leg(session_id="7f3a", transport="sse_get", last_event_id=412),
        post=Leg(session_id="9b1c", transport="post"),
        replay_complete=False,
    )
except SessionForkError as e:
    # Correct response: drop the 9b1c POST leg, re-open GET for 9b1c as fresh.
    print(f"detected: {e}")
