# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-resumable-stream-last-event-id-replay-as-a-session-continuity-hazard-rather-than-a-recovery-mechanism.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-resumable-stream-last-event-id-replay-as-a-session-continuity-hazard-rather-than-a-recovery-mechanism.warrant.json
# Markdown SHA-256:   2e16573109262dcb7f2315d00df042f60891b3a8922f7b37b5fe1f1d8ec808b0
# Code AST SHA-256:   1655f0e0f798f2d25ebdf84fc5481e8642b4f47fc5e4ba8ab3c67cd75126834b
# Verified Classes:   SessionContinuityForkError, DualCursorReplayGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionContinuityForkError(RuntimeError):
    """Raised when resumable-stream replay would fork agent action state from server truth."""
    pass


class DualCursorReplayGate:
    """
    Guards MCP resumable-stream replay. Replay is permitted only when the gap
    between the durable action cursor and the incoming replay start is provably
    side-effect-free and free of unresolved in-flight tool calls.
    """

    def __init__(self, action_cursor: int, transport_cursor: int,
                 in_flight_request_ids: set[str]):
        self.action_cursor = action_cursor
        self.transport_cursor = transport_cursor
        self.in_flight_request_ids = in_flight_request_ids

    def authorize_replay(self, replay_from_event_id: int,
                         gap_events: list[dict],
                         server_status_lookup) -> None:
        # 1. Replay must not start before the action cursor: events the LLM
        #    already acted upon must never be re-delivered for re-reasoning.
        if replay_from_event_id <= self.action_cursor:
            raise SessionContinuityForkError(
                f"replay starts at {replay_from_event_id} but action cursor is "
                f"{self.action_cursor}; re-delivering acted-upon events risks "
                f"duplicate irreversible tool calls"
            )

        # 2. Every in-flight call at disconnect must be reconcilable to a
        #    definitive outcome before the LLM sees replayed tool results.
        for req_id in self.in_flight_request_ids:
            status = server_status_lookup(req_id)
            if status not in ("executed", "not_executed"):
                raise SessionContinuityForkError(
                    f"in-flight request {req_id} has indeterminate status "
                    f"{status!r}; cannot safely replay, must re-establish session"
                )

        # 3. The gap must contain only idempotent events (notifications).
        for ev in gap_events:
            if ev.get("kind") == "tool_result" and not ev.get("idempotency_key"):
                raise SessionContinuityForkError(
                    f"gap event {ev.get('id')} is a non-idempotent tool_result; "
                    f"replay would inject an unsolicited result into LLM context"
                )


def handle_reconnect(gate: DualCursorReplayGate, replay_from_event_id: int,
                     gap_events: list[dict], server_status_lookup) -> str:
    try:
        gate.authorize_replay(replay_from_event_id, gap_events, server_status_lookup)
    except SessionContinuityForkError:
        # Conservative fallback: abandon replay, re-establish session from
        # server-side state, accept cold-start re-sync cost.
        return "reestablish_session"
    return "replay"
