# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumable-sse-fallback-from-silently-forking-an-mcp-tool-call-stream-during-http-native-transport-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumable-sse-fallback-from-silently-forking-an-mcp-tool-call-stream-during-http-native-transport-negotiation.warrant.json
# Markdown SHA-256:   2b9c17d85501b799527bc2275362019c6037dd67c77cbbcb208a8fb4bbe01d90
# Code AST SHA-256:   b9bcb828b19aa49de7057c212adb2293eaffc9f4c36c7de8839ab2bd6be406db
# Verified Classes:   StreamForkError, ResumableCallTracker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StreamForkError(RuntimeError):
    """Raised when SSE resumption and HTTP-native retry both target one tool-call ID."""
    pass


class ResumableCallTracker:
    def __init__(self, call_id: str, idempotency_key: str):
        self.call_id = call_id
        self.idempotency_key = idempotency_key
        self.epoch = None            # set on first event
        self.last_seq = 0
        self.resumable = False       # server advertised resumption
        self.retry_issued = False
        self.resume_attempted = False

    def on_event(self, raw_id: str) -> None:
        # Expect "<epoch>:<seq>"; a bare int that resets to 1 is a fork sign.
        if ":" in raw_id:
            epoch, seq = raw_id.split(":", 1)
            seq = int(seq)
        else:
            epoch, seq = "0", int(raw_id)

        if self.epoch is None:
            self.epoch = epoch
        elif epoch != self.epoch:
            raise StreamForkError(
                f"call {self.call_id}: event epoch {epoch} != open epoch "
                f"{self.epoch} — parallel producer detected"
            )
        if seq <= self.last_seq:
            raise StreamForkError(
                f"call {self.call_id}: seq {seq} <= last {self.last_seq} "
                f"in epoch {epoch} — replay/dedupe ambiguity"
            )
        self.last_seq = seq
        self.resumable = True

    def recover(self) -> str:
        """Choose exactly one recovery path. Returns the action taken."""
        if self.resumable and not self.retry_issued:
            self.resume_attempted = True
            return "resume_sse"          # continuation of the open epoch
        if self.resume_attempted and not self.retry_issued:
            # Resumption window expired or failed; retry is now legal ONLY
            # because no live stream handle remains.
            self.retry_issued = True
            return "retry_http_idempotent"
        raise StreamForkError(
            f"call {self.call_id}: both resumption and retry already used; "
            f"side-effect state unknown — fail closed"
        )
