# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-the-last-event-id-gap-when-an-mcp-streamable-http-session-resumes-across-an-sse-to-streamable-migration-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-the-last-event-id-gap-when-an-mcp-streamable-http-session-resumes-across-an-sse-to-streamable-migration-boundary.warrant.json
# Markdown SHA-256:   e285bb81be4884b6a2f8ca577f8d4a033f9fd5dac30340c1219f7585620d2abf
# Code AST SHA-256:   0d94de4238f7509d59bbad87dd20f0f8507ea6668fa4d55cf3b8e4af4b45745c
# Verified Classes:   ResumptionNamespaceViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionNamespaceViolation(RuntimeError):
    """Raised when a resumed MCP stream returns a 200 but the event-ID
    namespace cannot be proven continuous with the persisted cursor."""
    pass


def resume_stream(persisted_epoch: str,
                  persisted_last_id: int,
                  response_status: int,
                  response_epoch: str | None,
                  first_event_id: int | None) -> int:
    # 404 is the *safe* signal: explicitly unresumable -> caller re-initializes.
    if response_status == 404:
        raise ResumptionNamespaceViolation(
            "server declared session unresumable; re-initialize required"
        )
    if response_status != 200:
        raise ResumptionNamespaceViolation(
            f"unexpected resume status {response_status}"
        )
    # Epoch is the only trustworthy namespace-continuity proof.
    if response_epoch is None or response_epoch != persisted_epoch:
        raise ResumptionNamespaceViolation(
            f"epoch mismatch: persisted={persisted_epoch!r} "
            f"response={response_epoch!r}; event-ID space was redefined"
        )
    # A 200 with no first event, or a first event that does not strictly
    # succeed the cursor, means the interregnum was silently dropped.
    if first_event_id is None or first_event_id <= persisted_last_id:
        raise ResumptionNamespaceViolation(
            f"non-successor first event id={first_event_id} "
            f"for persisted cursor={persisted_last_id}; "
            "treat session as dead, do not advance cursor"
        )
    return first_event_id
