# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-the-resumability-boundary-has-been-crossed-in-mcp-http-native-streamable-transport-with-sse-fallback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-the-resumability-boundary-has-been-crossed-in-mcp-http-native-streamable-transport-with-sse-fallback.warrant.json
# Markdown SHA-256:   bf4c8d98700d9dfaeb5b69a47c4be448168dc030a5c49136190adac0d89cb783
# Code AST SHA-256:   413e49e12b1636a24f78baddf0bcde014568bca2f48ad00ed3eecbf267abd03f
# Verified Classes:   ResumptionBoundaryError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionBoundaryError(RuntimeError):
    """Raised when a resumed MCP stream is structurally discontinuous."""
    pass


def validate_resume(last_seen_app_seq: int,
                    last_seen_event_id: int,
                    resumed_first_event: dict) -> None:
    """
    Enforce the resume-coherence invariant.

    resumed_first_event must carry both the transport 'id' and the
    application-level 'app_seq' embedded by the tool. If they do not
    advance together from the last seen values, the stream is a
    synthesized replay and must not be trusted.
    """
    event_id = resumed_first_event.get("id")
    app_seq = resumed_first_event.get("app_seq")

    if event_id is None or app_seq is None:
        raise ResumptionBoundaryError(
            "resumed event missing transport id or app_seq; "
            "cannot prove continuity"
        )

    if event_id != last_seen_event_id + 1:
        raise ResumptionBoundaryError(
            f"transport id discontinuity: expected {last_seen_event_id + 1}, "
            f"got {event_id}"
        )

    if app_seq != last_seen_app_seq + 1:
        raise ResumptionBoundaryError(
            f"application sequence gap: expected {last_seen_app_seq + 1}, "
            f"got {app_seq}; buffer likely lost and events synthesized"
        )


def resume_stream(session, last_seen_app_seq: int, last_seen_event_id: int):
    first = session.reconnect(last_event_id=last_seen_event_id)
    validate_resume(last_seen_app_seq, last_seen_event_id, first)
    return session
