# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumable-sse-stream-when-the-server-s-last-event-id-watermark-regresses-below-the-client-s-last-ackno.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumable-sse-stream-when-the-server-s-last-event-id-watermark-regresses-below-the-client-s-last-ackno.warrant.json
# Markdown SHA-256:   aefd368172cd61e68cc6a4e178c1033b7fd11358ba2dab34225809cbe55870b7
# Code AST SHA-256:   d63317bdc115ecc38f0134ce8ddd0b1af341f77eef10a6641e8e6d46dcb50dd2
# Verified Classes:   ResumptionWatermarkRegression, ResumptionFramingMismatch, ResumptionSessionRebind, ResumptionResponse
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass

class ResumptionWatermarkRegression(RuntimeError):
    """Raised when a resumption GET response violates stream continuity."""

class ResumptionFramingMismatch(ResumptionWatermarkRegression):
    """Resumption request answered with non-SSE framing (JSON body)."""

class ResumptionSessionRebind(ResumptionWatermarkRegression):
    """Server silently rebound the session ID on resumption."""

@dataclass
class ResumptionResponse:
    content_type: str          # e.g. "text/event-stream" or "application/json"
    session_id: str
    first_event_id: int | None # None if body was not SSE
    body: dict | None          # parsed JSON if content_type was application/json

NON_IDEMPOTENT_TOOLS = {"shell.exec", "git.push", "npm.publish", "db.migrate"}

def validate_resumption(
    request_session_id: str,
    last_event_id: int,
    resp: ResumptionResponse,
) -> None:
    """
    Gate every resumption GET response before it reaches the JSON-RPC router.
    Must be called between transport read and message dispatch.
    """
    # Invariant 3: no silent session rebind
    if resp.session_id != request_session_id:
        raise ResumptionSessionRebind(
            f"session rebound {request_session_id} -> {resp.session_id} on resumption"
        )

    # Invariant 1: resumption MUST be SSE, not JSON fallback
    if resp.content_type != "text/event-stream":
        raise ResumptionFramingMismatch(
            f"resumption GET answered with {resp.content_type!r}; "
            f"treating as fresh session, not continuation"
        )

    # Invariant 2: watermark monotonicity
    if resp.first_event_id is None or resp.first_event_id <= last_event_id:
        raise ResumptionWatermarkRegression(
            f"watermark regressed: acked {last_event_id}, "
            f"stream opened at {resp.first_event_id}"
        )

def dispatch_resumed_message(
    request_session_id: str,
    last_event_id: int,
    resp: ResumptionResponse,
    gap_tool_calls: list[str] | None = None,
) -> dict:
    # Hard gate first.
    validate_resumption(request_session_id, last_event_id, resp)

    # Second-order boundary: replay-gap safety.
    if gap_tool_calls:
        unsafe = set(gap_tool_calls) & NON_IDEMPOTENT_TOOLS
        if unsafe:
            raise ResumptionWatermarkRegression(
                f"unreplayable gap contains non-idempotent tools: {sorted(unsafe)}; "
                f"must re-initialize and re-derive, not continue"
            )

    assert resp.body is not None
    return resp.body
