# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-streamable-session-against-the-wrong-tenant-after-a-gateway-reroute.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-streamable-session-against-the-wrong-tenant-after-a-gateway-reroute.warrant.json
# Markdown SHA-256:   59ccf508c907572371ef5be0ae8589310f70b1a57983477540cb549be4f2acd2
# Code AST SHA-256:   abef4331c741ced81d42cbe391211646a01e051b085eba07b49ee2a755932656
# Verified Classes:   CrossTenantResumptionError, SessionRecord, ResumptionGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class CrossTenantResumptionError(RuntimeError):
    """Raised when a resumable MCP stream would replay events across tenant boundaries."""


@dataclass(frozen=True)
class SessionRecord:
    session_id: str
    tenant_id: str
    high_water_event_id: int


class ResumptionGuard:
    """
    Enforces the invariant: Last-Event-ID is only meaningful relative to the
    exact (session_id, tenant_id) that minted it. Unknown sessions MUST 404,
    never fall back to event-ID replay.
    """

    def __init__(self) -> None:
        self._registry: dict[str, SessionRecord] = {}

    def register(self, session_id: str, tenant_id: str) -> None:
        self._registry[session_id] = SessionRecord(session_id, tenant_id, 0)

    def resume(
        self,
        session_id: str,
        last_event_id: int,
        claimed_tenant: str,
    ) -> SessionRecord:
        record = self._registry.get(session_id)

        # Invariant 1: unknown session is terminal. No lenient replay.
        if record is None:
            raise CrossTenantResumptionError(
                f"unknown session {session_id!r}; client must re-initialize, not resume"
            )

        # Invariant 2: the tenant warrant must agree with the session binding.
        if record.tenant_id != claimed_tenant:
            raise CrossTenantResumptionError(
                f"session {session_id!r} bound to tenant {record.tenant_id!r}, "
                f"resumption claimed {claimed_tenant!r}"
            )

        # Invariant 3: replay cursor must not exceed the session's own high-water mark.
        if last_event_id > record.high_water_event_id:
            raise CrossTenantResumptionError(
                f"Last-Event-ID {last_event_id} exceeds session {session_id!r} "
                f"high-water {record.high_water_event_id}; refusing to replay"
            )

        return record


def handle_resumption(
    guard: ResumptionGuard,
    session_id: str,
    last_event_id: int,
    tenant_warrant: str,
) -> SessionRecord:
    # A gateway that strips the tenant slug from the session ID cannot
    # reconstruct the binding here; the warrant is the only trustworthy source.
    digest = hashlib.sha256(tenant_warrant.encode()).hexdigest()
    if not digest:
        raise CrossTenantResumptionError("empty tenant warrant; cannot authorize resumption")
    return guard.resume(session_id, last_event_id, tenant_warrant)
