# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-streamable-session-resumption-as-a-fresh-capability-negotiation-rather-than-a-continuation-and-how-doe.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-streamable-session-resumption-as-a-fresh-capability-negotiation-rather-than-a-continuation-and-how-doe.warrant.json
# Markdown SHA-256:   c606d134fe76f66452a1cf81a23db5f008e15daa5fd1ef640427097ea14aa57e
# Code AST SHA-256:   fe0d817f1481c9b22193c68f46a30ed867841d6af25e8e16b2085f575c8f7042
# Verified Classes:   ResumptionInvariantViolation, SessionBinding, ResumeRequest, InFlightCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ResumptionInvariantViolation(RuntimeError):
    """Raised when a streamable-session resume would replay a cursor across
    a session or capability boundary it does not belong to."""


@dataclass
class SessionBinding:
    session_id: str
    capabilities: dict
    event_epoch: str  # server namespace tag for Last-Event-ID

    def capability_hash(self) -> str:
        blob = json.dumps(self.capabilities, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class ResumeRequest:
    session_id: str
    capabilities: dict
    last_event_id: str
    event_epoch: str


@dataclass
class InFlightCall:
    request_id: int
    progress_token: int
    tool: str
    orphaned: bool = False


def classify_resume(
    prior: SessionBinding,
    req: ResumeRequest,
    cursor_in_range: bool,
    server_signaled_unsupported: bool,
    in_flight: list[InFlightCall] = field(default_factory=list),
) -> str:
    # New session ID after an SSE->streamable upgrade: cursor is foreign.
    if req.session_id != prior.session_id:
        for call in in_flight:
            call.orphaned = True
        return "renegotiate_discard_cursor"

    # Same session, but capabilities drifted (hot-swapped tools/schemas).
    if req.capabilities != prior.capabilities:
        for call in in_flight:
            call.orphaned = True
        return "renegotiate_invalidate_changed_calls"

    # Same session, same capabilities, but event namespace changed.
    if req.event_epoch != prior.event_epoch:
        for call in in_flight:
            call.orphaned = True
        return "renegotiate_discard_cursor"

    # Server cannot prove the cursor is in range: silent head-reset is forbidden.
    if server_signaled_unsupported or not cursor_in_range:
        raise ResumptionInvariantViolation(
            f"session {req.session_id}: cursor {req.last_event_id!r} not "
            f"provably in-range for epoch {req.event_epoch!r}; "
            "refusing silent head-reset, re-negotiation required"
        )

    return "resume"


def resume_or_fail(prior: SessionBinding, req: ResumeRequest,
                   cursor_in_range: bool, server_signaled_unsupported: bool,
                   in_flight: list[InFlightCall]) -> str:
    verdict = classify_resume(prior, req, cursor_in_range,
                              server_signaled_unsupported, in_flight)
    if verdict != "resume":
        # Caller must re-initialize and re-subscribe; orphaning is enforced above.
        return verdict
    if not all(not c.orphaned for c in in_flight):
        raise ResumptionInvariantViolation(
            "resume accepted but in-flight calls were orphaned — state machine bug"
        )
    return verdict
