# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-sse-resumption-after-an-mcp-session-reattachment-loses-the-last-event-id-continuity-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-sse-resumption-after-an-mcp-session-reattachment-loses-the-last-event-id-continuity-anchor.warrant.json
# Markdown SHA-256:   60c6d58f52e83e16d011d9ce188c71124817fedcc26559076587d526c36e88b2
# Code AST SHA-256:   1198690ee928522c01e075656796bf87e1e4170fae392f9fe832d6a8d63981b8
# Verified Classes:   ResumptionContinuityError, PendingLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class ResumptionContinuityError(RuntimeError):
    """Raised when an SSE resumption cannot be tied to the pending-request ledger."""


@dataclass
class PendingLedger:
    outstanding: dict[str, str] = field(default_factory=dict)  # jsonrpc id -> method
    seen_progress_tokens: set[str] = field(default_factory=set)

    def register(self, req_id: str, method: str, progress_token: str | None) -> None:
        self.outstanding[req_id] = method
        if progress_token:
            self.seen_progress_tokens.add(progress_token)


def admit_replayed_event(ledger: PendingLedger, raw_data: str, last_event_id: str) -> dict:
    """Validate a replayed SSE frame against the pending ledger.

    Returns the parsed JSON-RPC message if it is safe to admit to the reasoning
    context. Raises ResumptionContinuityError if the frame cannot be attributed
    to an outstanding request in the current event-ID namespace.
    """
    try:
        msg = json.loads(raw_data)
    except json.JSONDecodeError as exc:
        raise ResumptionContinuityError(
            f"unparseable replay frame at Last-Event-ID={last_event_id}: {exc}"
        ) from exc

    # Progress notifications must reference a token this client issued.
    if msg.get("method") == "notifications/progress":
        token = (msg.get("params") or {}).get("progressToken")
        if token not in ledger.seen_progress_tokens:
            raise ResumptionContinuityError(
                f"foreign progressToken {token!r} replayed at event {last_event_id}; "
                "event-ID namespace forked — must re-issue, not resume"
            )
        return msg

    # Result/error frames must carry an id we have outstanding.
    if "result" in msg or "error" in msg:
        req_id = msg.get("id")
        if req_id is None or str(req_id) not in ledger.outstanding:
            raise ResumptionContinuityError(
                f"replay frame carries id={req_id!r} with no outstanding request "
                f"at event {last_event_id}; refusing to admit foreign result"
            )
        return msg

    # Unknown frame shapes are not admissible under resumption.
    raise ResumptionContinuityError(
        f"unrecognized replayed frame shape at event {last_event_id}: "
        f"keys={sorted(msg.keys())}"
    )


def resume_stream(ledger: PendingLedger, server_epoch: str, client_epoch: str,
                  frames: list[tuple[str, str]]) -> list[dict]:
    if server_epoch != client_epoch:
        raise ResumptionContinuityError(
            f"session epoch mismatch: client={client_epoch} server={server_epoch}; "
            "reattachment crossed a process boundary — re-issue required"
        )
    admitted: list[dict] = []
    for event_id, data in frames:
        admitted.append(admit_replayed_event(ledger, data, event_id))
    return admitted
