# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-half-resumed-mcp-stream-when-sse-to-websocket-upgrade-silently-rewinds-the-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-half-resumed-mcp-stream-when-sse-to-websocket-upgrade-silently-rewinds-the-event-cursor.warrant.json
# Markdown SHA-256:   7a2740bea9571e898276baab5309ad97d2855d4438248a318e35f835ce7eb1b0
# Code AST SHA-256:   660ede924c1db3c9e041f5f6343a3d70125af4be04f5735683631a024f1ff51e
# Verified Classes:   StreamResumeViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StreamResumeViolation(RuntimeError):
    """Raised when a post-upgrade MCP stream does not contiguously resume
    from the client's last acknowledged event id."""
    pass


def validate_upgrade_resume(
    last_ack_id: int,
    prior_epoch: int,
    first_event: dict,
    upgrade_headers: dict,
) -> None:
    """Assert that the first event on the upgraded transport is a valid
    continuation of the pre-upgrade SSE stream.

    Raises StreamResumeViolation if the stream rewound, gapped, or lost
    its epoch marker. Must be called BEFORE admitting first_event into
    agent reasoning state.
    """
    epoch = upgrade_headers.get("Mcp-Stream-Epoch")
    resume_from = upgrade_headers.get("Mcp-Resume-From")

    if epoch is None or resume_from is None:
        raise StreamResumeViolation(
            "upgrade missing epoch/resume_from headers; "
            "cannot distinguish resume from rewind"
        )

    if int(epoch) != prior_epoch:
        raise StreamResumeViolation(
            f"epoch mismatch: prior={prior_epoch} upgrade={epoch}; "
            "server reset stream sequence space"
        )

    if int(resume_from) != last_ack_id:
        raise StreamResumeViolation(
            f"resume_from={resume_from} != last_ack_id={last_ack_id}"
        )

    first_id = first_event.get("id")
    if first_id is None:
        raise StreamResumeViolation("first post-upgrade event has no id")

    if first_id <= last_ack_id:
        raise StreamResumeViolation(
            f"stream rewound: first_id={first_id} <= last_ack_id={last_ack_id}"
        )

    if first_id != last_ack_id + 1:
        raise StreamResumeViolation(
            f"stream gap: first_id={first_id} but expected {last_ack_id + 1}; "
            f"events ({last_ack_id}, {first_id}) were dropped"
        )
