# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-session-resumption-from-silently-duplicating-tool-effects-under-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-session-resumption-from-silently-duplicating-tool-effects-under-backpressure.warrant.json
# Markdown SHA-256:   54a75af295251c68c10c41bc737ff5ce5a8bdc0da5a4a1d1ac81da0ddf54dd73
# Code AST SHA-256:   4378be184bf110a8f2054e895b29e6e785b96838c06bdd7441f0abd34482c5d6
# Verified Classes:   ResumptionDuplicationError, OutboxEntry, SessionOutbox
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class ResumptionDuplicationError(RuntimeError):
    """Raised when a resume would replay an event whose effect is already committed."""


@dataclass
class OutboxEntry:
    event_id: int
    idempotency_key: str
    payload: dict
    committed: bool = False


@dataclass
class SessionOutbox:
    session_id: str
    ttl_seconds: float = 3600.0
    entries: dict = field(default_factory=dict)          # event_id -> OutboxEntry
    by_key: dict = field(default_factory=dict)           # idempotency_key -> event_id
    created_at: float = field(default_factory=time.time)

    def append(self, event_id: int, idempotency_key: str, payload: dict) -> OutboxEntry:
        if idempotency_key in self.by_key:
            # A replay of the same logical call: do not append a second effect.
            existing = self.entries[self.by_key[idempotency_key]]
            if existing.payload != payload:
                raise ResumptionDuplicationError(
                    f"idempotency_key {idempotency_key} reused with divergent payload"
                )
            return existing
        entry = OutboxEntry(event_id=event_id, idempotency_key=idempotency_key, payload=payload)
        self.entries[event_id] = entry
        self.by_key[idempotency_key] = event_id
        return entry

    def resume_from(self, last_event_id: int) -> list:
        if time.time() - self.created_at > self.ttl_seconds:
            raise ResumptionDuplicationError(
                f"session {self.session_id} TTL expired; resumption unsafe"
            )
        replayed = [e for eid, e in sorted(self.entries.items()) if eid > last_event_id]
        # Invariant: replay must not include an event whose effect is already committed
        # unless the client's request carries the same idempotency_key (dedupe path).
        return replayed


def handle_resume(outbox: SessionOutbox, last_event_id: int,
                  client_idempotency_key: Optional[str]) -> list:
    replayed = outbox.resume_from(last_event_id)
    for entry in replayed:
        if entry.committed and client_idempotency_key != entry.idempotency_key:
            raise ResumptionDuplicationError(
                f"event {entry.event_id} effect already committed under key "
                f"{entry.idempotency_key}, but resume carried "
                f"{client_idempotency_key!r}; refusing to replay into duplicate effect"
            )
    return replayed
