# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-mcp-streamable-http-resumption-when-the-sse-last-event-id-is-accepted-but-the-server-s-event-log-has-already-been-truncat.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-mcp-streamable-http-resumption-when-the-sse-last-event-id-is-accepted-but-the-server-s-event-log-has-already-been-truncat.warrant.json
# Markdown SHA-256:   a527aacf94d66680c43a8e6a3f4974a5a6f2c2128cee268f5401e54dd9c73e30
# Code AST SHA-256:   6883a9ae4828c845c76773c3aaa7e1c5171d26cabc0d1c1a84a630c897f659bc
# Verified Classes:   ResumptionContinuityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionContinuityError(RuntimeError):
    """Raised when an SSE reconnect cannot prove dense replay from the persisted Last-Event-ID."""
    pass


def resume_stream(persisted_id: str, reconnect_fn, id_is_ordered: bool = True):
    """
    Reconnect an MCP streamable-HTTP SSE stream and validate continuity.

    reconnect_fn(last_event_id) -> (first_received_id, iterator_of_events)
    """
    first_id, events = reconnect_fn(persisted_id)

    # A gap is only detectable if IDs are ordered and comparable.
    if not id_is_ordered:
        # Cannot prove continuity -> must reconcile from authoritative source.
        raise ResumptionContinuityError(
            f"Cannot verify replay continuity from {persisted_id!r}: "
            "event IDs are non-ordered; server may have resumed at head after truncation. "
            "Demote session to reconcile-from-authority before resuming reasoning."
        )

    expected_next = _next_id(persisted_id)
    if first_id != expected_next and first_id != persisted_id:
        # Server resumed at a head beyond our resume point: events were evicted.
        raise ResumptionContinuityError(
            f"Replay gap detected: requested resume at {persisted_id!r}, "
            f"server resumed at {first_id!r} (expected {expected_next!r}). "
            "Events in the gap (tool results, resource updates) were lost; "
            "re-query in-flight tools/call status by ID before re-issuing to avoid duplicate side effects."
        )

    return events


def _next_id(event_id: str) -> str:
    prefix, _, num = event_id.rpartition("-")
    if not num.isdigit():
        raise ResumptionContinuityError(
            f"Event ID {event_id!r} is not densely ordered; cannot compute successor."
        )
    return f"{prefix}-{int(num) + 1}"
