# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stream-resumption-replay-from-duplicating-tool-side-effects-across-mcp-http-native-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stream-resumption-replay-from-duplicating-tool-side-effects-across-mcp-http-native-sessions.warrant.json
# Markdown SHA-256:   7b02b1bb32c9fe0c16b09ee304dfa9e105cb88385e6e6318b99aeebf18128f84
# Code AST SHA-256:   96a13bee4f231f826ba0f685dd977d2b88024ddfd29d136306adce59bf238e92
# Verified Classes:   ResumeInvariantViolation, EventLog, IdempotencyRecord, ToolServer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ResumeInvariantViolation(RuntimeError):
    """Raised when stream resumption would silently degrade into effect duplication."""


@dataclass
class EventLog:
    """Append-only, ordered event log with ids assigned at emission."""
    events: list[tuple[int, str]] = field(default_factory=list)
    next_id: int = 1
    log_ttl_seconds: float = 0.0
    created_at: float = field(default_factory=time.monotonic)

    def append(self, payload: str) -> int:
        eid = self.next_id
        self.next_id += 1
        self.events.append((eid, payload))
        return eid

    def replay_after(self, last_event_id: int) -> list[tuple[int, str]]:
        if time.monotonic() - self.created_at > self.log_ttl_seconds:
            # Evidence discarded. We cannot assert "nothing happened after N".
            raise ResumeInvariantViolation(
                f"event log expired (ttl={self.log_ttl_seconds}s); "
                f"cannot serve resume for Last-Event-ID={last_event_id}"
            )
        return [(eid, p) for (eid, p) in self.events if eid > last_event_id]


@dataclass
class IdempotencyRecord:
    status: str  # "in_flight" | "committed"
    result: Optional[str] = None


class ToolServer:
    def __init__(self, log_ttl_seconds: float, tool_timeout_seconds: float) -> None:
        if log_ttl_seconds <= tool_timeout_seconds:
            raise ResumeInvariantViolation(
                "log_ttl must exceed tool_timeout; otherwise a mid-flush drop "
                "produces a silent retention gap and duplicate side effects"
            )
        self.log_ttl_seconds = log_ttl_seconds
        self.tool_timeout_seconds = tool_timeout_seconds
        self.sessions: dict[str, EventLog] = {}
        self.idempotency: dict[str, IdempotencyRecord] = {}

    def _log(self, session_id: str) -> EventLog:
        if session_id not in self.sessions:
            self.sessions[session_id] = EventLog(log_ttl_seconds=self.log_ttl_seconds)
        return self.sessions[session_id]

    def resume(self, session_id: str, last_event_id: int) -> list[tuple[int, str]]:
        log = self._log(session_id)
        # Raises ResumeInvariantViolation on retention gap -> caller must
        # surface 410 resume_failed, never an empty 200.
        return log.replay_after(last_event_id)

    def call_tool(self, session_id: str, idempotency_key: str, side_effect) -> str:
        log = self._log(session_id)
        existing = self.idempotency.get(idempotency_key)
        if existing is not None:
            if existing.status == "committed":
                return existing.result  # type: ignore[return-value]
            # in_flight: attach to the running operation rather than re-execute.
            return f"attached:{idempotency_key}"

        # Claim the key BEFORE executing the side effect.
        self.idempotency[idempotency_key] = IdempotencyRecord(status="in_flight")
        log.append(f"request:{idempotency_key}")
        try:
            result = side_effect()
        except Exception:
            # Side effect failed; release the claim so a retry may proceed.
            del self.idempotency[idempotency_key]
            raise
        # Commit dedupe record and result event together.
        self.idempotency[idempotency_key] = IdempotencyRecord(
            status="committed", result=result
        )
        log.append(f"result:{idempotency_key}:{result}")
        return result


def demo() -> None:
    server = ToolServer(log_ttl_seconds=60.0, tool_timeout_seconds=120.0)  # raises


if __name__ == "__main__":
    demo()
