# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-resumption-token-has-silently-replayed-a-partial-tool-result.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-resumption-token-has-silently-replayed-a-partial-tool-result.warrant.json
# Markdown SHA-256:   f722c5fdad4bffd426ad75799f4e5cfa7ed98fc79ef133e29dc2e0ab74d54f36
# Code AST SHA-256:   1ebb829f840458a3a5cc86337bc87b779115c2340b18b0c217e55585fe78950b
# Verified Classes:   ResumptionIntegrityError, ResumeLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResumptionIntegrityError(RuntimeError):
    """Raised when a streamable-HTTP resume violates event-ID contiguity
    or fails to deliver a terminal frame for an in-flight tools/call."""
    pass


@dataclass
class ResumeLedger:
    session_id: str
    last_acked_event_id: int
    terminal_event_ids: set = field(default_factory=set)
    instance_tag: str = "unknown"


def validate_resume(
    ledger: ResumeLedger,
    replayed_event_ids: list,
    frames: list,
    server_instance_tag: str,
) -> int:
    """Enforce the two-phase resumption invariant. Returns the new acked cursor.

    Invariants checked:
      1. Replayed IDs must be strictly greater than the client's last ack.
      2. Replayed IDs must be contiguous with the client's last ack.
      3. If any request was in-flight (cursor below a known terminal ID),
         the terminal frame must appear in the replayed set.
      4. Instance tag must match the session's origin instance, or the
         server must prove cursor durability via a non-empty replay.
    """
    if server_instance_tag != ledger.instance_tag and not replayed_event_ids:
        raise ResumptionIntegrityError(
            f"session {ledger.session_id}: resume hit instance "
            f"{server_instance_tag!r} != origin {ledger.instance_tag!r} "
            f"with empty replay; cursor durability unprovable"
        )

    if replayed_event_ids:
        first = replayed_event_ids[0]
        if first != ledger.last_acked_event_id + 1:
            raise ResumptionIntegrityError(
                f"session {ledger.session_id}: event-ID gap; "
                f"last_acked={ledger.last_acked_event_id} first_replayed={first}"
            )

    pending_terminal = {
        tid for tid in ledger.terminal_event_ids
        if tid > ledger.last_acked_event_id
    }
    delivered = set(replayed_event_ids)
    missing = pending_terminal - delivered
    if missing:
        raise ResumptionIntegrityError(
            f"session {ledger.session_id}: terminal event(s) {sorted(missing)} "
            f"for in-flight tools/call never replayed; result would be truncated"
        )

    has_terminal_frame = any(
        ("result" in f) or ("error" in f) for f in frames
    )
    if frames and not has_terminal_frame and not pending_terminal:
        raise ResumptionIntegrityError(
            f"session {ledger.session_id}: replayed frames contain no terminal "
            f"result/error; refusing to synthesize completion from idle timeout"
        )

    return replayed_event_ids[-1] if replayed_event_ids else ledger.last_acked_event_id


def idempotency_key(session_id: str, original_request_id: str) -> str:
    return hashlib.sha256(
        f"{session_id}:{original_request_id}".encode()
    ).hexdigest()[:32]
