# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-an-sse-event-id-after-an-mcp-session-resume-and-why-the-answer-is-not-always-replay-the-last-event.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-an-sse-event-id-after-an-mcp-session-resume-and-why-the-answer-is-not-always-replay-the-last-event.warrant.json
# Markdown SHA-256:   96cb3d638e7148536a37dfc19f10895d3c0419e45b198e447ecbf1a17c15ebfa
# Code AST SHA-256:   76e36210dc97b5a05ee7345574c77f6a57e70c59f3d3a245763851eae38634d5
# Verified Classes:   UnsafeResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsafeResumeError(RuntimeError):
    """Raised when an MCP session resume would replay effect-bearing events
    whose client-side effects are not proven committed."""
    pass


EFFECT_BEARING_EVENT_TYPES = frozenset({
    "sampling/createMessage",
    "elicitation/create",
    "roots/list",
    "progress/accumulate",
})


def plan_resume(
    last_event_id: int,
    buffer_head_id: int,
    buffer_floor_id: int,
    events_since_cursor: list[dict],
    effects_committed_through: int | None,
    server_received_request_log: set[str],
) -> dict:
    """
    Decide whether an MCP SSE resume may replay from last_event_id, or must
    force re-initialization.

    Returns {"action": "replay", "from": id} or {"action": "reinitialize"}.
    Raises UnsafeResumeError when the request is ambiguous and silent
    divergence would result.
    """
    # Gap check: buffer has evicted events between cursor and floor.
    if last_event_id < buffer_floor_id - 1:
        # Cannot distinguish client-processing gap from server-eviction gap.
        return {"action": "reinitialize", "reason": "buffer_evicted_gap"}

    if last_event_id > buffer_head_id:
        raise UnsafeResumeError(
            f"Last-Event-ID {last_event_id} exceeds server head {buffer_head_id}; "
            "client cursor is not credible, refusing replay"
        )

    effect_bearing = [
        e for e in events_since_cursor
        if e.get("type") in EFFECT_BEARING_EVENT_TYPES
    ]

    if not effect_bearing:
        # Observation-only segment: bare replay is safe.
        return {"action": "replay", "from": last_event_id + 1}

    # Effect-bearing segment: require a verifiable commitment cursor.
    if effects_committed_through is None:
        raise UnsafeResumeError(
            "Effect-bearing events in resume window but client supplied no "
            "effects_committed_through cursor; replay would risk double-application"
        )

    if effects_committed_through < last_event_id:
        # Client's committed effects lag its delivery cursor: it received
        # events whose effects it did not commit. Replaying them re-triggers
        # client->server requests.
        raise UnsafeResumeError(
            f"effects_committed_through={effects_committed_through} lags "
            f"Last-Event-ID={last_event_id}; replay would re-dispatch "
            f"{len(effect_bearing)} effect-bearing events"
        )

    # Cross-check: every effect-bearing event up to the commitment cursor
    # must have a corresponding received request, or the client's claim is
    # unverifiable.
    for e in effect_bearing:
        if e["id"] <= effects_committed_through:
            key = e.get("request_key")
            if key is None or key not in server_received_request_log:
                raise UnsafeResumeError(
                    f"event {e['id']} claims committed but server has no "
                    f"record of its triggering request; commitment unverifiable"
                )

    return {"action": "replay", "from": effects_committed_through + 1}
