# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-across-replicas-rather-than-resumed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-across-replicas-rather-than-resumed.warrant.json
# Markdown SHA-256:   0576309d12cd0c49d9ee1d26b69273f7f95fb6459aa331af4c54d1bd47711c20
# Code AST SHA-256:   c1615aa83e87db6a369feb1dea90b3c08bdf61e32e2dfb5c0a4a82448b4bd42e
# Verified Classes:   SessionForkError, EventLog, SessionRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SessionForkError(RuntimeError):
    """Raised when a resume request is accepted but the server cannot prove
    continuity of the event log for (session_id, last_event_id)."""


@dataclass
class EventLog:
    session_id: str
    origin_replica: str
    # sequence -> payload; authoritative only on the origin replica
    events: dict[int, str]

    def highest_seq(self) -> int:
        return max(self.events) if self.events else 0


@dataclass
class SessionRecord:
    session_id: str
    principal: str
    origin_replica: str


def resume_stream(
    session_id: str,
    last_event_id: int,
    shared_sessions: dict[str, SessionRecord],
    local_logs: dict[str, EventLog],
    this_replica: str,
) -> list[str]:
    """Attempt to resume an SSE stream. Returns the events to replay, or raises
    SessionForkError if continuity cannot be proven.

    The invariant enforced here: a resume is valid iff the local replica can
    produce the contiguous sequence last_event_id+1..highest_seq from the log
    that *originated* this session. Accepting the session without that proof is
    a fork.
    """
    record = shared_sessions.get(session_id)
    if record is None:
        raise SessionForkError(
            f"session {session_id!r} unknown; client must re-initialize"
        )

    if record.principal is None:
        raise SessionForkError(
            f"session {session_id!r} has no bound principal; refusing resume"
        )

    log = local_logs.get(session_id)

    # Case 1: no local log at all. The session record exists (it was replicated
    # or optimistically accepted) but this replica has never seen an event for
    # it. Any acceptance here is a silent fork. Refuse.
    if log is None:
        raise SessionForkError(
            f"session {session_id!r} has no event log on replica "
            f"{this_replica!r} (origin was {record.origin_replica!r}); "
            f"cannot prove continuity for Last-Event-ID {last_event_id}"
        )

    # Case 2: local log exists but originated elsewhere. We cannot trust its
    # sequence space; the client's Last-Event-ID refers to a different lineage.
    if log.origin_replica != record.origin_replica:
        raise SessionForkError(
            f"session {session_id!r} log origin {log.origin_replica!r} "
            f"!= session origin {record.origin_replica!r}; lineage mismatch"
        )

    # Case 3: local log exists and matches origin, but the requested resume
    # point is ahead of what we have. We would have to invent events to fill
    # the gap; that is a fork with extra steps.
    if last_event_id > log.highest_seq():
        raise SessionForkError(
            f"session {session_id!r}: Last-Event-ID {last_event_id} exceeds "
            f"local highest_seq {log.highest_seq()}; log truncated or forked"
        )

    # Case 4: contiguous replay is possible. This is the only admissible path.
    replay = []
    for seq in range(last_event_id + 1, log.highest_seq() + 1):
        if seq not in log.events:
            raise SessionForkError(
                f"session {session_id!r}: gap at seq {seq} in log; "
                f"cannot produce contiguous replay"
            )
        replay.append(log.events[seq])
    return replay


def handle_resume_request(
    session_id: str,
    last_event_id: int,
    shared_sessions: dict[str, SessionRecord],
    local_logs: dict[str, EventLog],
    this_replica: str,
) -> tuple[int, list[str]]:
    """Map a resume attempt to an HTTP status + body. 200 only on proven
    continuity; 400 otherwise, forcing the client to re-initialize."""
    try:
        replay = resume_stream(
            session_id, last_event_id, shared_sessions, local_logs, this_replica
        )
    except SessionForkError as exc:
        # Loud failure: client must discard its Last-Event-ID and re-initialize.
        # This is strictly better than a silent fork with duplicate side effects.
        return 400, [str(exc)]
    return 200, replay
