# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-across-a-stateful-terminating-intermediary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-unsafe-across-a-stateful-terminating-intermediary.warrant.json
# Markdown SHA-256:   1e38a40b1ca8ba8bac0f1fce4498c22d798b0b5645fd73533e93faebf40ab06f
# Code AST SHA-256:   3a9dbd23bf01910cf71ab462cd77f229768b45fbb62e808ec4ca02a863dff18c
# Verified Classes:   ResumptionGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an MCP streamable-HTTP resume cannot prove gap-free replay."""
    pass


def resume_stream(client, session_id: str, last_seen_seq: int,
                  retention_window: int, intermediary_timeout_s: float,
                  max_event_rate: float, in_flight_tool: dict | None) -> None:
    # Joint sizing invariant: retention must outlast the intermediary's
    # reconnect window plus client backoff, or a single proxy-induced
    # reconnect can outrun the replay buffer.
    safe_retention_s = retention_window / max_event_rate
    if safe_retention_s <= intermediary_timeout_s:
        raise ResumptionGapError(
            f"server retention {safe_retention_s:.1f}s <= intermediary "
            f"timeout {intermediary_timeout_s:.1f}s; resume cannot be proven "
            f"gap-free (session={session_id})"
        )

    resp = client.post_resume(session_id=session_id, last_event_id=last_seen_seq)
    first_replayed = resp.first_event_seq

    if first_replayed is None:
        # Server reset or proxy re-subscribed at head without forwarding
        # Last-Event-ID. Cursor regression: every event in
        # (last_seen_seq, head] may be lost.
        raise ResumptionGapError(
            f"cursor regression on resume: sent Last-Event-ID={last_seen_seq}, "
            f"server resumed at head with no replay (session={session_id})"
        )

    if first_replayed != last_seen_seq + 1:
        # Duplicate or gap. Duplicates are tolerable; gaps are not.
        if first_replayed > last_seen_seq + 1:
            gap = (last_seen_seq, first_replayed)
            if in_flight_tool and not in_flight_tool.get("idempotent", False):
                raise ResumptionGapError(
                    f"non-idempotent tool {in_flight_tool['name']} spans gap "
                    f"{gap}; abandon session and reconcile via idempotency key"
                )
            raise ResumptionGapError(
                f"event gap {gap} on resume (session={session_id}); "
                f"re-initialize rather than continue"
            )
        # first_replayed <= last_seen_seq: duplicates, safe to dedupe.
