# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-invalid-rather-than-replayable-and-how-does-silent-replay-corrupt-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-last-event-id-resumption-as-invalid-rather-than-replayable-and-how-does-silent-replay-corrupt-tool.warrant.json
# Markdown SHA-256:   5d5a1abcfddbedfda6a1ce72a8d8e1778847e3efd51552893c62fde864177eb7
# Code AST SHA-256:   24c7f89160d52cf6f111db2eee217f5b186877f8ca3a6fade3fbf2349f4a972f
# Verified Classes:   StaleResumptionCursor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleResumptionCursor(RuntimeError):
    """Raised when a Last-Event-ID cursor is not valid for the current stream epoch."""
    pass


def accept_resumption(
    session_id: str,
    last_event_id: str,
    current_stream_epoch: str,
    epoch_seq_high_water: int,
) -> int:
    """
    Validate an SSE resumption cursor against the current stream epoch.

    Returns the sequence number to resume from, or raises if the cursor is
    merely plausible (session-live) but not continuous (epoch-matched).
    """
    if not session_id:
        raise StaleResumptionCursor("missing Mcp-Session-Id; cannot scope cursor")

    # Event IDs are formatted "<epoch>:<seq>" to make cross-epoch reuse impossible.
    if ":" not in last_event_id:
        raise StaleResumptionCursor(
            f"unqualified event id {last_event_id!r}; epoch cannot be proven"
        )

    epoch, _, seq_str = last_event_id.partition(":")
    if epoch != current_stream_epoch:
        # Session may still be live, but the cursor points into a dead lineage.
        raise StaleResumptionCursor(
            f"cursor epoch {epoch!r} != current epoch {current_stream_epoch!r}; "
            "resync required, replay forbidden"
        )

    try:
        seq = int(seq_str)
    except ValueError as exc:
        raise StaleResumptionCursor(f"non-numeric sequence in {last_event_id!r}") from exc

    if seq > epoch_seq_high_water:
        # Cursor claims to be ahead of what this epoch has emitted.
        raise StaleResumptionCursor(
            f"cursor seq {seq} exceeds epoch high-water {epoch_seq_high_water}"
        )

    return seq + 1
