# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumable-sse-stream-against-an-oauth-2-1-resource-server-binding-when-the-mcp-session-outlives-the-access-token.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumable-sse-stream-against-an-oauth-2-1-resource-server-binding-when-the-mcp-session-outlives-the-access-token.warrant.json
# Markdown SHA-256:   22dbc783f29db7bc6d03825c22cf6c17212acbf0a509af354ac6a0fad992af5a
# Code AST SHA-256:   691119744f13cd4325a96a512a782ed212dee20c5906f620854601259571b884
# Verified Classes:   SessionResumeViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionResumeViolation(RuntimeError):
    """Raised when an SSE resume request cannot be reconciled with the
    session's OAuth 2.1 binding and scope high-water mark."""
    pass


def authorize_resume(
    session_binding: dict,       # {"sub", "client_id", "audience", "high_water_scopes"}
    token_claims: dict,          # {"sub", "client_id", "aud", "scope": set, "family_id"}
    last_event_id: int,
    session_cursor: int,
) -> int:
    # 1. Cursor must be a known position in this session's log.
    if last_event_id != session_cursor:
        raise SessionResumeViolation(
            f"cursor {last_event_id} does not match session cursor {session_cursor}; "
            "resume cannot be authorized against an unknown log position"
        )

    # 2. Binding tuple must match exactly (rotation drift is a hard failure).
    for field, claim_key in (("sub", "sub"), ("client_id", "client_id"), ("audience", "aud")):
        if session_binding[field] != token_claims[claim_key]:
            raise SessionResumeViolation(
                f"binding mismatch on {field}: session={session_binding[field]!r} "
                f"token={token_claims[claim_key]!r}; session must be invalidated, not retried"
            )

    # 3. Scope must be a superset of the session high-water mark.
    high_water = set(session_binding["high_water_scopes"])
    presented = set(token_claims["scope"])
    if not high_water.issubset(presented):
        # Terminal: no refresh can restore a revoked scope. Do NOT emit 403.
        raise SessionResumeViolation(
            f"scope regression: session high-water {sorted(high_water)} "
            f"not covered by token {sorted(presented)}; "
            "terminate session and require renegotiation"
        )

    return last_event_id
