# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-last-event-id-resumption-as-a-new-logical-turn-rather-than-a-continuation-and-how-does-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-streamable-http-last-event-id-resumption-as-a-new-logical-turn-rather-than-a-continuation-and-how-does-backpressure.warrant.json
# Markdown SHA-256:   a46ec95a79f8d91e64ca21c31078cd3e819222d0d943a6d64b42cd8d35eaa1cf
# Code AST SHA-256:   1f011094469ea5c63b797dce2b4da370095b934be3680c5e1ceb1ed23fce72f0
# Verified Classes:   ResumptionContinuityError, ResumeProbe
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionContinuityError(RuntimeError):
    """Raised when a resumed MCP stream cannot be safely spliced onto existing
    agent state because the causal prefix was not observed."""


@dataclass(frozen=True)
class ResumeProbe:
    last_event_id: int
    oldest_retained: int
    newest_emitted: int
    turn_id: str
    prior_turn_id: Optional[str]
    gap_signal_supported: bool


def classify_resume(probe: ResumeProbe) -> str:
    """Return 'continue' or 'demote'. Demotion is the sound default unless
    prefix coverage, turn identity, and gap signaling all hold."""
    if not probe.gap_signal_supported:
        return "demote"
    if probe.prior_turn_id is not None and probe.turn_id != probe.prior_turn_id:
        return "demote"
    if probe.last_event_id < probe.oldest_retained:
        # Server will resume at oldest_retained; the gap is real and unobserved.
        return "demote"
    if probe.last_event_id > probe.newest_emitted:
        # Client claims to have seen an event the server never emitted.
        return "demote"
    return "continue"


def resume_stream(probe: ResumeProbe, idempotency_key: str) -> str:
    decision = classify_resume(probe)
    if decision == "continue":
        return probe.turn_id
    if not idempotency_key:
        raise ResumptionContinuityError(
            f"Cannot demote resume for turn {probe.turn_id}: "
            f"last_event_id={probe.last_event_id} "
            f"oldest_retained={probe.oldest_retained} "
            f"prior_turn={probe.prior_turn_id} — "
            f"no idempotency key to safely re-execute tools/call"
        )
    # Demotion: caller must re-issue with idempotency_key and reset memory.
    return f"new-turn:{idempotency_key}"
