# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-a-streamable-mcp-session-whose-last-event-id-predates-a-server-side-tool-call-commit-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-a-streamable-mcp-session-whose-last-event-id-predates-a-server-side-tool-call-commit-boundary.warrant.json
# Markdown SHA-256:   4674abfa0ad4bf2976ef7f414edf529b38121c06944106a290a0d6cf7c2739f8
# Code AST SHA-256:   82a48d7201725f04042c7577ba58620bc13d80002f8f2aac183456e2b3602f18
# Verified Classes:   UncommittedResumptionWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UncommittedResumptionWindow(RuntimeError):
    """Raised when a client's Last-Event-ID lands inside an uncommitted tool-call window."""
    def __init__(self, cursor: int, commit_watermark: int, oldest_safe_id: int):
        self.cursor = cursor
        self.commit_watermark = commit_watermark
        self.oldest_safe_id = oldest_safe_id
        super().__init__(
            f"Last-Event-ID {cursor} exceeds commit watermark {commit_watermark}; "
            f"re-sync from {oldest_safe_id}"
        )


def resolve_resumption(
    last_event_id: int,
    commit_watermark: int,
    oldest_retained_id: int,
    last_emitted_id: int,
) -> int:
    """Return the event ID from which the server may safely replay.

    Raises UncommittedResumptionWindow if the cursor falls in the gap between
    the commit watermark and the last emitted event, where a tool call may
    have executed but not yet been durably recorded.
    """
    if last_event_id < oldest_retained_id:
        raise UncommittedResumptionWindow(
            cursor=last_event_id,
            commit_watermark=commit_watermark,
            oldest_safe_id=oldest_retained_id,
        )
    if last_event_id <= commit_watermark:
        return last_event_id
    if last_event_id <= last_emitted_id:
        # Cursor is in the uncommitted window: a tool call whose request event
        # is at or below this ID may have executed without a recorded outcome.
        raise UncommittedResumptionWindow(
            cursor=last_event_id,
            commit_watermark=commit_watermark,
            oldest_safe_id=commit_watermark,
        )
    # Cursor beyond what was emitted: client is confused; treat as fresh sync.
    return commit_watermark
